python - 使用 bluepy 委托(delegate)启用指示

标签 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

但我无法让 bluepy 做同样的事情:

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

最佳答案

我发现了这个问题。 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")

关于python - 使用 bluepy 委托(delegate)启用指示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52674952/

相关文章:

python - 2 个数组之间的所有数字对

python - 在骨架图像OpenCV python中查找线

bluetooth-lowenergy - 蓝牙低功耗广告扫描、 channel 信息或选择

ios - 当我在该地区时,CLRegionState 是未知的

c# - 使用 .Net Core 在 Raspberry Pi 上使用蓝牙 LE

Python 中整数列表与字符串结果的不同之处

python - TypeError : 'int' object is not iterable. 为什么会出现此错误?请帮忙

flutter - 从 BLE 设备收到的不完整响应出现抖动

ios - 蓝牙 LE 请求许可?

python - Pandas :删除值等于零的行