BLE使用gatttool或bluepy订阅通知

Ale*_*.It 5 python linux bluetooth-lowenergy gatt

我正在编写一个程序,使用bluepy来监听蓝牙设备发送的特性.我也可以使用任何库或语言,唯一的限制是在Linux上运行而不是在移动环境中运行(它似乎只在移动设备中广泛使用,没有人使用BLE与桌面).使用bluepy我注册了委托,并在尝试注册write('\x01\x00')蓝牙rfc中描述的通知调用之后.但它不起作用,收到任何关于特征的通知.也许我在编写订阅消息时错了.我写的小片段中有错误吗?非常感谢.

class MyDelegate(btle.DefaultDelegate):

    def __init__(self, hndl):
        btle.DefaultDelegate.__init__(self)
   self.hndl=hndl;

   def handleNotification(self, cHandle, data):
   if (cHandle==self.hndl):
            val = binascii.b2a_hex(data)
            val = binascii.unhexlify(val)
            val = struct.unpack('f', val)[0]
            print str(val) + " deg C"


p = btle.Peripheral("xx:xx:xx:xx", "random")

try:
   srvs = (p.getServices());
   chs=srvs[2].getCharacteristics();
   ch=chs[1];
   print(str(ch)+str(ch.propertiesToString()));
   p.setDelegate(MyDelegate(ch.getHandle()));
   # Setup to turn notifications on, e.g.
   ch.write("\x01\x00");

   # Main loop --------
   while True:
      if p.waitForNotifications(1.0):
      continue

      print "Waiting..."
finally:
    p.disconnect();
Run Code Online (Sandbox Code Playgroud)

小智 5

我自己也在为此苦苦挣扎,jgrant 的评论真的很有帮助。我想分享我的解决方案,如果它可以帮助任何人。

请注意,我需要指示,因此是 x02 而不是 x01。

如果可以使用 bluepy 读取描述符,我会这样做,但它似乎不起作用(bluepy v 1.0.5)。服务类中的方法好像缺失了,我尝试使用外设类中的方法卡住了。

from bluepy import btle

class MyDelegate(btle.DefaultDelegate):
    def __init__(self):
        btle.DefaultDelegate.__init__(self)

    def handleNotification(self, cHandle, data):
        print("A notification was received: %s" %data)


p = btle.Peripheral(<MAC ADDRESS>, btle.ADDR_TYPE_RANDOM)
p.setDelegate( MyDelegate() )

# Setup to turn notifications on, e.g.
svc = p.getServiceByUUID( <UUID> )
ch = svc.getCharacteristics()[0]
print(ch.valHandle)

p.writeCharacteristic(ch.valHandle+1, "\x02\x00")

while True:
    if p.waitForNotifications(1.0):
        # handleNotification() was called
        continue

    print("Waiting...")
    # Perhaps do something else here
Run Code Online (Sandbox Code Playgroud)


Jul*_*lie 3

看起来问题在于您正在尝试写入\x01\x00特征本身。您需要将其写入后续的客户端特征配置描述符 (0x2902)。句柄可能比特征大 1(但您可能需要通过读取描述符来确认)。

ch=chs[1]
cccd = ch.valHandle + 1
cccd.write("\x01\x00")
Run Code Online (Sandbox Code Playgroud)