DanielY DanielY - 2 months ago 16
Linux Question

Bluetooth - listening to a pairing even in a Linux device in Python

I'm pretty new to Bluetooth so this might be trivial, but I'll still ask:

I would like to connect 2 devices via Bluetooth - a mobile device with a Linux device (like Raspberry Pi, but another one...).

Side 1 - the mobile: It has an app that should pair with the Linux device, and send some data to it (a msg with "Hello" in this point).

Side 2 - the linux device: It should have a kind of listener to the fact that a device was connected to it via bluetooth, and then expect the data, receive it, and process it.

Side 1 is all fine and clear to me.

As for side 2, for now I only use some command line commands to turn Bluetooth on, set some name to the device, and wait for scan. I do it with "hciconfig", by running the following commands in Python script, one after the other:

hciconfig hci0 up
hciconfig hci0 name MyDevice
hciconfig hci0 sspmode 1
hciconfig hci0 piscan


At this point, my device is discover-able to my mobile and it pairs with it successfully. Now, I'm stuck with the listening part. I would like the linux device to run a certain function (prefer in Python) when the device is paired, and expect to receive data from it. I've read some links over the net, using RFCOMM and Bluez, but none succeeded...

Can someone please assist?
Thanks

Answer

Good morning, there is a library written in Python that handle Bluetooth connection for you already PyBluez to install use sudo pip install pybluez here is an example on how to use sockets to communicate with bluetooth devices

import bluetooth
bd_addr = "01:23:45:67:89:AB"
port = 1
sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
sock.connect((bd_addr, port))
sock.send("hello!!")
sock.close()

the complete guide is at Bluetooth Programming with PyBluez `

Comments