我正在使用bluepy编写程序,以监听蓝牙设备发送的特征。我也可以使用任何库或语言,唯一的限制是要在Linux上而不是在移动环境中运行(似乎仅在移动设备中广泛使用,没有人在桌面上使用BLE)。
我使用bluepy注册了代理,并尝试注册通知,如蓝牙rfc中所述,调用了write('\x01\x00')
。
但这是行不通的,不会收到有关该特性的任何通知。
在撰写订阅消息时,也许我是错误的。
我写的小片段中有错误吗?非常感谢。
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();
最佳答案
我本人为此感到挣扎,而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
关于python - BLE使用gatttool或bluepy订阅通知,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32807781/