From 74f32cfa90ec66eb8c8dfae596c931e6fc6218db Mon Sep 17 00:00:00 2001 From: On Freund Date: Sat, 27 Apr 2024 10:26:11 +0300 Subject: [PATCH] Avoid blocking the event loop when unloading Monoprice (#116141) * Avoid blocking the event loop when unloading Monoprice * Code review suggestions --- .../components/monoprice/__init__.py | 22 +++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/homeassistant/components/monoprice/__init__.py b/homeassistant/components/monoprice/__init__.py index 57282fb6545..c7683ebedd6 100644 --- a/homeassistant/components/monoprice/__init__.py +++ b/homeassistant/components/monoprice/__init__.py @@ -57,11 +57,25 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload a config entry.""" unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS) - if unload_ok: - hass.data[DOMAIN][entry.entry_id][UNDO_UPDATE_LISTENER]() - hass.data[DOMAIN].pop(entry.entry_id) + if not unload_ok: + return False - return unload_ok + hass.data[DOMAIN][entry.entry_id][UNDO_UPDATE_LISTENER]() + + def _cleanup(monoprice) -> None: + """Destroy the Monoprice object. + + Destroying the Monoprice closes the serial connection, do it in an executor so the garbage + collection does not block. + """ + del monoprice + + monoprice = hass.data[DOMAIN][entry.entry_id][MONOPRICE_OBJECT] + hass.data[DOMAIN].pop(entry.entry_id) + + await hass.async_add_executor_job(_cleanup, monoprice) + + return True async def _update_listener(hass: HomeAssistant, entry: ConfigEntry) -> None: