Chapter 3. Bluetooth programming with Python - PyBluez

Chapter 2 introduced the high level concepts needed to apply standard network programming techniques to Bluetooth programming. This chapter describes a Python extension module that allows these concepts to be easily and quickly implemented in just a few lines of code.

Python is a versatile and powerful dynamically typed object oriented language, providing syntactic clarity along with built-in memory management so that the programmer can focus on the algorithm at hand without worrying about memory leaks or matching braces. Although Python has a large and comprehensive standard library, Bluetooth support is not yet part of the standard distribution. A well documented C API allows software developers to create third-party extension modules that extend the language capabilities and provide access to operating system resources not otherwise exposed in Python.

PyBluez is a Python extension module written in C that provides access to system Bluetooth resources in an object oriented, modular manner. It is written for the Windows XP (Microsoft Bluetooth stack) and GNU/Linux (BlueZ stack).

3.1. Choosing a communication partner

Example 3-1 shows a Python program that looks for a nearby device with the user-friendly name ``My Phone". An explanation of the program follows.

Example 3-1. findmyphone.py


import bluetooth

target_name = "My Phone"
target_address = None

nearby_devices = bluetooth.discover_devices()

for bdaddr in nearby_devices:
    if target_name == bluetooth.lookup_name( bdaddr ):
        target_address = bdaddr
        break

if target_address is not None:
    print "found target bluetooth device with address ", target_address
else:
    print "could not find target bluetooth device nearby"

PyBluez represents a bluetooth address as a string of the form ``xx:xx:xx:xx:xx", where each x is a hexadecimal character representing one octet of the 48-bit address, with most significant octets listed first. Bluetooth devices in PyBluez will always be identified using an address string of this form.

Choosing a device really means choosing a bluetooth address. If only the user-friendly name of the target device is known, then two steps must be taken to find the correct address. First, the program must scan for nearby Bluetooth devices. The routine discover_devices() scans for approximately 10 seconds and returns a list of addresses of detected devices. Next, the program uses the routine lookup_name() to connect to each detected device, requests its user-friendly name, and compares the result to the target name.

Since both the Bluetooth detection and name lookup process are probabilistic, discover_devices() will sometimes fail to detect devices that are in range, and lookup_name() will sometimes return None to indicate that it couldn't determine the user-friendly name of the detected device. In these cases, it may be a good idea to try again once or twice before giving up.