HomePython Page 3 - Bluetooth Programming using Python
Bluetooth Programming, Step by Step - Python
Bluetooth is a way to connect devices wirelessly. This technology has a variety of uses. Python is an easy to learn scripting language that has been growing in popularity. The two can work well together, as will be explained in this article.
For whatever profile the programming is being done, there are two main steps that one has to follow. They are:
Discovering devices in range
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 on the first attempt. Hence, it is a good idea to repeat these steps twice or thrice before deciding that there are no devices nearby.
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 the discovery of devices. To discover devices in range, one needs to call the 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()
Looking up the human readable name
The addresses 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, one should know the "human readable format" of the address. One of the main reasons is that a person gives a name that he or she can remember for a particular device, and it's easier to match with that name rather than a 48-bit address for the same.
To get the human readable format one can use the 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 would be:
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 iterates 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, a message is printed and the method 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, 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.