对于GATT服务编程,我是BLE新手。当前正在使用OH1传感器 https://developer.polar.com/wiki/H6,_H7,_H10_and_OH1_Heart_rate_sensors
dev env = raspbian Stretch(v4.14),bluepy(python 3.5.3)
我设法使通知正常工作,以读取正确的小时,但是大约20-30秒后,连接断开。关于保持持久连接的任何建议,例如keepalive?
packet: 1 Handle: 37 HR (bpm): 77
packet: 2 Handle: 37 HR (bpm): 76
packet: 3 Handle: 37 HR (bpm): 76
...
...
packet: 27 Handle: 37 HR (bpm): 79
packet: 28 Handle: 37 HR (bpm): 80
Traceback (most recent call last):
File "hr.py", line 32, in <module>
if oh1.waitForNotifications(1.0):
File "/usr/local/lib/python3.5/dist-packages/bluepy/btle.py", line 560, in waitForNotifications
resp = self._getResp(['ntfy','ind'], timeout)
File "/usr/local/lib/python3.5/dist-packages/bluepy/btle.py", line 407, in _getResp
resp = self._waitResp(wantType + ['ntfy', 'ind'], timeout)
File "/usr/local/lib/python3.5/dist-packages/bluepy/btle.py", line 362, in _waitResp
raise BTLEDisconnectError("Device disconnected", resp)
bluepy.btle.BTLEDisconnectError: Device disconnected
下面的Python代码
import bluepy.btle as btle
import struct
#packet count
packets = 0
class hrCallback(btle.DefaultDelegate):
def __init__(self):
btle.DefaultDelegate.__init__(self)
def handleNotification(self, cHandle, data):
global packets
packets += 1
print("packet: %s Handle: %s HR (bpm): %s " % (packets, cHandle, data[1]))
#connect to OH1
mac = "a0:9e:1a:4f:ef:8b"
oh1 = btle.Peripheral( mac )
oh1.setDelegate( hrCallback() )
#start hr notification
service_uuid = 0x180D
svc = oh1.getServiceByUUID( service_uuid )
ch = svc.getCharacteristics()[0]
desc = ch.getDescriptors()[0]
desc.write(b"\x01\x00", True)
#listen for notifications
while True:
if oh1.waitForNotifications(1.0):
continue
答案 0 :(得分:0)
在您的if语句周围加上try / except,这样在发生该异常时不会崩溃
while True:
try:
if oh1.waitForNotifications(1.0):
continue
except bluepy.btle.BTLEDisconnectError:
pass