Debian Codegraph @

src/govee_local_api/message.py

raw symbols SCIP
1 from __future__ import annotations
2
3 import base64
4 import json
5 from typing import Any, TypeVar
6
7
8 class GoveeMessage:
9 command: str = ""
10 _data: dict[str, Any]
11
12 def __init__(self, data: dict[str, Any]) -> None:
13 self._data = data
14
15 def as_dict(self) -> dict[str, Any]:
16 return {"msg": {"cmd": self.command, "data": self.data}}
17
18 def as_json(self) -> str:
19 return json.dumps(self.as_dict(), separators=(",", ":"))
20
21 def __bytes__(self) -> bytes:
22 return self.as_json().encode("utf-8")
23
24 def __str__(self) -> str:
25 return self.as_json()
26
27 @property
28 def data(self) -> dict[str, Any]:
29 return self._data
30
31
32 M = TypeVar("M", bound=GoveeMessage)
33
34
35 class ScanMessage(GoveeMessage):
36 command = "scan"
37
38 def __init__(self) -> None:
39 super().__init__({"account_topic": "reserve"})
40
41
42 class DevStatusMessage(GoveeMessage):
43 command = "devStatus"
44
45 def __init__(self) -> None:
46 super().__init__({})
47
48
49 class StatusMessage(GoveeMessage):
50 command = "status"
51
52 def __init__(self) -> None:
53 super().__init__({})
54
55
56 class OnOffMessage(GoveeMessage):
57 command = "turn"
58
59 def __init__(self, on: bool) -> None:
60 super().__init__({"value": int(on)})
61
62
63 class BrightnessMessage(GoveeMessage):
64 command = "brightness"
65
66 def __init__(self, brightness_pct: int) -> None:
67 super().__init__({"value": max(0, min(brightness_pct, 100))})
68
69
70 class ColorMessage(GoveeMessage):
71 TEMPERATURE_MAX_KELVIN = 9000
72 TEMPERATURE_MIN_KELVIN = 2000
73
74 command = "colorwc"
75
76 def __init__(
77 self, *, rgb: tuple[int, int, int] | None, temperature: int | None
78 ) -> None:
79 if rgb:
80 nrgb = [max(0, min(c, 255)) for c in rgb]
81 data = {
82 "color": {"r": nrgb[0], "g": nrgb[1], "b": nrgb[2]},
83 "colorTemInKelvin": 0,
84 }
85 elif temperature:
86 data = {
87 "color": {"r": 0, "g": 0, "b": 0},
88 "colorTemInKelvin": max(
89 self.TEMPERATURE_MIN_KELVIN,
90 min(temperature, self.TEMPERATURE_MAX_KELVIN),
91 ),
92 }
93 else:
94 raise ValueError(
95 "ColorMessage requires either a non-empty rgb tuple or a "
96 "non-zero temperature"
97 )
98
99 super().__init__(data)
100
101
102 class PtRealMessage(GoveeMessage):
103 command = "ptReal"
104
105 def __init__(self, data: list[bytes], do_checksum: bool = True) -> None:
106 checksumed_data: list[str] = (
107 [
108 base64.b64encode(PtRealMessage._with_checksum(d)).decode("utf-8")
109 for d in data
110 ]
111 if do_checksum
112 else [base64.b64encode(d).decode("utf-8") for d in data]
113 )
114
115 super().__init__({"command": checksumed_data})
116
117 @staticmethod
118 def _with_checksum(data: bytes) -> bytes:
119 xor_result: int = 0
120 for byte in data:
121 xor_result ^= byte
122 return data + xor_result.to_bytes(1, "big")
123
124
125 class HexMessage(PtRealMessage):
126 def __init__(self, data: list[str]) -> None:
127 super().__init__([bytes.fromhex(d) for d in data], do_checksum=False)
128
129
130 class SegmentColorMessages(PtRealMessage):
131 def __init__(self, segment: bytes, color: tuple[int, int, int]) -> None:
132 capped_color = [max(0, min(c, 255)) for c in color]
133 data = (
134 b"\x33\x05\x15\x01"
135 + bytes(capped_color)
136 + b"\x00\x00\x00\x00\x00"
137 + segment
138 + b"\x00\x00\x00\x00\x00"
139 )
140 super().__init__([data])
141
142
143 class SceneMessages(PtRealMessage):
144 def __init__(self, scene: bytes) -> None:
145 data = (
146 b"\x33\x05\x04"
147 + scene
148 + b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
149 )
150 super().__init__([data])
151
152
153 class ScanResponse(GoveeMessage):
154 command = "scan"
155
156 def __init__(self, data: dict[str, Any]) -> None:
157 super().__init__(data)
158
159 @property
160 def device(self):
161 return self._data.get("device", None)
162
163 @property
164 def sku(self):
165 return self._data.get("sku", None)
166
167 @property
168 def ip(self):
169 return self._data.get("ip", None)
170
171 def set_ip(self, ip_addr: str) -> None:
172 self._data["ip"] = ip_addr
173
174
175 class DevStatusResponse(GoveeMessage):
176 command = "devStatus"
177
178 def __init__(self, data: dict[str, Any]) -> None:
179 super().__init__(data)
180
181 # All accessors use .get() with safe defaults. A firmware variant or a
182 # malformed payload that omits a field must not crash device.update()
183 # partway through (which would leave the device half-updated).
184
185 @property
186 def is_on(self) -> bool:
187 return bool(self._data.get("onOff", 0))
188
189 @property
190 def color(self) -> tuple[int, int, int]:
191 color = self._data.get("color") or {}
192 return (color.get("r", 0), color.get("g", 0), color.get("b", 0))
193
194 @property
195 def brightness(self) -> int:
196 return int(self._data.get("brightness", 0))
197
198 @property
199 def color_temperature(self) -> int:
200 return int(self._data.get("colorTemInKelvin", 0))
201
202
203 class StatusResponse(GoveeMessage):
204 command = "status"
205
206 def __init__(self, data: dict[str, Any]) -> None:
207 super().__init__(data)
208
209 def hex(self) -> str:
210 return base64.b64decode(self._data["pt"]).hex()
211
212
213 class MessageResponseFactory:
214 def __init__(self) -> None:
215 self._messages: set[type[GoveeMessage]] = {
216 ScanResponse,
217 DevStatusResponse,
218 StatusResponse,
219 }
220
221 def create_message(self, data: bytes | bytearray | str) -> GoveeMessage | None:
222 # Background UDP noise (mDNS, SSDP, other devices) lands on port 4002
223 # too. Treat any parse failure as "not for us" and drop silently
224 # instead of raising into the datagram handler.
225 try:
226 msg_json = json.loads(data)
227 inner = msg_json["msg"]
228 cmd = inner["cmd"]
229 message_data = inner["data"]
230 except (json.JSONDecodeError, KeyError, TypeError):
231 return None
232
233 message_cls = next((m for m in self._messages if m.command == cmd), None)
234 if message_cls is None:
235 return None
236 return message_cls(message_data)