我正在写一个使用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();发布于 2017-03-10 03:06:42
我自己也在努力解决这个问题,jgrant的评论真的很有帮助。我愿意分享我的解决方案,如果它能帮助任何人。
请注意,我需要指示,因此使用x02而不是x01。
如果可以使用bluepy读取描述符,我会这样做,但它似乎不起作用(bluepy v1.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发布于 2016-06-01 02:30:30
看起来问题在于您试图将\x01\x00写到特征本身。您需要将其写入前面的客户机特征配置描述符(0x2902)。句柄可能比特征大1(但您可能希望通过读取描述符来确认)。
ch=chs[1]
cccd = ch.valHandle + 1
cccd.write("\x01\x00")发布于 2019-06-04 17:00:56
让我困惑的是,在https://ianharvey.github.io/bluepy-doc/notifications.html中,启用通知的部分是在评论中,所以对我来说,它看起来并不是强制性的。
对我来说,最低要求(假设MAC地址已经包含了所有内容并声明了Delegateclass)是
p1 = Peripheral(<MAC>)
ch1 = p1.getCharacteristics()[3]
p1.setDelegate(MyDelegate())
p1.writeCharacteristic(ch1.valHandle + 1, b"\x01\x00")请注意,我已经知道我想要从characteristic#3获得通知,而且,如果没有"\x0\x00“前缀的”b“-bytesprefix,它将不适用于我。
https://stackoverflow.com/questions/32807781
复制相似问题