Debian Codegraph @

hass_nabucasa/iot_base.py

raw
1 """Base class to keep a websocket connection open to a server."""
2
3 from __future__ import annotations
4
5 import asyncio
6 from collections.abc import Awaitable, Callable
7 import dataclasses
8 import logging
9 import pprint
10 import random
11 from socket import gaierror
12 from typing import TYPE_CHECKING, Any
13
14 from aiohttp import (
15 ClientError,
16 ClientWebSocketResponse,
17 WSMessage,
18 WSMsgType,
19 WSServerHandshakeError,
20 client_exceptions,
21 hdrs,
22 )
23
24 from .const import (
25 MESSAGE_EXPIRATION,
26 STATE_CONNECTED,
27 STATE_CONNECTING,
28 STATE_DISCONNECTED,
29 SubscriptionReconnectionReason,
30 )
31 from .exceptions import CloudError
32 from .utils import gather_callbacks
33
34 if TYPE_CHECKING:
35 from . import Cloud, _ClientT
36
37
38 @dataclasses.dataclass
39 class DisconnectReason:
40 """Disconnect reason."""
41
42 clean: bool
43 reason: str
44
45
46 class NotConnected(Exception):
47 """Exception raised when trying to handle unknown handler."""
48
49
50 class BaseIoT:
51 """Class to manage the IoT connection."""
52
53 mark_connected_after_first_message = False
54
55 def __init__(self, cloud: Cloud[_ClientT]) -> None:
56 """Initialize the CloudIoT class."""
57 self.cloud = cloud
58 # The WebSocket client
59 self.client: ClientWebSocketResponse | None = None
60 # Scheduled sleep task till next connection retry
61 self.retry_task: asyncio.Task | None = None
62 # Boolean to indicate if we wanted the connection to close
63 self.close_requested: bool = False
64 # The current number of attempts to connect, impacts wait time
65 self.tries: int = 0
66 # Current state of the connection
67 self.state: str = STATE_DISCONNECTED
68 self._on_connect: list[Callable[[], Awaitable[None]]] = []
69 self._on_disconnect: list[Callable[[], Awaitable[None]]] = []
70 self._logger = logging.getLogger(self.package_name)
71 self._disconnect_event: asyncio.Event | None = None
72 self.last_disconnect_reason: DisconnectReason | None = None
73
74 @property
75 def package_name(self) -> str:
76 """Return package name for logging."""
77 raise NotImplementedError
78
79 @property
80 def ws_heartbeat(self) -> float | None:
81 """Server to connect to."""
82 return None
83
84 @property
85 def ws_server_url(self) -> str:
86 """Server to connect to."""
87 raise NotImplementedError
88
89 @property
90 def require_subscription(self) -> bool:
91 """If the server requires a valid subscription."""
92 return True
93
94 def async_handle_message(self, msg: dict[str, Any]) -> None:
95 """Handle incoming message.
96
97 Run all async tasks in a wrapper to log appropriately.
98 """
99 raise NotImplementedError
100
101 # --- Do not override after this line ---
102
103 def register_on_connect(self, on_connect_cb: Callable[[], Awaitable[None]]) -> None:
104 """Register an async on_connect callback."""
105 self._on_connect.append(on_connect_cb)
106
107 def register_on_disconnect(
108 self,
109 on_disconnect_cb: Callable[[], Awaitable[None]],
110 ) -> None:
111 """Register an async on_disconnect callback."""
112 self._on_disconnect.append(on_disconnect_cb)
113
114 @property
115 def connected(self) -> bool:
116 """Return if we're currently connected."""
117 return self.state == STATE_CONNECTED
118
119 async def async_send_json_message(self, message: dict[str, Any]) -> None:
120 """Send a message.
121
122 Raises NotConnected if client not connected.
123 """
124 if self.state != STATE_CONNECTED or self.client is None:
125 raise NotConnected
126
127 if self._logger.isEnabledFor(logging.DEBUG):
128 self._logger.debug("Publishing message:\n%s\n", pprint.pformat(message))
129
130 await self.client.send_json(message)
131
132 async def connect(self) -> None:
133 """Connect to the IoT broker."""
134 if self.state != STATE_DISCONNECTED:
135 raise RuntimeError("Connect called while not disconnected")
136
137 self.close_requested = False
138 self.state = STATE_CONNECTING
139 self.tries = 0
140 self._disconnect_event = asyncio.Event()
141
142 while True:
143 try:
144 self._logger.debug("Trying to connect")
145 await self._handle_connection()
146 except Exception: # pylint: disable=broad-except
147 # Safety net. This should never hit.
148 # Still adding it here to make sure we can always reconnect
149 self._logger.exception("Unexpected error in connection handler")
150
151 if self.state == STATE_CONNECTED:
152 await self._disconnected()
153
154 if self.close_requested:
155 break
156
157 if self.require_subscription and self.cloud.subscription_expired:
158 self.cloud.async_initialize_subscription_reconnection_handler(
159 SubscriptionReconnectionReason.SUBSCRIPTION_EXPIRED,
160 )
161 break
162
163 self.state = STATE_CONNECTING
164 self.tries += 1
165
166 try:
167 await self._wait_retry()
168 except asyncio.CancelledError:
169 # Happens if disconnect called
170 break
171
172 self.state = STATE_DISCONNECTED
173 self._disconnect_event.set()
174 self._disconnect_event = None
175
176 async def _wait_retry(self) -> None:
177 """Wait until it's time till the next retry."""
178 # Sleep 2^tries + 0…tries*3 seconds between retries
179 self.retry_task = asyncio.create_task(
180 asyncio.sleep(2 ** min(9, self.tries) + random.randint(0, self.tries * 3)),
181 )
182 await self.retry_task
183 self.retry_task = None
184
185 async def _handle_connection(self) -> None:
186 """Connect to the IoT broker."""
187 try:
188 await self.cloud.auth.async_check_token()
189 except CloudError as err:
190 self._logger.warning(
191 "Unable to connect due to token refresh failure: %s",
192 err,
193 )
194 return
195
196 if self.require_subscription and self.cloud.subscription_expired:
197 self._logger.debug("Cloud subscription expired, cancelling connection")
198 self.cloud.client.user_message(
199 "cloud_subscription_expired",
200 "Home Assistant Cloud",
201 MESSAGE_EXPIRATION,
202 )
203 self.close_requested = True
204 return
205
206 disconnect_clean: bool = False
207 disconnect_reason: (
208 str
209 | WSServerHandshakeError
210 | ClientError
211 | ConnectionResetError
212 | gaierror
213 | None
214 ) = None
215 try:
216 self.client = await self.cloud.websession.ws_connect(
217 self.ws_server_url,
218 heartbeat=self.ws_heartbeat,
219 headers={
220 hdrs.AUTHORIZATION: f"Bearer {self.cloud.id_token}",
221 hdrs.USER_AGENT: self.cloud.client.client_name,
222 },
223 )
224
225 if not self.mark_connected_after_first_message:
226 await self._connected()
227
228 while not self.client.closed:
229 msg: WSMessage | None | str = None
230 try:
231 msg = await self.client.receive(55)
232 except TimeoutError:
233 # This is logged as info instead of warning because when
234 # this hits there is not really much that can be done about it.
235 # But the context is still valuable to have while
236 # troubleshooting.
237 self._logger.info("Timeout while waiting to receive message")
238 await self.client.ping()
239 continue
240
241 if msg.type in (WSMsgType.CLOSE, WSMsgType.CLOSED, WSMsgType.CLOSING):
242 disconnect_clean = self.state == STATE_CONNECTED
243 disconnect_reason = f"Closed by server. {msg.extra} ({msg.data})"
244 break
245
246 # Do this inside the loop because if 2 clients are connected,
247 # it can happen that we get connected with valid auth,
248 # but then server decides to drop our connection.
249 if self.state != STATE_CONNECTED:
250 await self._connected()
251
252 if msg.type == WSMsgType.ERROR:
253 disconnect_reason = "Connection error"
254 break
255
256 if msg.type != WSMsgType.TEXT:
257 disconnect_reason = f"Received non-Text message: {msg.type}"
258 break
259
260 try:
261 msg_content: dict[str, Any] = msg.json()
262 except ValueError:
263 disconnect_reason = "Received invalid JSON."
264 break
265
266 if self._logger.isEnabledFor(logging.DEBUG):
267 self._logger.debug(
268 "Received message:\n%s\n",
269 pprint.pformat(msg_content),
270 )
271
272 try:
273 self.async_handle_message(msg_content)
274 except Exception: # pylint: disable=broad-except
275 self._logger.exception(
276 "Unexpected error handling message: %s", msg_content
277 )
278
279 if self.client.closed:
280 if self.close_requested:
281 disconnect_clean = True
282 disconnect_reason = "Close requested"
283 elif disconnect_reason is None:
284 disconnect_reason = "Closed by server. Unknown reason"
285
286 except client_exceptions.WSServerHandshakeError as err:
287 if err.status == 401:
288 disconnect_reason = "Invalid auth."
289 self.close_requested = True
290 # Should we notify user?
291 else:
292 disconnect_reason = err
293
294 except (client_exceptions.ClientError, ConnectionResetError, gaierror) as err:
295 disconnect_reason = err
296
297 except asyncio.CancelledError:
298 disconnect_clean = True
299 disconnect_reason = "Connection Cancelled"
300
301 finally:
302 if self.client:
303 base_msg = "Connection closed"
304 await self.client.close()
305 self.client = None
306 else:
307 base_msg = "Unable to connect"
308 msg = f"{base_msg}: {disconnect_reason}"
309 self.last_disconnect_reason = DisconnectReason(disconnect_clean, msg)
310
311 if self.close_requested or disconnect_clean:
312 self._logger.info(msg)
313 else:
314 self._logger.warning(msg)
315
316 async def disconnect(self) -> None:
317 """Disconnect the client."""
318 self.close_requested = True
319
320 if self.client is not None:
321 await self.client.close()
322 elif self.retry_task is not None:
323 self.retry_task.cancel()
324
325 if self._disconnect_event is not None:
326 await self._disconnect_event.wait()
327
328 async def _connected(self) -> None:
329 """Handle connected."""
330 self.last_disconnect_reason = None
331 self.tries = 0
332 self.state = STATE_CONNECTED
333 self._logger.info("Connected")
334
335 if self._on_connect:
336 await gather_callbacks(self._logger, "on_connect", self._on_connect)
337
338 async def _disconnected(self) -> None:
339 """Handle connected."""
340 if self._on_disconnect:
341 await gather_callbacks(self._logger, "on_disconnect", self._on_disconnect)