Skip to content

Commit

Permalink
Merge pull request #86 from vincentwolsink/catch_task_error_on_unload
Browse files Browse the repository at this point in the history
Catch potential errors while awaiting the cancelled task.
  • Loading branch information
vincentwolsink authored Aug 29, 2023
2 parents edfa78b + b04ae9a commit 863a178
Showing 1 changed file with 14 additions and 5 deletions.
19 changes: 14 additions & 5 deletions custom_components/enphase_envoy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ async def read_realtime_updates() -> None:
@callback
async def _async_stop(_: Event) -> None:
_LOGGER.debug("Stopping loop for /stream/meter")
task.cancel()
await _cancel_realtime_task(task)

hass.data[DOMAIN][entry.entry_id]["realtime_loop"] = False

Expand All @@ -207,15 +207,24 @@ async def _async_stop(_: Event) -> None:
return True


async def _cancel_realtime_task(task) -> None:
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
except Exception as e:
_LOGGER.exception(
f"While waiting for task to be cancelled, this execption occured: {e}"
)


async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""

if task := hass.data[DOMAIN][entry.entry_id].get("realtime_loop", False):
_LOGGER.debug("Stopping loop for /stream/meter")

with suppress(asyncio.CancelledError):
task.cancel()
await task
await _cancel_realtime_task(task)

hass.data[DOMAIN][entry.entry_id]["realtime_loop"] = False

Expand Down

0 comments on commit 863a178

Please sign in to comment.