Sunday, January 19, 2014

Connect BeagleBone Black to Android (xpost)

19th January '14
Some of the methods that I think can be used to setup duplex communication between an Android application and a Beaglebone Black.
  1. Android uses the mtp filesystem. You can setup libmtpfs and mtptools on your BeagleBone Black. Then connect the Android device to the USB host port of BBB, mount the Android filesystem in Angstrom and read/write on files there. Problem with this method is there is no recipe for libmtp in the Angstrom kernel tree here OpenEmbedded has support for mtp here. So it might not be a difficult thing to get mtp to play along with a BBB.
  2. Android has the AOA protocol(Android Open Accessory Protocol). It basically allows one to connect an Android device to an Arduino. Look at ADK Rowboat project has implemented the protocol for the BeagleBone. According to me there isn't any difference between BBB and BeagleBone White when it comes to this, but I was unsuccessful while getting the rowboat project to work on the Black.
  3. Bluetooth : You could attach a USB dongle like this to your BBB. bluez on Linux allows you to pair devices too.
  4. Similar to method number 1, we have a protocol called PTP (Picture Transfer Protocol). PTP makes your Android device appear as a camera. PTP is a subset of MTP . I was able to use gphoto2, a tool based on PTP, to get and put files on an Android device connected to the Beaglebone Black.
Basic outline is as follows :
opkg update
opkg install libusb-@-dev #Replace @ with the latest version number
libusb comes pre installed with Angstrom. We need the -dev version to build libgphoto2 and gphoto2.
Next fetch the tars available on the sourceforge pages
Untar both the files, and run the following commands in each.
./configure
make
make install
First install, libgphoto, followed by the gphoto tool. Now you should be able to use gphoto2 tool from the command line on the beaglebone black.
Next we look at some of the commonly used options with gphoto2.
  • --list-ports
    If you installed libusb correctly, running gphoto2 with this option will show you 6 results. We are interested in the one that reads USB.
  • --auto-detect
    This will detect the cameras (in our case the Android device), that's connected to the beagle. It will show it's model number.
  • --list-files
    This will list all the files that are present on the mounted device.
A comprehensive list can be found at the man page.
This neat setup should help in a lot of projects that I have in mind :)

- Anuj Deshpande

Saturday, October 19, 2013

Using Raspberry Pi as IRC Client

I wanted to be continually logged into IRC and also use it as a logging client for message on the #doothings IRC channel.
What better way than to use Raspberry Pi?

Steps for using Raspberry Pi as IRC Client

  1. We will use IRSSI, whici is a terminal based IRC client.
  2. Install it by running sudo apt-get install irssi
  3. Also install screen by running sudo apt-get install screen
  4. screen and then press Enter
  5. IRSSI irssi
  6. /server irc.freenode.net
  7. /join #doothings
  8. Now you have logged-in to the #doothings IRC Channel.
  9. To Detach from the Client. Press Ctrl + a and then d
  10. You should be back to the terminal window.
  11. To rejoin the IRC window run screen -r

Settings for irssi

  1. To ignore joins / quits / nicks changes on a specific channel.
    /ignore -channels #chan1,#chan2,#chan3 * JOINS PARTS QUITS NICKS
  2. Auto Connect to a Server on startup
    /SERVER ADD -auto -network IRCnet irc.freenode.net 6667
  3. Auto Join to Specificed channels
    /CHANNEL ADD -auto #doothings IRCnet
  4. To Keep logging all these conversations
    /SET AUTOLOG ON
  5. To set Nicks and Real Name etc.
    /SET -> This should show all existing configured parameters.
    To change these just say
    /SET param-name value like /SET nick nism-pi
  6. /SAVE to save the entire configuration.
    All these steps if you think need to be improved, you can send in a pull request here https://github.com/iot-pune/raspberrypi/blob/master/IRC-client.md

Thursday, October 10, 2013

Using Raspberry Pi as a torrent client.

Using Raspberry Pi as a torrent client

Advantage of using raspberry pi as a torrent client is that it uses very less power. For a comparison,

Power consumption of Raspberry Pi device is very less. (5V, 500 mA (2.5W) without any devices connected).

So obviously, its a better solution for downloads that take a long time. and better to keep raspberry pi always on over a desktop / laptop.

Steps

  1. sudo apt-get update
    sudo apt-get upgrade
  2. sudo apt-get install deluged
    sudo apt-get install deluge-console
  3. Start the deluge daemon by running deluged
    It creates the necessary files that we can now edit.
    Stop this after some time (5-10 seconds) by running sudo pkill deluged
  4. Now edit the auth file. But first create a backup.
    cp ~/.config/deluge/auth ~/.config/deluge/auth.copy`
    Editing the auth file. nano ~/.config/deluge/auth
    Add a line at the bottom of the configuration file with the following convention: user:password:level
    Example : pi:pi:10 (10 is full-access/administrative level for the daemon)
  5. Now let's update the settings for allowing remote connections.
    deluged
    
    deluge-console
    
    config -s allow_remote True
    
    config allow_remote
    
    exit
    
  6. Restart deluged for this configuration to take effect.
    sudo pkill deluged
    
    deluged
    
  7. Intall deluge-web to be able to access it from remote.
    sudo apt-get install python-mako
    
    sudo apt-get install deluge-web
    
    deluge-web
    
  8. Access deluge-web from a remote machine on the same network.
    Navigate to http://<rasberrypi-ip>:8112/ .
    You have a torrent server at your service!
    Enter the password as deluge and immediately change it.
  9. In addition to accessing the web-gui from you can also access it from an Android application like Torrent Manager.
    While using this app just provide the password which was changed in step 8.

    You can take a look at the RaspberryPi code repository of IOT-Pune

Wednesday, October 2, 2013

Home Automation with RaspberryPi Python - Django


Home Automation with RaspberryPi Python - Django

So after attending the 2 meet-ups for IOT-Pune. I got a Raspberry Pi and decided to play around with it a little bit. The following post will walk you through the steps needed to turn on/off a light bulb.

Things needed
1. Raspberry Pi
2. Relay switch
3. light bulb with wire to plug into main power supply

Lets us start!!!

  • sudo apt-get install python-dev python-setuptools
  • sudo pip install django
  • django-admin.py startproject mysite
  • cd mysite/
  • django-admin.py startapp ledblink
  • cd mysite
  • open file named setting.py and add the ledblink app in the INSTALLED_APPS so that it looks like this
INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'ledblink',
    # Uncomment the next line to enable the admin:
    'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
)
  • add this to the templates dir make sure you  add import os at the top of the page
TEMPLATE_DIRS = (
     os.path.join(os.path.dirname(__file__), 'templates').replace('\\','/'),
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)
  • cd ledblink
  • open the views.py file and change it to this
from django.shortcuts import render
from django.http import HttpResponse
import RPi.GPIO as GPIO
import time


GPIO.setmode(GPIO.BOARD)
GPIO.setup(18,GPIO.OUT)


def blinker(request):
    if 'on' in request.POST:
        GPIO.output(18,1)
    elif 'off' in request.POST:
        GPIO.output(18,0)
    return render(request,'control_page.html')
    
  • Let us add the template control pages so go ahead and create a templates directory in your ledblink app and add the following html code and name it control_page.html
<!DOCTYPE html>
<html>
<head>

</head>
<body>

<form action="" method="post">{% csrf_token %}
<input type="submit" name="on" value="on" />
<input type="submit" name="off" value="off" />
</form>
</body>
</html>

  • now let us create a url that links to this view. Goto the urls.py file in mysite directory cd ../mysite
from django.conf.urls import patterns, include, url
from ledblink.views import blinker
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

urlpatterns = patterns('',
    url(r'^ledblink/$',blinker),
    # Examples:
    # url(r'^$', 'mysite.views.home', name='home'),
    # url(r'^mysite/', include('mysite.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    # url(r'^admin/', include(admin.site.urls)),
)
  • Goto main folder of the project where the manage.py file is located and run the following command
sudo python manage.py runserver 192.168.0.106:8000

open up a web browser and type http://192.168.0.106:8000/ledblink/ in the address bar and you should have the following result




now lets get to the part where we connect every thing to the raspberry pi.



  • Sorry I couldn't get a better picture even though Nishant suggested to take the book out. :P But yoy connect the 5V out of the Pi that is pin 2 to the positive on the relay . The ground pin 6 to the regative of the relay and finaly GPIO18 to the corresponding pin on the relay board.

  • Plug the bulb in the main power supply. Go ahead and try turning on the bulb from the web Browser


Friday, August 2, 2013

Arduino with real time web application using web sockets


Purpose of this experiment is to demonstrate real time aspect of the web to pull data from an Arduino.

Arduino can be clubbed together with several sensor to receive data of surroundings and do anything with data. Once you have data with you, imagination is the limit like sending surrounding temperature to Twitter as tweet, check mail when you come close to your computer, turn off volume when an ad comes on TV etc. 

Following POC shows use of Arduino with LDR sensor to plot real time graph of Light around you.

You will need following things for our project : 

  1. Arduino UNO or Freeduino 
  2. LDR or photo-resistor 
  3. 10k ohm resistor (Voltage divider)
  4. Computer 
LDR is basically a simple light sensor that changes the resistance with light. We will measure amount of voltage is on LDR using analog read of Arduino. With Arduino analog read, 5v is highest value read as 1023 and 0v is lowest value read as 0.

Let connect things 



Connect your LDR and resistor as shown in figure., 

Now coding part,
The idea here is to read sensor reading using Arduino and send them to computer for further processing, so we will read sensor data and send it serial port of computer where Arduino is connected. 

filename: LDR.ino

int LDR = 0;

void setup(){
  Serial.begin(9600);
}

void loop(){ 
  int Reading = analogRead(LDR);
  Serial.println(Reading);
  delay(250);
}


Code is pretty self-explanatory. Now the web part here we will use websocket for reading values and plotting real time graph out of read values. We will not discuss websocket and its implementation as this is out of scope of this project (which itself is big topic for discussion).

In order to run the code you need to install Python with following modules 
  1. geventwebsocket.handler 
  2. gevent 
  3. serial 
Python provides module called 'serial' which enables to read and write to serial port of computer.
Here websocket server written in Python, 

filename: LDRreader.py 

from geventwebsocket.handler import WebSocketHandler
from gevent import pywsgi
import gevent
import serial

# PORT used for websocket client
PORT = 8090
import os
import random
def handle(ws):
    """  This is the websocket handler function.  Note that we
    can dispatch based on path in here, too."""
    serial_read = serial.Serial('COM31', 9600)
    if ws.path == '/data':
        for i in xrange(10000):
            signal = serial_read.readline()
            ws.send("0 %s %s\n" % (i, signal))
            print "0 %s %s\n" % (i, signal)
            gevent.sleep(0.1)

def app(environ, start_response):
    if environ['PATH_INFO'] == '/test':
        start_response("200 OK", [('Content-Type', 'text/plain')])
        return ["blah blah"]
    elif environ['PATH_INFO'] in ("/data"):
        handle(environ['wsgi.websocket'])
    else:
        start_response("404 Not Found", [])
        return []


def main():
print "In main, Starting WSGIServer"
server = pywsgi.WSGIServer(('0.0.0.0', PORT), app,
handler_class=WebSocketHandler)
try:
server.serve_forever() 
except:
pass

if __name__ == "__main__":
main()

Now websocket client which will actual receive data and plot it on web browser, you need this library for plotting graph. Download and keep in same directory where LDR.html is present. 

filename: LDR.html

<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="jquery.flot.js"></script>
<script>
var iets = "";
window.onload = function() {
    var data = {};
try {
var s = new WebSocket("ws://localhost:8090/data");
}
catch (e) {
var s = new MozWebSocket("ws://localhost:8090/data");
}
    s.onopen = function() {
        console.log('Websocket Open');
        s.send('hi');
    };
    s.onmessage = function(e) {

      console.log('got ' + e.data);
      var lines = e.data.split('\n');
      for (var i = 0; i < lines.length - 1; i++) {
        var parts = lines[i].split(' ');
        var d = parts[0], x = parseFloat(parts[1]), y = parseFloat(parts[2]);
        if (!(d in data)) data[d] = [];
        data[d].push([x,y]);
      }
      var plots = [];
      for (var d in data) plots.push( { data: data[d].slice(data[d].length - 200) } );
      $.plot( $("#holder"), plots,
              {
                series: {
                  lines: { show: true, fill: true },
                },
                yaxis: { min: 0 },
              } );

      s.send('');
    };
};
</script>
</head>
<body>
<h3>LDR Plot</h3>
<div id="holder" style="width:800px;height:350px"></div>
</body>
</html>

Now start our websocket server using 
# python LDRreader.py  

now go to browser and type http://localhost:8090 and bam !!! 

You will see plotting graph.