Debian Codegraph @

aioshelly/block_device/device.py

raw
1 """Shelly Gen1 CoAP block based device."""
2
3 from __future__ import annotations
4
5 import asyncio
6 import logging
7 from collections.abc import Callable
8 from enum import Enum, auto
9 from http import HTTPStatus
10 from typing import Any, ClassVar, cast
11
12 from aiohttp import ClientResponse, ClientResponseError, ClientSession, ClientTimeout
13 from yarl import URL
14
15 from ..common import (
16 ConnectionOptions,
17 IpOrOptionsType,
18 get_info,
19 is_firmware_supported,
20 process_ip_or_options,
21 )
22 from ..const import (
23 CIT_RETRIES,
24 CONNECT_ERRORS,
25 DEFAULT_HTTP_PORT,
26 DEVICE_IO_TIMEOUT,
27 FIRMWARE_PATTERN,
28 GEN1_HTTP_CIT_D_MIN_FIRMWARE_DATE,
29 HTTP_CALL_TIMEOUT,
30 MODEL_RGBW2,
31 )
32 from ..exceptions import (
33 CustomPortNotSupported,
34 DeviceConnectionError,
35 DeviceConnectionTimeoutError,
36 InvalidAuthError,
37 MacAddressMismatchError,
38 NotInitialized,
39 ShellyError,
40 WrongShellyGen,
41 )
42 from ..json import json_loads
43 from .coap import COAP, CoapMessage, CoapType
44
45 BLOCK_VALUE_UNIT = "U"
46 BLOCK_VALUE_TYPE = "T"
47
48 BLOCK_VALUE_TYPE_ALARM = "A"
49 BLOCK_VALUE_TYPE_BATTERY_LEVEL = "B"
50 BLOCK_VALUE_TYPE_CONCENTRATION = "C"
51 BLOCK_VALUE_TYPE_ENERGY = "E"
52 BLOCK_VALUE_TYPE_EVENT = "EV"
53 BLOCK_VALUE_TYPE_EVENT_COUNTER = "EVC"
54 BLOCK_VALUE_TYPE_HUMIDITY = "H"
55 BLOCK_VALUE_TYPE_CURRENT = "I"
56 BLOCK_VALUE_TYPE_LUMINOSITY = "L"
57 BLOCK_VALUE_TYPE_POWER = "P"
58 BLOCK_VALUE_TYPE_STATUS = "S" # (catch-all if no other fits)
59 BLOCK_VALUE_TYPE_TEMPERATURE = "T"
60 BLOCK_VALUE_TYPE_VOLTAGE = "V"
61
62
63 HTTP_CALL_TIMEOUT_CLIENT_TIMEOUT = ClientTimeout(total=HTTP_CALL_TIMEOUT)
64
65 _LOGGER = logging.getLogger(__name__)
66
67
68 class BlockUpdateType(Enum):
69 """Block Update type."""
70
71 COAP_PERIODIC = auto()
72 COAP_REPLY = auto()
73 INITIALIZED = auto()
74 ONLINE = auto()
75
76
77 class BlockDevice:
78 """Shelly block device representation."""
79
80 def __init__(
81 self,
82 coap_context: COAP,
83 aiohttp_session: ClientSession,
84 options: ConnectionOptions,
85 ) -> None:
86 """Device init."""
87 if options.ip_address is None:
88 raise ValueError("Block devices require ip_address")
89 self.coap_context: COAP = coap_context
90 self.aiohttp_session: ClientSession = aiohttp_session
91 self.options: ConnectionOptions = options
92 self.coap_d: dict[str, Any] | None = None
93 self.blocks: list[Block] = []
94 self.coap_s: dict[str, Any] | None = None
95 self._settings: dict[str, Any] | None = None
96 self._shelly: dict[str, Any] | None = None
97 self._status: dict[str, Any] | None = None
98 sub_id = options.ip_address
99 if options.device_mac:
100 sub_id = options.device_mac[-6:]
101 self._unsub_coap: Callable | None = coap_context.subscribe_updates(
102 sub_id, self._coap_message_received
103 )
104 self._update_listener: Callable | None = None
105 self._coap_response_events: dict[str, asyncio.Event] = {}
106 self.initialized = False
107 self._initializing = False
108 self._last_error: ShellyError | None = None
109
110 @classmethod
111 async def create(
112 cls: type[BlockDevice],
113 aiohttp_session: ClientSession,
114 coap_context: COAP,
115 ip_or_options: IpOrOptionsType,
116 ) -> BlockDevice:
117 """Device creation."""
118 options = await process_ip_or_options(ip_or_options)
119 if options.ip_address is None:
120 raise ValueError("Block devices require ip_address")
121 # Try sending cit/s request to trigger a sleeping device
122 try:
123 await coap_context.request(options.ip_address, "s")
124 except OSError as err:
125 _LOGGER.debug("host %s: error: %r", options.ip_address, err)
126 _LOGGER.debug(
127 "host %s: block device create, MAC: %s",
128 options.ip_address,
129 options.device_mac,
130 )
131 return cls(coap_context, aiohttp_session, options)
132
133 @property
134 def ip_address(self) -> str:
135 """Device ip address."""
136 if self.options.ip_address is None:
137 raise RuntimeError("Block device ip_address is None")
138 return self.options.ip_address
139
140 async def initialize(self) -> None:
141 """Device initialization."""
142 _LOGGER.debug("host %s: block device initialize", self.ip_address)
143 if self._initializing:
144 raise RuntimeError("Already initializing")
145
146 # GEN1 cannot be configured behind a range extender as CoAP port cannot be
147 # natted
148 if self.options.port != DEFAULT_HTTP_PORT:
149 raise CustomPortNotSupported
150
151 self._initializing = True
152
153 # First initialize may already have CoAP status from wakeup event
154 # If device is initialized again we need to fetch new CoAP status
155 if self.initialized:
156 self.initialized = False
157 self.coap_s = None
158
159 ip = self.ip_address
160 try:
161 self._shelly = await get_info(
162 self.aiohttp_session, self.ip_address, self.options.device_mac
163 )
164
165 if self.requires_auth and not self.options.auth:
166 raise InvalidAuthError("auth missing and required")
167
168 async with asyncio.timeout(DEVICE_IO_TIMEOUT):
169 await self.update_settings()
170 await self.update_status()
171
172 # Older devices has incompatible CoAP protocol (v1)
173 # Skip CoAP to avoid parsing errors
174 if self.firmware_supported:
175 await self._update_cit_d()
176
177 if self.coap_s is None:
178 await self._update_cit_s()
179
180 self.initialized = True
181 except ClientResponseError as err:
182 if err.status == HTTPStatus.UNAUTHORIZED:
183 self._last_error = InvalidAuthError(err)
184 else:
185 self._last_error = DeviceConnectionError(err)
186 _LOGGER.debug("host %s: error: %r", ip, self._last_error)
187 raise self._last_error from err
188 except MacAddressMismatchError as err:
189 self._last_error = err
190 _LOGGER.debug("host %s: error: %r", ip, err)
191 raise
192 except TimeoutError as err:
193 self._last_error = DeviceConnectionTimeoutError(err)
194 _LOGGER.debug("host %s: timeout error: %r", ip, self._last_error)
195 raise self._last_error from err
196 except CONNECT_ERRORS as err:
197 self._last_error = DeviceConnectionError(err)
198 _LOGGER.debug("host %s: error: %r", ip, self._last_error)
199 raise self._last_error from err
200 finally:
201 self._initializing = False
202
203 if self._update_listener:
204 self._update_listener(self, BlockUpdateType.INITIALIZED)
205
206 async def shutdown(self) -> None:
207 """Shutdown device."""
208 _LOGGER.debug("host %s: block device shutdown", self.ip_address)
209 self._update_listener = None
210
211 if self._unsub_coap:
212 try:
213 self._unsub_coap()
214 except KeyError as err:
215 _LOGGER.error(
216 "host %s: error during shutdown: %r", self.options.ip_address, err
217 )
218 self._unsub_coap = None
219
220 def _coap_message_received(self, msg: CoapMessage) -> None:
221 """COAP message received."""
222 if not self._initializing and not self.initialized and self._update_listener:
223 self._update_listener(self, BlockUpdateType.ONLINE)
224
225 if not msg.payload:
226 return
227 if "G" in msg.payload:
228 self._update_s(msg.payload, msg.coap_type)
229 path = "s"
230 elif "blk" in msg.payload:
231 self._update_d(msg.payload)
232 path = "d"
233 else:
234 # Unknown msg
235 return
236
237 event = self._coap_response_events.pop(path, None)
238 if event is not None:
239 event.set()
240
241 async def update(self) -> None:
242 """Device update."""
243 try:
244 async with asyncio.timeout(DEVICE_IO_TIMEOUT):
245 event = await self._coap_request("s")
246 await event.wait()
247 except TimeoutError as err:
248 self._last_error = DeviceConnectionTimeoutError(err)
249 raise self._last_error from err
250 except CONNECT_ERRORS as err:
251 self._last_error = DeviceConnectionError(err)
252 raise self._last_error from err
253
254 def _update_d(self, data: dict[str, Any]) -> None:
255 """Device update from cit/d call."""
256 self.coap_d = data
257 blocks = []
258
259 for blk in self.coap_d["blk"]:
260 blk_index = blk["I"]
261 blk_sensors = {
262 val["I"]: val
263 for val in self.coap_d["sen"]
264 if (
265 val["L"] == blk_index
266 if isinstance(val["L"], int)
267 else blk_index in val["L"]
268 )
269 }
270 block = Block.create(self, blk, blk_sensors)
271
272 if block:
273 blocks.append(block)
274
275 self.blocks = blocks
276
277 def _update_s(self, data: dict[str, Any], coap_type: CoapType) -> None:
278 """Device update from cit/s call."""
279 self.coap_s = {info[1]: info[2] for info in data["G"]}
280
281 if self._update_listener and self.initialized:
282 if coap_type is CoapType.PERIODIC:
283 self._update_listener(self, BlockUpdateType.COAP_PERIODIC)
284 return
285
286 self._update_listener(self, BlockUpdateType.COAP_REPLY)
287
288 def subscribe_updates(self, update_listener: Callable) -> None:
289 """Subscribe to device status updates."""
290 self._update_listener = update_listener
291
292 async def update_status(self) -> None:
293 """Device update from /status (HTTP)."""
294 self._status = await self.http_request("get", "status")
295
296 async def update_settings(self) -> None:
297 """Device update from /settings (HTTP)."""
298 self._settings = await self.http_request("get", "settings")
299
300 async def update_shelly(self) -> None:
301 """Device update for /shelly (HTTP)."""
302 self._shelly = await get_info(self.aiohttp_session, self.ip_address)
303
304 async def _update_cit_d(self) -> None:
305 """Update CoAP cit/d.
306
307 cit/d via HTTP introduced in firmware 1.10
308 If device does not support cit/d via HTTP,
309 fallback to cit/d via CoAP request.
310 """
311 match = FIRMWARE_PATTERN.search(self.firmware_version)
312 if match is not None and int(match[0]) >= GEN1_HTTP_CIT_D_MIN_FIRMWARE_DATE:
313 cit_d_res = await self.http_request("get", "cit/d")
314 self._update_d(cit_d_res)
315 return
316
317 await self._update_cit("d")
318
319 async def _update_cit_s(self) -> None:
320 """Update CoAP cit/s."""
321 await self._update_cit("s")
322
323 async def _update_cit(self, path: str) -> None:
324 """Update CoAP cit with retry."""
325 for retry in range(CIT_RETRIES):
326 _LOGGER.debug(
327 "host %s: CoAP cit/%s request (retries=%s)",
328 self.ip_address,
329 path,
330 retry,
331 )
332 try:
333 async with asyncio.timeout(DEVICE_IO_TIMEOUT / 4):
334 event = await self._coap_request(path)
335 await event.wait()
336 return
337 except TimeoutError:
338 if retry == CIT_RETRIES - 1:
339 raise
340
341 async def _coap_request(self, path: str) -> asyncio.Event:
342 """Device CoAP request."""
343 if path not in self._coap_response_events:
344 self._coap_response_events[path] = asyncio.Event()
345
346 event: asyncio.Event = self._coap_response_events[path]
347
348 await self.coap_context.request(self.ip_address, path)
349 return event
350
351 async def http_request(
352 self, method: str, path: str, params: Any | None = None, retry: bool = True
353 ) -> dict[str, Any]:
354 """Device HTTP request."""
355 if self.options.auth is None and self.requires_auth:
356 raise InvalidAuthError("auth missing and required")
357
358 host = self.ip_address
359 _LOGGER.debug("host %s: http request: /%s (params=%s)", host, path, params)
360 try:
361 resp: ClientResponse = await self.aiohttp_session.request(
362 method,
363 URL.build(scheme="http", host=host, path=f"/{path}"),
364 params=params,
365 auth=self.options.auth,
366 raise_for_status=True,
367 timeout=HTTP_CALL_TIMEOUT_CLIENT_TIMEOUT,
368 )
369 except ClientResponseError as err:
370 if err.status == HTTPStatus.UNAUTHORIZED:
371 self._last_error = InvalidAuthError(err)
372 raise InvalidAuthError(err) from err
373
374 self._last_error = DeviceConnectionError(err)
375 raise self._last_error from err
376 except TimeoutError as err:
377 self._last_error = DeviceConnectionTimeoutError(err)
378 if retry:
379 _LOGGER.debug(
380 "host %s: http request timeout: %r", host, self._last_error
381 )
382 return await self.http_request(method, path, params, retry=False)
383
384 _LOGGER.debug(
385 "host %s: http request retry timeout: %r", host, self._last_error
386 )
387 raise self._last_error from err
388 except CONNECT_ERRORS as err:
389 self._last_error = DeviceConnectionError(err)
390 if retry:
391 _LOGGER.debug("host %s: http request error: %r", host, self._last_error)
392 return await self.http_request(method, path, params, retry=False)
393
394 _LOGGER.debug(
395 "host %s: http request retry error: %r", host, self._last_error
396 )
397 raise self._last_error from err
398
399 resp_json = await resp.json(loads=json_loads)
400 _LOGGER.debug("aiohttp response: %s", resp_json)
401 return cast(dict, resp_json)
402
403 async def switch_light_mode(self, mode: str) -> dict[str, Any]:
404 """Change device mode color/white."""
405 return await self.http_request("get", "settings", {"mode": mode})
406
407 async def trigger_ota_update(
408 self, beta: bool = False, url: str | None = None
409 ) -> dict[str, Any]:
410 """Trigger an ota update."""
411 params = {"update": "true"}
412
413 if url:
414 params = {"url": url}
415 elif beta:
416 params = {"beta": "true"}
417
418 return await self.http_request("get", "ota", params=params)
419
420 async def trigger_reboot(self) -> None:
421 """Trigger a device reboot."""
422 await self.http_request("get", "reboot")
423
424 async def trigger_shelly_gas_self_test(self) -> None:
425 """Trigger a Shelly Gas self test."""
426 await self.http_request("get", "self_test")
427
428 async def trigger_shelly_gas_mute(self) -> None:
429 """Trigger a Shelly Gas mute action."""
430 await self.http_request("get", "mute")
431
432 async def trigger_shelly_gas_unmute(self) -> None:
433 """Trigger a Shelly Gas unmute action."""
434 await self.http_request("get", "unmute")
435
436 async def set_shelly_motion_detection(self, enable: bool) -> None:
437 """Enable or disable Shelly Motion motion detection."""
438 params = {"motion_enable": "true"} if enable else {"motion_enable": "false"}
439
440 await self.http_request("get", "settings", params)
441
442 async def set_thermostat_state(self, channel: int = 0, **kwargs: Any) -> None:
443 """Set thermostat state (Shelly TRV)."""
444 await self.http_request("get", f"thermostat/{channel}", kwargs)
445
446 async def configure_coiot_protocol(self, address: str, port: int) -> None:
447 """Configure CoIoT protocol."""
448 params = {"coiot_enable": "true", "coiot_peer": f"{address}:{port}"}
449 await self.http_request("post", "settings/advanced", params)
450
451 @property
452 def requires_auth(self) -> bool:
453 """Device check for authentication."""
454 if "auth" not in self.shelly:
455 raise WrongShellyGen
456
457 return bool(self.shelly["auth"])
458
459 @property
460 def settings(self) -> dict[str, Any]:
461 """Get device settings via HTTP."""
462 if not self.initialized:
463 raise NotInitialized
464
465 if self._settings is None:
466 raise InvalidAuthError
467
468 return self._settings
469
470 @property
471 def status(self) -> dict[str, Any]:
472 """Get device status via HTTP."""
473 if not self.initialized:
474 raise NotInitialized
475
476 if self._status is None:
477 raise InvalidAuthError
478
479 return self._status
480
481 @property
482 def shelly(self) -> dict[str, Any]:
483 """Device firmware version."""
484 if self._shelly is None:
485 raise NotInitialized
486
487 return self._shelly
488
489 @property
490 def gen(self) -> int:
491 """Device generation: GEN1 - CoAP."""
492 return 1
493
494 @property
495 def firmware_version(self) -> str:
496 """Device firmware version."""
497 return cast(str, self.shelly["fw"])
498
499 @property
500 def model(self) -> str:
501 """Device model."""
502 return cast(str, self.shelly["type"])
503
504 @property
505 def hostname(self) -> str:
506 """Device hostname."""
507 return cast(str, self.settings["device"]["hostname"])
508
509 @property
510 def name(self) -> str:
511 """Device name."""
512 return cast(str, self.settings["name"] or self.hostname)
513
514 @property
515 def last_error(self) -> ShellyError | None:
516 """Return the last error during async device init."""
517 return self._last_error
518
519 @property
520 def firmware_supported(self) -> bool:
521 """Return True if device firmware version is supported."""
522 return is_firmware_supported(self.gen, self.model, self.firmware_version)
523
524
525 class Block:
526 """Shelly CoAP block."""
527
528 TYPES: ClassVar[dict] = {}
529 type = None
530
531 def __init_subclass__(cls, blk_type: str = "", **kwargs: Any) -> None:
532 """Initialize a subclass, register if possible."""
533 super().__init_subclass__(**kwargs)
534 Block.TYPES[blk_type] = cls
535
536 @staticmethod
537 def create(device: BlockDevice, blk: dict, sensors: dict[str, dict]) -> Any:
538 """Block create."""
539 blk_type = blk["D"].split("_")[0]
540 cls = Block.TYPES.get(blk_type, Block)
541 return cls(device, blk_type, blk, sensors)
542
543 def __init__(
544 self, device: BlockDevice, blk_type: str, blk: dict, sensors: dict[str, dict]
545 ) -> None:
546 """Block initialize."""
547 self.type = blk_type
548 self.device = device
549 self.blk = blk
550 self.sensors = sensors
551 sensor_ids = {}
552 for sensor in sensors.values():
553 if sensor["D"] not in sensor_ids:
554 sensor_ids[sensor["D"]] = sensor["I"]
555 continue
556
557 if sensor[BLOCK_VALUE_TYPE] != BLOCK_VALUE_TYPE_TEMPERATURE:
558 raise ValueError(
559 "Found duplicate description for non-temperature sensor"
560 )
561
562 if sensor[BLOCK_VALUE_UNIT] == device.options.temperature_unit:
563 sensor_ids[sensor["D"]] = sensor["I"]
564
565 self.sensor_ids = sensor_ids
566
567 @property
568 def index(self) -> str:
569 """Block index."""
570 return cast(str, self.blk["I"])
571
572 @property
573 def description(self) -> str:
574 """Block description."""
575 return cast(str, self.blk["D"])
576
577 @property
578 def channel(self) -> str | None:
579 """Block description for channel."""
580 return self.description.split("_")[1] if "_" in self.description else None
581
582 def info(self, attr: str) -> dict[str, Any]:
583 """Return info over attribute."""
584 return self.sensors[self.sensor_ids[attr]]
585
586 def current_values(self) -> dict[str, Any]:
587 """Block values."""
588 if self.device.coap_s is None:
589 return {}
590
591 return {
592 desc: self.device.coap_s.get(index)
593 for desc, index in self.sensor_ids.items()
594 }
595
596 async def set_state(self, **kwargs: Any) -> dict[str, Any]:
597 """Set state request (HTTP)."""
598 return await self.device.http_request(
599 "get", f"{self.type}/{self.channel}", kwargs
600 )
601
602 async def toggle(self) -> dict[str, Any]:
603 """Toggle status."""
604 return await self.set_state(turn="off" if self.output else "on")
605
606 def __getattr__(self, attr: str) -> str | None:
607 """Get attribute."""
608 if attr not in self.sensor_ids:
609 msg = (
610 f"Device {self.device.model} with firmware "
611 f"{self.device.firmware_version} has no attribute '{attr}' "
612 f"in block {self.type}"
613 )
614 raise AttributeError(msg)
615
616 if self.device.coap_s is None:
617 return None
618
619 return self.device.coap_s.get(self.sensor_ids[attr])
620
621 def __str__(self) -> str:
622 """Format string."""
623 return f"<{self.type} {self.blk}>"
624
625
626 class LightBlock(Block, blk_type="light"):
627 """Get light status."""
628
629 async def set_state(self, **kwargs: Any) -> dict[str, Any]:
630 """Set light state."""
631 if self.device.settings["device"]["type"] == MODEL_RGBW2:
632 path = f"{self.device.settings['mode']}/{self.channel}"
633 else:
634 path = f"{self.type}/{self.channel}"
635
636 return await self.device.http_request("get", path, kwargs)