codem
codem

Reputation: 333

bluetooth (bluepy) disconnects during GATT notifications

I'm just new to BLE with GATT services programming. Currently using an OH1 sensor https://developer.polar.com/wiki/H6,_H7,_H10_and_OH1_Heart_rate_sensors

dev env = raspbian stretch (v4.14), bluepy (python 3.5.3)

I have managed to get the notifications working to read correct hr but after about 20-30secs the connection drops. Any suggestions on keeping persistent connection e.g 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 code below

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

Upvotes: 3

Views: 2182

Answers (1)

Thinh Pham
Thinh Pham

Reputation: 402

Wrap a try/except around your if statement so it doesn't blow up if that exception happened

while True:
    try:
        if oh1.waitForNotifications(1.0):
            continue
    except bluepy.btle.BTLEDisconnectError:
        pass

Upvotes: 0

Related Questions