From 1eeb12ba1c9b24ca6fe489dc0ded37a6c4f73351 Mon Sep 17 00:00:00 2001 From: jjlawren Date: Tue, 10 Aug 2021 12:57:39 -0500 Subject: [PATCH] Support unloading/reloading Sonos (#54418) --- homeassistant/components/sonos/__init__.py | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/sonos/__init__.py b/homeassistant/components/sonos/__init__.py index f0219ea8cf0..45f5cf9276c 100644 --- a/homeassistant/components/sonos/__init__.py +++ b/homeassistant/components/sonos/__init__.py @@ -138,6 +138,15 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: return True +async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: + """Unload a Sonos config entry.""" + unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS) + await hass.data[DATA_SONOS_DISCOVERY_MANAGER].async_shutdown() + hass.data.pop(DATA_SONOS) + hass.data.pop(DATA_SONOS_DISCOVERY_MANAGER) + return unload_ok + + class SonosDiscoveryManager: """Manage sonos discovery.""" @@ -151,6 +160,11 @@ class SonosDiscoveryManager: self.hosts = hosts self.discovery_lock = asyncio.Lock() + async def async_shutdown(self): + """Stop all running tasks.""" + await self._async_stop_event_listener() + self._stop_manual_heartbeat() + def _create_soco(self, ip_address: str, source: SoCoCreationSource) -> SoCo | None: """Create a soco instance and return if successful.""" if ip_address in self.data.discovery_ignored: @@ -171,7 +185,7 @@ class SonosDiscoveryManager: ) return None - async def _async_stop_event_listener(self, event: Event) -> None: + async def _async_stop_event_listener(self, event: Event | None = None) -> None: await asyncio.gather( *(speaker.async_unsubscribe() for speaker in self.data.discovered.values()), return_exceptions=True, @@ -179,7 +193,7 @@ class SonosDiscoveryManager: if events_asyncio.event_listener: await events_asyncio.event_listener.async_stop() - def _stop_manual_heartbeat(self, event: Event) -> None: + def _stop_manual_heartbeat(self, event: Event | None = None) -> None: if self.data.hosts_heartbeat: self.data.hosts_heartbeat() self.data.hosts_heartbeat = None