2015-09-27 132 views
5

我正在使用bluepy编写一个程序,用于侦听由蓝牙设备发送的特征。我也可以使用任何库或语言,唯一的约束是在Linux上运行,而不是在移动环境中(似乎广泛用于移动设备,没有人使用BLE与桌面)。 使用bluepy我注册的代表,并试图注册通知后调用write('\x01\x00')蓝牙rfc中所述。 但它不起作用,收到任何特征通知。 也许我写错了订阅的讯息。 我写的小片段有错误吗?非常感谢。BLE使用gatttool或bluepy订阅通知

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(); 

回答

1

看起来问题是,您正试图将\x01\x00写入特征本身。您需要将其写入客户端特征配置描述符(0x2902)。句柄可能比特征大1(但您可能需要通过阅读描述符进行确认)。

ch=chs[1] 
cccd = ch.valHandle + 1 
cccd.write("\x01\x00") 
2

我一直在为自己挣扎,jgrant的评论确实有帮助。我想分享我的解决方案,如果它可以帮助任何人。

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

如果有可能使用蓝图读取描述符,我会这样做,但它似乎不起作用(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