@jessicaisleep/dsh-mihome 1.0.0 → 2.0.0

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.
Files changed (51) hide show
  1. package/README.md +141 -78
  2. package/client.js +1149 -19
  3. package/cordis.patch.yml +2 -2
  4. package/docs/REPAIR-VALIDATION.md +62 -0
  5. package/lib/bridge.js +126 -44
  6. package/lib/connections.js +46 -0
  7. package/lib/format.js +148 -0
  8. package/lib/index.js +274 -31
  9. package/lib/panel.js +138 -7
  10. package/locale/en.json +3 -3
  11. package/locale/zh.json +2 -2
  12. package/package.json +13 -4
  13. package/python/app/core/service.py +62 -31
  14. package/python/mihome_bridge.py +211 -9
  15. package/python/smart_home/__init__.py +24 -0
  16. package/python/smart_home/adapters/__init__.py +50 -0
  17. package/python/smart_home/adapters/base.py +143 -0
  18. package/python/smart_home/adapters/ble.py +100 -0
  19. package/python/smart_home/adapters/dlna.py +227 -0
  20. package/python/smart_home/adapters/home_assistant.py +454 -0
  21. package/python/smart_home/adapters/hue.py +225 -0
  22. package/python/smart_home/adapters/kasa.py +239 -0
  23. package/python/smart_home/adapters/mihome.py +342 -0
  24. package/python/smart_home/adapters/network.py +250 -0
  25. package/python/smart_home/adapters/shelly.py +289 -0
  26. package/python/smart_home/adapters/tuya.py +95 -0
  27. package/python/smart_home/adapters/tv.py +26 -0
  28. package/python/smart_home/catalog.py +336 -0
  29. package/python/smart_home/cloud.py +85 -0
  30. package/python/smart_home/discovery.py +934 -0
  31. package/python/smart_home/localize.py +787 -0
  32. package/python/smart_home/manager.py +672 -0
  33. package/python/smart_home/oui_table.py +40550 -0
  34. package/python/smart_home/scan.py +73 -0
  35. package/python/smart_home/test_discovery_repairs.py +186 -0
  36. package/python/smart_home/test_localization_repairs.py +229 -0
  37. package/python/smart_home/test_offline.py +195 -0
  38. package/python/smart_home/test_repairs.py +107 -0
  39. package/python/smart_home/util.py +320 -0
  40. package/python/tests/test_bridge_integration.py +108 -0
  41. package/python/tests/test_ha_discovery.py +260 -0
  42. package/python/tests/test_home_assistant.py +365 -0
  43. package/python/tests/test_manager_integration.py +150 -0
  44. package/python/tests/test_mihome_repairs.py +117 -0
  45. package/python/tests/test_network_read_contract.py +50 -0
  46. package/python/tests/test_power_confirmation.py +95 -0
  47. package/python/tests/test_protocol_repairs.py +369 -0
  48. package/python/tests/test_yeelight_repairs.py +70 -0
  49. package/requirements-optional.txt +4 -0
  50. package/requirements.txt +5 -0
  51. package/scripts/update-oui.py +108 -0
@@ -0,0 +1,672 @@
1
+ # SPDX-License-Identifier: GPL-3.0-or-later
2
+ """Unify discovered and configured home-device adapters.
3
+
4
+ The manager exposes device identity, observed capabilities, private connection
5
+ injection, read/write operations and manually run user-defined scenes. It does
6
+ not infer writable controls from a device category. Scene steps are recorded
7
+ individually and later steps continue after an earlier step fails.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import os
14
+ import tempfile
15
+ import time
16
+ import uuid
17
+ from pathlib import Path
18
+
19
+ from . import catalog, discovery, localize
20
+ from .adapters import get_adapter_class
21
+
22
+
23
+ _STATE_UNSET = object()
24
+
25
+
26
+ def _now() -> float:
27
+ return time.time()
28
+
29
+
30
+ def _ts() -> str:
31
+ return time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime())
32
+
33
+
34
+ # 指纹识别出的「更细的厂商协议」映射到实际能用的适配器。
35
+ #
36
+ # 扫描层出于展示需要会给出 tplink / h3c / openwrt / synology / qnap 这类
37
+ # 更具体的协议名(用户一眼能看出是什么牌子),但它们没有独立适配器——
38
+ # 它们全都靠「扒管理页」工作,走 _PageAdapter 那一族即可。少了这张表,
39
+ # 扫到的路由器点开会报「没有 tplink 协议的适配器」。
40
+ _ADAPTER_ALIASES: dict[str, str] = {
41
+ "tplink": "router",
42
+ "h3c": "router",
43
+ "openwrt": "router",
44
+ "mirouter": "router",
45
+ "synology": "nas",
46
+ "qnap": "nas",
47
+ "truenas": "nas",
48
+ # 海信 / TCL 电视:目前没有专门的本地控制适配器(各家协议不统一),
49
+ # 先按「能开管理页的 HTTP 设备」展示,不假装能控制。
50
+ "hisense_tv": "http",
51
+ "tcl_tv": "http",
52
+ "airplay": "cast",
53
+ "mdns": "cast",
54
+ "matter": "http",
55
+ "homekit": "http",
56
+ "mqtt": "http",
57
+ }
58
+
59
+
60
+ class SmartHomeManager:
61
+ """全屋智能家居统一管理器。"""
62
+
63
+ def __init__(self, config: dict | None = None):
64
+ self.config = dict(config or {})
65
+ self.data_dir = Path(self.config.get("data_dir") or "data")
66
+ self.cloud = self.config.get("cloud")
67
+ self._scan: dict = {}
68
+ self._scan_at: float = 0.0
69
+ self._scan_key: tuple = ()
70
+ self._adapters: dict[str, object] = {}
71
+ self._connections: dict[str, dict] = {}
72
+ self._discovered_credentials: dict[str, dict] = {}
73
+ self._connection_refs: dict[str, str] = {}
74
+
75
+ def _connection_for(self, device_id: str) -> dict:
76
+ key = self._connection_refs.get(device_id, device_id)
77
+ return dict(self._connections.get(key, {}))
78
+
79
+ async def set_connections(self, connections: dict) -> None:
80
+ if not isinstance(connections, dict) or any(not isinstance(v, dict) for v in connections.values()):
81
+ raise ValueError("连接配置必须是设备 ID 到对象的映射")
82
+ if connections == self._connections:
83
+ return
84
+ await self.close()
85
+ self._connections = {str(k): dict(v) for k, v in connections.items()}
86
+ self._connection_refs.clear()
87
+ self._scan = {}
88
+ self._scan_at = 0
89
+
90
+ # ------------------------------------------------------------------ 扫描
91
+
92
+ async def scan(
93
+ self,
94
+ subnets: list[str] | None = None,
95
+ prefix: int = 24,
96
+ extra_subnets: list[str] | None = None,
97
+ ports: list[int] | None = None,
98
+ scan_ping: bool = True,
99
+ force: bool = False,
100
+ ) -> dict:
101
+ """扫描网段,返回统一设备列表。
102
+
103
+ 默认缓存 60 秒,避免面板反复点刷新就反复扫网。``force=True`` 强制
104
+ 重新扫描。
105
+ """
106
+ options = discovery.normalize_scan_options(subnets, prefix, extra_subnets, ports, scan_ping)
107
+ subnets, prefix, extra_subnets, ports, scan_ping = options
108
+ scan_key = (
109
+ tuple(sorted(str(x) for x in (subnets or []))),
110
+ int(prefix),
111
+ tuple(sorted(str(x) for x in (extra_subnets or []))),
112
+ tuple(sorted(int(x) for x in ports)),
113
+ bool(scan_ping),
114
+ )
115
+ if not force and self._scan and self._scan_key == scan_key and (_now() - self._scan_at) < 60:
116
+ return {"devices": self._scan["devices"], "cached": True, "scanned_at": self._scan_at}
117
+
118
+ found = await discovery.discover_all(
119
+ subnets=subnets,
120
+ prefix=prefix,
121
+ extra_subnets=extra_subnets,
122
+ ports=ports,
123
+ scan_ping=scan_ping,
124
+ )
125
+ self._discovered_credentials.clear()
126
+ devices = [self._build_device(d) for d in found]
127
+
128
+ # 叠加米家云端设备(只加未被局域网识别到的,避免重复)
129
+ try:
130
+ cloud_devices = await self._cloud_devices()
131
+ except Exception as exc: # noqa: BLE001 - 云端没登录不阻断局域网扫描
132
+ print(f"[smart-home] 米家云端设备读取失败:{exc}")
133
+ cloud_devices = []
134
+ seen_ids = {d["id"] for d in devices}
135
+ for device in cloud_devices:
136
+ if device["id"] in seen_ids:
137
+ continue
138
+ devices.append(device)
139
+
140
+ old_adapters = self._adapters
141
+ self._adapters = {}
142
+ for adapter in old_adapters.values():
143
+ try:
144
+ await adapter.close()
145
+ except Exception: # noqa: BLE001 - one adapter must not block a rescan
146
+ pass
147
+ # Configured endpoints also work without multicast or ping discovery.
148
+ for device_id, connection in self._connections.items():
149
+ if any(d["id"] == device_id for d in devices):
150
+ continue
151
+ protocol = device_id.split(":", 1)[0]
152
+ devices.append({"id": device_id, "protocol": protocol,
153
+ "name": str(connection.get("name") or device_id),
154
+ "ip": str(connection.get("ip") or ""), "ports": [],
155
+ "category": str(connection.get("category") or "other"),
156
+ "category_zh": catalog.category_zh(connection.get("category") or "other"),
157
+ "category_en": catalog.category_en(connection.get("category") or "other"),
158
+ "source": "configured", "fields": {}, "controls": [], "online": None})
159
+ expanded = []
160
+ self._connection_refs.clear()
161
+ ids = {d["id"] for d in devices}
162
+ for device in devices:
163
+ if device["protocol"] != "home_assistant":
164
+ continue
165
+ # Explicitly configured entities are leaves, not hubs to expand.
166
+ if self._connection_for(device["id"]).get("entity_id"):
167
+ continue
168
+ try:
169
+ hub = self._adapter_for(device)
170
+ for raw in await hub.discover_entities():
171
+ entity_id = str(raw.get("entity_id") or raw.get("fields", {}).get("entity_id") or "")
172
+ if not entity_id:
173
+ continue
174
+ # A HA entity ID is unique only inside its own instance.
175
+ entity = dict(raw)
176
+ entity["id"] = f"{device['id']}/{entity_id}"
177
+ if entity["id"] in ids:
178
+ continue
179
+ ids.add(entity["id"])
180
+ category = entity.get("category") or "other"
181
+ entity.update(category=category, category_zh=catalog.category_zh(category),
182
+ category_en=catalog.category_en(category), source="home_assistant",
183
+ ip=device.get("ip", ""), ports=[], controls=[],
184
+ fields={**entity.get("fields", {}), "entity_id": entity_id})
185
+ self._connection_refs[entity["id"]] = device["id"]
186
+ expanded.append(entity)
187
+ except Exception:
188
+ device["connection_error"] = "Home Assistant 连接失败,请检查地址、访问令牌与网络"
189
+ devices.extend(expanded)
190
+ for device in devices:
191
+ device["configured"] = self._connection_refs.get(device["id"], device["id"]) in self._connections
192
+ self._scan = {"devices": devices}
193
+ self._scan_key = scan_key
194
+ self._scan_at = _now()
195
+ return {"devices": devices, "cached": False, "scanned_at": self._scan_at,
196
+ "scan_time": _ts()}
197
+
198
+ async def devices(self, refresh: bool = False) -> list[dict]:
199
+ result = await self.scan(force=refresh)
200
+ return result["devices"]
201
+
202
+ # ------------------------------------------------------------------ 设备
203
+
204
+ def _build_device(self, scanned) -> dict:
205
+ """把扫描结果整理成统一设备结构。"""
206
+ protocol = str(getattr(scanned, "protocol", "unknown") or "unknown")
207
+ ip = str(getattr(scanned, "ip", "") or "")
208
+ mac = str(getattr(scanned, "mac", "") or "")
209
+ raw_fields = dict(getattr(scanned, "fields", {}) or {})
210
+ fields = discovery._public_value(raw_fields)
211
+ address = str(getattr(scanned, "address", "") or fields.get("address") or mac)
212
+ identity = (
213
+ ip
214
+ or address
215
+ or str(fields.get("device_id") or fields.get("uuid") or fields.get("gw_id") or "")
216
+ or str(getattr(scanned, "name", "") or "")
217
+ )
218
+ device_id = f"{protocol}:{identity}" if identity else f"{protocol}:unknown"
219
+ private = dict(getattr(scanned, "credentials", {}) or {})
220
+ private.update({k: v for k, v in raw_fields.items() if discovery._SENSITIVE_FIELD_RE.search(str(k))})
221
+ if private:
222
+ self._discovered_credentials[device_id] = private
223
+ category = getattr(scanned, "category", "other") or "other"
224
+ name = getattr(scanned, "name", "") or ""
225
+ if not name:
226
+ name = getattr(scanned, "http_title", "") or device_id
227
+ if address and "address" not in fields:
228
+ fields["address"] = address
229
+ return {
230
+ "id": device_id,
231
+ "name": name,
232
+ "model": getattr(scanned, "model", "") or "",
233
+ "category": category,
234
+ "category_zh": catalog.category_zh(category),
235
+ "category_en": catalog.category_en(category),
236
+ "protocol": protocol,
237
+ "platform": getattr(scanned, "platform", "") or "",
238
+ "ip": ip,
239
+ "mac": mac,
240
+ "vendor": getattr(scanned, "vendor", "") or "",
241
+ "ports": list(getattr(scanned, "ports", []) or []),
242
+ "online": True,
243
+ "source": "lan",
244
+ "controls": [],
245
+ "fields": fields,
246
+ }
247
+
248
+ async def _cloud_devices(self) -> list[dict]:
249
+ """读取米家云端设备,映射成统一结构。"""
250
+ if self.cloud is None:
251
+ return []
252
+ devices = self.cloud.list_devices()
253
+ out: list[dict] = []
254
+ for item in devices or []:
255
+ did = str(item.get("did") or "")
256
+ if not did:
257
+ continue
258
+ category = catalog.guess_category(str(item.get("model") or ""), str(item.get("name") or ""))
259
+ out.append({
260
+ "id": f"mihome:{did}",
261
+ "name": str(item.get("name") or ""),
262
+ "model": str(item.get("model") or ""),
263
+ "category": category,
264
+ "category_zh": catalog.category_zh(category),
265
+ "category_en": catalog.category_en(category),
266
+ "protocol": "mihome",
267
+ "platform": "mihome",
268
+ "ip": str(item.get("ip") or ""),
269
+ "mac": "",
270
+ "vendor": "",
271
+ "ports": [],
272
+ "online": bool(item.get("online")),
273
+ "source": "cloud",
274
+ "room": str(item.get("room_name") or ""),
275
+ "home": str(item.get("home_name") or ""),
276
+ "controls": [],
277
+ "fields": {},
278
+ })
279
+ return out
280
+
281
+ def _find_device(self, device_id: str) -> dict | None:
282
+ requested = str(device_id or "").strip()
283
+ if not requested:
284
+ return None
285
+ devices = self._scan.get("devices", [])
286
+ for device in devices:
287
+ if str(device.get("id") or "") == requested:
288
+ return device
289
+ # 米家工具历史上接受裸 did;只对明确的 mihome:<did> 做前缀兼容,
290
+ # 避免 endswith 把任意设备误匹配到另一个设备。
291
+ for device in devices:
292
+ current = str(device.get("id") or "")
293
+ if current.startswith("mihome:") and current.split(":", 1)[1] == requested:
294
+ return device
295
+ if current.startswith("ble:") and current.split(":", 1)[1] == requested:
296
+ return device
297
+ return None
298
+
299
+ async def device(self, device_id: str, refresh: bool = False) -> dict:
300
+ """设备详情:能力项 + 当前值 + 动作。"""
301
+ if refresh or not self._scan.get("devices"):
302
+ await self.scan(force=refresh)
303
+ found = self._find_device(device_id)
304
+ if found is None:
305
+ raise ValueError(f"找不到设备:{device_id}(先扫描,或检查设备 id)")
306
+ adapter = self._adapter_for(found)
307
+ detail = dict(found)
308
+ try:
309
+ controls = localize.localize_controls(await adapter.list_capabilities(), found["protocol"])
310
+ except Exception:
311
+ detail.update(controls=[], values={}, capability_error="无法读取设备能力,请检查连接配置或配对状态")
312
+ return detail
313
+ values: dict = {}
314
+ try:
315
+ values = await adapter.read_all()
316
+ except Exception: # noqa: BLE001 - 读失败也要把能力项还给前端
317
+ detail["read_error"] = "设备状态读取失败,请检查连接配置或网络"
318
+ detail["controls"] = controls
319
+ detail["values"] = values
320
+ detail["adapter"] = adapter.protocol
321
+ return detail
322
+
323
+ def _adapter_for(self, device: dict):
324
+ key = device["id"]
325
+ if key in self._adapters:
326
+ return self._adapters[key]
327
+ protocol = device["protocol"]
328
+ cls = get_adapter_class(protocol)
329
+ if cls is None:
330
+ cls = get_adapter_class(_ADAPTER_ALIASES.get(protocol, ""))
331
+ if cls is None:
332
+ raise ValueError(f"没有 {protocol} 协议的适配器")
333
+ connection = self._connection_for(key)
334
+ source_key = self._connection_refs.get(key, key)
335
+ source_device = device if source_key == key else (self._find_device(source_key) or device)
336
+ # Discovered HA base URLs are public transport metadata; explicit user
337
+ # connection settings always win, and children inherit the hub endpoint.
338
+ if protocol == "home_assistant" and not connection.get("base_url"):
339
+ base_url = source_device.get("fields", {}).get("base_url")
340
+ if base_url:
341
+ connection["base_url"] = base_url
342
+ credentials = {**self._discovered_credentials.get(source_key, {}), **connection}
343
+ scanned = _ScannedView(device, credentials)
344
+ adapter = cls(scanned, {**self.config, **connection, "cloud": self.cloud})
345
+ self._adapters[key] = adapter
346
+ return adapter
347
+
348
+ async def read_states(self, device_ids: list[str]) -> dict:
349
+ """批量读多台设备的当前值(面板首屏用)。"""
350
+ if not self._scan.get("devices"):
351
+ await self.scan()
352
+ out: dict = {}
353
+ for device_id in device_ids:
354
+ try:
355
+ adapter = self._adapter_for(self._require(device_id))
356
+ out[device_id] = await adapter.read_all()
357
+ except Exception as exc: # noqa: BLE001 - 单台失败不影响其余
358
+ print(f"[smart-home] 读取 {device_id} 失败:{exc}")
359
+ out[device_id] = {}
360
+ return out
361
+
362
+ def _require(self, device_id: str) -> dict:
363
+ found = self._find_device(device_id)
364
+ if found is None:
365
+ raise ValueError(f"找不到设备:{device_id}")
366
+ return found
367
+
368
+ # ------------------------------------------------------------------ 控制
369
+
370
+ async def control(
371
+ self,
372
+ device_id: str,
373
+ mode: str,
374
+ name: str = "",
375
+ value=None,
376
+ params: dict | None = None,
377
+ state=_STATE_UNSET,
378
+ ) -> dict:
379
+ """统一控制入口。
380
+
381
+ mode:
382
+ - ``power``:开关;``state`` 省略时取反。
383
+ - ``write``:写某个能力项(``name`` 是能力项 key,如 ``brightness``)。
384
+ - ``action``:执行动作(``name`` 是动作名)。
385
+ - ``scrape``:扒设置页。
386
+ """
387
+ if mode == "power" and state is None:
388
+ raise ValueError("state 不能为 null;省略 state 才表示切换电源")
389
+ if mode == "scrape":
390
+ return await self.scrape(device_id)
391
+ if not self._scan.get("devices"):
392
+ await self.scan()
393
+ device = self._require(device_id)
394
+ adapter = self._adapter_for(device)
395
+
396
+ if mode == "power":
397
+ power_state = getattr(adapter, "power_state", None)
398
+ if state is _STATE_UNSET:
399
+ current = await power_state() if callable(power_state) else await adapter.read_capability("power")
400
+ if current is None:
401
+ raise ValueError("当前电源状态未知,请明确传入 state=true 或 false")
402
+ state = not adapter._value_for_capability("power", current)
403
+ else:
404
+ state = adapter._value_for_capability("power", state)
405
+ # 优先走专用电源方法(云端/米家),否则用能力项写入。
406
+ power_method = getattr(adapter, "power", None)
407
+ if callable(power_method):
408
+ result = await power_method(state)
409
+ else:
410
+ result = await adapter.write_capability("power", state)
411
+ if not isinstance(result, dict):
412
+ result = {"ok": False, "error": "适配器未返回有效结果"}
413
+ return {
414
+ **result,
415
+ "ok": result.get("ok") is True,
416
+ "device": device_id,
417
+ "mode": mode,
418
+ "on": adapter._value_for_capability("power", result.get("on", state)) if result.get("ok") is True else None,
419
+ }
420
+
421
+ if mode == "write":
422
+ if not name:
423
+ raise ValueError("mode=write 需要 name(能力项,如 brightness)")
424
+ result = await adapter.write_capability(name, value)
425
+ if not isinstance(result, dict):
426
+ result = {"ok": False, "error": "适配器未返回有效结果"}
427
+ return {"device": device_id, "mode": mode, "capability": name, "value": value, **result,
428
+ "ok": result.get("ok") is True}
429
+
430
+ if mode == "action":
431
+ if not name:
432
+ raise ValueError("mode=action 需要 name(动作名)")
433
+ result = await adapter.run_action(name, params)
434
+ if not isinstance(result, dict):
435
+ result = {"ok": False, "error": "适配器未返回有效结果"}
436
+ return {"device": device_id, "mode": mode, "action": name, **result,
437
+ "ok": result.get("ok") is True}
438
+
439
+ raise ValueError(f"未知 mode:{mode}(可选 power / write / action / scrape)")
440
+
441
+ async def scrape(self, device_id: str) -> dict:
442
+ """扒一台管理类设备的设置页。"""
443
+ if not self._scan.get("devices"):
444
+ await self.scan()
445
+ device = self._require(device_id)
446
+ adapter = self._adapter_for(device)
447
+ try:
448
+ data = await adapter.scrape()
449
+ except NotImplementedError as exc:
450
+ return {"ok": False, "device": device_id, "error": str(exc), "note": "该设备不支持设置页扒取"}
451
+ data.setdefault("device", device_id)
452
+ data.setdefault("protocol", device["protocol"])
453
+ return data
454
+
455
+ # ------------------------------------------------------------------ 场景
456
+
457
+ def _scenes_path(self) -> Path:
458
+ path = self.data_dir / "smart_home" / "scenes.json"
459
+ path.parent.mkdir(parents=True, exist_ok=True)
460
+ return path
461
+
462
+ def scenes_list(self) -> list[dict]:
463
+ try:
464
+ data = json.loads(self._scenes_path().read_text("utf-8"))
465
+ except FileNotFoundError:
466
+ return []
467
+ except (OSError, ValueError) as exc:
468
+ raise ValueError("场景文件无法读取,已保留原文件;请修复后重试") from exc
469
+ if not isinstance(data, dict) or not isinstance(data.get("scenes"), list) or any(not isinstance(s, dict) for s in data["scenes"]):
470
+ raise ValueError("场景文件格式无效,已保留原文件")
471
+ return data["scenes"]
472
+
473
+ def _write_scenes(self, data: dict) -> None:
474
+ """原子替换场景文件,避免写到一半断电后损坏整个场景库。"""
475
+ path = self._scenes_path()
476
+ temp_path = None
477
+ try:
478
+ with tempfile.NamedTemporaryFile(
479
+ mode="w", encoding="utf-8", dir=path.parent, prefix="scenes-", suffix=".tmp", delete=False
480
+ ) as stream:
481
+ temp_path = Path(stream.name)
482
+ json.dump(data, stream, ensure_ascii=False, indent=2)
483
+ stream.flush()
484
+ os.fsync(stream.fileno())
485
+ os.replace(temp_path, path)
486
+ finally:
487
+ if temp_path is not None:
488
+ try:
489
+ temp_path.unlink(missing_ok=True)
490
+ except OSError:
491
+ pass
492
+
493
+ @staticmethod
494
+ def _validate_scene_actions(actions) -> list[dict]:
495
+ if not isinstance(actions, list) or not actions:
496
+ raise ValueError("场景至少需要一个动作")
497
+ normalized = []
498
+ for index, action in enumerate(actions):
499
+ if not isinstance(action, dict):
500
+ raise ValueError(f"场景动作 {index + 1} 必须是对象")
501
+ device = str(action.get("device") or "").strip()
502
+ mode = str(action.get("mode") or "write").strip()
503
+ if not device:
504
+ raise ValueError(f"场景动作 {index + 1} 缺少 device")
505
+ if mode not in {"power", "write", "action", "scrape"}:
506
+ raise ValueError(f"场景动作 {index + 1} 的 mode 无效:{mode}")
507
+ if mode in {"write", "action"} and not str(action.get("name") or action.get("capability") or "").strip():
508
+ raise ValueError(f"场景动作 {index + 1} 的 {mode} 模式需要 name")
509
+ if mode == "power" and "state" in action and not isinstance(action["state"], bool):
510
+ raise ValueError(f"场景动作 {index + 1} 的 state 必须是布尔值")
511
+ normalized.append(dict(action))
512
+ return normalized
513
+
514
+ def scene_save(self, scene: dict) -> dict:
515
+ """新增或更新一个场景。``scene`` 至少要有 ``name`` 和 ``actions``。"""
516
+ if not isinstance(scene, dict):
517
+ raise ValueError("scene 必须是对象")
518
+ if not str(scene.get("name") or "").strip():
519
+ raise ValueError("场景需要 name")
520
+ actions = self._validate_scene_actions(scene.get("actions"))
521
+ data = {"scenes": self.scenes_list()}
522
+ if scene.get("id"):
523
+ for index, item in enumerate(data["scenes"]):
524
+ if item.get("id") == scene["id"]:
525
+ merged = {**item, **scene, "actions": actions}
526
+ data["scenes"][index] = merged
527
+ self._write_scenes(data)
528
+ return merged
529
+ # 新增
530
+ new = {
531
+ "id": str(uuid.uuid4()),
532
+ "name": scene["name"],
533
+ "actions": actions,
534
+ "enabled": bool(scene.get("enabled", True)),
535
+ "created_at": _ts(),
536
+ }
537
+ data["scenes"].append(new)
538
+ self._write_scenes(data)
539
+ return new
540
+
541
+ def scene_delete(self, scene_id: str) -> bool:
542
+ data = {"scenes": [s for s in self.scenes_list() if s.get("id") != scene_id]}
543
+ existed = len(data["scenes"]) != len(self.scenes_list())
544
+ if existed:
545
+ self._write_scenes(data)
546
+ return existed
547
+
548
+ async def scene_run(self, scene_id: str) -> dict:
549
+ """执行一个场景:逐个动作执行,记录每步结果。"""
550
+ scene = next((s for s in self.scenes_list() if s.get("id") == scene_id), None)
551
+ if scene is None:
552
+ raise ValueError(f"找不到场景:{scene_id}")
553
+ if not scene.get("enabled", True):
554
+ raise ValueError("该场景已停用")
555
+ results: list[dict] = []
556
+ success = 0
557
+ actions = scene.get("actions", [])
558
+ if not isinstance(actions, list):
559
+ actions = []
560
+ for index, action in enumerate(actions):
561
+ if not isinstance(action, dict):
562
+ results.append({"ok": False, "error": f"场景动作 {index + 1} 必须是对象"})
563
+ continue
564
+ device_id = str(action.get("device") or "")
565
+ mode = str(action.get("mode") or "write")
566
+ try:
567
+ out = await self.control(
568
+ device_id,
569
+ mode,
570
+ name=str(action.get("name") or action.get("capability") or ""),
571
+ value=action.get("value"),
572
+ params=action.get("params"),
573
+ **({"state": action["state"]} if "state" in action else {}),
574
+ )
575
+ action_ok = isinstance(out, dict) and out.get("ok") is True
576
+ if action_ok:
577
+ success += 1
578
+ results.append({"device": device_id, "ok": action_ok, "mode": mode, "result": out})
579
+ except Exception as exc: # noqa: BLE001 - 单步失败不中断整条场景
580
+ print(f"[smart-home] 场景 {scene_id} 动作失败 {device_id} {mode}: {exc}")
581
+ results.append({"device": device_id, "ok": False, "mode": mode, "error": str(exc)})
582
+ return {"ok": bool(results) and success == len(results), "scene": scene.get("name"), "success": success,
583
+ "total": len(results), "results": results}
584
+
585
+ # ------------------------------------------------------------------ 目录
586
+
587
+ def catalog(self) -> dict:
588
+ """返回能力项目录(中英对照),供模型与前端展示。"""
589
+ return {
590
+ "categories": [
591
+ {"key": key, "zh": catalog.category_zh(key), "en": catalog.category_en(key)}
592
+ for key in catalog.CATEGORY_LABELS
593
+ ],
594
+ "capabilities": [catalog.capability_info(key) for key in catalog.CAPABILITY_LABELS],
595
+ "enums": {
596
+ name: catalog.enum_values(name) for name in catalog.ENUM_LABELS
597
+ },
598
+ }
599
+
600
+ async def close(self) -> None:
601
+ for adapter in self._adapters.values():
602
+ try:
603
+ await adapter.close()
604
+ except Exception: # noqa: BLE001
605
+ pass
606
+ self._adapters.clear()
607
+
608
+
609
+ class _ScannedView:
610
+ """把统一设备字典包装成适配器需要的 ``device`` 对象。
611
+
612
+ 适配器基类按属性访问 ``device.ip`` / ``device.mac`` / ``device.category`` /
613
+ ``device.name`` / ``device.did``,这里统一提供。
614
+ """
615
+
616
+ def __init__(self, device: dict, credentials: dict | None = None):
617
+ self._device = device
618
+ self.credentials = dict(credentials or {})
619
+
620
+ def __getattr__(self, item):
621
+ if item.startswith("_"):
622
+ raise AttributeError(item)
623
+ return self._device.get(item, "")
624
+
625
+ @property
626
+ def ip(self) -> str:
627
+ return self._device.get("ip", "")
628
+
629
+ @property
630
+ def mac(self) -> str:
631
+ return self._device.get("mac", "")
632
+
633
+ @property
634
+ def category(self) -> str:
635
+ return self._device.get("category", "other")
636
+
637
+ @property
638
+ def name(self) -> str:
639
+ return self._device.get("name", "")
640
+
641
+ @property
642
+ def did(self) -> str:
643
+ value = self._device.get("id", "")
644
+ return value.split(":", 1)[1] if value.startswith("mihome:") else ""
645
+
646
+ @property
647
+ def fields(self) -> dict:
648
+ return self._device.get("fields", {})
649
+
650
+ @property
651
+ def ports(self) -> list[int]:
652
+ return self._device.get("ports", [])
653
+
654
+ @property
655
+ def platform(self) -> str:
656
+ return self._device.get("platform", "")
657
+
658
+ @property
659
+ def local_key(self) -> str:
660
+ return self.credentials.get("local_key", "")
661
+
662
+ @property
663
+ def version(self) -> str:
664
+ return self._device.get("fields", {}).get("version", "")
665
+
666
+ @property
667
+ def gw_id(self) -> str:
668
+ return self._device.get("fields", {}).get("gw_id", "")
669
+
670
+ @property
671
+ def dps(self) -> dict:
672
+ return self._device.get("fields", {}).get("dps", {})