@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
package/locale/en.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "meta": {
3
- "title": "Mi Home",
4
- "description": "Control Xiaomi Mi Home devices through mijiaAPI: device list, property read/write, actions and scenes, sensor readings. The Node plugin talks to a local Python bridge over JSON-Lines, and offers a Mi Home workbench in the sidebar as well as six mihome_* tools the agent can call directly."
3
+ "title": "Smart home",
4
+ "description": "Discover and manage devices in one workbench through Mi Home cloud, Home Assistant entities and supported local protocols. Includes LAN/BLE discovery, capability-based controls, private connection settings and custom scenes. Routers, ONTs, switches and NAS currently expose public management-page information; see the README for discovery-only protocols and control limits."
5
5
  }
6
- }
6
+ }
package/locale/zh.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "meta": {
3
- "title": "米家",
4
- "description": "用 mijiaAPI 控制小米米家设备:设备列表、属性读写、动作与场景执行、传感器读数。Node 插件与 Python 桥接进程之间走本地 JSON-Lines 协议,界面在侧栏提供「米家」工作台,也能被 AI 直接调用六个 mihome_* 工具。"
3
+ "title": "全屋智能",
4
+ "description": "在一个工作台发现并管理全屋设备:米家云端、Home Assistant 实体和已支持的本地协议。提供局域网/蓝牙发现、按实际能力生成的中文控件、私有连接配置与自定义场景。路由器、光猫、交换机及 NAS 当前以公开管理页读取为主;仅识别的协议与控制限制见 README。"
5
5
  }
6
6
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@jessicaisleep/dsh-mihome",
3
- "version": "1.0.0",
4
- "description": "DeepSeek Harness plugin: control Mi Home (米家) devices — list devices, read/write properties, run actions and scenes, read sensors — through mijiaAPI over a local JSON-Lines bridge, with a sidebar workbench. · 通过 mijiaAPI 本地桥接控制米家设备:设备列表、属性读写、场景执行、传感器读数,并在侧栏提供工作台面板。",
3
+ "version": "2.0.0",
4
+ "description": "DSH 全屋智能工作台:局域网与蓝牙发现、米家云端、Home Assistant 实体控制、已支持的本地协议、私有连接配置与自定义场景。控制项按设备实际能力提供;管理页读取和仅识别协议见支持矩阵。 · DSH smart-home workbench with LAN/BLE discovery, Mi Home cloud, Home Assistant entities, supported local protocols, private connection settings and custom scenes. Controls follow reported device capabilities; see the support matrix for read-only and discovery-only protocols.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
7
7
  "exports": {
@@ -22,7 +22,11 @@
22
22
  "icon.svg",
23
23
  "locale/*.json",
24
24
  "LICENSE",
25
- "README.md"
25
+ "README.md",
26
+ "requirements.txt",
27
+ "requirements-optional.txt",
28
+ "scripts/update-oui.py",
29
+ "docs/*.md"
26
30
  ],
27
31
  "license": "GPL-3.0-or-later",
28
32
  "author": "Jessicaisleep",
@@ -51,11 +55,12 @@
51
55
  }
52
56
  },
53
57
  "engines": {
54
- "dsh": ">=0.1.0-rc.6 <0.3.0-0"
58
+ "dsh": ">=0.2.2-rc.3 <0.3.0-0"
55
59
  },
56
60
  "peerDependencies": {
57
61
  "@deepseek-ai/cordis": "^4.0.1",
58
62
  "@deepseek-ai/dsh-tools": "*",
63
+ "@deepseek-ai/dsh-credentials": ">=0.2.2-rc.3 <0.3.0-0",
59
64
  "@deepseek-ai/schemastery": "^3.18.1"
60
65
  },
61
66
  "keywords": [
@@ -66,6 +71,10 @@
66
71
  "mijia",
67
72
  "xiaomi",
68
73
  "smart-home",
74
+ "tuya",
75
+ "shelly",
76
+ "router",
77
+ "home-automation",
69
78
  "cordis"
70
79
  ],
71
80
  "scripts": {
@@ -20,6 +20,7 @@ import logging
20
20
  import re
21
21
  import threading
22
22
  from concurrent.futures import ThreadPoolExecutor
23
+ from contextlib import contextmanager
23
24
  from pathlib import Path
24
25
  from typing import Any
25
26
 
@@ -102,6 +103,49 @@ def _wrap_error(exc: Exception, context: str) -> ServiceError:
102
103
  return ServiceError(f"{context}: {detail}")
103
104
 
104
105
 
106
+ def _require_device_confirmation(response) -> None:
107
+ """Only an explicit device success may be reported as a completed write."""
108
+ items = response if isinstance(response, list) else [response]
109
+ if not items or any(not isinstance(item, dict) for item in items):
110
+ raise ServiceError("未收到有效的设备执行确认,状态未知,请读取设备状态")
111
+ for item in items:
112
+ code = item.get("code")
113
+ if type(code) is int and code == 0:
114
+ continue
115
+ if type(code) is int and code == 1:
116
+ raise ServiceError("网关已接收指令,但设备执行结果未确认,请读取设备状态")
117
+ raise ServiceError(f"设置失败或未确认(错误码 {code})")
118
+
119
+
120
+ class _ConfirmedDeviceAPI:
121
+ """Keep upstream validation, but check responses before it discards them."""
122
+ def __init__(self, api):
123
+ self._api = api
124
+
125
+ def __getattr__(self, name):
126
+ return getattr(self._api, name)
127
+
128
+ def set_devices_prop(self, data):
129
+ response = self._api.set_devices_prop(data)
130
+ _require_device_confirmation(response)
131
+ return response
132
+
133
+ def run_action(self, data):
134
+ response = self._api.run_action(data)
135
+ _require_device_confirmation(response)
136
+ return response
137
+
138
+
139
+ @contextmanager
140
+ def _confirmed_device_api(device):
141
+ original = device.api
142
+ device.api = _ConfirmedDeviceAPI(original)
143
+ try:
144
+ yield
145
+ finally:
146
+ device.api = original
147
+
148
+
105
149
  def _serialized(method):
106
150
  """把服务方法串到实例锁上,避免多线程同时碰上游客户端。"""
107
151
  @functools.wraps(method)
@@ -324,7 +368,8 @@ class MijiaService:
324
368
  def write_prop(self, did: str, name: str, value) -> None:
325
369
  dev = self._get_device(did)
326
370
  try:
327
- dev.set(name, value)
371
+ with _confirmed_device_api(dev):
372
+ dev.set(name, value)
328
373
  except Exception as exc:
329
374
  raise _wrap_error(exc, f"设置属性 {name} 失败") from exc
330
375
 
@@ -332,25 +377,22 @@ class MijiaService:
332
377
  def run_action(self, did: str, name: str, params=None) -> None:
333
378
  dev = self._get_device(did)
334
379
  try:
335
- if params is not None:
336
- # 小爱类文本指令需走 _in 通道(见 mijiaAPI __main__.py:523
337
- # wifispeaker.run_action('execute-text-directive', _in=[prompt, quiet]))
338
- if name in ("execute-text-directive", "play-text", "play-music", "play-radio"):
339
- # 统一按 _in 传递,兼容单字符串与列表
340
- in_val = params if isinstance(params, (list, tuple)) else [params]
341
- # execute-text-directive 为 [文本, 是否静默](0/1),缺省按非静默补齐
342
- if name == "execute-text-directive" and len(in_val) == 1:
343
- in_val = [in_val[0], 0]
344
- dev.run_action(name, _in=in_val)
345
- elif isinstance(params, (list, tuple)):
346
- dev.run_action(name, params)
380
+ with _confirmed_device_api(dev):
381
+ if params is not None:
382
+ # 小爱文本指令使用 MIoT in 参数,保留上游参数编码。
383
+ if name in ("execute-text-directive", "play-text", "play-music", "play-radio"):
384
+ in_val = params if isinstance(params, (list, tuple)) else [params]
385
+ if name == "execute-text-directive" and len(in_val) == 1:
386
+ in_val = [in_val[0], 0]
387
+ dev.run_action(name, _in=in_val)
388
+ elif isinstance(params, (list, tuple)):
389
+ dev.run_action(name, params)
390
+ else:
391
+ dev.run_action(name, [params])
347
392
  else:
348
- dev.run_action(name, [params])
349
- else:
350
- # 文本类动作无参必报 -704220025,这里直接引导上层弹输入
351
- if name in ("execute-text-directive", "play-text"):
352
- raise ServiceError(f"动作 {name} 需要文本参数")
353
- dev.run_action(name)
393
+ if name in ("execute-text-directive", "play-text"):
394
+ raise ServiceError(f"动作 {name} 需要文本参数")
395
+ dev.run_action(name)
354
396
  except ServiceError:
355
397
  raise
356
398
  except Exception as exc:
@@ -508,18 +550,7 @@ class MijiaService:
508
550
  )
509
551
  except Exception as exc:
510
552
  raise _wrap_error(exc, "设置开关状态失败") from exc
511
- # 写接口的 code 语义与读不同:上游把 code∈(0,1) 的响应统一
512
- # 改写为「成功」(apis.py set_devices_prop 出口),其余一律失败
513
- items = rets if isinstance(rets, list) else [rets]
514
- for item in items:
515
- if not isinstance(item, dict):
516
- continue
517
- code = item.get("code")
518
- if code in (0, 1):
519
- continue
520
- raise ServiceError(
521
- f"设置失败({item.get('message', '未知错误')},错误码 {code})"
522
- )
553
+ _require_device_confirmation(rets)
523
554
 
524
555
  @_serialized
525
556
  def power_states(self, dids: list[str]) -> dict[str, bool | None]:
@@ -8,7 +8,7 @@ DSH 插件本体是 Node,米家协议栈是 Python(mijiaAPI)。本文件
8
8
  构造既慢又会重复读盘)。
9
9
 
10
10
  为什么不复用 app/ui:整个 app.ui 与 app.core.jobs 都 import PySide6,
11
- 而米家控制本身并不需要 Qt。只 import app.core.service 就能完整控制设备,
11
+ 而米家控制本身并不需要 Qt。通过 app.core.service 调用已适配的米家能力,
12
12
  也让插件不必为插件本体拖一份 200MB 的 Qt 运行时。
13
13
 
14
14
  日志一律走 stderr——stdout 是协议通道,任何多余字符都会让 Node 侧
@@ -17,9 +17,11 @@ JSON.parse 失败。
17
17
 
18
18
  from __future__ import annotations
19
19
 
20
+ import asyncio
20
21
  import json
21
22
  import os
22
23
  import sys
24
+ import threading
23
25
  import time
24
26
  import traceback
25
27
  from dataclasses import asdict, is_dataclass
@@ -54,8 +56,6 @@ _service_auth_mtime: float = 0.0
54
56
  def _auth_file() -> Path | None:
55
57
  """mijiaAPI 的凭据文件路径(与 mijiaAPI CLI 共用)。"""
56
58
  try:
57
- from mijiaAPI import mijiaLogin # noqa: F401 (仅用于确认包未损坏)
58
-
59
59
  return Path.home() / ".config" / "mijia-api" / "auth.json"
60
60
  except Exception: # noqa: BLE001 - 拿不到就以 mtime 0 处理,不阻断主流程
61
61
  return None
@@ -98,6 +98,8 @@ def _plain(value):
98
98
 
99
99
  def _err_code(exc: BaseException) -> str:
100
100
  """给异常一个稳定的机器可读分类,Node 侧据此决定要不要引导用户登录。"""
101
+ if isinstance(exc, OperationTimeout):
102
+ return "operation_timeout"
101
103
  name = type(exc).__name__
102
104
  text = str(exc)
103
105
  if "ServiceError" in name:
@@ -111,6 +113,88 @@ def _err_code(exc: BaseException) -> str:
111
113
  return "error"
112
114
 
113
115
 
116
+ # ---------------------------------------------------------------- 全屋智能家居
117
+
118
+ # 局域网扫描/控制是 asyncio 写的,而桥接主循环是同步逐行读 stdin。这里起一条
119
+ # 常驻后台事件循环线程,处理函数用 run_coroutine_threadsafe 投递进去等结果。
120
+ # 主循环仍串行等候请求完成;Node 取消/超时时终止桥接,避免继续处理排队请求。
121
+ _loop: asyncio.AbstractEventLoop | None = None
122
+ _loop_lock = threading.Lock()
123
+ _manager: object | None = None
124
+
125
+
126
+ def _event_loop() -> asyncio.AbstractEventLoop:
127
+ global _loop
128
+ with _loop_lock:
129
+ if _loop is None:
130
+ loop = asyncio.new_event_loop()
131
+ thread = threading.Thread(target=loop.run_forever, daemon=True,
132
+ name="smart-home-loop")
133
+ thread.start()
134
+ _loop = loop
135
+ return _loop
136
+
137
+
138
+ class OperationTimeout(TimeoutError):
139
+ """The shared process must exit: cancellation cannot stop blocking threads."""
140
+
141
+
142
+ def _run_async(coro, timeout: float | None = None):
143
+ async def capture_device_timeout():
144
+ try:
145
+ return await coro, None
146
+ except TimeoutError as exc:
147
+ # Future.result also raises TimeoutError for a finished device call.
148
+ # Carry that exception as data so it cannot be confused with our budget.
149
+ return None, exc
150
+
151
+ future = asyncio.run_coroutine_threadsafe(capture_device_timeout(), _event_loop())
152
+ try:
153
+ result, device_timeout = future.result(timeout=timeout)
154
+ except TimeoutError:
155
+ # Cancellation cannot interrupt a blocking cloud call or to_thread worker.
156
+ # The dispatcher marks this process terminal; main exits without joining
157
+ # workers and Node invalidates every queued request. Remote effects remain unknown.
158
+ future.cancel()
159
+ raise OperationTimeout("操作超时,执行结果未知;请先读取设备状态,再决定是否重试") from None
160
+ if device_timeout is not None:
161
+ raise device_timeout
162
+ return result
163
+
164
+
165
+ def smart_home_manager():
166
+ """懒构造全屋智能家居管理器(米家云为可选,失败则仅走局域网)。"""
167
+ global _manager
168
+ if _manager is None:
169
+ try:
170
+ from smart_home.cloud import MiHomeCloudProxy
171
+ from smart_home.manager import SmartHomeManager
172
+ except ImportError as exc:
173
+ raise RuntimeError(f"全屋智能家居依赖缺失:{exc}") from exc
174
+ cloud = None
175
+ try:
176
+ cloud = MiHomeCloudProxy(service())
177
+ except Exception as exc: # noqa: BLE001 - 未登录/无凭据不该阻断局域网
178
+ print(f"[smart-home] 米家云端不可用,本次仅用局域网:{exc}", file=sys.stderr)
179
+ data_dir = os.environ.get("MIHOME_DATA_DIR") or str(_HERE.parent / "data")
180
+ _manager = SmartHomeManager({"data_dir": data_dir, "cloud": cloud})
181
+ else:
182
+ from smart_home.cloud import MiHomeCloudProxy
183
+ try:
184
+ current = service()
185
+ if getattr(_manager.cloud, "_svc", None) is not current:
186
+ _manager.cloud = MiHomeCloudProxy(current)
187
+ _manager.config["cloud"] = _manager.cloud
188
+ # Invalidate adapters which still reference the previous session.
189
+ _run_async(_manager.close(), timeout=5)
190
+ _manager._scan = {}
191
+ except OperationTimeout:
192
+ raise # A timed-out worker must not survive in a reusable bridge.
193
+ except Exception:
194
+ pass # Local connections remain usable when Mi Home is unavailable.
195
+ return _manager
196
+
197
+
114
198
  # ---------------------------------------------------------------- handlers
115
199
 
116
200
  def op_status(_args):
@@ -330,13 +414,15 @@ def op_power(args):
330
414
  """电源:不带 state 时按当前状态取反。"""
331
415
  svc = service()
332
416
  did = _require(args, "did")
333
- if "state" in args and args["state"] is not None:
334
- state = bool(args["state"])
417
+ if "state" in args:
418
+ if not isinstance(args["state"], bool):
419
+ raise ValueError("state 必须为布尔值")
420
+ state = args["state"]
335
421
  svc.set_power_state(did, state)
336
422
  return {"on": state}
337
423
  current = svc.power_state(did)
338
- svc.toggle_power(did, current)
339
- return {"on": not bool(current)}
424
+ state = svc.toggle_power(did, current)
425
+ return {"on": state}
340
426
 
341
427
 
342
428
  def op_power_states(args):
@@ -352,7 +438,7 @@ def op_power_states(args):
352
438
  states = {}
353
439
  for did in [str(d) for d in dids]:
354
440
  try:
355
- states[did] = bool(svc.power_state(did))
441
+ states[did] = svc.power_state(did)
356
442
  except Exception as exc: # noqa: BLE001 - 单台失败不影响其余
357
443
  print(f"读电源状态失败 {did}: {exc}", file=sys.stderr)
358
444
  return {"states": states}
@@ -482,6 +568,104 @@ def op_names(args):
482
568
  return {"names": names}
483
569
 
484
570
 
571
+ def op_smart_home_scan(args):
572
+ """扫描本网段,识别全屋智能家居(含 BLE)并叠加米家云端设备。"""
573
+ mgr = smart_home_manager()
574
+ return _run_async(
575
+ mgr.scan(
576
+ subnets=args.get("subnets") or None,
577
+ prefix=args.get("prefix", 24),
578
+ extra_subnets=args.get("extra_subnets") or None,
579
+ ports=args.get("ports") or None,
580
+ scan_ping=args.get("scan_ping", True),
581
+ force=bool(args.get("force", False)),
582
+ ),
583
+ timeout=180,
584
+ )
585
+
586
+
587
+ def op_smart_home_devices(args):
588
+ """全屋设备列表(默认 60 秒缓存,refresh=True 强制重扫)。"""
589
+ mgr = smart_home_manager()
590
+ return {"devices": _run_async(
591
+ mgr.devices(refresh=bool(args.get("refresh", False))), timeout=180)}
592
+
593
+
594
+ def op_smart_home_device(args):
595
+ """单台设备详情:能力项(已翻译)+ 当前值。"""
596
+ mgr = smart_home_manager()
597
+ return _run_async(
598
+ mgr.device(_require(args, "id"), refresh=bool(args.get("refresh", False))),
599
+ timeout=180,
600
+ )
601
+
602
+
603
+ def op_smart_home_control(args):
604
+ """统一控制:mode = power / write / action / scrape。"""
605
+ mgr = smart_home_manager()
606
+ return _run_async(
607
+ mgr.control(
608
+ _require(args, "device_id"),
609
+ str(args.get("mode") or "power"),
610
+ name=str(args.get("name") or ""),
611
+ value=args.get("value"),
612
+ params=args.get("params"),
613
+ **({"state": args["state"]} if "state" in args else {}),
614
+ ),
615
+ timeout=180,
616
+ )
617
+
618
+
619
+ def op_smart_home_scrape(args):
620
+ """扒管理类设备(路由器 / 交换机 / 光猫 / NAS)的设置页。"""
621
+ mgr = smart_home_manager()
622
+ return _run_async(mgr.scrape(_require(args, "device_id")), timeout=180)
623
+
624
+
625
+ def op_smart_home_scenes(args):
626
+ """自定义场景:mode = list / save / run / delete。
627
+
628
+ 之前只实现了 list,Node 侧却声明了四种模式——save/run/delete 会落到
629
+ 「没有返回」的静默路径。这里补齐,并让返回值结构与前端/渲染一致。
630
+ """
631
+ mode = str(args.get("mode") or "list")
632
+ mgr = smart_home_manager()
633
+ if mode == "list":
634
+ return {"ok": True, "mode": mode, "scenes": mgr.scenes_list()}
635
+ if mode == "save":
636
+ scene = args.get("scene") or args
637
+ if not isinstance(scene, dict):
638
+ raise ValueError("mode=save 需要 scene 对象(含 name 与 actions)")
639
+ saved = mgr.scene_save(scene)
640
+ return {"ok": True, "mode": mode, "saved": saved, "scenes": mgr.scenes_list()}
641
+ if mode == "delete":
642
+ deleted = mgr.scene_delete(_require(args, "scene_id"))
643
+ return {"ok": deleted, "mode": mode, "deleted": deleted, "scenes": mgr.scenes_list()}
644
+ if mode == "run":
645
+ result = _run_async(mgr.scene_run(_require(args, "scene_id")), timeout=180)
646
+ return {"mode": mode, **result}
647
+ raise ValueError(f"未知 mode:{mode}(可选 list / save / run / delete)")
648
+
649
+
650
+ def op_smart_home_scene_save(args):
651
+ scene = args.get("scene") or args
652
+ return smart_home_manager().scene_save(scene)
653
+
654
+
655
+ def op_smart_home_scene_delete(args):
656
+ return {"deleted": smart_home_manager().scene_delete(_require(args, "scene_id"))}
657
+
658
+
659
+ def op_smart_home_scene_run(args):
660
+ mgr = smart_home_manager()
661
+ return _run_async(mgr.scene_run(_require(args, "scene_id")), timeout=180)
662
+
663
+
664
+ def op_smart_home_catalog(_args):
665
+ """能力项目录(中英对照),供模型与前端使用。"""
666
+ return smart_home_manager().catalog()
667
+
668
+
485
669
  HANDLERS = {
486
670
  "status": op_status,
487
671
  "login_begin": op_login_qr,
@@ -500,6 +684,16 @@ HANDLERS = {
500
684
  "icons": op_icons,
501
685
  "homes": op_homes,
502
686
  "names": op_names,
687
+ "smart_home_scan": op_smart_home_scan,
688
+ "smart_home_devices": op_smart_home_devices,
689
+ "smart_home_device": op_smart_home_device,
690
+ "smart_home_control": op_smart_home_control,
691
+ "smart_home_scrape": op_smart_home_scrape,
692
+ "smart_home_scenes": op_smart_home_scenes,
693
+ "smart_home_scene_save": op_smart_home_scene_save,
694
+ "smart_home_scene_delete": op_smart_home_scene_delete,
695
+ "smart_home_scene_run": op_smart_home_scene_run,
696
+ "smart_home_catalog": op_smart_home_catalog,
503
697
  }
504
698
 
505
699
 
@@ -517,7 +711,11 @@ def handle(request: dict) -> dict:
517
711
  if handler is None:
518
712
  return {"id": req_id, "ok": False, "error": f"未知 op:{op}", "code": "unknown_op"}
519
713
  try:
520
- return {"id": req_id, "ok": True, "result": _plain(handler(request.get("args") or {}))}
714
+ args = dict(request.get("args") or {})
715
+ connections = args.pop("_connections", {})
716
+ if op.startswith("smart_home_"):
717
+ _run_async(smart_home_manager().set_connections(connections), timeout=10)
718
+ return {"id": req_id, "ok": True, "result": _plain(handler(args))}
521
719
  except BaseException as exc: # noqa: BLE001 - 顶点不能崩,错误要回给调用方
522
720
  traceback.print_exc(file=sys.stderr)
523
721
  return {
@@ -545,6 +743,10 @@ def main() -> int:
545
743
  response = handle(request)
546
744
  sys.stdout.write(json.dumps(response, ensure_ascii=False) + "\n")
547
745
  sys.stdout.flush()
746
+ if response.get("code") == "operation_timeout":
747
+ # Normal interpreter shutdown waits for executor threads. Force this
748
+ # dedicated bridge process to exit before accepting another request.
749
+ os._exit(124)
548
750
  return 0
549
751
 
550
752
 
@@ -0,0 +1,24 @@
1
+ # SPDX-License-Identifier: GPL-3.0-or-later
2
+ """dsh-mihome 全屋智能家居扩展(Python SDK)。
3
+
4
+ 在原米家(Mi Home)云端控制之上,增加**局域网发现 + 多协议控制**能力:
5
+ 扫描本网段,识别路由器、交换机、光猫、NAS、电视、扫地机器人、灯具、开关、
6
+ 插座、空调、冰箱、洗衣机、烘干机、传感器等设备,统一成一套可读写的控制面。
7
+
8
+ 模块划分:
9
+ - ``catalog`` :设备类别 / 能力项的中英对照字典(翻译基准)。
10
+ - ``util`` :网络与 HTTP 工具。
11
+ - ``discovery`` :局域网扫描(ARP/ping/端口/SSDP/mDNS)与设备指纹识别。
12
+ - ``adapters`` :各协议的读写实现。
13
+ - ``manager`` :统一设备模型、状态刷新、控制分发、扫描结果缓存。
14
+
15
+ 设计原则:
16
+ - 每个适配器只负责「探测 + 读状态 + 写控制」,不关心 UI。
17
+ - 控制写操作只走显式声明的映射,不做无根据的猜测;拿不到的就如实报不支持。
18
+ - 所有能力项的中文名统一由 ``catalog`` 提供,避免同一能力多套叫法。
19
+ """
20
+
21
+ from .manager import SmartHomeManager # noqa: F401
22
+
23
+ __all__ = ["SmartHomeManager"]
24
+ __version__ = "2.0.0"
@@ -0,0 +1,50 @@
1
+ # SPDX-License-Identifier: GPL-3.0-or-later
2
+ """各协议适配器。
3
+
4
+ 导入本包即完成全部适配器的注册(见 ``base.register``)。新增协议时在
5
+ 这里加一行 import,并给新适配器类加上 ``@register``。
6
+ """
7
+
8
+ from .base import BaseAdapter, get_adapter_class, register, all_protocols # noqa: F401
9
+ from .mihome import MiHomeCloudAdapter, MiIOAdapter # noqa: F401
10
+ from .tuya import TuyaAdapter # noqa: F401
11
+ from .shelly import ShellyAdapter, TasmotaAdapter, WledAdapter, EspHomeAdapter # noqa: F401
12
+ from .kasa import KasaAdapter, YeelightAdapter # noqa: F401
13
+ from .hue import HueAdapter, LifxAdapter # noqa: F401
14
+ from .network import RouterAdapter, SwitchAdapter, OnuAdapter, NasAdapter, HttpGenericAdapter # noqa: F401
15
+ from .dlna import DlnaAdapter, OnvifAdapter, CastAdapter # noqa: F401
16
+ from .tv import SamsungTvAdapter, LgTvAdapter, VizioTvAdapter # noqa: F401
17
+ from .ble import BleAdapter, ble_scan # noqa: F401
18
+ from .home_assistant import HomeAssistantAdapter # noqa: F401
19
+
20
+ __all__ = [
21
+ "BaseAdapter",
22
+ "register",
23
+ "get_adapter_class",
24
+ "all_protocols",
25
+ "MiHomeCloudAdapter",
26
+ "MiIOAdapter",
27
+ "TuyaAdapter",
28
+ "ShellyAdapter",
29
+ "TasmotaAdapter",
30
+ "WledAdapter",
31
+ "EspHomeAdapter",
32
+ "KasaAdapter",
33
+ "YeelightAdapter",
34
+ "HueAdapter",
35
+ "LifxAdapter",
36
+ "RouterAdapter",
37
+ "SwitchAdapter",
38
+ "OnuAdapter",
39
+ "NasAdapter",
40
+ "HttpGenericAdapter",
41
+ "DlnaAdapter",
42
+ "OnvifAdapter",
43
+ "CastAdapter",
44
+ "SamsungTvAdapter",
45
+ "LgTvAdapter",
46
+ "VizioTvAdapter",
47
+ "HomeAssistantAdapter",
48
+ "BleAdapter",
49
+ "ble_scan",
50
+ ]