[Python] Bluepy scan for devices and connect to them

Discussão em 'Python' iniciado por Stack, Janeiro 26, 2025.

  1. Stack

    Stack Membro Participativo

    My task is to search for some devices with Bluetooth with a Raspberry PI 4B and to connect to send some commands and disconnect. For this, I started using bluepy package and I was able to do the two things separately. I can connect to a device with:

    from bluepy.btle import Peripheral, DefaultDelegate, BTLEException, Scanner

    peripheral = Peripheral(mac_address)
    service = peripheral.getServiceByUUID(CONFIGURATION_SERVICE_UUID)
    write_char = service.getCharacteristics(WRITE_CHAR_UUID)[0]
    read_char = service.getCharacteristics(READ_CHAR_UUID)[0]
    write_char.write(command, withResponse=True)
    # etc.
    peripheral.disconnect()


    and I can scan for devices with


    class ScanDelegate(DefaultDelegate):
    def handleDiscovery(self, dev, isNewDev, isNewData):
    print(dev.addr)

    scanner = Scanner().withDelegate(ScanDelegate())
    scanner.scan(60)


    The problem that I have with the first part, and the reason I want to put them together, is that the devices I want to connect to are connectable only in the period they are broadcasting some information (almost a second) and the connection will go in timeout before succeeding most of the times. My idea is that I should start with the scanner and inside the handleDiscovery I should try to connect but just pasting the code inside doesn't work. Does anyone know how to do it?

    Continue reading...

Compartilhe esta Página