Is there an example using Python where you connect or disconnect from an already paired device programmatically?

726 views Asked by At

I am using the Pybluez module in Python and got an example program to run where I could get the target address of my bluetooth headset device by name.

But what does one do as a method where you actually get connected or disconnected from your program to this device?

the sock.connect() below fails as I suppose I am not looking to transfer any data to it and that is not supported or works for the kind of "Connect" that I am looking for.

example code:

import bluetooth

target_name = "Airpods Pro - Todd"
target_address = None

nearby_devices = bluetooth.discover_devices()
print(nearby_devices)
for bdaddr in nearby_devices:
    print(bdaddr)
    name1 = bluetooth.lookup_name(bdaddr)
    if target_name == name1:
        target_address = bdaddr

        break

if target_address is not None:
    print("found target bluetooth device with address ", target_address)
    sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
    try:
        sock.connect((target_address, 1))
        sock.setblocking(False)
        sock.close()
        print("connected")
    except:
        print('Could not connect to device')
else:enter code here

import bluetooth

target_name = "Airpods Pro - Todd"
target_address = None

nearby_devices = bluetooth.discover_devices()
print(nearby_devices)
for bdaddr in nearby_devices:
    print(bdaddr)
    name1 = bluetooth.lookup_name(bdaddr)
    if target_name == name1:
        target_address = bdaddr

        break

if target_address is not None:
    print("found target bluetooth device with address ", target_address)
    sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
    try:
        sock.connect((target_address, 1))
        sock.setblocking(False)
        sock.close()
        print("connected")
    except:
        print('Could not connect to device')
else:
    print("could not find target bluetooth device nearby")
0

There are 0 answers