蓝牙(bluepy)在GATT通知期间断开连接

问题描述 投票:0回答:1

我刚接触BLE并使用GATT服务编程。目前使用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
python bluetooth gatt bluetooth-gatt
1个回答
0
投票

在if语句周围包装一个try / except,以便在发生异常时不会爆炸

while True:
    try:
        if oh1.waitForNotifications(1.0):
            continue
    except bluepy.btle.BTLEDisconnectError:
        pass
© www.soinside.com 2019 - 2024. All rights reserved.