Skip to content

Commit

Permalink
perf: close connection improvements (#369)
Browse files Browse the repository at this point in the history
* Eliminated unneeded self.heartbeater.cancel()

* Logical order of actions

* Direct call instead of await

* Wait for async tasks to finish on close
  • Loading branch information
Lurker00 authored Oct 18, 2024
1 parent 618139f commit 7ab8297
Showing 1 changed file with 12 additions and 5 deletions.
17 changes: 12 additions & 5 deletions custom_components/localtuya/core/pytuya/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -965,6 +965,7 @@ async def keep_alive_loop(action):
self.exception("Heartbeat failed (%s), disconnecting", ex)
break

self.heartbeater = None
if self.transport is not None:
self.clean_up_session()

Expand Down Expand Up @@ -1016,6 +1017,12 @@ async def close(self):
self.debug("Closing connection")
self.clean_up_session()

if self.heartbeater:
await self.heartbeater

if self._sub_devs_query_task:
await self._sub_devs_query_task

def clean_up_session(self):
"""Clean up session."""
self.debug(f"Cleaning up session.")
Expand All @@ -1027,12 +1034,12 @@ def clean_up_session(self):
if self._sub_devs_query_task:
self._sub_devs_query_task.cancel()

if self.dispatcher:
self.dispatcher.abort()

if self.is_connected:
self.transport.close()

if self.dispatcher:
self.dispatcher.abort()

async def exchange_quick(self, payload, recv_retries):
"""Similar to exchange() but never retries sending and does not decode the response."""
if not self.is_connected:
Expand All @@ -1048,8 +1055,8 @@ async def exchange_quick(self, payload, recv_retries):
try:
await self.transport_write(enc_payload)
except Exception: # pylint: disable=broad-except
await self.close()
return None
return self.clean_up_session()

while recv_retries:
try:
seqno = MessageDispatcher.SESS_KEY_SEQNO
Expand Down

0 comments on commit 7ab8297

Please sign in to comment.