Android Linux / Raspberry Pi Bluetooth communication

This post explores my attempt to get bidirectional bluetooth communication going between an android device and a linux computer (in this case a Raspberry Pi running Raspbian). This post is part of the documentation of knowledge acquired while building an “AquaPi” – a raspberry pi that will act as a control center for an aquarium. Here is a video showing a working example:


https://www.youtube.com/watch?v=hvykOO73LbM


Hardware:

Software:

  • On the raspberry pi: setting up and using pybluez

Note: these instructions have also been confirmed to work on an ubuntu workstation with in-built bluetooth support.

First, plugin the bluetooth dongle and fire up the raspberry pi. Next, install the pre-requisites to get bluetooth support on the raspberry pi by running:

sudo apt-get install bluez python-bluez

There are plenty of guides in the internet on how to get bluetooth working, but the only method that worked consistently for me is the following:

1. Disable bluetooth pnat support as there seems to be a bug which stops proper operation with pnat enabled. Full details can be found here: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=690749

A workaround is to add the following to /etc/bluetooth/main.conf:
   DisablePlugins = pnat

Not following the above will give errors similar to:

 (111, 'Connection refused')

Incidentally, the “Steps to Reproduce” section of the bug link are a very good way of testing your bluetooth stack and making sure you have the proper groundwork in place

2. Make note of the following two commands which will be useful when pairing your raspberry pi to the android phone:

sudo hciconfig hci0 piscan [make your device discover-able]
sudo hciconfig hci0 name 'Device Name' [change your device name to something else you fancy]

3. Download the following python script someplace on your raspberry pi. The script is a modified version of the “simple rfcomm server” script found under /usr/share/doc/python-bluez/examples/simple/rfcomm-server.py

Note that as previously stated, this script stems from a build to control an aquarium. So you may need to modify the if/elif/else statements beginning at line 60 to do something more meaningful in your particular case. Simply run the server via:

sudo python /path/to/script.py
  • On android: testing bluetooth and writing an app

Before proceeding, you must make sure to pair your android device to your raspberry pi. To do this, ensure that your raspberry pi is discover able (see step 2 above), and search for the device in the bluetooth settings in your android. After successful pairing, you should be able to continue.

1. Install “BlueTerm” from the playstore (https://play.google.com/store/apps/details?id=es.pymasde.blueterm). This will allow you to test your bluetooth setup up this stage. Your raspberry pi should accept connections and even respond to typed commands

2. Write an android app to establish a bluetooth rfcomm channel and send commands to the raspberry pi as well as read information. Following is a sample main activity from the mobile app written for the video demo:

Notes on the android script:

  • Line 33: note the UUID. This must match the UUID being advertised by the rfcomm server – which is the python script (line 46)
  • Lines 31-51: this is a function which will send information to the raspberry pi (hence the android here is acting as a “client”) . If not already connected, the function creates an RFCOMM socket, gets a writeable stream, and pushes the message through the socket. The message to be sent is passed as an argument to the function
  • Lines 67-141: this is the runnable (thread) which is used to send and receive information over the bluetooth RFCOMM channel. We need to run this in a seperate thread so as to avoid ANR (application not responding) notifications, and hence leaving the GUI responsive. The thread first sends a message using the sendBtMsg function (line 77), and then opens an input stream and waits for response data. The app waits for response data by creating a buffer (of 1024 bytes in this case – line 95). When data is received, the app checks if the delimiter character is present (in this case the delimiter character is the exclamation mark [!] – ascii character 33 – line 27). We implement this pattern so as to be sure that we received the entire intended data stream before displaying the information to the end user. Obviously, you may want to change my choice of using ! as a delimiter to something more suited to your needs.
  • Line 113: here we set a text view to the received data from the raspberry Pi
  • Line 129: if the data is received and displayed to the user, close the bluetooth connection and break out of the listener loop to finish the thread
  • Lines 144-179: here we are simply attaching onClickListeners to buttons on the GUI to send commands to the raspberry pi. These differ only in the string which is sent over the bluetooth RFCOMM connection to the raspberry pi
  • Lines 184-185: here we check if bluetooth is enabled. If not, we fire off an intent to ask the user to allow bluetooth use
  • Lines 188-199: go through the list of paired devices, and find the raspberry pi. Note, you may need to change the name in the code if you didnt use the standard (line 193). Once the raspberry pi is found, assign it as the device to be used (line 196)
About these ads

Raspberry Pi : Home Control Center Part 1

In this series i’ll document how I put together a lot of people’s hard work into a home control center that is based off the raspberry pi, both for my future reference and for anyone out there who needs to build something similar. By the end of it, we should be able to have the following features:

  • Monitor temperature and humidity across various points in the house – wirelessly
  • Connect to your network via wireless
  • Display essential info on an OLED screen
  • Have a “webcam” mode that will allow you to stream real-time video of a room in your house wherever a raspberry pi is installed
  • Have a “security mode” that will record about 30-60 seconds of video everytime movement is sensed wherever a raspberry pi is installed
  • Trigger alarms whenever movement is sensed or doors open/close – wirelessly
  • Have an easy to use WEB UI that also works on your mobile phone
  • Can control lights on sensing movement

That’s quite a list which I hope to eventually complete and document. In this 1st part, I’ll focus on:

  • Connect to the network via  wireless
  • Display IP address, local temperature and humidity on an OLED screen

Most of the heavy lifting has been done by the awesome folks over at www.adafruit.com , in most cases I was just gluing everything together…. This guide assumes a fresh raspbian install (preferably via NOOBS). Without further ado

  • Connect to the network via  wireless

Really simple and run of the mill – if you have the right hardware. This point is key… I’ve had other wireless cards and they involved compiling drivers, not working, rinse, repeat. Save yourself a lot of hassle and just get a wireless USB that works out of the box. The adafruit one is perfect:

http://www.adafruit.com/products/814

Simply switch off your raspberry pi, plug it in and wait for a bootup and run an ifconfig to make sure wlan0 is listed. Then it’s the usual connect-your-linux-to-wlan procedure… In my case, I am connecting to a WPA2, pre shared key wireless lan. First add the following to your /etc/network/interfaces file:

allow-hotplug wlan0
iface wlan0 inet manual
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf
iface wlan0 inet static
    address 192.168.1.245
    netmask 255.255.255.0
    network 192.168.1.0
    gateway 192.168.1.1
The above will give a static IP to your Pi, amend as necessary. And also in your /etc/wpa_supplicant/wpa_supplicant.conf file:
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
network={
 ssid="YOUR_WLAN_SSID"
 proto=RSN
 key_mgmt=WPA-PSK
 pairwise=CCMP TKIP
 group=CCMP TKIP
 psk="YOUR_PASSWORD"
}

Once again amend as necessary. I also added the following to the /etc/rc.local file to make sure the wireless connected on bootup:

ifdown --force wlan0
ifup --force wlan0

That’s it for wireless.

  • Display IP address, local temperature and humidity on an OLED screen

The OLED screen purchase and setup were a breeze thanks to adafruit. Visit and follow the tutorial here: http://learn.adafruit.com/adafruit-oled-displays-for-raspberry-pi.

The author of this post already includes how to display IP addresses on the OLED screen in one of his python examples so you’re halfway there. Adding the temperature and humidity are equally easy, again due to adafruit’s amazing tutorials. In this case, follow the one here: http://learn.adafruit.com/dht-humidity-sensing-on-raspberry-pi-with-gdocs-logging/overview

I obviously did deviate here since I wanted to place the information on the OLED screen rather than google docs. So in my case, after performing this step:

$ git clone git://github.com/adafruit/Adafruit-Raspberry-Pi-Python-Code.git
$ cd Adafruit-Raspberry-Pi-Python-Code
$ cd Adafruit_DHT_Driver

I compiled and installed the python library for the DHT driver as follows:

cd ../Adafruit_DHT_Driver_Python
python setup.py build

This results in a dhtreader.so file in the build directory which we can now use directly in python. Next to code:

  • Create a directory for the project. In my case:
mkdir /home/pi/raspiCC
  • Create a new python file and copy/paste the following:

If you notice, in the above code I’ve placed the main logic in a for loop with specific sleep periods. This was done so the whole script executes for a total of just under 60 seconds. This way, we can schedule a cron job that runs every minute and will continuously cycle between IP and environment information. This is quite simply done via first entering

sudo su -
crontab -e


Then entering the following crontab entry:

* *  *   *   *     /home/pi/raspiCC/daveOLED.py

The above will run our script every minute and refresh our OLED display. Here are the results so far:

Raspi PI OLED screen showing temperature and humidity

Raspi PI OLED screen showing temperature and humidity

... and showing network information

… and showing network information

Note the camera and infrared sensor in the last photo, which is coming up next… connecting the raspi cam to record about 30-60 seconds of video everytime movement is sensed near your pi :)