Use background task logic for the on_stop callback (#780)

This commit is contained in:
J. Nick Koston 2023-11-28 12:03:55 -06:00 committed by GitHub
parent d40e046d1a
commit 5c8370c506
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -206,7 +206,6 @@ class APIClient:
"cached_name",
"_background_tasks",
"_loop",
"_on_stop_task",
"log_name",
)
@ -253,7 +252,6 @@ class APIClient:
self.cached_name: str | None = None
self._background_tasks: set[asyncio.Task[Any]] = set()
self._loop = asyncio.get_event_loop()
self._on_stop_task: asyncio.Task[None] | None = None
self._set_log_name()
def set_debug(self, enabled: bool) -> None:
@ -314,20 +312,7 @@ class APIClient:
# Hook into on_stop handler to clear connection when stopped
self._connection = None
if on_stop:
self._on_stop_task = asyncio.create_task(
on_stop(expected_disconnect),
name=f"{self.log_name} aioesphomeapi on_stop",
)
self._on_stop_task.add_done_callback(self._remove_on_stop_task)
def _remove_on_stop_task(self, _fut: asyncio.Future[None]) -> None:
"""Remove the stop task.
We need to do this because the asyncio does not hold
a strong reference to the task, so it can be garbage
collected unexpectedly.
"""
self._on_stop_task = None
self._create_background_task(on_stop(expected_disconnect))
async def start_connection(
self,