@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/cordis.patch.yml CHANGED
@@ -8,8 +8,8 @@
8
8
  # 桥接用的 Python 解释器。留空 = 插件自带的 .venv
9
9
  # (Windows: .venv\Scripts\python.exe;其它平台: .venv/bin/python)
10
10
  pythonPath: ''
11
- # 米家缓存与配置目录。留空 = <插件目录>/data
12
- # (登录凭据本身由 mijiaAPI 存在 ~/.config/mijia-api/auth.json,不在这里)
11
+ # 运行时数据目录(二维码、产品图、自定义场景)。留空 = <插件目录>/data
12
+ # (米家登录凭据由 mijiaAPI 存在 ~/.config/mijia-api/auth.json,不在这里)
13
13
  dataDir: ''
14
14
  # 普通设备操作的请求超时(毫秒)
15
15
  requestTimeoutMs: 30000
@@ -0,0 +1,62 @@
1
+ # 全屋智能修复与验证记录
2
+
3
+ 验证日期:2026-11-22。对象:本地工作树中的 `@jessicaisleep/dsh-mihome` 2.0.0,不代表 npm/GitHub 已发布版本。
4
+
5
+ ## 当前结果
6
+
7
+ 插件提供米家云端、Home Assistant 实体和已适配本地协议的统一入口。主路径是“发现或手动配置 → 获取实际能力 → 按原始 key 控制 → 状态回读/逐步场景结果”。没有能力证据时不生成可写控件,不把型号、分类或厂商名称当作控制规格。
8
+
9
+ 本轮修复解决了审计中已复现的失败误报、场景计数、参数丢失、发现与身份、私有连接接线、取消/进程重启、来源校验和界面状态等问题。**尚不能声称直接控制所有品牌、型号和固件,或已经复刻全部官网 APP 功能。** 各协议的条件见 README 的支持矩阵。
10
+
11
+ ## 需求对照
12
+
13
+ | 需求 | 实现与证据 | 剩余条件 |
14
+ | --- | --- | --- |
15
+ | 一个插件管理全屋设备 | 保留米家入口;增加 HA 网关/实体、私有连接和本地协议;多个 HA 实例同名实体互相隔离 | 非米家生态推荐先用相应 HA 集成接入;具体家电能力由集成暴露的实体决定 |
16
+ | 局域网扫描、BLE 等多种发现 | ARP、受限 ping、TCP/HTTP、SSDP、mDNS、Tuya/miIO UDP、BLE;修复空候选提前退出、无 TCP 主机丢失、字符串参数、蓝牙 ID 冲突和跨协议合并 | 只支持 IPv4 扫描;隔离网络、休眠/不广播设备不保证发现;BLE 发现不等于私有 GATT 控制 |
17
+ | 可靠控制和真实反馈 | 严格传播 `ok:false`;米家仅整数 `code=0` 确认,`code=1` 保持未确认;未知电源不显示为关机;动作 JSON 原类型保留 | HTTP/协议确认不保证物理动作完成;需要状态回读及型号实机验收 |
18
+ | 中文能力与选项 | 保留 canonical key、类型、权限、范围、单位、枚举、动作 schema;官方规格/协议/平台术语/通用翻译;IEEE OUI 可重建 | 未知术语保留原文;上游米家规格的同名属性及单位缺失仍受上游模型限制 |
19
+ | 私有设备连接 | 面板保存到 DSH `mihome/devices` 凭据记录;只返回 ID/配置状态;Node→Python 私有传递,不进入公共列表 | 用户须在面板提供有效凭据、地址和显式映射;不会从聊天工具收集密钥 |
20
+ | 自定义场景 | 创建、编辑、删除、顺序执行;失败后继续,逐步显示结果;原子保存,损坏 JSON 不静默覆盖 | 当前是手动执行,没有自动到家、定时或事件触发引擎 |
21
+ | 路由器/交换机/光猫/NAS | 公开管理页读取;HTTP 失败保留失败;不把登录页读取当作设置写入 | 未实现通用认证、超管登录及设置编辑;已移除未经核实的重启/登录命令 |
22
+ | README/市场介绍中文在前 | README 中文完整在前、English 在后;包描述与 locale 按真实能力说明 | 未发布到市场,因此外部已发布页面尚未更新 |
23
+
24
+ ## 已执行的验证
25
+
26
+ 在项目根目录执行;均未向真实家电发送控制命令。
27
+
28
+ | 命令或检查 | 最新结果 | 证明范围 |
29
+ | --- | --- | --- |
30
+ | `node --test` | 80 tests,80 pass,0 fail/skip/cancel(约 4.45 秒) | Node bridge、来源/JSON 校验、私有连接、工具、UI 行为、formatter、localhost E2E、operation/device timeout 分类、进程退出输出排空、子进程替换竞争和旧米家路由输入校验 |
31
+ | `.venv\Scripts\python.exe -m unittest discover -s python/tests -q` | 109 tests,OK(约 2.13 秒) | Python manager/bridge、电源状态回读和米家确认、发现、协议和 HA 模拟契约 |
32
+ | 四个 `python/smart_home/test_*.py` 自检 | 全部通过,localization 14 tests | 旧离线回归、核心修复、发现、本地化 |
33
+ | `.venv\Scripts\python.exe -m pyflakes python/smart_home python/mihome_bridge.py` | 无诊断,exit 0 | 本轮生产 Python 模块静态检查;不声称整个上游 UI 测试目录零告警 |
34
+ | `.venv\Scripts\python.exe -m pip check` | No broken requirements found | 当前虚拟环境依赖一致性 |
35
+ | `node --check` 六个生产 JS 文件 | 全部 exit 0 | client、index、panel、bridge、connections、format 语法 |
36
+ | `node scripts/check-i18n.mjs client.js` | zh/en 134/134,无缺失或未定义 key | 字典一致性;不等于翻译语义逐设备验收 |
37
+ | `node scripts/render-smoke.mjs client.js` | 六条页面路径通过,无 undefined/NaN/[object Object] | fake React/hooks/HTTP 的模拟渲染契约;显式切换全屋与米家,检查两端列表、详情和米家场景/耗材;不是浏览器视觉验收 |
38
+ | 实际 DSH Electron 运行 `scripts/verify-dsh-tools.cjs` | Node 24.21.0;13 tools;scanSchema、objectAndArrayActionParams、cancellation passed | 使用真实 DSH defineTool/schemastery/credentialKey,mock Python transport 和 Host ctx;不是真实 Host 挂载 |
39
+ | `npm pack --dry-run --json` | 必需运行文件齐全,无 `.venv`、运行数据、认证文件或 `_probe` 入包 | 包清单检查,不代表已经发布 |
40
+ | `git diff --check` | exit 0 | 工作区补丁空白检查;保留既有 service.py CRLF,Git 有 EOL 提示 |
41
+
42
+ `tests/whole-home-e2e.test.js` 使用本机临时 HTTP 服务和临时令牌,经过真实 Node Bridge → JSON-Lines Python → SmartHomeManager → HA REST。它验证实体展开、电源控制/状态回读、场景两步中一步 HTTP 503 时汇总 `ok:false, success:1, total:2`,以及秘密不进入结果。子进程网络 guard 禁止非回环访问;这不是家中 HA 或真实家电测试。
43
+
44
+ 回归测试曾在修复前观察到对应红灯,包含失败被包装成功、错误场景计数、字符串子网逐字符解析、空参数容器被转换为 None、旧进程影响新请求、未知电源显示关闭及键盘冒泡等;修复后分别和完整套件复测。最终 UI 复核又补测了设备详情读取错误被误说成“无控制项”,以及打开设备时连接状态误用初始空 ID 的闭包问题;现在显式呈现后端能力/状态诊断,连接状态从私有配置 ID 列表按当前设备派生,HA 子实体也识别所属网关的继承配置。最后控制复核还发现协程取消不能停止同步调用或后台线程;新增真实子进程文件 gate 测试,确认 Python 操作预算耗尽返回 `operation_timeout`/结果未知、进程退出、阻塞本地写入及排队请求均不继续,下一请求启动新进程。另覆盖同步调用和 `asyncio.to_thread` 中由设备自身抛出的 `TimeoutError`:它作为设备级 I/O 错误返回,不终止桥接、不会标成 operation timeout,后续请求仍由同一进程服务。测试还覆盖进程退出后的 stdout 排空、退出与新进程启动重叠,以及旧请求定时器不得杀掉 replacement。测试的外部写入均用本地文件替代。
45
+
46
+ ## 未执行的验收与明确边界
47
+
48
+ - 未安装或启用此工作树到当前 DSH profile,未提交、推送或发布。现有未提交成果保留在工作区。
49
+ - 未在真实设备/固件上执行控制;模拟报文和本机服务器不能替代实机兼容性验收。
50
+ - DSH Host URL 的 WCU 浏览器访问被策略拒绝(`WCU_POLICY_DENIED: this address belongs to the DSH host.`);未绕过,也未把 mock React 画面当作真实 UI 验收。真实 Host 挂载、明暗主题、窄屏布局和运行时控制台仍需在可用环境验收。
51
+ - 独立 UI/UX 复核发现的问题已按用例修复,界面行为测试仍使用测试 harness,不证明浏览器布局或辅助技术实际朗读。
52
+ - 原生 LIFX、Samsung/LG/Vizio、ESPHome 伪 REST、ONVIF 重启、未知网络设备写入没有经过可靠实现,当前禁用;可由合适的 HA 集成补充。
53
+ - 取消/超时会结束共享桥接;其他在途请求标记为结果未知。已经发送的远端命令不能撤回,已开始的外部请求也不因协程取消自动回滚。重试前先读状态。
54
+
55
+ ## 外部经验与来源
56
+
57
+ - React 键盘事件会冒泡。复合设备磁贴仅在 `event.target === event.currentTarget` 时处理自己的 Enter/Space,避免内层电源按钮触发父磁贴导航。[React 事件传播](https://react.dev/learn/responding-to-events#stopping-propagation)
58
+ - 选项按钮用 `aria-pressed` 暴露选择状态;未知布尔状态提供明确开/关操作,不伪造 `aria-checked=false`。[MDN aria-pressed](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Reference/Attributes/aria-pressed)
59
+ - HTTP 成功按 200–299 判断,401/403 不当作已读出认证设置。[MDN HTTP 状态](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status)
60
+ - 同源包含 scheme、host 和 port;面板 POST 同时检查 Origin 与 JSON Content-Type。[MDN 同源策略](https://developer.mozilla.org/en-US/docs/Web/Security/Defenses/Same-origin_policy)
61
+ - `run_coroutine_threadsafe().result(timeout)` 超时不会自动取消 coroutine;`future.cancel()` 也不能停止正在运行的同步调用或 executor 线程。本插件将操作超时标为终止性错误,退出专用 Python 进程并使排队请求失效;远端已发送的命令仍不能撤回。[Python asyncio](https://docs.python.org/3/library/asyncio-task.html#asyncio.run_coroutine_threadsafe) / [Future.cancel](https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Future.cancel)
62
+ - miIO UDP/AES-CBC、HA REST/实例发现、TinyTuya、Shelly、Yeelight、Hue、Tasmota/WLED、Bleak/zeroconf 与 IEEE 的依据和协议条件集中维护在 README 的资料来源及支持矩阵,不把社区经验表述成所有厂商的官方承诺。
package/lib/bridge.js CHANGED
@@ -43,10 +43,7 @@ export class Bridge {
43
43
  this.child = null;
44
44
  this.pending = new Map();
45
45
  this.nextId = 1;
46
- this.stderrTail = [];
47
- this.decoder = new StringDecoder("utf8");
48
- this.stdoutBuffer = "";
49
- this.stderrBuffer = "";
46
+ this.childStates = new WeakMap();
50
47
  this.disposed = false;
51
48
  }
52
49
 
@@ -64,7 +61,9 @@ export class Bridge {
64
61
 
65
62
  #ensureChild() {
66
63
  if (this.disposed) throw new Error("MiHome 桥接已关闭");
67
- if (this.child && this.child.exitCode === null) return this.child;
64
+ if (this.child && this.child.exitCode === null && this.child.signalCode === null) return this.child;
65
+ // The exited process may still drain stdout; its pending IDs and timers remain owned by it.
66
+ if (this.child) this.child = null;
68
67
 
69
68
  if (!existsSync(this.pythonExe)) {
70
69
  throw new Error(
@@ -92,65 +91,93 @@ export class Bridge {
92
91
  },
93
92
  });
94
93
 
95
- child.stdout.on("data", (chunk) => this.#onStdout(chunk));
96
- child.stderr.on("data", (chunk) => this.#onStderr(chunk));
97
-
94
+ const state = {
95
+ stdoutDecoder: new StringDecoder("utf8"),
96
+ stderrDecoder: new StringDecoder("utf8"),
97
+ stdoutBuffer: "",
98
+ stderrBuffer: "",
99
+ stderrTail: [],
100
+ };
101
+ this.childStates.set(child, state);
102
+ child.stdout.on("data", (chunk) => this.#onStdout(child, chunk));
103
+ child.stderr.on("data", (chunk) => this.#onStderr(child, chunk));
104
+ child.stdin.on("error", (error) => {
105
+ if (this.child === child) this.#terminateForRequest(new Error(`桥接输入通道失败:${error.message}`));
106
+ });
98
107
  child.on("error", (error) => {
99
- this.#failAll(new Error(`米家桥接进程启动失败:${error.message}`));
108
+ if (this.child === child) this.child = null;
109
+ this.#failForChild(child, new Error(`米家桥接进程启动失败:${error.message}`));
100
110
  });
101
111
 
102
- child.on("exit", (code, signal) => {
103
- const tail = this.stderrTail.join("\n").trim();
112
+ // exit can precede the last stdout data event. Keep draining the current
113
+ // child until close; #ensureChild retires its requests before replacement.
114
+ child.on("close", (code, signal) => {
115
+ const state = this.childStates.get(child);
116
+ const tail = state?.stderrTail.join("\n").trim() ?? "";
117
+ if (this.child === child) this.child = null;
104
118
  const why = signal ? `信号 ${signal}` : `退出码 ${code}`;
105
- this.#failAll(new Error(
119
+ this.#failForChild(child, new Error(
106
120
  `米家桥接进程已退出(${why})。` + (tail ? `\n最近的 stderr:\n${tail}` : ""),
107
121
  ));
108
- this.child = null;
109
- this.stdoutBuffer = "";
122
+ this.childStates.delete(child);
110
123
  });
111
124
 
112
125
  this.child = child;
113
126
  return child;
114
127
  }
115
128
 
116
- #onStdout(chunk) {
117
- this.stdoutBuffer += this.decoder.write(chunk);
118
- // 一行一个响应;最后一段可能不完整,留在缓冲里等下一块
129
+ #onStdout(child, chunk) {
130
+ const state = this.childStates.get(child);
131
+ if (!state) return;
132
+ state.stdoutBuffer += state.stdoutDecoder.write(chunk);
133
+ // 一行一个响应;最后一段可能不完整,留在该进程的缓冲里等下一块。
119
134
  let index;
120
- while ((index = this.stdoutBuffer.indexOf("\n")) >= 0) {
121
- const line = this.stdoutBuffer.slice(0, index).trim();
122
- this.stdoutBuffer = this.stdoutBuffer.slice(index + 1);
135
+ while ((index = state.stdoutBuffer.indexOf("\n")) >= 0) {
136
+ const line = state.stdoutBuffer.slice(0, index).trim();
137
+ state.stdoutBuffer = state.stdoutBuffer.slice(index + 1);
123
138
  if (!line) continue;
124
- this.#onLine(line);
139
+ this.#onLine(child, line);
125
140
  }
126
141
  }
127
142
 
128
- #onStderr(chunk) {
129
- this.stderrBuffer += this.decoder.write(chunk);
143
+ #onStderr(child, chunk) {
144
+ const state = this.childStates.get(child);
145
+ if (!state) return;
146
+ state.stderrBuffer += state.stderrDecoder.write(chunk);
130
147
  let index;
131
- while ((index = this.stderrBuffer.indexOf("\n")) >= 0) {
132
- const line = this.stderrBuffer.slice(0, index);
133
- this.stderrBuffer = this.stderrBuffer.slice(index + 1);
148
+ while ((index = state.stderrBuffer.indexOf("\n")) >= 0) {
149
+ const line = state.stderrBuffer.slice(0, index);
150
+ state.stderrBuffer = state.stderrBuffer.slice(index + 1);
134
151
  if (!line.trim()) continue;
135
- this.stderrTail.push(line);
136
- if (this.stderrTail.length > STDERR_KEEP) this.stderrTail.shift();
152
+ state.stderrTail.push(line);
153
+ if (state.stderrTail.length > STDERR_KEEP) state.stderrTail.shift();
137
154
  }
138
155
  }
139
156
 
140
- #onLine(line) {
157
+ #onLine(child, line) {
141
158
  let message;
142
159
  try {
143
160
  message = JSON.parse(line);
144
161
  } catch {
145
- // 不是协议数据就当日志收着(Python 侧理论上不会往 stdout 写别的)
146
- this.stderrTail.push(`[stdout] ${line}`);
147
- if (this.stderrTail.length > STDERR_KEEP) this.stderrTail.shift();
162
+ // 非协议 stdout 也要留在产生它的进程诊断上下文中。
163
+ const tail = this.childStates.get(child)?.stderrTail;
164
+ if (tail) {
165
+ tail.push(`[stdout] ${line}`);
166
+ if (tail.length > STDERR_KEEP) tail.shift();
167
+ }
148
168
  return;
149
169
  }
150
170
  const entry = this.pending.get(message.id);
151
171
  if (!entry) return;
172
+ if (message.ok === false && message.code === "operation_timeout") {
173
+ const error = new Error("操作超时,执行结果未知;桥接已终止,请先读取设备状态,再决定是否重试。");
174
+ error.code = "operation_timeout";
175
+ error.outcomeUnknown = true;
176
+ this.#terminateForRequest(error, message.id);
177
+ return;
178
+ }
152
179
  this.pending.delete(message.id);
153
- clearTimeout(entry.timer);
180
+ this.#cleanupEntry(entry);
154
181
  if (message.ok) {
155
182
  entry.resolve(message.result ?? {});
156
183
  return;
@@ -160,43 +187,98 @@ export class Bridge {
160
187
  entry.reject(error);
161
188
  }
162
189
 
190
+ #cleanupEntry(entry) {
191
+ clearTimeout(entry.timer);
192
+ if (entry.signal && entry.abortHandler) {
193
+ entry.signal.removeEventListener("abort", entry.abortHandler);
194
+ }
195
+ }
196
+
163
197
  #failAll(error) {
164
198
  for (const [, entry] of this.pending) {
165
- clearTimeout(entry.timer);
199
+ this.#cleanupEntry(entry);
166
200
  entry.reject(error);
167
201
  }
168
202
  this.pending.clear();
169
203
  }
170
204
 
205
+ #failForChild(child, error) {
206
+ for (const [id, entry] of this.pending) {
207
+ if (entry.child !== child) continue;
208
+ this.pending.delete(id);
209
+ this.#cleanupEntry(entry);
210
+ entry.reject(error);
211
+ }
212
+ }
213
+
214
+ #terminateForRequest(error, requestId, ownerChild) {
215
+ const entry = requestId === undefined ? null : this.pending.get(requestId);
216
+ const child = ownerChild ?? entry?.child ?? this.child;
217
+ if (this.child === child) this.child = null;
218
+ if (requestId !== undefined) {
219
+ if (entry) {
220
+ this.pending.delete(requestId);
221
+ this.#cleanupEntry(entry);
222
+ entry.reject(error);
223
+ }
224
+ const interrupted = new Error("共享桥接已中断;其他在途请求的执行结果未知,请读取设备状态后再决定是否重试。");
225
+ interrupted.code = "bridge_interrupted";
226
+ if (child) this.#failForChild(child, interrupted);
227
+ } else if (child) {
228
+ this.#failForChild(child, error);
229
+ } else {
230
+ this.#failAll(error);
231
+ }
232
+ if (child && child.exitCode === null) {
233
+ try { child.kill(); } catch { /* already exited */ }
234
+ }
235
+ }
236
+
171
237
  /**
172
238
  * 调用一个 op,等到对应的响应行。
173
239
  *
174
240
  * @param {string} op
175
241
  * @param {Record<string, unknown>} [args]
176
242
  * @param {number} [timeoutMs] 单次请求超时;登录长轮询要单独给大值
243
+ * @param {AbortSignal} [signal] 取消时终止当前桥接进程
177
244
  * @returns {Promise<any>}
178
245
  */
179
- request(op, args = {}, timeoutMs = 30_000) {
246
+ request(op, args = {}, timeoutMs = 30_000, signal) {
247
+ if (timeoutMs && typeof timeoutMs === "object") {
248
+ signal = timeoutMs.signal;
249
+ timeoutMs = timeoutMs.timeoutMs ?? 30_000;
250
+ }
251
+ if (signal?.aborted) {
252
+ const error = new Error("请求已取消");
253
+ error.name = "AbortError";
254
+ return Promise.reject(error);
255
+ }
180
256
  const child = this.#ensureChild();
181
257
  const id = this.nextId++;
182
258
  const payload = JSON.stringify({ id, op, args }) + "\n";
183
259
 
184
260
  return new Promise((resolve, reject) => {
185
- const timer = setTimeout(() => {
186
- this.pending.delete(id);
187
- reject(new Error(
261
+ const entry = { resolve, reject, timer: null, signal, abortHandler: null, child };
262
+ const abortError = () => {
263
+ const error = new Error(`米家桥接请求已取消(${op})。`);
264
+ error.name = "AbortError";
265
+ this.#terminateForRequest(error, id, child);
266
+ };
267
+ entry.abortHandler = abortError;
268
+ entry.timer = setTimeout(() => {
269
+ this.#terminateForRequest(new Error(
188
270
  `米家桥接请求超时(${op},${timeoutMs}ms)。` +
189
- (this.stderrTail.length ? `\n最近的 stderr:\n${this.stderrTail.slice(-8).join("\n")}` : ""),
190
- ));
271
+ (this.childStates.get(child)?.stderrTail.length ? `\n最近的 stderr:\n${this.childStates.get(child).stderrTail.slice(-8).join("\n")}` : ""),
272
+ ), id, child);
191
273
  }, timeoutMs);
192
- if (typeof timer.unref === "function") timer.unref();
193
-
194
- this.pending.set(id, { resolve, reject, timer });
274
+ if (typeof entry.timer.unref === "function") entry.timer.unref();
275
+ signal?.addEventListener("abort", abortError, { once: true });
276
+ this.pending.set(id, entry);
195
277
  try {
196
278
  child.stdin.write(payload, "utf8");
197
279
  } catch (error) {
198
280
  this.pending.delete(id);
199
- clearTimeout(timer);
281
+ this.#cleanupEntry(entry);
200
282
  reject(new Error(`写入米家桥接进程失败:${error.message}`));
201
283
  }
202
284
  });
@@ -0,0 +1,46 @@
1
+ // Device connection payloads remain in DSH's Host credential store.
2
+ const object = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
3
+
4
+ export function createConnections(credentials, key) {
5
+ async function read() {
6
+ const record = await credentials.readRecord(key);
7
+ return record?.kind === 'grant' && object(record.payload?.devices) ? record.payload.devices : {};
8
+ }
9
+ function validate(deviceId, payload) {
10
+ const separator = deviceId.indexOf(":");
11
+ const protocol = deviceId.slice(0, separator);
12
+ const identity = deviceId.slice(separator + 1);
13
+ if (separator < 1 || !/^[a-z][a-z0-9_-]*$/.test(protocol) || !identity || identity.length > 240 || /[\u0000-\u001f\u007f]/.test(identity)) throw new Error('设备 ID 必须是有效的 protocol:identity');
14
+ if (!object(payload)) throw new Error('连接配置必须是 JSON 对象');
15
+ const text = JSON.stringify(payload);
16
+ if (Buffer.byteLength(text) > 48 * 1024) throw new Error('连接配置过大');
17
+ return JSON.parse(text);
18
+ }
19
+ return {
20
+ list: async () => Object.keys(await read()).sort(),
21
+ async save(deviceId, payload) {
22
+ const clean = validate(deviceId, payload);
23
+ await credentials.modifyRecord(key, async (record) => ({
24
+ kind: 'grant', payload: { devices: { ...(record?.payload?.devices ?? {}), [deviceId]: clean } },
25
+ }));
26
+ },
27
+ async delete(deviceId) {
28
+ validate(deviceId, {});
29
+ await credentials.modifyRecord(key, async (record) => {
30
+ const devices = { ...(record?.payload?.devices ?? {}) };
31
+ delete devices[deviceId];
32
+ return { kind: 'grant', payload: { devices } };
33
+ });
34
+ },
35
+ wrap(bridge) {
36
+ return {
37
+ check: () => bridge.check(),
38
+ dispose: () => bridge.dispose(),
39
+ request: async (op, args = {}, timeoutMs, signal) => {
40
+ const payload = op.startsWith('smart_home_') ? { ...args, _connections: await read() } : args;
41
+ return bridge.request(op, payload, timeoutMs, signal);
42
+ },
43
+ };
44
+ },
45
+ };
46
+ }
package/lib/format.js CHANGED
@@ -128,3 +128,151 @@ export function formatScenes(value) {
128
128
  lines.push("执行:mihome_scenes(mode=run,scene_id=…,home_id=…)");
129
129
  return lines.join("\n");
130
130
  }
131
+
132
+ /**
133
+ * 全屋设备列表:按类别分组,标出来源(局域网/云端)与地址。
134
+ *
135
+ * 来源与地址按扫描结果展示;只有适配器明确确认的能力才可用于控制。
136
+ */
137
+ export function formatSmartHomeList(value) {
138
+ const v = value ?? {};
139
+ const devices = Array.isArray(v.devices) ? v.devices : [];
140
+ if (!devices.length) {
141
+ return "没有发现任何智能家居设备。可以先调用 smart_home_scan 重新扫描," +
142
+ "或检查子网参数(subnets / prefix)。";
143
+ }
144
+
145
+ const groups = new Map();
146
+ for (const device of devices) {
147
+ const category = device?.category_zh || device?.category || "其他设备";
148
+ if (!groups.has(category)) groups.set(category, []);
149
+ groups.get(category).push(device);
150
+ }
151
+
152
+ const lines = [`共发现 ${devices.length} 台设备:`, ""];
153
+ for (const [category, items] of groups) {
154
+ lines.push(`【${category}】`);
155
+ for (const device of items) {
156
+ const source = device?.source === "cloud" ? "云端" :
157
+ device?.source === "configured" ? "已配置" :
158
+ device?.source === "ble" ? "蓝牙" : device?.source === "home_assistant" ? "Home Assistant" :
159
+ device?.source === "mihome" ? "米家" : "局域网";
160
+ const addr = device?.ip || device?.address ? ` ${device.ip ?? device.address}` : "";
161
+ const model = device?.model ? ` · ${device.model}` : "";
162
+ lines.push(`- ${device?.name ?? "未命名"}(${source}${addr})id=${device?.id ?? ""}${model}`);
163
+ }
164
+ lines.push("");
165
+ }
166
+ lines.push("设备 id 是后续 smart_home_device / smart_home_control 的键。");
167
+ return lines.join("\n").trimEnd();
168
+ }
169
+
170
+ /**
171
+ * 全屋设备详情:能力项(已翻译)+ 当前值。
172
+ *
173
+ * 能力项来自统一目录,属性名已带中文;值是「能力项 -> 值」的字典,
174
+ * 读不到的键不显示,避免把空值当成有效状态。
175
+ */
176
+ export function formatSmartHomeDetail(value) {
177
+ const d = value ?? {};
178
+ const lines = [`${d.name ?? "未命名"}(${d.category_zh ?? d.category ?? "未知类别"})`, `id=${d.id ?? ""}`];
179
+ if (d.protocol) lines.push(`协议=${d.protocol}${d.ip ? ` · 地址=${d.ip}` : ""}`);
180
+ if (d.source) {
181
+ const source = d.source === "cloud" ? "米家云端" : d.source === "configured" ? "已配置" :
182
+ d.source === "ble" ? "蓝牙" : d.source === "home_assistant" ? "Home Assistant" :
183
+ d.source === "mihome" ? "米家" : d.source;
184
+ lines.push(`来源=${source}`);
185
+ }
186
+ lines.push("");
187
+
188
+ const controls = Array.isArray(d.controls) ? d.controls : [];
189
+ if (controls.length) {
190
+ lines.push(`可控制(${controls.length}):`);
191
+ for (const control of controls) {
192
+ const bits = [`- ${(control?.zh || control?.name || control?.key) ?? "?"}`,
193
+ `key=${control?.key ?? ""}`, `name=${control?.name ?? ""}`, `kind=${control?.kind ?? "unknown"}`,
194
+ `readable=${control?.readable ?? "unknown"}`, `writable=${control?.writable ?? "unknown"}`];
195
+ const range = control?.range ?? (control?.min !== undefined || control?.max !== undefined
196
+ ? { min: control.min, max: control.max, step: control.step } : undefined);
197
+ if (range !== undefined) bits.push(`range=${JSON.stringify(range)}`);
198
+ const enums = control?.value_list?.length ? control.value_list : control?.values;
199
+ if (Array.isArray(enums) && enums.length) {
200
+ bits.push(`enums=${enums.map((item) => {
201
+ const option = item && typeof item === "object" ? item : { value: item };
202
+ const label = option.zh ?? option.description ?? option.desc ?? option.name;
203
+ return `${JSON.stringify(option.value)}${label === undefined ? "" : `=${label}`}`;
204
+ }).join(" / ")}`);
205
+ }
206
+ const unit = control?.unit ?? control?.units;
207
+ if (unit !== undefined) bits.push(`units=${JSON.stringify(unit)}`);
208
+ if (control?.kind === "action") {
209
+ if (control.params_schema !== undefined) bits.push(`params_schema=${JSON.stringify(control.params_schema)}`);
210
+ const inputs = control.inputs ?? control.in ?? control.params;
211
+ if (inputs !== undefined) bits.push(`inputs=${JSON.stringify(inputs)}`);
212
+ }
213
+ lines.push(bits.join(" "));
214
+ }
215
+ lines.push("");
216
+ } else if (!d.capability_error && !d.read_error) {
217
+ lines.push("这台设备没有返回可控制项。", "");
218
+ }
219
+ if (d.capability_error) lines.push(`能力读取失败:${d.capability_error}`, "");
220
+ if (d.read_error) lines.push(`状态读取失败:${d.read_error}`, "");
221
+
222
+ const values = d.values && typeof d.values === "object" ? d.values : {};
223
+ const entries = Object.entries(values);
224
+ if (entries.length) {
225
+ lines.push(`当前值(${entries.length}):`);
226
+ for (const [key, val] of entries) {
227
+ lines.push(`- ${key} = ${JSON.stringify(val)}`);
228
+ }
229
+ } else if (!d.read_error) {
230
+ lines.push("当前没有读到任何数值(设备可能离线或不支持状态读取)。");
231
+ }
232
+ return lines.join("\n");
233
+ }
234
+
235
+ /** 自定义场景:按请求模式显示保存、删除、执行结果或列表。 */
236
+ export function formatSmartHomeScenes(value, mode = "list") {
237
+ const v = value ?? {};
238
+ mode = v.mode ?? mode;
239
+ if (mode === "save") {
240
+ const saved = v.saved ?? v.scene;
241
+ if (v.ok === false || !saved || typeof saved !== "object") return `场景保存失败:${v.error ?? "未返回已保存场景"}`;
242
+ return `已保存场景:${saved.name ?? "未命名"} id=${saved.id ?? ""}`;
243
+ }
244
+ if (mode === "delete") {
245
+ return v.ok !== false && v.deleted === true ? "场景已删除。" : `场景删除失败:${v.error ?? "场景不存在或未删除"}`;
246
+ }
247
+ if (mode === "run") {
248
+ const steps = Array.isArray(v.steps) ? v.steps : Array.isArray(v.results) ? v.results : [];
249
+ const success = Number.isInteger(v.success) ? v.success : steps.filter((step) => step?.ok === true).length;
250
+ const total = Number.isInteger(v.total) ? v.total : steps.length;
251
+ const failed = Number.isInteger(v.failed) ? v.failed : Math.max(0, total - success);
252
+ const lines = [`场景${v.scene ? `「${typeof v.scene === "object" ? v.scene.name : v.scene}」` : ""}执行${v.ok === true ? "成功" : "失败"}:成功 ${success},失败 ${failed},共 ${total} 步。`];
253
+ if (v.error) lines.push(`错误:${v.error}`);
254
+ for (const [index, step] of steps.entries()) {
255
+ const error = step?.error ?? step?.result?.error;
256
+ lines.push(`${index + 1}. ${step?.device ?? step?.device_id ?? "?"} ${step?.mode ?? ""}:${step?.ok === true ? "成功" : "失败"}${error ? ` · ${error}` : ""}`);
257
+ }
258
+ return lines.join("\n");
259
+ }
260
+ if (v.ok === false) return `读取场景失败:${v.error ?? "未知错误"}`;
261
+ const scenes = Array.isArray(v.scenes) ? v.scenes : [];
262
+ if (!scenes.length) return "还没有保存任何自定义场景。用 smart_home_scenes(mode=save)创建,如「回家时开灯、关窗帘」。";
263
+ const lines = [`共 ${scenes.length} 个自定义场景:`, ""];
264
+ for (const scene of scenes) {
265
+ const actions = Array.isArray(scene?.actions) ? scene.actions : [];
266
+ lines.push(`- ${scene?.name ?? "未命名"}(${actions.length} 个动作)id=${scene?.id ?? ""}`);
267
+ for (const action of actions) {
268
+ const target = action?.device ?? "?";
269
+ const label = action?.name || action?.mode || "";
270
+ const args = ["value", "params", "state"].filter((key) => Object.hasOwn(action ?? {}, key))
271
+ .map((key) => `${key}=${JSON.stringify(action[key])}`).join(" ");
272
+ lines.push(` · ${target} ${action?.mode ?? ""}${label ? ` ${label}` : ""}${args ? ` ${args}` : ""}`);
273
+ }
274
+ }
275
+ lines.push("");
276
+ lines.push("执行:smart_home_scenes(mode=run,scene_id=…);删除:mode=delete。");
277
+ return lines.join("\n").trimEnd();
278
+ }