broadlink-magic 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,270 @@
1
+ """RM Max gateway registry and multi-gateway fan-out."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import time
7
+ from collections.abc import Callable, Iterable
8
+ from dataclasses import dataclass
9
+
10
+ from .fastcon import apply_family_token, device_control, scene_control
11
+ from .inbound import (
12
+ GATEWAY_SESSION_TIMEOUT,
13
+ MSG_CONTROL,
14
+ MSG_DISCOVERY,
15
+ MSG_HEARTBEAT,
16
+ MSG_STATUS_QUERY_ACK,
17
+ MSG_STATUS_UPLOAD,
18
+ pack_message,
19
+ pack_status_query,
20
+ parse_status_upload,
21
+ unpack_header,
22
+ )
23
+ from .models import DiscoveredRMMax, Family, normalize_mac
24
+
25
+ DatagramSender = Callable[[bytes, tuple[str, int]], None]
26
+ ReportCallback = Callable[[int, bytes], None]
27
+ _LOGGER = logging.getLogger(__name__)
28
+
29
+
30
+ @dataclass(slots=True)
31
+ class GatewayState:
32
+ """Runtime state for one RM Max."""
33
+
34
+ mac: str
35
+ host: str
36
+ port: int = 0
37
+ name: str = ""
38
+ online: bool = False
39
+ peer: tuple[str, int] | None = None
40
+ last_seen: float = 0.0
41
+
42
+
43
+ class GatewaySet:
44
+ """All RM Max gateways currently associated with one family."""
45
+
46
+ def __init__(
47
+ self,
48
+ family: Family,
49
+ gateways: Iterable[DiscoveredRMMax] = (),
50
+ *,
51
+ sender: DatagramSender | None = None,
52
+ report_callback: ReportCallback | None = None,
53
+ ) -> None:
54
+ self.family = family
55
+ self._sender = sender
56
+ self._report_callback = report_callback
57
+ self._gateways: dict[str, GatewayState] = {}
58
+ self._fastcon_seq = 0
59
+ self._gateway_seq = 0
60
+ for device in self.family.gateways:
61
+ mac = normalize_mac(device.mac or device.did)
62
+ if mac:
63
+ self._gateways[mac] = GatewayState(
64
+ mac=mac,
65
+ host="",
66
+ name=device.name,
67
+ )
68
+ self.update_discovered(gateways)
69
+
70
+ @property
71
+ def gateways(self) -> tuple[GatewayState, ...]:
72
+ """Return all matched gateway states."""
73
+ return tuple(self._gateways.values())
74
+
75
+ @property
76
+ def online_gateways(self) -> tuple[GatewayState, ...]:
77
+ """Return all online gateways."""
78
+ self.expire_sessions()
79
+ return tuple(
80
+ gateway
81
+ for gateway in self._gateways.values()
82
+ if gateway.online and gateway.peer is not None
83
+ )
84
+
85
+ def set_report_callback(self, callback: ReportCallback) -> None:
86
+ """Set the callback for decrypted FastCon reports."""
87
+ self._report_callback = callback
88
+
89
+ def update_discovered(self, devices: Iterable[DiscoveredRMMax]) -> None:
90
+ """Reconcile LAN discovery results with imported RM Max devices."""
91
+ expected = {
92
+ normalize_mac(device.mac or device.did)
93
+ for device in self.family.gateways
94
+ if normalize_mac(device.mac or device.did)
95
+ }
96
+ for device in devices:
97
+ mac = normalize_mac(device.mac)
98
+ if expected and mac not in expected:
99
+ continue
100
+ state = self._gateways.get(mac)
101
+ if state is None:
102
+ self._gateways[mac] = GatewayState(
103
+ mac=mac,
104
+ host=device.host,
105
+ port=device.port,
106
+ name=device.name,
107
+ )
108
+ else:
109
+ state.host = device.host
110
+ state.port = device.port
111
+ state.name = device.name or state.name
112
+
113
+ def _next_fastcon_seq(self) -> int:
114
+ self._fastcon_seq = (self._fastcon_seq % 0xFF) + 1
115
+ return self._fastcon_seq
116
+
117
+ def _next_gateway_seq(self) -> int:
118
+ self._gateway_seq = (self._gateway_seq + 1) & 0xFFFF
119
+ return self._gateway_seq
120
+
121
+ def handle_packet(
122
+ self,
123
+ mac: str,
124
+ data: bytes,
125
+ addr: tuple[str, int],
126
+ ) -> None:
127
+ """Update one inbound gateway session and dispatch status reports."""
128
+ gateway = self._gateways.get(normalize_mac(mac))
129
+ if gateway is None:
130
+ return
131
+ try:
132
+ message_type, _sequence = unpack_header(data)
133
+ except ValueError:
134
+ return
135
+ if message_type not in (
136
+ MSG_DISCOVERY,
137
+ MSG_HEARTBEAT,
138
+ MSG_STATUS_UPLOAD,
139
+ MSG_STATUS_QUERY_ACK,
140
+ ):
141
+ return
142
+ session_changed = not gateway.online or gateway.peer != addr
143
+ gateway.host = addr[0]
144
+ gateway.port = addr[1]
145
+ gateway.peer = addr
146
+ gateway.online = True
147
+ gateway.last_seen = time.monotonic()
148
+ if session_changed:
149
+ _LOGGER.debug(
150
+ "Gateway inbound session online gateway=%s peer=%s",
151
+ gateway.mac,
152
+ addr,
153
+ )
154
+ if message_type == MSG_STATUS_UPLOAD and self._report_callback is not None:
155
+ for short_addr, payload in parse_status_upload(data):
156
+ _LOGGER.debug(
157
+ "Received device status gateway=%s peer=%s short_addr=%s payload=%s",
158
+ gateway.mac,
159
+ addr,
160
+ short_addr,
161
+ payload.hex(),
162
+ )
163
+ self._report_callback(short_addr, payload)
164
+ elif message_type == MSG_STATUS_QUERY_ACK:
165
+ _LOGGER.debug(
166
+ "Received status query ACK gateway=%s peer=%s sequence=%s",
167
+ gateway.mac,
168
+ addr,
169
+ _sequence,
170
+ )
171
+
172
+ def expire_sessions(self, now: float | None = None) -> None:
173
+ """Mark sessions offline after the Industry heartbeat timeout."""
174
+ current = time.monotonic() if now is None else now
175
+ for gateway in self._gateways.values():
176
+ if (
177
+ gateway.online
178
+ and gateway.last_seen
179
+ and current - gateway.last_seen >= GATEWAY_SESSION_TIMEOUT
180
+ ):
181
+ gateway.online = False
182
+ gateway.peer = None
183
+
184
+ async def async_close(self) -> None:
185
+ """Forget runtime sessions without owning the shared listener."""
186
+ for gateway in self._gateways.values():
187
+ gateway.online = False
188
+ gateway.peer = None
189
+
190
+ async def _async_send_fastcon(self, frame: bytes) -> int:
191
+ """Wrap and fan out one FastCon frame through active inbound sessions."""
192
+ gateways = list(self.online_gateways)
193
+ if not gateways:
194
+ return 0
195
+ _LOGGER.debug(
196
+ "Sending FastCon frame gateways=%s frame=%s",
197
+ [gateway.mac for gateway in gateways],
198
+ frame.hex(),
199
+ )
200
+ if self._sender is None:
201
+ return 0
202
+ successful = 0
203
+ for gateway in gateways:
204
+ assert gateway.peer is not None
205
+ self._sender(
206
+ pack_message(MSG_CONTROL, self._next_gateway_seq(), frame),
207
+ gateway.peer,
208
+ )
209
+ successful += 1
210
+ return successful
211
+
212
+ async def send_remote_payloads(
213
+ self,
214
+ short_addr: int,
215
+ payloads: Iterable[bytes],
216
+ ) -> int:
217
+ """Encode and fan out remote payloads to every online RM Max."""
218
+ sent = 0
219
+ source_addr = bytes.fromhex(self.family.bletoken)[-1]
220
+ for payload in payloads:
221
+ frame = device_control(
222
+ short_addr,
223
+ payload,
224
+ seq=self._next_fastcon_seq(),
225
+ source_addr=source_addr,
226
+ )
227
+ frame = apply_family_token(frame, self.family.bletoken)
228
+ sent += await self._async_send_fastcon(frame)
229
+ return sent
230
+
231
+ async def send_scene(self, scene_id: int) -> int:
232
+ """Activate a stored scene on every online RM Max."""
233
+ source_addr = bytes.fromhex(self.family.bletoken)[-1]
234
+ frame = scene_control(
235
+ scene_id,
236
+ seq=self._next_fastcon_seq(),
237
+ source_addr=source_addr,
238
+ )
239
+ frame = apply_family_token(frame, self.family.bletoken)
240
+ return await self._async_send_fastcon(frame)
241
+
242
+ async def send_status_query(
243
+ self,
244
+ addresses: Iterable[int],
245
+ *,
246
+ delay: int = 0,
247
+ ) -> int:
248
+ """Query device status through every active family gateway."""
249
+ gateways = list(self.online_gateways)
250
+ if not gateways or self._sender is None:
251
+ return 0
252
+ query_addresses = list(addresses)
253
+ sent = 0
254
+ for gateway in gateways:
255
+ assert gateway.peer is not None
256
+ packet = pack_status_query(
257
+ query_addresses,
258
+ sequence=self._next_gateway_seq(),
259
+ delay=delay,
260
+ )
261
+ _LOGGER.debug(
262
+ "Sending status query gateway=%s peer=%s addresses=%s frame=%s",
263
+ gateway.mac,
264
+ gateway.peer,
265
+ query_addresses,
266
+ packet.hex(),
267
+ )
268
+ self._sender(packet, gateway.peer)
269
+ sent += 1
270
+ return sent
@@ -0,0 +1,353 @@
1
+ """Magic Home family import payload parsing."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import binascii
7
+ import json
8
+ from collections.abc import Mapping
9
+ from typing import Any
10
+
11
+ from .const import RM_MAX_PID
12
+ from .exceptions import ImportDataError
13
+ from .models import (
14
+ DeviceKind,
15
+ Family,
16
+ ImportedDevice,
17
+ ImportedGroup,
18
+ ImportedScene,
19
+ Room,
20
+ VirtualSubToken,
21
+ normalize_mac,
22
+ normalize_pid,
23
+ rm_profile_for_pid,
24
+ )
25
+
26
+
27
+ def _get(mapping: Mapping[str, Any], *names: str, default: Any = None) -> Any:
28
+ for name in names:
29
+ if name in mapping:
30
+ return mapping[name]
31
+ return default
32
+
33
+
34
+ def _string(value: object, default: str = "") -> str:
35
+ if value is None:
36
+ return default
37
+ if not isinstance(value, (str, int, float)):
38
+ raise ImportDataError("text field has an invalid type")
39
+ return str(value)
40
+
41
+
42
+ def _optional_int(value: object) -> int | None:
43
+ if value is None or value == "":
44
+ return None
45
+ if isinstance(value, bool) or not isinstance(value, (int, str)):
46
+ raise ImportDataError("integer field has an invalid type")
47
+ try:
48
+ return int(str(value), 0)
49
+ except ValueError as err:
50
+ raise ImportDataError("integer field has an invalid value") from err
51
+
52
+
53
+ def _decode_mtag(value: object) -> object:
54
+ if not isinstance(value, str) or not value:
55
+ raise ImportDataError("mtag data must be a non-empty base64 string")
56
+ try:
57
+ decoded = base64.b64decode(value, validate=True)
58
+ except (binascii.Error, ValueError) as err:
59
+ raise ImportDataError("invalid mtag base64 data") from err
60
+ try:
61
+ return json.loads(decoded)
62
+ except (UnicodeDecodeError, json.JSONDecodeError) as err:
63
+ raise ImportDataError("mtag data is not valid JSON") from err
64
+
65
+
66
+ def _parse_rooms(data: Mapping[str, Any]) -> list[Room]:
67
+ room_list = _get(data, "roomlist", "roomList", default=[])
68
+ if not isinstance(room_list, list):
69
+ raise ImportDataError("family roomlist must be an array")
70
+ rooms: list[Room] = []
71
+ for item in room_list:
72
+ if not isinstance(item, Mapping):
73
+ continue
74
+ room_id = _optional_int(_get(item, "roomId", "roomid", default=0))
75
+ rooms.append(
76
+ Room(
77
+ room_id=room_id or 0,
78
+ name=_string(_get(item, "roomName", "name", default="")),
79
+ )
80
+ )
81
+ return rooms
82
+
83
+
84
+ def _parse_functions(data: Mapping[str, Any]) -> dict[str, int]:
85
+ """Return RM child key names mapped to the command codes in functionList."""
86
+ function_list: object = None
87
+ for key in ("extend", "extendInfo"):
88
+ extend = data.get(key)
89
+ if isinstance(extend, str) and extend.strip():
90
+ try:
91
+ extend = json.loads(extend)
92
+ except json.JSONDecodeError:
93
+ continue
94
+ if isinstance(extend, Mapping):
95
+ function_list = _get(extend, "functionList", "functionlist")
96
+ if isinstance(function_list, list):
97
+ break
98
+ if not isinstance(function_list, list):
99
+ return {}
100
+ functions: dict[str, int] = {}
101
+ for item in function_list:
102
+ if not isinstance(item, Mapping):
103
+ continue
104
+ function = _string(_get(item, "function")).strip()
105
+ # Learned keys all use function "extend" and are told apart by name.
106
+ name = _string(_get(item, "name")).strip() if function == "extend" else function
107
+ try:
108
+ code = _optional_int(_get(item, "type"))
109
+ except ImportDataError:
110
+ continue
111
+ if name and code is not None and 0 <= code <= 0xFF:
112
+ functions.setdefault(name, code)
113
+ return functions
114
+
115
+
116
+ def _parse_channel_names(data: Mapping[str, Any]) -> list[str]:
117
+ """Return switch key names from vGroups, indexed by channel."""
118
+ groups = _get(data, "vGroups", "vgroups")
119
+ if not isinstance(groups, list):
120
+ return []
121
+ names: dict[int, str] = {}
122
+ for group in groups:
123
+ if not isinstance(group, Mapping) or group.get("ignoreflag"):
124
+ continue
125
+ try:
126
+ channel = _optional_int(_get(group, "channel"))
127
+ except ImportDataError:
128
+ continue
129
+ if channel is not None and 0 <= channel <= 7:
130
+ names.setdefault(channel, _string(_get(group, "name")).strip())
131
+ if not names:
132
+ return []
133
+ return [names.get(channel, "") for channel in range(max(names) + 1)]
134
+
135
+
136
+ def _parse_device(data: Mapping[str, Any]) -> ImportedDevice:
137
+ short_addr = _optional_int(_get(data, "shortaddr", "shortAddr"))
138
+ devtype = _optional_int(_get(data, "devtype", "devType"))
139
+ channel_names = _parse_channel_names(data)
140
+ channel_count = (
141
+ max(_optional_int(_get(data, "cnt", "channelCount")) or 0, len(channel_names))
142
+ or 1
143
+ )
144
+ mac = normalize_mac(_string(_get(data, "mac", "deviceid", "deviceId")))
145
+ return ImportedDevice(
146
+ did=_string(_get(data, "did", "deviceid", "deviceId")),
147
+ pid=_string(_get(data, "pid", "devpid", "devPid")),
148
+ name=_string(_get(data, "devname", "name", default="BroadLink device")),
149
+ mac=mac,
150
+ sdid=_string(_get(data, "sdid")),
151
+ spid=_string(_get(data, "spid")),
152
+ short_addr=short_addr,
153
+ ble_category=_string(_get(data, "blecatetory", "blecategory")),
154
+ ble_device_type=_string(_get(data, "bledevtype")),
155
+ devtype=devtype,
156
+ room_id=_optional_int(_get(data, "roomId", "roomid")),
157
+ token=_string(_get(data, "token", "aeskey", "aesKey")),
158
+ bletoken=_string(_get(data, "bletoken")),
159
+ version=_string(_get(data, "version")),
160
+ channel_count=max(1, min(8, channel_count)),
161
+ channel_names=channel_names,
162
+ functions=_parse_functions(data),
163
+ raw=dict(data),
164
+ )
165
+
166
+
167
+ def mark_rm_children(devices: list[ImportedDevice]) -> None:
168
+ """Associate RM children after a complete imported device list is available."""
169
+ gateways_by_did: dict[str, list[ImportedDevice]] = {}
170
+ for device in devices:
171
+ if (
172
+ normalize_pid(device.pid) == RM_MAX_PID
173
+ and not device.sdid
174
+ and device.ble_device_type.upper() != "GROUP"
175
+ ):
176
+ gateways_by_did.setdefault(device.did, []).append(device)
177
+
178
+ for device in devices:
179
+ if device.ble_device_type.upper() == "GROUP" or not device.sdid:
180
+ continue
181
+ normalized_sdid = (
182
+ device.sdid.lower().replace(":", "").replace("-", "").replace("_", "")
183
+ )
184
+ for gateway in gateways_by_did.get(device.did, []):
185
+ gateway_mac = normalize_mac(gateway.mac or gateway.did)
186
+ if (
187
+ gateway is not device
188
+ and gateway_mac
189
+ and normalized_sdid.startswith(gateway_mac)
190
+ ):
191
+ device.is_rm_child = True
192
+ device.rm_profile = rm_profile_for_pid(device.spid)
193
+ break
194
+
195
+
196
+ def _parse_virtual_subtokens(value: object) -> list[VirtualSubToken]:
197
+ if value is None:
198
+ return []
199
+ if not isinstance(value, list):
200
+ raise ImportDataError("vtsubtoken must be an array")
201
+ result: list[VirtualSubToken] = []
202
+ for item in value:
203
+ if not isinstance(item, Mapping):
204
+ raise ImportDataError("vtsubtoken entry must be an object")
205
+ result.append(
206
+ VirtualSubToken(
207
+ did=_string(_get(item, "did")),
208
+ pid=_string(_get(item, "pid")),
209
+ token=_string(_get(item, "token")),
210
+ type=_string(_get(item, "type")),
211
+ )
212
+ )
213
+ return result
214
+
215
+
216
+ def _parse_group(data: Mapping[str, Any]) -> ImportedGroup:
217
+ group_id = _optional_int(_get(data, "groupId", "groupid"))
218
+ if group_id is None:
219
+ raise ImportDataError("groupId is required")
220
+ members = _get(data, "containDidList", "containDidlist", default=[])
221
+ if not isinstance(members, list):
222
+ members = []
223
+ return ImportedGroup(
224
+ group_id=group_id,
225
+ name=_string(_get(data, "groupName", "name", default=f"Group {group_id}")),
226
+ ble_category=_string(_get(data, "blecatetory", "blecategory")),
227
+ room_id=_optional_int(_get(data, "roomId", "roomid")),
228
+ room_name=_string(_get(data, "roomName", "room")),
229
+ member_ids=[_string(member) for member in members],
230
+ )
231
+
232
+
233
+ def _parse_scene(data: Mapping[str, Any]) -> ImportedScene:
234
+ scene_id = _string(_get(data, "moduleid", "sceneId", "sceneid"))
235
+ if not scene_id:
236
+ raise ImportDataError("scene moduleid is required")
237
+ modules = _get(data, "moduledev", default=[])
238
+ if not isinstance(modules, list):
239
+ modules = []
240
+ return ImportedScene(
241
+ scene_id=scene_id,
242
+ name=_string(_get(data, "name", default=f"Scene {scene_id}")),
243
+ room_id=_optional_int(_get(data, "roomId", "roomid")),
244
+ room_name=_string(_get(data, "room", "roomName")),
245
+ module_devices=[
246
+ dict(module) for module in modules if isinstance(module, Mapping)
247
+ ],
248
+ )
249
+
250
+
251
+ def parse_import_payload(body: bytes) -> list[Family]:
252
+ """Parse the Magic Home family import request body.
253
+
254
+ Every malformed body raises ImportDataError, whose message never contains
255
+ values from the body.
256
+ """
257
+ try:
258
+ return _parse_import_payload(body)
259
+ except ImportDataError:
260
+ raise
261
+ except (AttributeError, KeyError, TypeError, ValueError) as err:
262
+ raise ImportDataError("import body has an unexpected structure") from err
263
+
264
+
265
+ def _parse_import_payload(body: bytes) -> list[Family]:
266
+ if not body:
267
+ raise ImportDataError("import body is empty")
268
+ try:
269
+ payload = json.loads(body)
270
+ except (UnicodeDecodeError, json.JSONDecodeError) as err:
271
+ raise ImportDataError("import body is not valid JSON") from err
272
+ if not isinstance(payload, list) or not payload:
273
+ raise ImportDataError("import body must be a non-empty array")
274
+
275
+ families: list[Family] = []
276
+ for bundle in payload:
277
+ if not isinstance(bundle, Mapping):
278
+ raise ImportDataError("family import entry must be an object")
279
+ family_id = _string(_get(bundle, "did"))
280
+ if not family_id:
281
+ raise ImportDataError("family did is required")
282
+
283
+ family_info: Mapping[str, Any] = {}
284
+ devices: list[ImportedDevice] = []
285
+ groups: list[ImportedGroup] = []
286
+ scenes: list[ImportedScene] = []
287
+ data_list = _get(bundle, "dataList", "datalist", default=[])
288
+ if not isinstance(data_list, list):
289
+ raise ImportDataError("dataList must be an array")
290
+ for mtag_entry in data_list:
291
+ if not isinstance(mtag_entry, Mapping):
292
+ raise ImportDataError("dataList entry must be an object")
293
+ mtag = _string(_get(mtag_entry, "mtag"))
294
+ decoded = _decode_mtag(_get(mtag_entry, "data"))
295
+ if mtag == "familyInfo":
296
+ if not isinstance(decoded, Mapping):
297
+ raise ImportDataError("familyInfo must decode to an object")
298
+ family_info = decoded
299
+ elif mtag == "devlist":
300
+ if not isinstance(decoded, list):
301
+ raise ImportDataError("devlist must decode to an array")
302
+ devices = [
303
+ _parse_device(item) for item in decoded if isinstance(item, Mapping)
304
+ ]
305
+ elif mtag == "grouplist":
306
+ if not isinstance(decoded, list):
307
+ raise ImportDataError("grouplist must decode to an array")
308
+ for item in decoded:
309
+ if not isinstance(item, Mapping):
310
+ continue
311
+ try:
312
+ groups.append(_parse_group(item))
313
+ except ImportDataError:
314
+ continue
315
+ elif mtag == "scenelist":
316
+ if not isinstance(decoded, list):
317
+ raise ImportDataError("scenelist must decode to an array")
318
+ for item in decoded:
319
+ if not isinstance(item, Mapping):
320
+ continue
321
+ try:
322
+ scenes.append(_parse_scene(item))
323
+ except ImportDataError:
324
+ continue
325
+
326
+ mark_rm_children(devices)
327
+ for device in devices:
328
+ if device.kind is DeviceKind.GATEWAY and not device.mac:
329
+ device.mac = normalize_mac(device.did)
330
+ bletoken = _string(
331
+ _get(family_info, "bletoken", "bleToken", default=bundle.get("token", ""))
332
+ ).strip()
333
+ try:
334
+ token = bytes.fromhex(bletoken)
335
+ except ValueError as err:
336
+ raise ImportDataError("family bletoken must be hexadecimal") from err
337
+ if not token:
338
+ raise ImportDataError("family bletoken is required")
339
+ families.append(
340
+ Family(
341
+ family_id=family_id,
342
+ name=_string(_get(family_info, "name", default=family_id)),
343
+ bletoken=bletoken,
344
+ pid=_string(_get(bundle, "pid")),
345
+ token=_string(_get(bundle, "token")),
346
+ rooms=_parse_rooms(family_info),
347
+ devices=devices,
348
+ groups=groups,
349
+ scenes=scenes,
350
+ virtual_subtokens=_parse_virtual_subtokens(_get(bundle, "vtsubtoken")),
351
+ )
352
+ )
353
+ return families