Saturday, June 15, 2013

Bluetooth Programming On Linux

Sometimes we need to write programs that run on a PC and communicate with an external bluetooth capable device such as a smartphone. In such cases we need some good programming library which provide the necessary capabilities to access bluetooth hardware components in our PC easily. While looking for a good programming library for this task I came across a library called Bluez. It seems it has been widely used for Bluetooth programming in linux based environments. So, I decided to take a look at it.

I tried it on a Ubuntu 12.04 system connected with a USB Bluetooth adaptor. First thing is to install the necessary packages. Give following commands to install those packages.

sudo apt-get install bluez
sudo apt-get install python-bluez

After these library packages completes the installation, we will first check whether our hardware setup works. Connect the bluetooth adaptor to the USB port and turn On bluetooth. I had some problems with the default bluetooth manager that comes with Ubuntu 12.04 as I mentioned in my previous post. Therefore I use Blueman bluetooth manager to turn on/off and do anything with bluetooth on my PC.

After turning bluetooth ON, first I checked whether every thing's fine by pairing my PC with a smartphone and sending and receiving some files. Then it's time to check our Bluez libray. Put the following code in the text editor and save as somewhere in the file system.

1:  import bluetooth  
2:  target_name = "SHV-E210K"  
3:  target_address = None  
4:  nearby_devices = bluetooth.discover_devices()  
5:  for bdaddr in nearby_devices:  
6:    print bluetooth.lookup_name( bdaddr )  
7:    if target_name == bluetooth.lookup_name( bdaddr ):  
8:      target_address = bdaddr  
9:      break  
10:  if target_address is not None:  
11:    print "found target bluetooth device with address ", target_address  
12:  else:  
13:    print "could not find target bluetooth device nearby"  

Please note that the target name variable is set to the name of the external bluetooth device we are going to connect. "SHV-E210K" was the name of my smartphone for bluetooth connection. According to the program, it print the names of available Bluetooth devices around and check whether our target device is available.

Now go to the location of the file from terminal and issue following command to run the python program. 

sudo python

If every thing is fine, it should print that target device is found just like the one shown above. That means simply our Bluez library is capable of accessing the Bluetooth adaptor and using it. Following link will be a good reference for learning to use Bluez library.


Enjoy with Bluetooth  programming on Linux! :)

1 comment: