使用Bluepy委托启用指示

时间:2018-10-06 01:30:17

标签: python bluetooth-lowenergy

我能够遍历bluepy中的BLE设备的服务和特征,但是我无法获得要打印的异步指示。我查看了此question中的建议,但无法正常工作。

在使用gattool时确实有效:

$ sudo gatttool -b "DF:01:93:A9:86:FF" -t random  --char-write-req --handle=0x002c --value=0200 --listen
Characteristic value was written successfully
Indication   handle = 0x002b value: 00 8a 00 
Indication   handle = 0x002b value: 00 8a 00 
Indication   handle = 0x002b value: 30 30 2d

但是我无法让蓝皮做同样的事情:

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

class ReadCharacteristicDelegate(DefaultDelegate):
    def __init__(self):
        DefaultDelegate.__init__(self)

    def handleNotification(self, cHandle, data):
        print "  got data: 0x%x" % data

periph = Peripheral('df:01:93:a9:86:ff', addrType=ADDR_TYPE_RANDOM)
periph.setDelegate(ReadCharacteristicDelegate())
periph.writeCharacteristic(0x002c, "\0x02\0x00")
print "Enabled indications"
while True:
    if periph.waitForNotifications(3.0):
        # handleNotification() was called
        continue
    print("Waiting")

它可以运行,但是没有任何打印出来的提示:

$ sudo python simple.py 
Enabled indications
Waiting
Waiting

1 个答案:

答案 0 :(得分:0)

我发现了问题。 writeCharacteristic()调用上有错字。显然,字节中不应包含前导“ 0”。解决此问题后,还必须更新数据打印回调以处理传入的3个字节的数据。这现在有效:

from bluepy.btle import Scanner, DefaultDelegate, Peripheral, ADDR_TYPE_RANDOM
from struct import unpack

class ReadCharacteristicDelegate(DefaultDelegate):
    def __init__(self):
        DefaultDelegate.__init__(self)

    def handleNotification(self, cHandle, data):
        print "got handle: 0x%x  data: 0x%x" % (cHandle, unpack('>i','\x00'+data)[0])

periph = Peripheral('df:01:93:a9:86:ff', addrType=ADDR_TYPE_RANDOM)
periph.setDelegate(ReadCharacteristicDelegate())
periph.writeCharacteristic(0x002c, b"\x02\x00")
print "Enabled indications"
while True:
    if periph.waitForNotifications(3.0):
        # handleNotification() was called
        continue
    print("Waiting")