| 1 |
"""COAP for Shelly.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import asyncio |
| 6 |
import logging |
| 7 |
import socket |
| 8 |
import struct |
| 9 |
from collections.abc import Callable |
| 10 |
from enum import Enum, auto |
| 11 |
from ipaddress import IPv4Address |
| 12 |
from types import TracebackType |
| 13 |
from typing import TYPE_CHECKING, Self, cast |
| 14 |
|
| 15 |
from ..const import DEFAULT_COAP_PORT, END_OF_OPTIONS_MARKER, PERIODIC_COAP_TYPE_CODE |
| 16 |
from ..json import JSONDecodeError, json_loads |
| 17 |
|
| 18 |
COAP_OPTION_DEVICE_ID = 3332 |
| 19 |
|
| 20 |
_LOGGER = logging.getLogger(__name__) |
| 21 |
|
| 22 |
|
| 23 |
class CoapError(Exception): |
| 24 |
"""Base class for COAP errors.""" |
| 25 |
|
| 26 |
|
| 27 |
class InvalidMessage(CoapError): |
| 28 |
"""Raised during COAP message parsing errors.""" |
| 29 |
|
| 30 |
|
| 31 |
class CoapType(Enum): |
| 32 |
"""Coap message type.""" |
| 33 |
|
| 34 |
PERIODIC = auto() |
| 35 |
REPLY = auto() |
| 36 |
|
| 37 |
|
| 38 |
class CoapMessage: |
| 39 |
"""Represents a received coap message.""" |
| 40 |
|
| 41 |
def __init__(self, sender_addr: tuple[str, int], payload: bytes) -> None: |
| 42 |
"""Initialize a coap message.""" |
| 43 |
self.ip = sender_addr[0] |
| 44 |
self.port = sender_addr[1] |
| 45 |
self.options: dict[int, bytes] = {} |
| 46 |
self.coap_type = CoapType.REPLY |
| 47 |
|
| 48 |
try: |
| 49 |
self.vttkl, self.code, self.mid = struct.unpack("!BBH", payload[:4]) |
| 50 |
except struct.error as err: |
| 51 |
raise InvalidMessage("Message too short") from err |
| 52 |
|
| 53 |
if self.code not in (30, 69): |
| 54 |
raise InvalidMessage(f"Wrong type, {self.code}") |
| 55 |
|
| 56 |
raw_data = payload[4:] |
| 57 |
option_number = 0 |
| 58 |
data = b"" |
| 59 |
|
| 60 |
# parse options |
| 61 |
while raw_data: |
| 62 |
if raw_data[0] == END_OF_OPTIONS_MARKER: |
| 63 |
data = raw_data[1:] |
| 64 |
break |
| 65 |
|
| 66 |
delta = (raw_data[0] & 0xF0) >> 4 |
| 67 |
length = raw_data[0] & 0x0F |
| 68 |
(delta, raw_data) = self._read_extended_field_value(delta, raw_data[1:]) |
| 69 |
(length, raw_data) = self._read_extended_field_value(length, raw_data) |
| 70 |
option_number += delta |
| 71 |
|
| 72 |
if len(raw_data) < length: |
| 73 |
raise InvalidMessage("Option announced but absent") |
| 74 |
|
| 75 |
self.options[option_number] = raw_data[:length] |
| 76 |
raw_data = raw_data[length:] |
| 77 |
|
| 78 |
if not data: |
| 79 |
raise InvalidMessage("Received message without data") |
| 80 |
|
| 81 |
try: |
| 82 |
self.payload = json_loads(data.decode()) |
| 83 |
except (JSONDecodeError, UnicodeDecodeError) as err: |
| 84 |
raise InvalidMessage( |
| 85 |
f"Message type {self.code} is not a valid JSON format: {payload!s}" |
| 86 |
) from err |
| 87 |
|
| 88 |
if self.code == PERIODIC_COAP_TYPE_CODE: |
| 89 |
self.coap_type = CoapType.PERIODIC |
| 90 |
|
| 91 |
_LOGGER.debug( |
| 92 |
"CoapMessage: ip=%s, type=%s(%s), options=%s, payload=%s", |
| 93 |
self.ip, |
| 94 |
self.coap_type, |
| 95 |
self.code, |
| 96 |
self.options, |
| 97 |
self.payload, |
| 98 |
) |
| 99 |
|
| 100 |
@staticmethod |
| 101 |
def _read_extended_field_value(value: int, raw_data: bytes) -> tuple[int, bytes]: |
| 102 |
"""Decode large values of option delta and option length.""" |
| 103 |
if 0 <= value < 13: # noqa: PLR2004 |
| 104 |
return (value, raw_data) |
| 105 |
if value == 13: # noqa: PLR2004 |
| 106 |
if len(raw_data) < 1: |
| 107 |
raise InvalidMessage("Option ended prematurely") |
| 108 |
return (raw_data[0] + 13, raw_data[1:]) |
| 109 |
if value == 14: # noqa: PLR2004 |
| 110 |
if len(raw_data) < 2: # noqa: PLR2004 |
| 111 |
raise InvalidMessage("Option ended prematurely") |
| 112 |
return (int.from_bytes(raw_data[:2], "big") + 269, raw_data[2:]) |
| 113 |
|
| 114 |
raise InvalidMessage("Option contained partial payload marker.") |
| 115 |
|
| 116 |
|
| 117 |
def socket_init( |
| 118 |
socket_port: int = DEFAULT_COAP_PORT, |
| 119 |
socket_ips: list[IPv4Address] | None = None, |
| 120 |
) -> socket.socket: |
| 121 |
"""Init UDP socket to send/receive data with Shelly devices.""" |
| 122 |
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) |
| 123 |
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
| 124 |
sock.bind(("", socket_port)) |
| 125 |
sock.setblocking(False) |
| 126 |
multicast_ip_bytes = socket.inet_aton("224.0.1.187") |
| 127 |
|
| 128 |
if not socket_ips: |
| 129 |
_LOGGER.debug("Socket initialized on port %s (default interface)", socket_port) |
| 130 |
# INADDR_ANY indicates that the OS will chose an interface to join the given |
| 131 |
# multicast group. |
| 132 |
mreq = struct.pack("=4sl", multicast_ip_bytes, socket.INADDR_ANY) |
| 133 |
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) |
| 134 |
return sock |
| 135 |
|
| 136 |
had_successful_joins = False |
| 137 |
last_exception: OSError | None = None |
| 138 |
for address in socket_ips: |
| 139 |
_LOGGER.debug("Socket initialized on %s:%s", address, socket_port) |
| 140 |
mreq = multicast_ip_bytes + address.packed |
| 141 |
try: |
| 142 |
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) |
| 143 |
had_successful_joins = True |
| 144 |
except OSError as ex: |
| 145 |
_LOGGER.warning("Failed to join multicast group on %s", address) |
| 146 |
last_exception = ex |
| 147 |
|
| 148 |
if not had_successful_joins and last_exception is not None: |
| 149 |
raise last_exception |
| 150 |
|
| 151 |
return sock |
| 152 |
|
| 153 |
|
| 154 |
class COAP(asyncio.DatagramProtocol): |
| 155 |
"""COAP manager.""" |
| 156 |
|
| 157 |
def __init__(self, message_received: Callable | None = None) -> None: |
| 158 |
"""Initialize COAP manager.""" |
| 159 |
self.sock: socket.socket | None = None |
| 160 |
# Will receive all updates |
| 161 |
self._message_received = message_received |
| 162 |
self.subscriptions: dict[str, Callable] = {} |
| 163 |
self.transport: asyncio.DatagramTransport | None = None |
| 164 |
|
| 165 |
async def initialize( |
| 166 |
self, |
| 167 |
socket_port: int = DEFAULT_COAP_PORT, |
| 168 |
socket_ips: list[IPv4Address] | None = None, |
| 169 |
) -> None: |
| 170 |
"""Initialize the COAP manager.""" |
| 171 |
loop = asyncio.get_running_loop() |
| 172 |
self.sock = socket_init(socket_port, socket_ips) |
| 173 |
await loop.create_datagram_endpoint(lambda: self, sock=self.sock) |
| 174 |
|
| 175 |
async def request(self, ip: str, path: str) -> None: |
| 176 |
"""Request a CoAP message. |
| 177 |
|
| 178 |
Subscribe with `subscribe_updates` to receive answer. |
| 179 |
""" |
| 180 |
if TYPE_CHECKING: |
| 181 |
assert self.transport is not None |
| 182 |
|
| 183 |
msg = b"\x50\x01\x00\x0a\xb3cit\x01" + path.encode() + b"\xff\x00" |
| 184 |
_LOGGER.debug("Sending request 'cit/%s' to device %s", path, ip) |
| 185 |
self.transport.sendto(msg, (ip, 5683)) |
| 186 |
|
| 187 |
def close(self) -> None: |
| 188 |
"""Close.""" |
| 189 |
if self.transport is not None: |
| 190 |
self.transport.close() |
| 191 |
|
| 192 |
def connection_made(self, transport: asyncio.BaseTransport) -> None: |
| 193 |
"""When the socket is set up.""" |
| 194 |
self.transport = cast(asyncio.DatagramTransport, transport) |
| 195 |
|
| 196 |
def datagram_received(self, data: bytes, addr: tuple[str, int]) -> None: |
| 197 |
"""Handle incoming datagram messages.""" |
| 198 |
host_ip = addr[0] |
| 199 |
try: |
| 200 |
msg = CoapMessage(addr, data) |
| 201 |
except InvalidMessage as err: |
| 202 |
_LOGGER.debug("Invalid Message from host %s: %s", host_ip, err) |
| 203 |
return |
| 204 |
|
| 205 |
if self._message_received: |
| 206 |
self._message_received(msg) |
| 207 |
|
| 208 |
if COAP_OPTION_DEVICE_ID not in msg.options: |
| 209 |
_LOGGER.debug("Message from host %s missing device id option", host_ip) |
| 210 |
return |
| 211 |
|
| 212 |
try: |
| 213 |
device_id = msg.options[COAP_OPTION_DEVICE_ID].decode().split("#")[1][-6:] |
| 214 |
except (UnicodeDecodeError, IndexError) as err: |
| 215 |
_LOGGER.debug("Invalid device id from host %s: %s", host_ip, err) |
| 216 |
return |
| 217 |
|
| 218 |
if device_id in self.subscriptions: |
| 219 |
_LOGGER.debug("Calling CoAP message update for device id %s", device_id) |
| 220 |
self.subscriptions[device_id](msg) |
| 221 |
return |
| 222 |
|
| 223 |
if msg.ip in self.subscriptions: |
| 224 |
_LOGGER.debug("Calling CoAP message update for host %s", msg.ip) |
| 225 |
self.subscriptions[msg.ip](msg) |
| 226 |
|
| 227 |
def subscribe_updates( |
| 228 |
self, ip_or_device_id: str, message_received: Callable |
| 229 |
) -> Callable: |
| 230 |
"""Subscribe to received updates.""" |
| 231 |
_LOGGER.debug("Adding device %s to CoAP message subscriptions", ip_or_device_id) |
| 232 |
self.subscriptions[ip_or_device_id] = message_received |
| 233 |
return lambda: self.subscriptions.pop(ip_or_device_id) |
| 234 |
|
| 235 |
async def __aenter__(self) -> Self: |
| 236 |
"""Entering async context manager.""" |
| 237 |
await self.initialize() |
| 238 |
return self |
| 239 |
|
| 240 |
async def __aexit__( |
| 241 |
self, |
| 242 |
exc_type: type[BaseException] | None, |
| 243 |
exc_value: BaseException | None, |
| 244 |
traceback: TracebackType | None, |
| 245 |
) -> None: |
| 246 |
"""Leaving async context manager.""" |
| 247 |
self.close() |
| 248 |
|
| 249 |
|
| 250 |
async def discovery_dump() -> None: |
| 251 |
"""Dump all discovery data as it comes in.""" |
| 252 |
async with COAP(lambda msg: print(msg.ip, msg.payload)): # noqa: T201 |
| 253 |
# This is for diagnostic purposes only. |
| 254 |
while True: # noqa: ASYNC110 |
| 255 |
await asyncio.sleep(0.1) |
| 256 |
|
| 257 |
|
| 258 |
if __name__ == "__main__": |
| 259 |
try: # noqa: SIM105 |
| 260 |
asyncio.run(discovery_dump()) |
| 261 |
except KeyboardInterrupt: |
| 262 |
pass |