Skip to content

Commit

Permalink
winrt/client: ignore session closed event during connect
Browse files Browse the repository at this point in the history
As described in #1280, it is
possible for a session to be closed then activated again while getting
services. This will cause an OSError because the closed event triggers
the disconnect cleanup code, then trying to use the session after that
fails because it has been closed.

This works around the problem by disabling the disconnect cleanup code
until the connect method has returned successfully. If the connect
method raises an exception, it handles cleanup already so the cleanup
code in the session status event handler never gets called in this case.
  • Loading branch information
dlech committed Apr 19, 2023
1 parent 028b153 commit e9b591b
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 2 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ Fixed
-----
- Fixed ``org.bluez.Error.InProgress`` in characteristic and descriptor read and
write methods in BlueZ backend.
- Fixed ``OSError: [WinError -2147483629] The object has been closed`` when
connecting on Windows. Fixes #1280.

`0.20.1`_ (2023-03-24)
======================
Expand Down
9 changes: 7 additions & 2 deletions bleak/backends/winrt/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,8 @@ def handle_disconnect():
self._session.close()
self._session = None

is_connect_complete = False

def handle_session_status_changed(
args: GattSessionStatusChangedEventArgs,
):
Expand All @@ -311,7 +313,9 @@ def handle_session_status_changed(
for e in self._session_active_events:
e.set()

elif args.status == GattSessionStatus.CLOSED:
# Don't run this if we have not exited from the connect method yet.
# Cleanup is handled by the connect method in that case.
elif args.status == GattSessionStatus.CLOSED and is_connect_complete:
if self._disconnected_callback:
self._disconnected_callback()

Expand All @@ -326,7 +330,7 @@ def session_status_changed_event_handler(
):
logger.debug(
"session_status_changed_event_handler: id: %s, error: %s, status: %s",
sender.device_id,
sender.device_id.id,
args.error,
args.status,
)
Expand Down Expand Up @@ -442,6 +446,7 @@ def max_pdu_size_changed_handler(sender: GattSession, args):
# device, so we have to get services before the GATT session
# is set to active
await event.wait()
is_connect_complete = True
finally:
self._services_changed_events.remove(services_changed_event)

Expand Down

0 comments on commit e9b591b

Please sign in to comment.