In today world ad-hoc networks have become common. The main aspect of an ad-hoc network is that the participants of the network communicate more or less in wireless way. Bluetooth has emerged as the prominent mode of wireless communication among devices forming an ad-hoc network. Hence, any software targeted at such devices needs to be Bluetooth enabled. In other words, the language with which such software is developed need to provide API that facilitates Bluetooth enabling. However, most of the time the APIs provided by the languages introduce a steep learning curve due to the lack of flexibility of the language itself. It is here that scripting languages especially a language such as Python provides an easier way. In this discussion, I will focus on the use of Python API for programming Bluetooth devices. The first section will be about the whys and wherefores of Bluetooth and how Python fits into the picture. The second section will enumerate the steps in using Python API in accessing the Bluetooth devices and their services. The third section will put the theory into practice by developing a real world application. That’s the outline for the discussion.

Bluetooth and Python – the Whys and Wherefores:

According to definition Bluetooth is “A radio standard and communications protocol primarily designed for low power consumption, with a short-range (power-class-dependent: 1 metre, 10 metres, 100 m) based on low-cost transceiver microchips in each device”. In other words, Bluetooth is a standard and protocol that uses short-range frequencies to create a wireless connection between two compatible (Bluetooth enabled) devices. Since radio communication system is used, so there is no ‘Line of Sight’ problem that is common with Infra Red based devices. As long as the devices are in range, they can communicate with each other even if one device is in one room and the other device is in a separate room. Bluetooth enabled devices are categorized into three classes which are:

1. Class 1

2. Class 2

3. Class 3

The classification is based on the range in which the devices can communicate. The ordering is from the longest range to the shortest one.

1. Class 1:

The devices under this category have the longest range. The range is approximately up to 100 metres. Devices of this class consume highest amount of power among all the three classes. It consumes 100 mW of power.

2. Class 2:

The devices under this category can be called as medium range devices. The range in which they can communicate is upto 10 metres. With respect to power consumption, they require 2.5 mW.

3. Class 3:

The devices that cannot communicate beyond 1 metre come under this class. The power requirement also is the least for the devices of this class. They require only 1 mW.

If you observe closely the power requirement decreases with the decrease in range. That was a bird’s eye view of Bluetooth. Next let us look at how a device provides services to other device using Bluetooth. Each device provides certain based on a specification known as Wireless Interface Specification. A set of such services forms a profile. Sometimes the profile contains only one service such as streaming of sound from an audio file or it can contain a set of different services such as capturing a live video and streaming it. There are 27 standard profiles that are currently used by different devices. Some of the common profiles are

1. Basic Imaging Profile – Profile for sending, receiving and resizing images.

2. Basic Printing Profile – Profile using which vCards, text, e-mail etc. to the printer

from the device.

3. File Transfer Profile – Profile to access the file system of another device.

4. Headset Profile – One of the most common profiles that provides support for

Bluetooth headsets to work with Bluetooth enabled mobile phones for wireless audio.

5. Serial Port Profile – It emulates the serial cable connectivity and communication.

It uses RFCOMM protocol.

Writing a program for a Bluetooth device, in reality, means programming for the profiles or accessing the functionalities of the profile. For programming, BlueZ library is used commonly that provides access to Bluetooth stack in an object-oriented and modular manner. The Python wrapper for the BlueZ is PyBluez.

The wrapper targets Microsoft Bluetooth stack on Windows and BlueZ stack on GNU/Linux. Using PyBlueZ, one can easily create connection between traditional systems such as laptop, desktop and mobile devices and program the basic profiles such as File Transfer, network communication etc. Now that the library that supports programming for the Bluetooth has been introduced, we can look at the steps required to program the Bluetooth devices using Python.

Bluetooth Programming – Step by Step:

For whatever profile the programming is being done, there are two main steps that one has to follow. They are:

1. Discovering Devices in Range

2. Looking up the Human Readable name

One point to keep in mind is that both of these are probabilistic i.e. sometimes these steps may fail at first attempt. Hence, it is a good idea to repeat these steps twice or thrice before deciding that there are no devices nearby.

1. Discovering Devices in Range:

The first step is to find the devices that are in range so that a connection can be established with them. This is known as discovery of devices. To discover devices in range, one needs to call discover_devices() method. It returns a list of addresses of devices discovered. For example, the following statement discovers devices in range and returns a list of such devices:

discovered_devices = discover_devices()

2. Looking up the Human Readable name:

The address of the discovered devices are of the form “XX:XX:XX:XX:XX” where each X is a hexadecimal character representing “one octet of the 48-bit address”. However, to actually access the device with which one needs to communicate, he/she should know the ‘human readable format’ of the address. One of the main reason is a person gives a name that he or she can remember for a particular device and its easier to match with that name rather than a 48-bit address for the same. To get the human readable format one can use lookup_name() method. It accepts the address of a device and returns its user-friendly or human readable format. For example, to find a device named ‘Raj’ from the list of the of return addresses the code will be:

target_device  = “Raj”

target_device_address = None

for address in discovered_devices:

if target_device==lookup_name(address):

target_device_address=address

break

if target_device_address is not None:

print “The address of the target device is :”, target_device_address

else:

print “Could not find address of target device”

The code iterate over the list of addresses and passes one address at a time to the lookup_name method. Then it compares the returned name with the desired device name. if it matches, then a message is printed and breaks out of the loop.

That completes the basic steps required to connect to any device. Once the discovery is done, then based on type of service, the communication can begin. Now that the steps are clear, let us look at a real world example that uses the steps just detailed to access a Bluetooth device.

Bluetooth Programming – In Real World:

The first rule of any program that one to target the real world is to provide modularity. In our case, we can provide modularity by wrapping up the device discovery code in a class. The name of the class will be Devices. Lets start with the imports

from bluetooth import *

Next comes the class with the constructor. The constructor takes the name of the device whose address has to be found.

from bluetooth import *

class Devices:

def __init__( self, target_device_name):

self.target_device=target_device_name

self.target_device_address= None

Next let us define the method that will perform the method lookup. If the target device is found, it will set the address to the variable self.target_device_address. To find the address, it iterate over the list of addresses returned by discover_devices() method and pass each address to the lookup_name method.

from bluetooth import *

class Devices:

def __init__( self, target_device_name):

self.target_device=target_device_name

self.target_device_address= None

def check_devices(self):

discovered_devices=discover_devices()

for address in discovered_devices:

if self.target_device==lookup_name(address):

self.target_device_address=address

break

Next comes the method that checks whether the address of the target device is found or not. If found it will return the address otherwise it will return None.

from bluetooth import *

class Devices:

def __init__( self, target_device_name):

self.target_device=target_device_name

self.target_device_address= None

def check_devices(self):

discovered_devices=discover_devices()

for address in discovered_devices:

if self.target_device==lookup_name(address):

self.target_device_address=address

break

def device_found(self):

self.check_devices()

if self.target_device_address is not None:

return self.target_device_address

else:

return None

That completes our class. Now let us test it by calling it from another module. The module will first ask the user to enter the name of the device to be discovered. Then it will create an object of the Device class and call the check_device method. The returned result will be displayed to the user. Following is the code

user_device= raw_input(“Enter the device to be discovered:”)

device = Devices(user_device)

addr = device.device_found()

if addr is not None:

print “The address for the device is :”. Adder

else:

print “The device could not be discovered”

That completes our discussion on the basics of Bluetooth programming using Python. The next step is to create and discover services. That will be the topic of next discussion. Till then….

Advertisement