我正在使用 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();
我自己也在努力解决这个问题,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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)