Debian Codegraph @

hass_nabucasa/iot.py

raw
1 """Module to handle messages from Home Assistant cloud."""
2
3 from __future__ import annotations
4
5 import asyncio
6 from contextlib import suppress
7 import logging
8 import pprint
9 import random
10 from typing import TYPE_CHECKING, Any
11 import uuid
12
13 from . import iot_base
14 from .events.types import RelayerConnectedEvent, RelayerDisconnectedEvent
15 from .utils import Registry
16
17 if TYPE_CHECKING:
18 from . import Cloud, _ClientT
19
20 HANDLERS = Registry()
21 _LOGGER = logging.getLogger(__name__)
22
23
24 class UnknownHandler(Exception):
25 """Exception raised when trying to handle unknown handler."""
26
27
28 class ErrorMessage(Exception):
29 """Exception raised when there was error handling message in the cloud."""
30
31 def __init__(self, error: Any) -> None:
32 """Initialize Error Message."""
33 super().__init__("Error in Cloud")
34 self.error = error
35
36
37 class HandlerError(Exception):
38 """Exception raised when the handler failed."""
39
40 def __init__(self, error: str) -> None:
41 """Initialize Error Message."""
42 super().__init__("Error in handler")
43 self.error = error
44
45
46 class CloudIoT(iot_base.BaseIoT):
47 """Class to manage the IoT connection."""
48
49 mark_connected_after_first_message: bool = True
50
51 def __init__(self, cloud: Cloud[_ClientT]) -> None:
52 """Initialize the CloudIoT class."""
53 super().__init__(cloud)
54
55 # Local code waiting for a response
56 self._response_handler: dict[str, asyncio.Future[Any]] = {}
57
58 # Register start/stop
59 cloud.register_on_start(self.start)
60 cloud.register_on_stop(self.disconnect)
61
62 @property
63 def package_name(self) -> str:
64 """Return the package name for logging."""
65 return __name__
66
67 @property
68 def ws_heartbeat(self) -> float | None:
69 """Server to connect to."""
70 return 300
71
72 @property
73 def ws_server_url(self) -> str:
74 """Server to connect to."""
75 return self.cloud.service_discovery.action_url("relayer_connect")
76
77 async def start(self) -> None:
78 """Start the CloudIoT server."""
79 if self.cloud.subscription_expired:
80 return
81 asyncio.create_task(self.connect())
82
83 async def async_send_message(
84 self,
85 handler: str,
86 payload: Any,
87 expect_answer: bool = True,
88 ) -> Any | None:
89 """Send a message."""
90 msgid = uuid.uuid4().hex
91 fut: asyncio.Future[Any] | None = None
92
93 if expect_answer:
94 fut = self._response_handler[msgid] = asyncio.Future()
95
96 try:
97 await self.async_send_json_message(
98 {"msgid": msgid, "handler": handler, "payload": payload},
99 )
100
101 if expect_answer and fut is not None:
102 return await fut
103 return None
104 finally:
105 self._response_handler.pop(msgid, None)
106
107 def async_handle_message(self, msg: dict[str, Any]) -> None:
108 """Handle a message."""
109 response_handler = self._response_handler.get(msg["msgid"])
110
111 if response_handler is not None:
112 if "payload" in msg:
113 response_handler.set_result(msg["payload"])
114 else:
115 response_handler.set_exception(ErrorMessage(msg["error"]))
116 return
117
118 asyncio.create_task(self._async_handle_handler_message(msg))
119
120 async def _async_handle_handler_message(self, message: dict[str, Any]) -> None:
121 """Handle incoming IoT message."""
122 response = {"msgid": message["msgid"]}
123
124 try:
125 handler = HANDLERS.get(message["handler"])
126
127 if handler is None:
128 raise UnknownHandler
129
130 result = await handler(self.cloud, message.get("payload"))
131
132 # No response from handler
133 if result is None:
134 return
135
136 response["payload"] = result
137
138 except UnknownHandler:
139 response["error"] = "unknown-handler"
140
141 except HandlerError as err:
142 self._logger.warning("Error handling message: %s", err.error)
143 response["error"] = err.error
144
145 except Exception: # pylint: disable=broad-except
146 self._logger.exception("Unexpected error handling message")
147 response["error"] = "exception"
148
149 # Client is unset in case the connection has been lost.
150 if self.client is None:
151 return
152
153 if self._logger.isEnabledFor(logging.DEBUG):
154 self._logger.debug("Publishing message:\n%s\n", pprint.pformat(response))
155
156 # Suppress when client is closing.
157 with suppress(ConnectionResetError):
158 await self.client.send_json(response)
159
160 async def _connected(self) -> None:
161 """Handle connected."""
162 await super()._connected()
163 await self.cloud.events.publish(event=RelayerConnectedEvent())
164 await self.cloud.client.cloud_connected()
165
166 async def _disconnected(self) -> None:
167 """Handle connected."""
168 await super()._disconnected()
169 await self.cloud.events.publish(
170 event=RelayerDisconnectedEvent(reason=self.last_disconnect_reason)
171 )
172 await self.cloud.client.cloud_disconnected()
173
174
175 @HANDLERS.register("system")
176 async def async_handle_system(cloud: Cloud[_ClientT], payload: dict[str, Any]) -> None:
177 """Handle an incoming IoT message for System."""
178 return await cloud.client.async_system_message(payload)
179
180
181 @HANDLERS.register("alexa")
182 async def async_handle_alexa(
183 cloud: Cloud[_ClientT],
184 payload: dict[str, Any],
185 ) -> dict[str, Any]:
186 """Handle an incoming IoT message for Alexa."""
187 return await cloud.client.async_alexa_message(payload)
188
189
190 @HANDLERS.register("google_actions")
191 async def async_handle_google_actions(
192 cloud: Cloud[_ClientT],
193 payload: dict[str, Any],
194 ) -> dict[str, Any]:
195 """Handle an incoming IoT message for Google Actions."""
196 return await cloud.client.async_google_message(payload)
197
198
199 @HANDLERS.register("cloud")
200 async def async_handle_cloud(cloud: Cloud[_ClientT], payload: dict[str, Any]) -> None:
201 """Handle an incoming IoT message for cloud component."""
202 action = payload["action"]
203
204 if action == "logout":
205 # Log out of Home Assistant Cloud
206 await cloud.logout()
207 _LOGGER.error(
208 "You have been logged out from Home Assistant cloud: %s",
209 payload["reason"],
210 )
211 elif action == "disconnect_remote":
212 # Disconnect Remote connection
213 await cloud.remote.disconnect(clear_snitun_token=True)
214 elif action == "evaluate_remote_security":
215
216 async def _reconnect() -> None:
217 """Reconnect after a random timeout."""
218 await asyncio.sleep(random.randint(60, 7200))
219 await cloud.remote.disconnect(clear_snitun_token=True)
220 await cloud.remote.connect()
221
222 # Reconnect to remote frontends
223 cloud.client.loop.create_task(_reconnect())
224 elif action in ("user_notification", "critical_user_notification"):
225 # Send user Notification
226 cloud.client.user_message(
227 "homeassistant_cloud_notification",
228 payload["title"],
229 payload["message"],
230 )
231 else:
232 _LOGGER.warning("Received unknown cloud action: %s", action)
233
234
235 @HANDLERS.register("remote_sni")
236 async def async_handle_remote_sni(
237 cloud: Cloud[_ClientT],
238 payload: dict[str, Any], # noqa: ARG001
239 ) -> dict[str, Any]:
240 """Handle remote UI requests for cloud."""
241 await cloud.client.async_cloud_connect_update(True)
242 return {"server": cloud.remote.snitun_server}
243
244
245 @HANDLERS.register("connection_info")
246 async def async_handle_connection_info(
247 cloud: Cloud[_ClientT],
248 payload: dict[str, Any],
249 ) -> dict[str, Any]:
250 """Handle connection info requests for cloud."""
251 return await cloud.client.async_cloud_connection_info(payload)
252
253
254 @HANDLERS.register("webhook")
255 async def async_handle_webhook(
256 cloud: Cloud[_ClientT],
257 payload: dict[str, Any],
258 ) -> dict[str, Any]:
259 """Handle an incoming IoT message for cloud webhooks."""
260 return await cloud.client.async_webhook_message(payload)