1 """Websocket handler for UniFi Network integration."""
3 from __future__
import annotations
6 from datetime
import datetime, timedelta
15 from ..const
import LOGGER
22 """Manages a single UniFi Network instance."""
25 self, hass: HomeAssistant, api: aiounifi.Controller, signal: str
27 """Initialize the system."""
32 self.
ws_taskws_task: asyncio.Task |
None =
None
39 """Start websocket handler."""
47 """Stop websocket handler."""
52 if self.
ws_taskws_task
is not None:
56 """Stop websocket handler and await tasks."""
61 if self.
ws_taskws_task
is not None:
64 _, pending = await asyncio.wait([self.
ws_taskws_task], timeout=10)
68 "Unloading UniFi Network (%s). Task %s did not complete in time",
69 self.
apiapi.connectivity.config.host,
75 """Start up connection to websocket."""
77 async
def _websocket_runner() -> None:
78 """Start websocket."""
81 except (aiohttp.ClientConnectorError, aiohttp.WSServerHandshakeError):
82 LOGGER.error(
"Websocket setup failed")
83 except aiounifi.WebsocketError:
84 LOGGER.error(
"Websocket disconnected")
88 self.
hasshass.loop.call_later(RETRY_TIMER, self.
reconnectreconnect,
True)
94 self.
ws_taskws_task = self.
hasshass.loop.create_task(_websocket_runner())
98 """Prepare to reconnect UniFi session."""
100 async
def _reconnect() -> None:
101 """Try to reconnect UniFi Network session."""
103 async
with asyncio.timeout(5):
104 await self.
apiapi.login()
109 aiounifi.ServiceUnavailable,
110 aiounifi.AiounifiException,
112 LOGGER.debug(
"Schedule reconnect to UniFi Network '%s'", exc)
113 self.
hasshass.loop.call_later(RETRY_TIMER, self.
reconnectreconnect)
119 LOGGER.info(
"Will try to reconnect to UniFi Network")
121 self.
hasshass.loop.create_task(_reconnect())
125 """Watch timestamp for last received websocket message."""
127 "Last received websocket timestamp: %s",
128 self.
apiapi.connectivity.ws_message_received,
None reconnect(self, bool log=False)
None _async_watch_websocket(self, datetime now)
None __init__(self, HomeAssistant hass, aiounifi.Controller api, str signal)
None start_websocket(self)
None async_dispatcher_send(HomeAssistant hass, str signal, *Any args)
CALLBACK_TYPE async_track_time_interval(HomeAssistant hass, Callable[[datetime], Coroutine[Any, Any, None]|None] action, timedelta interval, *str|None name=None, bool|None cancel_on_shutdown=None)