Debian Codegraph @

hass_nabucasa/google_report_state.py

raw
1 """Module to handle Google Report State."""
2
3 from __future__ import annotations
4
5 import asyncio
6 from asyncio.queues import Queue
7 from typing import TYPE_CHECKING, Any
8 import uuid
9
10 from aiohttp import ClientResponse, ClientTimeout
11
12 from . import iot_base
13 from .api import ApiBase, CloudApiError, CloudApiRawResponse, api_exception_handler
14
15 if TYPE_CHECKING:
16 from . import Cloud, _ClientT
17
18 MAX_PENDING = 100
19
20 ERR_DISCARD_CODE = "message_discarded"
21 ERR_DISCARD_MSG = "Message discarded because max messages reachced"
22
23
24 class GoogleReportStateError(CloudApiError):
25 """Exception raised when handling Google Report State API calls."""
26
27
28 class ErrorResponse(Exception):
29 """Raised when a request receives a success=false response."""
30
31 def __init__(self, code: str, message: str) -> None:
32 """Initialize error response."""
33 super().__init__(code)
34 self.code = code
35 self.message = message
36
37
38 class GoogleReportState(iot_base.BaseIoT, ApiBase):
39 """Report states to Google.
40
41 Uses a queue to send messages.
42 """
43
44 def __init__(self, cloud: Cloud[_ClientT]) -> None:
45 """Initialize Google Report State."""
46 # Initialize both parent classes explicitly
47 iot_base.BaseIoT.__init__(self, cloud)
48 ApiBase.__init__(self, cloud)
49
50 self._connect_lock = asyncio.Lock()
51 self._to_send: Queue[dict[str, Any]] = Queue(100)
52 self._message_sender_task: asyncio.Task | None = None
53 # Local code waiting for a response
54 self._response_handler: dict[str, asyncio.Future[None]] = {}
55 self.register_on_connect(self._async_on_connect)
56 self.register_on_disconnect(self._async_on_disconnect)
57
58 # Register start/stop
59 cloud.register_on_stop(self.disconnect)
60
61 @property
62 def package_name(self) -> str:
63 """Return the package name for logging."""
64 return __name__
65
66 @property
67 def ws_server_url(self) -> str:
68 """Server to connect to."""
69 return self.cloud.service_discovery.action_url("google_report_state_websocket")
70
71 async def async_send_message(self, msg: Any) -> None:
72 """Send a message."""
73 msgid: str = uuid.uuid4().hex
74
75 # Since connect is async, guard against send_message called twice in parallel.
76 async with self._connect_lock:
77 if self.state == iot_base.STATE_DISCONNECTED:
78 asyncio.create_task(self.connect())
79 # Give connect time to start up and change state.
80 await asyncio.sleep(0)
81
82 if self._to_send.full():
83 discard_msg = self._to_send.get_nowait()
84 self._response_handler.pop(discard_msg["msgid"]).set_exception(
85 ErrorResponse(ERR_DISCARD_CODE, ERR_DISCARD_MSG),
86 )
87
88 fut = self._response_handler[msgid] = asyncio.Future()
89
90 self._to_send.put_nowait({"msgid": msgid, "payload": msg})
91
92 try:
93 return await fut
94 finally:
95 self._response_handler.pop(msgid, None)
96
97 def async_handle_message(self, msg: dict[str, Any]) -> None:
98 """Handle a message."""
99 response_handler = self._response_handler.get(msg["msgid"])
100
101 if response_handler is not None:
102 if "error" in msg:
103 response_handler.set_exception(
104 ErrorResponse(msg["error"], msg["message"]),
105 )
106 else:
107 response_handler.set_result(msg.get("payload"))
108 return
109
110 self._logger.warning("Unhandled message received: %s", msg)
111
112 async def _async_on_connect(self) -> None:
113 """On Connect handler."""
114 self._message_sender_task = asyncio.create_task(self._async_message_sender())
115
116 async def _async_on_disconnect(self) -> None:
117 """On disconnect handler."""
118 if self._message_sender_task is not None:
119 self._message_sender_task.cancel()
120 self._message_sender_task = None
121
122 async def _async_message_sender(self) -> None:
123 """Start sending messages."""
124 self._logger.debug("Message sender task activated")
125 try:
126 while True:
127 await self.async_send_json_message(await self._to_send.get())
128 except asyncio.CancelledError:
129 pass
130 self._logger.debug("Message sender task shut down")
131
132 @api_exception_handler(GoogleReportStateError)
133 async def request_sync(self) -> ClientResponse:
134 """Request a Google Actions sync request."""
135 resp: CloudApiRawResponse = await self._call_cloud_api(
136 method="POST",
137 action="google_report_state_request_sync",
138 raw_response=True,
139 client_timeout=ClientTimeout(total=300),
140 )
141 return resp.response