Add callback or method for user to detect device disconnections
eraguzin opened this issue · 2 comments
As far as I see, there is no callback or way of detecting if the BLE device disconnected, shut off, or went out of range. Even after I turn off the BLE device, adapter._connections
still shows the device handle, so I don't see any way of polling to find out whether the device is currently connected or not.
However, running adapter.stop()
will fail at for device in self._connections.values()
because RuntimeError: dictionary changed size during iteration
, even though print(adapter._connections.values())
looks the same to me, no matter if the device was disconnected or not during the test run.
Further, once this has happened, any attempt to exit the script and start again with adapter.start()
will fail due to BGAPIError: Unable to detect BLED112 serial port: COM8.
unless I exit the entire Python console and start a new one.
Is there a more graceful way of dealing with devices disconnecting? Am I missing something?
No, you aren't missing anything. Today there isn't a way for the library user to be notified when a device disconnects. I'll re-title this ticket to be a feature request since I agree it's an obvious omission.
I fixed the bug in the adapter.stop()
method (#23) if you'd like to give a full reset and re-connection another try.
As a temporary workaround to this I have been periodically checking the RSSI of the device - a value of 0 seems to indicate a disconnect so can act as a proxy for connection status:
rssi = device.get_rssi()
if rssi == 0:
try:
print("Connecting...")
device = adapter.connect(closestDevice, address_type=ADDRESS_TYPE)
print("Done...")
except pygatt.backends.bgapi.exceptions.ExpectedResponseTimeout:
pass
else:
print("RSSI: ", rssi)