IanHarvey / bluepy

Python interface to Bluetooth LE on Linux
Other
1.6k stars 490 forks source link

Disconnect during notification #351

Open michael-mortimer opened 5 years ago

michael-mortimer commented 5 years ago

disconnection occurs between 20-30secs after notifications turned on (reads notifications fine until disconnect), notifications work fine when tested in bluetoothctl without disconnection. How to keep alive?

CODE

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]
handle = ch.getHandle()
oh1.writeCharacteristic(handle+1, b"\x01\x00", True)

#listen for notifications
while True:
    try:
        if oh1.waitForNotifications(1.0):
            continue
    except btle.BTLEDisconnectError:
        pass

THROWS

Traceback (most recent call last):
  File "hr.py", line 35, 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 338, in _waitResp
    if self._helper.poll() is not None:
AttributeError: 'NoneType' object has no attribute 'poll'
OldShaterhan commented 4 years ago

Quite similar issue happens to me. Only in Python3, for Python2 it was okay.

rcslProject commented 3 years ago

in my case, the NoneType bug sometimes happen when I disconnect bluetooth device. my solution is as follow btle.Peripheral(self.address)._stopHelper() btle.Peripheral(self.address).disconnect() before I disconnect bluetooth device, I call the _stopHelper() function. and It works