Reputation: 9758
I'm trying to learn to communicate with a Bluetooth device using Python but my first steps fail.
I can successfully connect to a given device using bluetoothctl
:
[bluetooth]# connect F5:EE:1C:40:21:44
Attempting to connect to F5:EE:1C:40:21:44
[CHG] Device F5:EE:1C:40:21:44 Connected: yes
Connection successful
[NEW] Primary Service (Handle 0xa9bd)
/org/bluez/hci0/dev_F5_EE_1C_40_21_44/service000a
00001801-0000-1000-8000-00805f9b34fb
Generic Attribute Profile
[NEW] Primary Service (Handle 0xa9bd)
/org/bluez/hci0/dev_F5_EE_1C_40_21_44/service000b
53300001-0023-4bd4-bbd5-a6920e4c5653
Vendor specific
[NEW] Characteristic (Handle 0x6f54)
/org/bluez/hci0/dev_F5_EE_1C_40_21_44/service000b/char000c
53300002-0023-4bd4-bbd5-a6920e4c5653
Vendor specific
[NEW] Characteristic (Handle 0x6604)
/org/bluez/hci0/dev_F5_EE_1C_40_21_44/service000b/char000e
53300003-0023-4bd4-bbd5-a6920e4c5653
Vendor specific
[NEW] Descriptor (Handle 0x0164)
/org/bluez/hci0/dev_F5_EE_1C_40_21_44/service000b/char000e/desc0010
00002902-0000-1000-8000-00805f9b34fb
Client Characteristic Configuration
but trying to connect via Python3's pybluez module results in an exception being raised:
sock=bluetooth.BluetoothSocket(bluetooth.RFCOMM)
sock.connect(("F5:EE:1C:40:21:44", 1))
...
BluetoothError Traceback (most recent call last)
<ipython-input-17-2af54455681d> in <module>
----> 1 sock.connect(("F5:EE:1C:40:21:44", 1))
~/.local/lib/python3.9/site-packages/bluetooth/bluez.py in connect(self, *args, **kwargs)
BluetoothError: [Errno 112] Host is down
What am I doing wrong here? Very likely I'm just missing the very basics of Bluetooth development - maybe you can give me a direction..
Upvotes: 0
Views: 1003
Reputation: 7954
Looking at the log information you shared from when you connected with bluetoothctl
, it looks like you are connecting to a Bluetooth Low Energy (BLE) device.
The commands you are you issuing with PyBlueZ is to connect to a Bluetooth Classic (BR/EDR) device and I suspect that is why the device is not responding.
PyBlueZ uses a deprecated API for BlueZ. The currently supported APIs are documented at: https://git.kernel.org/pub/scm/bluetooth/bluez.git/tree/doc
It is the Device API that is used for connecting to a device. Below is an example of how to use it with the generic D-Bus library pydbus
from time import sleep
import pydbus
DEVICE_ADDR = 'F5:EE:1C:40:21:44' # device address
# DBus object paths
BLUEZ_SERVICE = 'org.bluez'
device_path = f"/org/bluez/hci0/dev_{DEVICE_ADDR.replace(':', '_')}"
# setup dbus
bus = pydbus.SystemBus()
device = bus.get(BLUEZ_SERVICE, device_path)
# Connect to device
device.Connect()
sleep(10)
device.Disconnect()
Upvotes: 2