Sunday, February 27, 2011

Linux and Bluetooth

There are 2 widespread Bluetooth stack implementations in Linux: BlueZ and Affix. Today we will use the BlueZ library for writing a simple "nearby device finder" program. Before you start, make sure you have installed the necessary Bluetooth packages. Ubuntu users can install them by running:
    sudo apt-get install bluez libbluetooth-dev
At first we need to include the following BlueZ header files
#include <bluetooth/bluetooth.h>
#include <bluetooth/hci.h>
#include <bluetooth/hci_lib.h>

To work with a Bluetooth device we need a device id, which can be retrieved by "hci_get_route"  function: if pass NULL argument to "hci_get_route", it will return the id of first available device, or -1 if there isn't any. Now we can use "hci_get_route" function, which search the nearby Bluetooth devices and return basic information about them in a "inquiry_info" structure:
typedef struct {
  bdaddr_t  bdaddr;
  uint8_t   pscan_rep_mode;
  uint8_t   pscan_period_mode;
  uint8_t   pscan_mode;
  uint8_t   dev_class[3];
  uint16_t  clock_offset;
} __attribute__ ((packed)) inquiry_info;

The "bdaddr" member contains the address of a device (it is like a MAC address of network devices, by the way they have the same syntax).
There are 2 functions to convert between strigns and "bdaddr_t" structures.
int str2ba( const char *str, bdaddr_t *ba );
int ba2str( const bdaddr_t *ba, char *str );
The address of remote Bluetooth device is enough to work with it, but the end users usually work with the device names. The "hci_read_remote_name" function retrieve the name of remote device using it's address. But "hci_open_dev" require an open socket. The "hci_open_dev" function opens an appropriate Bluetooth socket. And at last we can use "hci_open_dev" function to get the name and address of the local Bluetooth device.
See the source code for details:

No comments:

Post a Comment