@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.
- package/README.md +141 -78
- package/client.js +1149 -19
- package/cordis.patch.yml +2 -2
- package/docs/REPAIR-VALIDATION.md +62 -0
- package/lib/bridge.js +126 -44
- package/lib/connections.js +46 -0
- package/lib/format.js +148 -0
- package/lib/index.js +274 -31
- package/lib/panel.js +138 -7
- package/locale/en.json +3 -3
- package/locale/zh.json +2 -2
- package/package.json +13 -4
- package/python/app/core/service.py +62 -31
- package/python/mihome_bridge.py +211 -9
- package/python/smart_home/__init__.py +24 -0
- package/python/smart_home/adapters/__init__.py +50 -0
- package/python/smart_home/adapters/base.py +143 -0
- package/python/smart_home/adapters/ble.py +100 -0
- package/python/smart_home/adapters/dlna.py +227 -0
- package/python/smart_home/adapters/home_assistant.py +454 -0
- package/python/smart_home/adapters/hue.py +225 -0
- package/python/smart_home/adapters/kasa.py +239 -0
- package/python/smart_home/adapters/mihome.py +342 -0
- package/python/smart_home/adapters/network.py +250 -0
- package/python/smart_home/adapters/shelly.py +289 -0
- package/python/smart_home/adapters/tuya.py +95 -0
- package/python/smart_home/adapters/tv.py +26 -0
- package/python/smart_home/catalog.py +336 -0
- package/python/smart_home/cloud.py +85 -0
- package/python/smart_home/discovery.py +934 -0
- package/python/smart_home/localize.py +787 -0
- package/python/smart_home/manager.py +672 -0
- package/python/smart_home/oui_table.py +40550 -0
- package/python/smart_home/scan.py +73 -0
- package/python/smart_home/test_discovery_repairs.py +186 -0
- package/python/smart_home/test_localization_repairs.py +229 -0
- package/python/smart_home/test_offline.py +195 -0
- package/python/smart_home/test_repairs.py +107 -0
- package/python/smart_home/util.py +320 -0
- package/python/tests/test_bridge_integration.py +108 -0
- package/python/tests/test_ha_discovery.py +260 -0
- package/python/tests/test_home_assistant.py +365 -0
- package/python/tests/test_manager_integration.py +150 -0
- package/python/tests/test_mihome_repairs.py +117 -0
- package/python/tests/test_network_read_contract.py +50 -0
- package/python/tests/test_power_confirmation.py +95 -0
- package/python/tests/test_protocol_repairs.py +369 -0
- package/python/tests/test_yeelight_repairs.py +70 -0
- package/requirements-optional.txt +4 -0
- package/requirements.txt +5 -0
- package/scripts/update-oui.py +108 -0
package/client.js
CHANGED
|
@@ -73,6 +73,11 @@ window.__ModuleLoader__.load({
|
|
|
73
73
|
deviceFallback: '设备',
|
|
74
74
|
|
|
75
75
|
// 电源
|
|
76
|
+
turnOn: '开启',
|
|
77
|
+
turnOff: '关闭',
|
|
78
|
+
shConnectionUnknown: '连接状态未知',
|
|
79
|
+
shConnectionRetry: '重试连接状态',
|
|
80
|
+
shRefreshFailed: '刷新设备失败,请重试。',
|
|
76
81
|
power: '电源',
|
|
77
82
|
powerOn: '开机',
|
|
78
83
|
powerOff: '关机',
|
|
@@ -124,6 +129,63 @@ window.__ModuleLoader__.load({
|
|
|
124
129
|
consumableThreshold: '建议更换线',
|
|
125
130
|
consumableAllGood: '所有耗材都还够用',
|
|
126
131
|
consumableAllGoodHint: '等有耗材快用完时,这里会提前提醒你。',
|
|
132
|
+
|
|
133
|
+
// 全屋智能(不限于米家:局域网扫描 + 统一控制)
|
|
134
|
+
shNav: '全屋智能',
|
|
135
|
+
shTitle: '全屋智能',
|
|
136
|
+
shTabMihome: '米家',
|
|
137
|
+
shTabSmart: '全屋',
|
|
138
|
+
shScan: '扫描全屋',
|
|
139
|
+
shScanning: '扫描中…',
|
|
140
|
+
shScanDone: '扫描完成,发现 {n} 台设备。',
|
|
141
|
+
shDevicesCount: '台设备',
|
|
142
|
+
shHint: '这里包含局域网里能发现的设备(路由器、光猫、NAS、电视、灯、开关等)与米家设备。点一台可以看它能控制什么。',
|
|
143
|
+
shNoDevices: '还没发现设备',
|
|
144
|
+
shNoDevicesHint: '点右上角「扫描全屋」,插件会扫描本网段的设备;米家设备在「米家」页签里。',
|
|
145
|
+
shCapabilityError: '能力读取失败',
|
|
146
|
+
shReadError: '状态读取失败',
|
|
147
|
+
shNoControls: '这台设备没有可远程控制的项',
|
|
148
|
+
shNoControlsHint: '能发现它,但它没有公开的控制接口(或需要本地密钥)。可以在设置页 / 官方 App 里操作。',
|
|
149
|
+
shNoScenes: '还没有自定义场景',
|
|
150
|
+
shNoScenesHint: '可以让 AI 帮你建,比如「回家时开灯、关窗帘」,之后在这里一键执行。',
|
|
151
|
+
shWritable: '可写',
|
|
152
|
+
shActions: '个动作',
|
|
153
|
+
shOther: '其他设备',
|
|
154
|
+
shNewScene: '新建场景',
|
|
155
|
+
shEditScene: '编辑',
|
|
156
|
+
shDeleteScene: '删除',
|
|
157
|
+
shSaveScene: '保存场景',
|
|
158
|
+
shCancel: '取消',
|
|
159
|
+
shSceneJSON: '场景 JSON',
|
|
160
|
+
shSceneHelp: '填写 name 和 actions。每个动作明确填写 device、mode(write/action/power/scrape)及所需的 name、value、params 或 state。保存只保存配置,执行按钮才会运行。',
|
|
161
|
+
shJSONInvalid: 'JSON 格式不正确,请检查引号、逗号和括号。',
|
|
162
|
+
shObjectRequired: '请输入 JSON 对象。',
|
|
163
|
+
shSceneNameRequired: '场景需要非空的 name。',
|
|
164
|
+
shSceneActionsRequired: 'actions 至少需要一个动作。',
|
|
165
|
+
shSceneActionInvalid: '第 {n} 个动作缺少 device,或 mode / 参数无效。',
|
|
166
|
+
shSceneRetry: '重试场景',
|
|
167
|
+
shSceneResult: '成功 {success} / {total} 步',
|
|
168
|
+
shStepOK: '成功',
|
|
169
|
+
shStepFailed: '失败',
|
|
170
|
+
shActionObjectHint: '此动作需要 JSON 对象 {},按下面参数结构填写。',
|
|
171
|
+
shActionArrayHint: '此动作需要 JSON 数组 [],按下面输入顺序填写。',
|
|
172
|
+
shActionSchema: '参数结构',
|
|
173
|
+
shActionParams: '动作参数 JSON',
|
|
174
|
+
shActionParamsHint: '明确输入参数 JSON(数组或对象);无参数动作请输入 []。',
|
|
175
|
+
shActionParamsRequired: '请输入参数 JSON;无参数时填写 []。',
|
|
176
|
+
shValueInvalid: '请输入有效的数值。',
|
|
177
|
+
shNotConfirmed: '操作未返回成功确认。',
|
|
178
|
+
shConnection: '配置连接',
|
|
179
|
+
shConnectionJSON: '连接配置 JSON',
|
|
180
|
+
shConnectionTarget: '连接目标 ID',
|
|
181
|
+
shConnectionTargetRequired: '请输入连接目标 ID,例如 home_assistant:main。',
|
|
182
|
+
shConnectionHelp: 'Home Assistant 新连接使用目标 ID home_assistant:main,配置填 base_url、token;小米局域网可填 token;Tuya 可填 local_key、device_id、version 和 dps(显式 DP 映射,如 {"power":"1"})。只保存到私有凭据,不会回显原值。保存会替换该目标整份配置。',
|
|
183
|
+
shConnectionSave: '保存连接',
|
|
184
|
+
shConnectionDelete: '删除连接',
|
|
185
|
+
shConnectionConfigured: '已保存连接配置',
|
|
186
|
+
shConnectionEmpty: '尚未保存连接配置',
|
|
187
|
+
shConnectionFailed: '连接配置未保存,请检查字段或稍后重试。',
|
|
188
|
+
shConnectionDeleteFailed: '连接配置未删除,请稍后重试。',
|
|
127
189
|
},
|
|
128
190
|
en: {
|
|
129
191
|
nav: 'Mi Home',
|
|
@@ -164,6 +226,11 @@ window.__ModuleLoader__.load({
|
|
|
164
226
|
noDevicesHint: 'Add devices in the Mi Home app and they show up here.',
|
|
165
227
|
deviceFallback: 'Device',
|
|
166
228
|
|
|
229
|
+
turnOn: 'On',
|
|
230
|
+
turnOff: 'Off',
|
|
231
|
+
shConnectionUnknown: 'Connection status unknown',
|
|
232
|
+
shConnectionRetry: 'Retry connection status',
|
|
233
|
+
shRefreshFailed: 'Device refresh failed. Try again.',
|
|
167
234
|
power: 'Power',
|
|
168
235
|
powerOn: 'Turn on',
|
|
169
236
|
powerOff: 'Turn off',
|
|
@@ -211,6 +278,63 @@ window.__ModuleLoader__.load({
|
|
|
211
278
|
consumableThreshold: 'Replace below',
|
|
212
279
|
consumableAllGood: 'All consumables are fine',
|
|
213
280
|
consumableAllGoodHint: 'You will be warned here before one runs out.',
|
|
281
|
+
|
|
282
|
+
// Whole-home smart devices (LAN scan + unified control, not only Mi Home)
|
|
283
|
+
shNav: 'Smart Home',
|
|
284
|
+
shTitle: 'Whole-home devices',
|
|
285
|
+
shTabMihome: 'Mi Home',
|
|
286
|
+
shTabSmart: 'Whole home',
|
|
287
|
+
shScan: 'Scan',
|
|
288
|
+
shScanning: 'Scanning…',
|
|
289
|
+
shScanDone: 'Scan finished: {n} device(s) found.',
|
|
290
|
+
shDevicesCount: 'devices',
|
|
291
|
+
shHint: 'Devices found on your LAN (routers, ONTs, NAS, TVs, lights, switches…) plus Mi Home devices. Tap one to see what it can do.',
|
|
292
|
+
shNoDevices: 'No devices found yet',
|
|
293
|
+
shNoDevicesHint: 'Press "Scan" to look for devices on your subnet. Mi Home devices live on the Mi Home tab.',
|
|
294
|
+
shCapabilityError: 'Could not read capabilities',
|
|
295
|
+
shReadError: 'Could not read device state',
|
|
296
|
+
shNoControls: 'No remotely controllable items',
|
|
297
|
+
shNoControlsHint: 'The device was found but exposes no public control interface (or needs a local key). Use its settings page or official app.',
|
|
298
|
+
shNoScenes: 'No custom scenes yet',
|
|
299
|
+
shNoScenesHint: 'Ask the AI to create one, e.g. "when I get home, turn on the lights and close the curtains", then run it here.',
|
|
300
|
+
shWritable: 'writable',
|
|
301
|
+
shActions: 'action(s)',
|
|
302
|
+
shOther: 'Other devices',
|
|
303
|
+
shNewScene: 'New scene',
|
|
304
|
+
shEditScene: 'Edit',
|
|
305
|
+
shDeleteScene: 'Delete',
|
|
306
|
+
shSaveScene: 'Save scene',
|
|
307
|
+
shCancel: 'Cancel',
|
|
308
|
+
shSceneJSON: 'Scene JSON',
|
|
309
|
+
shSceneHelp: 'Enter name and actions. Each action must explicitly specify device, mode (write/action/power/scrape), and required name, value, params, or state. Save stores the configuration; only Run executes it.',
|
|
310
|
+
shJSONInvalid: 'Invalid JSON. Check quotes, commas, and brackets.',
|
|
311
|
+
shObjectRequired: 'Enter a JSON object.',
|
|
312
|
+
shSceneNameRequired: 'Scene name is required.',
|
|
313
|
+
shSceneActionsRequired: 'At least one action is required.',
|
|
314
|
+
shSceneActionInvalid: 'Action {n} is missing device or has an invalid mode or parameters.',
|
|
315
|
+
shSceneRetry: 'Retry scenes',
|
|
316
|
+
shSceneResult: 'Successful steps: {success} / {total}',
|
|
317
|
+
shStepOK: 'Succeeded',
|
|
318
|
+
shStepFailed: 'Failed',
|
|
319
|
+
shActionObjectHint: 'This action requires a JSON object {} matching the structure below.',
|
|
320
|
+
shActionArrayHint: 'This action requires a JSON array [] in the input order below.',
|
|
321
|
+
shActionSchema: 'Parameter structure',
|
|
322
|
+
shActionParams: 'Action parameters JSON',
|
|
323
|
+
shActionParamsHint: 'Explicitly enter parameters as JSON (array or object); enter [] for an action without parameters.',
|
|
324
|
+
shActionParamsRequired: 'Enter params as JSON; use [] when no parameters are needed.',
|
|
325
|
+
shValueInvalid: 'Enter a valid number.',
|
|
326
|
+
shNotConfirmed: 'The operation did not return success confirmation.',
|
|
327
|
+
shConnection: 'Connection settings',
|
|
328
|
+
shConnectionJSON: 'Connection JSON',
|
|
329
|
+
shConnectionTarget: 'Connection target ID',
|
|
330
|
+
shConnectionTargetRequired: 'Enter a connection target ID, e.g. home_assistant:main.',
|
|
331
|
+
shConnectionHelp: 'For a new Home Assistant connection, use target ID home_assistant:main and enter base_url and token. Mi Home LAN may use token; Tuya may use local_key, device_id, version, and dps (explicit DP mapping, e.g. {"power":"1"}). Stored privately and never read back. Saving replaces the entire target configuration.',
|
|
332
|
+
shConnectionSave: 'Save connection',
|
|
333
|
+
shConnectionDelete: 'Delete connection',
|
|
334
|
+
shConnectionConfigured: 'Connection configuration saved',
|
|
335
|
+
shConnectionEmpty: 'No connection configuration saved',
|
|
336
|
+
shConnectionFailed: 'Connection configuration was not saved. Check the fields or try again.',
|
|
337
|
+
shConnectionDeleteFailed: 'Connection configuration was not deleted. Try again.',
|
|
214
338
|
},
|
|
215
339
|
};
|
|
216
340
|
|
|
@@ -234,8 +358,27 @@ window.__ModuleLoader__.load({
|
|
|
234
358
|
radiusMd: 'var(--dsw-radius-md, 12px)',
|
|
235
359
|
};
|
|
236
360
|
|
|
237
|
-
//
|
|
238
|
-
const ORANGE =
|
|
361
|
+
// 高亮跟随宿主主题;未提供主题 token 时使用米家品牌色回退。
|
|
362
|
+
const ORANGE = C.brand;
|
|
363
|
+
const brandTint = (percent) => `color-mix(in srgb, ${C.brand} ${percent}%, transparent)`;
|
|
364
|
+
|
|
365
|
+
function booleanState(value) {
|
|
366
|
+
if (value === true || value === 1) return true;
|
|
367
|
+
if (value === false || value === 0) return false;
|
|
368
|
+
if (typeof value === 'string') {
|
|
369
|
+
const normalized = value.trim().toLowerCase();
|
|
370
|
+
if (['true', 'on', '1'].includes(normalized)) return true;
|
|
371
|
+
if (['false', 'off', '0'].includes(normalized)) return false;
|
|
372
|
+
}
|
|
373
|
+
return undefined;
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
function unknownBoolean(t, label, disabled, onChange) {
|
|
377
|
+
return h('div', { role: 'group', 'aria-label': label, style: { display: 'flex', gap: 6, alignItems: 'center', flexWrap: 'wrap' } },
|
|
378
|
+
h('span', { style: muted }, t('unknown')),
|
|
379
|
+
h('button', { type: 'button', ...focusable, style: btn(), disabled, onClick: () => onChange(true) }, t('turnOn')),
|
|
380
|
+
h('button', { type: 'button', ...focusable, style: btn(), disabled, onClick: () => onChange(false) }, t('turnOff')));
|
|
381
|
+
}
|
|
239
382
|
|
|
240
383
|
/* ---------------------------------------------------------------- 工具 */
|
|
241
384
|
|
|
@@ -261,8 +404,9 @@ window.__ModuleLoader__.load({
|
|
|
261
404
|
} catch {
|
|
262
405
|
body = null;
|
|
263
406
|
}
|
|
264
|
-
|
|
265
|
-
|
|
407
|
+
const failure = body?.ok === false ? body : body?.result?.ok === false ? body.result : null;
|
|
408
|
+
if (!res.ok || failure) {
|
|
409
|
+
const error = new Error(failure?.error || body?.error || `${res.status} ${path}`);
|
|
266
410
|
error.body = body;
|
|
267
411
|
throw error;
|
|
268
412
|
}
|
|
@@ -426,7 +570,7 @@ window.__ModuleLoader__.load({
|
|
|
426
570
|
/* -------------------------------------------------------------- 控件 */
|
|
427
571
|
|
|
428
572
|
/** 开关(不用原生 checkbox,颜色跟主题走)。 */
|
|
429
|
-
function Switch({ checked, disabled, onChange, label }) {
|
|
573
|
+
function Switch({ checked, disabled, onChange, label, ...accessibility }) {
|
|
430
574
|
const on = Boolean(checked);
|
|
431
575
|
return h(
|
|
432
576
|
'button',
|
|
@@ -435,6 +579,7 @@ window.__ModuleLoader__.load({
|
|
|
435
579
|
role: 'switch',
|
|
436
580
|
'aria-checked': on,
|
|
437
581
|
'aria-label': label,
|
|
582
|
+
...accessibility,
|
|
438
583
|
disabled,
|
|
439
584
|
onClick: () => onChange(!on),
|
|
440
585
|
...focusable,
|
|
@@ -889,6 +1034,7 @@ window.__ModuleLoader__.load({
|
|
|
889
1034
|
onClick: () => onOpen(device),
|
|
890
1035
|
...focusable,
|
|
891
1036
|
onKeyDown: (e) => {
|
|
1037
|
+
if (e.target !== e.currentTarget) return;
|
|
892
1038
|
if (e.key === 'Enter' || e.key === ' ') {
|
|
893
1039
|
e.preventDefault();
|
|
894
1040
|
onOpen(device);
|
|
@@ -914,7 +1060,7 @@ window.__ModuleLoader__.load({
|
|
|
914
1060
|
position: 'absolute',
|
|
915
1061
|
inset: 0,
|
|
916
1062
|
borderRadius: C.radiusMd,
|
|
917
|
-
background:
|
|
1063
|
+
background: brandTint(6),
|
|
918
1064
|
pointerEvents: 'none',
|
|
919
1065
|
},
|
|
920
1066
|
})
|
|
@@ -1067,7 +1213,7 @@ window.__ModuleLoader__.load({
|
|
|
1067
1213
|
const props = detail?.props ?? [];
|
|
1068
1214
|
const actions = detail?.actions ?? [];
|
|
1069
1215
|
const powerProp = props.find((p) => p.name === 'on');
|
|
1070
|
-
const powerOn = values?.on;
|
|
1216
|
+
const powerOn = booleanState(values?.on);
|
|
1071
1217
|
const commonProps = props.filter((p) => p.writable && p.name !== 'on' && !p.advanced);
|
|
1072
1218
|
const readonlyProps = props.filter((p) => !p.writable && !p.advanced);
|
|
1073
1219
|
const advancedProps = props.filter((p) => p.advanced);
|
|
@@ -1170,7 +1316,9 @@ window.__ModuleLoader__.load({
|
|
|
1170
1316
|
problem && !/公开的功能规格/.test(problem)
|
|
1171
1317
|
? h('div', { style: { ...muted, marginTop: 8 } }, problem)
|
|
1172
1318
|
: null,
|
|
1173
|
-
powerProp
|
|
1319
|
+
powerProp && powerOn === undefined
|
|
1320
|
+
? unknownBoolean(t, t('power'), busy || !online, runPower)
|
|
1321
|
+
: powerProp
|
|
1174
1322
|
? h(
|
|
1175
1323
|
'div',
|
|
1176
1324
|
{ style: { marginTop: 14 } },
|
|
@@ -1197,7 +1345,9 @@ window.__ModuleLoader__.load({
|
|
|
1197
1345
|
}
|
|
1198
1346
|
|
|
1199
1347
|
const powerBlock =
|
|
1200
|
-
|
|
1348
|
+
powerProp && powerOn === undefined
|
|
1349
|
+
? h('div', { style: { ...card, padding: 18 } }, unknownBoolean(t, t('power'), busy || !online, runPower))
|
|
1350
|
+
: typeof powerOn === 'boolean' || powerProp
|
|
1201
1351
|
? h(
|
|
1202
1352
|
'div',
|
|
1203
1353
|
{
|
|
@@ -1208,8 +1358,8 @@ window.__ModuleLoader__.load({
|
|
|
1208
1358
|
alignItems: 'center',
|
|
1209
1359
|
justifyContent: 'space-between',
|
|
1210
1360
|
gap: 16,
|
|
1211
|
-
background: powerOn ?
|
|
1212
|
-
borderColor: powerOn ?
|
|
1361
|
+
background: powerOn ? brandTint(7) : C.bgBase,
|
|
1362
|
+
borderColor: powerOn ? brandTint(35) : C.border,
|
|
1213
1363
|
},
|
|
1214
1364
|
},
|
|
1215
1365
|
h(
|
|
@@ -1434,10 +1584,923 @@ window.__ModuleLoader__.load({
|
|
|
1434
1584
|
|
|
1435
1585
|
/* ---------------------------------------------------------------- 面板 */
|
|
1436
1586
|
|
|
1587
|
+
/* -------------------------------------------------------- 全屋智能面板 */
|
|
1588
|
+
|
|
1589
|
+
/**
|
|
1590
|
+
* 全屋设备面板。
|
|
1591
|
+
*
|
|
1592
|
+
* 与米家面板的区别:这里的设备大多在**局域网**(路由器、光猫、NAS、
|
|
1593
|
+
* 第三方灯/开关…),不需要米家账号,所以刻意不放在登录门禁后面。
|
|
1594
|
+
*
|
|
1595
|
+
* 数据流:/smart-home/devices 拿清单 → 按类别分组 → 点开单台拉详情
|
|
1596
|
+
* (能力项已由 Python 侧翻译成中文)→ 控制走 /smart-home/control。
|
|
1597
|
+
*/
|
|
1598
|
+
function SmartHomePanel({ t }) {
|
|
1599
|
+
const [devices, setDevices] = useState([]);
|
|
1600
|
+
const [scenes, setScenes] = useState([]);
|
|
1601
|
+
const [scenesReady, setScenesReady] = useState(false);
|
|
1602
|
+
const [sceneLoadError, setSceneLoadError] = useState('');
|
|
1603
|
+
const [sceneRunDetails, setSceneRunDetails] = useState({});
|
|
1604
|
+
const [ready, setReady] = useState(false);
|
|
1605
|
+
const [error, setError] = useState('');
|
|
1606
|
+
const [scanning, setScanning] = useState(false);
|
|
1607
|
+
const [openId, setOpenId] = useState('');
|
|
1608
|
+
const [detail, setDetail] = useState(null);
|
|
1609
|
+
const [detailError, setDetailError] = useState('');
|
|
1610
|
+
const [busy, setBusy] = useState('');
|
|
1611
|
+
const [toast, setToast] = useState('');
|
|
1612
|
+
const [mode, setMode] = useState('smart'); // 面板内部页签:设备 / 场景
|
|
1613
|
+
const [sceneDraft, setSceneDraft] = useState('');
|
|
1614
|
+
const [editingScene, setEditingScene] = useState(null);
|
|
1615
|
+
const [sceneError, setSceneError] = useState('');
|
|
1616
|
+
const [credentialStatus, setCredentialStatus] = useState('loading');
|
|
1617
|
+
const [credentialRefreshError, setCredentialRefreshError] = useState('');
|
|
1618
|
+
const [configuredCredentialIds, setConfiguredCredentialIds] = useState([]);
|
|
1619
|
+
const [credentialTarget, setCredentialTarget] = useState('home_assistant:main');
|
|
1620
|
+
const [credentialDraft, setCredentialDraft] = useState('');
|
|
1621
|
+
const [credentialBusy, setCredentialBusy] = useState(false);
|
|
1622
|
+
const requestVersion = useRef(0);
|
|
1623
|
+
const listRequestVersion = useRef(0);
|
|
1624
|
+
const sceneRequestVersion = useRef(0);
|
|
1625
|
+
const operationVersion = useRef(0);
|
|
1626
|
+
const toastTimer = useRef(null);
|
|
1627
|
+
const credentialRequestVersion = useRef(0);
|
|
1628
|
+
|
|
1629
|
+
const flash = (message, isError) => {
|
|
1630
|
+
clearTimeout(toastTimer.current);
|
|
1631
|
+
setToast(isError ? `${t('errorPrefix')}${message}` : message);
|
|
1632
|
+
toastTimer.current = setTimeout(() => setToast(''), isError ? 3600 : 1800);
|
|
1633
|
+
};
|
|
1634
|
+
|
|
1635
|
+
const loadCredentials = useCallback(async () => {
|
|
1636
|
+
const request = ++credentialRequestVersion.current;
|
|
1637
|
+
setCredentialStatus('loading');
|
|
1638
|
+
try {
|
|
1639
|
+
const result = await getJSON('smart-home/credentials');
|
|
1640
|
+
if (!Array.isArray(result.devices)) throw new Error('Invalid credential status');
|
|
1641
|
+
if (request !== credentialRequestVersion.current) return;
|
|
1642
|
+
setConfiguredCredentialIds(result.devices);
|
|
1643
|
+
setCredentialStatus('ready');
|
|
1644
|
+
} catch {
|
|
1645
|
+
if (request === credentialRequestVersion.current) setCredentialStatus('unknown');
|
|
1646
|
+
}
|
|
1647
|
+
}, []);
|
|
1648
|
+
|
|
1649
|
+
const loadScenes = useCallback(async () => {
|
|
1650
|
+
const request = ++sceneRequestVersion.current;
|
|
1651
|
+
setSceneLoadError(''); setScenesReady(false);
|
|
1652
|
+
try {
|
|
1653
|
+
const result = await getJSON('smart-home/scenes');
|
|
1654
|
+
if (request === sceneRequestVersion.current) setScenes(Array.isArray(result.scenes) ? result.scenes : []);
|
|
1655
|
+
} catch (err) {
|
|
1656
|
+
if (request === sceneRequestVersion.current) setSceneLoadError(err?.body?.error ?? err.message ?? String(err));
|
|
1657
|
+
} finally { if (request === sceneRequestVersion.current) setScenesReady(true); }
|
|
1658
|
+
}, []);
|
|
1659
|
+
|
|
1660
|
+
const load = useCallback(
|
|
1661
|
+
async (force) => {
|
|
1662
|
+
const request = ++listRequestVersion.current;
|
|
1663
|
+
setError(''); setReady(false); setScanning(false);
|
|
1664
|
+
const scenesRequest = loadScenes();
|
|
1665
|
+
try {
|
|
1666
|
+
const dev = await getJSON(`smart-home/devices${force ? '?refresh=1' : ''}`);
|
|
1667
|
+
if (request === listRequestVersion.current) setDevices(Array.isArray(dev.devices) ? dev.devices : []);
|
|
1668
|
+
} catch (err) {
|
|
1669
|
+
if (request === listRequestVersion.current) setError(err?.body?.error ?? err.message ?? String(err));
|
|
1670
|
+
} finally {
|
|
1671
|
+
if (request === listRequestVersion.current) setReady(true);
|
|
1672
|
+
await scenesRequest;
|
|
1673
|
+
}
|
|
1674
|
+
},
|
|
1675
|
+
[loadScenes],
|
|
1676
|
+
);
|
|
1677
|
+
|
|
1678
|
+
useEffect(() => {
|
|
1679
|
+
load(false);
|
|
1680
|
+
loadCredentials();
|
|
1681
|
+
return () => { requestVersion.current += 1; listRequestVersion.current += 1; sceneRequestVersion.current += 1; operationVersion.current += 1; credentialRequestVersion.current += 1; clearTimeout(toastTimer.current); };
|
|
1682
|
+
}, [load, loadCredentials]);
|
|
1683
|
+
|
|
1684
|
+
const scan = async () => {
|
|
1685
|
+
const request = ++listRequestVersion.current;
|
|
1686
|
+
setScanning(true); setError('');
|
|
1687
|
+
try {
|
|
1688
|
+
const result = await getJSON('smart-home/scan?force=1');
|
|
1689
|
+
if (request !== listRequestVersion.current) return;
|
|
1690
|
+
const list = Array.isArray(result.devices) ? result.devices : [];
|
|
1691
|
+
setDevices(list);
|
|
1692
|
+
flash(tf(t, 'shScanDone', { n: list.length }));
|
|
1693
|
+
} catch (err) {
|
|
1694
|
+
if (request === listRequestVersion.current) flash(err?.body?.error ?? err.message ?? String(err), true);
|
|
1695
|
+
} finally {
|
|
1696
|
+
if (request === listRequestVersion.current) { setScanning(false); setReady(true); }
|
|
1697
|
+
}
|
|
1698
|
+
};
|
|
1699
|
+
|
|
1700
|
+
const openDevice = async (device) => {
|
|
1701
|
+
const version = ++requestVersion.current;
|
|
1702
|
+
operationVersion.current += 1;
|
|
1703
|
+
setBusy('');
|
|
1704
|
+
setOpenId(device.id);
|
|
1705
|
+
setCredentialTarget(device.id);
|
|
1706
|
+
setDetail(null);
|
|
1707
|
+
setDetailError('');
|
|
1708
|
+
setCredentialDraft(''); setCredentialRefreshError('');
|
|
1709
|
+
loadCredentials();
|
|
1710
|
+
try {
|
|
1711
|
+
const result = await getJSON(`smart-home/device?id=${encodeURIComponent(device.id)}`);
|
|
1712
|
+
if (requestVersion.current !== version) return;
|
|
1713
|
+
setDetail(result.detail ?? null);
|
|
1714
|
+
} catch (err) {
|
|
1715
|
+
if (requestVersion.current === version) setDetailError(err?.body?.error ?? err.message ?? String(err));
|
|
1716
|
+
}
|
|
1717
|
+
};
|
|
1718
|
+
|
|
1719
|
+
const control = async (deviceId, body, label) => {
|
|
1720
|
+
const version = requestVersion.current;
|
|
1721
|
+
const operation = ++operationVersion.current;
|
|
1722
|
+
setBusy(`${deviceId}:${label}`);
|
|
1723
|
+
try {
|
|
1724
|
+
const result = await postJSON('smart-home/control', { device_id: deviceId, ...body });
|
|
1725
|
+
if (result?.ok !== true || result?.result?.ok === false) throw new Error(result?.error ?? result?.result?.error ?? t('shNotConfirmed'));
|
|
1726
|
+
if (operationVersion.current === operation && requestVersion.current === version && openId === deviceId) flash(t('done'));
|
|
1727
|
+
if (requestVersion.current === version && openId === deviceId) {
|
|
1728
|
+
const refreshed = await getJSON(`smart-home/device?id=${encodeURIComponent(deviceId)}`);
|
|
1729
|
+
if (requestVersion.current === version && openId === deviceId) setDetail(refreshed.detail ?? null);
|
|
1730
|
+
}
|
|
1731
|
+
} catch (err) {
|
|
1732
|
+
if (operationVersion.current === operation && requestVersion.current === version && openId === deviceId)
|
|
1733
|
+
flash(err?.body?.error ?? err.message ?? String(err), true);
|
|
1734
|
+
} finally {
|
|
1735
|
+
if (operationVersion.current === operation) setBusy('');
|
|
1736
|
+
}
|
|
1737
|
+
};
|
|
1738
|
+
|
|
1739
|
+
const runScene = async (scene) => {
|
|
1740
|
+
setBusy(`scene:${scene.id}`);
|
|
1741
|
+
try {
|
|
1742
|
+
const result = await postJSON('smart-home/scene', { mode: 'run', scene_id: scene.id });
|
|
1743
|
+
setSceneRunDetails((previous) => ({ ...previous, [scene.id]: result.result ?? result }));
|
|
1744
|
+
if (result?.ok !== true || result?.result?.ok === false) throw new Error(t('shNotConfirmed'));
|
|
1745
|
+
flash(t('done'));
|
|
1746
|
+
} catch (err) {
|
|
1747
|
+
if (err?.body) setSceneRunDetails((previous) => ({ ...previous, [scene.id]: err.body.result ?? err.body }));
|
|
1748
|
+
flash(err?.body?.error ?? err.message ?? String(err), true);
|
|
1749
|
+
} finally {
|
|
1750
|
+
setBusy('');
|
|
1751
|
+
}
|
|
1752
|
+
};
|
|
1753
|
+
|
|
1754
|
+
const saveScene = async () => {
|
|
1755
|
+
let scene;
|
|
1756
|
+
try { scene = JSON.parse(sceneDraft); }
|
|
1757
|
+
catch { setSceneError(t('shJSONInvalid')); return; }
|
|
1758
|
+
if (!scene || typeof scene !== 'object' || Array.isArray(scene)) { setSceneError(t('shObjectRequired')); return; }
|
|
1759
|
+
if (!String(scene.name ?? '').trim()) { setSceneError(t('shSceneNameRequired')); return; }
|
|
1760
|
+
if (!Array.isArray(scene.actions) || !scene.actions.length) { setSceneError(t('shSceneActionsRequired')); return; }
|
|
1761
|
+
const modes = new Set(['power', 'write', 'action', 'scrape']);
|
|
1762
|
+
for (const [index, action] of scene.actions.entries()) {
|
|
1763
|
+
if (!action || typeof action !== 'object' || Array.isArray(action) || !String(action.device ?? '').trim() || !modes.has(action.mode ?? 'write') ||
|
|
1764
|
+
(['write', 'action'].includes(action.mode ?? 'write') && !String(action.name ?? '').trim()) ||
|
|
1765
|
+
(action.mode === 'power' && action.state !== undefined && typeof action.state !== 'boolean') ||
|
|
1766
|
+
(action.mode === 'action' && !Object.hasOwn(action, 'params'))) {
|
|
1767
|
+
setSceneError(tf(t, 'shSceneActionInvalid', { n: index + 1 })); return;
|
|
1768
|
+
}
|
|
1769
|
+
}
|
|
1770
|
+
setSceneError(''); setBusy('scene:edit');
|
|
1771
|
+
try {
|
|
1772
|
+
const result = await postJSON('smart-home/scene', { mode: 'save', scene });
|
|
1773
|
+
if (result?.ok !== true || result?.result?.ok === false) throw new Error(t('shNotConfirmed'));
|
|
1774
|
+
if (Array.isArray(result?.scenes)) setScenes(result.scenes);
|
|
1775
|
+
else await load(false);
|
|
1776
|
+
setEditingScene(null); setSceneDraft(''); flash(t('done'));
|
|
1777
|
+
} catch (err) { setSceneError(err?.body?.error ?? err.message ?? String(err)); }
|
|
1778
|
+
finally { setBusy(''); }
|
|
1779
|
+
};
|
|
1780
|
+
|
|
1781
|
+
const deleteScene = async (scene) => {
|
|
1782
|
+
setBusy(`scene:${scene.id}`);
|
|
1783
|
+
try {
|
|
1784
|
+
const result = await postJSON('smart-home/scene', { mode: 'delete', scene_id: scene.id });
|
|
1785
|
+
if (result?.deleted !== true && result?.result?.deleted !== true) throw new Error(t('shNotConfirmed'));
|
|
1786
|
+
if (Array.isArray(result?.scenes)) setScenes(result.scenes);
|
|
1787
|
+
else setScenes((previous) => previous.filter((item) => item.id !== scene.id));
|
|
1788
|
+
flash(t('done'));
|
|
1789
|
+
} catch (err) { flash(err?.body?.error ?? err.message ?? String(err), true); }
|
|
1790
|
+
finally { setBusy(''); }
|
|
1791
|
+
};
|
|
1792
|
+
|
|
1793
|
+
const refreshAfterCredentials = async (target, version) => {
|
|
1794
|
+
if (requestVersion.current !== version) return;
|
|
1795
|
+
if (!openId) { await load(false); return; }
|
|
1796
|
+
try {
|
|
1797
|
+
const refreshed = await getJSON(`smart-home/device?id=${encodeURIComponent(target)}`);
|
|
1798
|
+
if (requestVersion.current === version) setDetail(refreshed.detail ?? null);
|
|
1799
|
+
} catch {
|
|
1800
|
+
if (requestVersion.current === version) setCredentialRefreshError(t('shRefreshFailed'));
|
|
1801
|
+
}
|
|
1802
|
+
};
|
|
1803
|
+
|
|
1804
|
+
const saveCredentials = async () => {
|
|
1805
|
+
const version = requestVersion.current;
|
|
1806
|
+
const target = (credentialTarget || '').trim() || openId;
|
|
1807
|
+
if (!target) { flash(t('shConnectionTargetRequired'), true); return; }
|
|
1808
|
+
let payload;
|
|
1809
|
+
try { payload = JSON.parse(credentialDraft); }
|
|
1810
|
+
catch { flash(t('shJSONInvalid'), true); return; }
|
|
1811
|
+
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) { flash(t('shObjectRequired'), true); return; }
|
|
1812
|
+
setCredentialDraft(''); setCredentialBusy(true); setCredentialRefreshError('');
|
|
1813
|
+
let saved = false;
|
|
1814
|
+
try {
|
|
1815
|
+
const result = await postJSON('smart-home/credentials', { device_id: target, mode: 'save', payload });
|
|
1816
|
+
if (result?.ok !== true || result?.result?.ok === false) throw new Error(t('shConnectionFailed'));
|
|
1817
|
+
credentialRequestVersion.current += 1;
|
|
1818
|
+
setConfiguredCredentialIds((previous) => Array.from(new Set([...previous, target])));
|
|
1819
|
+
setCredentialStatus('ready');
|
|
1820
|
+
saved = true; flash(t('shConnectionConfigured'));
|
|
1821
|
+
} catch { flash(t('shConnectionFailed'), true); }
|
|
1822
|
+
finally { setCredentialBusy(false); }
|
|
1823
|
+
if (saved) await refreshAfterCredentials(target, version);
|
|
1824
|
+
};
|
|
1825
|
+
|
|
1826
|
+
const removeCredentials = async () => {
|
|
1827
|
+
const version = requestVersion.current;
|
|
1828
|
+
const target = (credentialTarget || '').trim() || openId;
|
|
1829
|
+
if (!target) { flash(t('shConnectionTargetRequired'), true); return; }
|
|
1830
|
+
setCredentialBusy(true); setCredentialDraft(''); setCredentialRefreshError('');
|
|
1831
|
+
let deleted = false;
|
|
1832
|
+
try {
|
|
1833
|
+
const result = await postJSON('smart-home/credentials', { device_id: target, mode: 'delete' });
|
|
1834
|
+
if (result?.ok !== true || result?.result?.ok === false || (Object.hasOwn(result, 'configured') && result.configured !== false))
|
|
1835
|
+
throw new Error(t('shConnectionDeleteFailed'));
|
|
1836
|
+
credentialRequestVersion.current += 1;
|
|
1837
|
+
setConfiguredCredentialIds((previous) => previous.filter((id) => id !== target));
|
|
1838
|
+
setCredentialStatus('ready');
|
|
1839
|
+
deleted = true; flash(t('shConnectionEmpty'));
|
|
1840
|
+
} catch { flash(t('shConnectionDeleteFailed'), true); }
|
|
1841
|
+
finally { setCredentialBusy(false); }
|
|
1842
|
+
if (deleted) await refreshAfterCredentials(target, version);
|
|
1843
|
+
};
|
|
1844
|
+
|
|
1845
|
+
const connectionEditor = h('details', { open: !openId && (!devices.length || Boolean(error)), style: { ...card, padding: 16, marginTop: 16 } },
|
|
1846
|
+
h('summary', { ...focusable, style: { cursor: 'pointer', fontSize: 13, color: C.label, outline: '2px solid transparent' } }, t('shConnection')),
|
|
1847
|
+
!openId ? h('input', { type: 'text', 'aria-label': t('shConnectionTarget'), value: credentialTarget,
|
|
1848
|
+
disabled: credentialBusy, onChange: (event) => { setCredentialTarget(event.target.value); setCredentialDraft(''); },
|
|
1849
|
+
style: btn({ width: '100%', boxSizing: 'border-box', marginTop: 10 }) }) : null,
|
|
1850
|
+
h('div', { role: credentialStatus === 'unknown' ? 'alert' : 'status', style: { ...muted, marginTop: 8, color: credentialStatus === 'unknown' ? C.error : C.label3 } },
|
|
1851
|
+
credentialStatus === 'unknown' ? t('shConnectionUnknown') : credentialStatus === 'loading' ? t('loading') :
|
|
1852
|
+
configuredCredentialIds.some((id) => id === (openId || credentialTarget.trim()) ||
|
|
1853
|
+
(openId && id.startsWith('home_assistant:') && openId.startsWith(`${id}/`)))
|
|
1854
|
+
? t('shConnectionConfigured') : t('shConnectionEmpty')),
|
|
1855
|
+
credentialStatus === 'unknown' ? h('button', { type: 'button', ...focusable, style: btn({ marginTop: 6 }), onClick: loadCredentials }, t('shConnectionRetry')) : null,
|
|
1856
|
+
credentialRefreshError ? h('div', { role: 'alert', style: { color: C.error, marginTop: 6 } }, credentialRefreshError) : null,
|
|
1857
|
+
h('div', { style: { ...muted, lineHeight: '20px', margin: '8px 0' } }, t('shConnectionHelp')),
|
|
1858
|
+
h('textarea', { 'aria-label': t('shConnectionJSON'), value: credentialDraft, rows: 5, disabled: credentialBusy,
|
|
1859
|
+
autoComplete: 'off', spellCheck: false, onChange: (event) => setCredentialDraft(event.target.value),
|
|
1860
|
+
style: btn({ width: '100%', boxSizing: 'border-box', fontFamily: 'monospace', resize: 'vertical', textAlign: 'left' }) }),
|
|
1861
|
+
h('div', { style: { display: 'flex', gap: 8, marginTop: 8 } },
|
|
1862
|
+
h('button', { type: 'button', ...focusable, style: btn(), disabled: credentialBusy, onClick: saveCredentials }, t('shConnectionSave')),
|
|
1863
|
+
h('button', { type: 'button', ...focusable, style: btn({ color: C.error }), disabled: credentialBusy, onClick: removeCredentials }, t('shConnectionDelete')),
|
|
1864
|
+
),
|
|
1865
|
+
);
|
|
1866
|
+
|
|
1867
|
+
const header = h(
|
|
1868
|
+
'div',
|
|
1869
|
+
{
|
|
1870
|
+
style: {
|
|
1871
|
+
display: 'flex',
|
|
1872
|
+
alignItems: 'center',
|
|
1873
|
+
justifyContent: 'space-between',
|
|
1874
|
+
gap: 12,
|
|
1875
|
+
paddingBottom: 12,
|
|
1876
|
+
borderBottom: `1px solid ${C.border}`,
|
|
1877
|
+
...stickyHeader(),
|
|
1878
|
+
},
|
|
1879
|
+
},
|
|
1880
|
+
h(
|
|
1881
|
+
'div',
|
|
1882
|
+
null,
|
|
1883
|
+
h('div', { style: { fontSize: 18, fontWeight: 600, color: C.label } }, t('shTitle')),
|
|
1884
|
+
h(
|
|
1885
|
+
'div',
|
|
1886
|
+
{ style: { ...muted, marginTop: 2 } },
|
|
1887
|
+
`${devices.length} ${t('shDevicesCount')}`,
|
|
1888
|
+
),
|
|
1889
|
+
),
|
|
1890
|
+
h(
|
|
1891
|
+
'div',
|
|
1892
|
+
{ style: { display: 'flex', gap: 8 } },
|
|
1893
|
+
h(
|
|
1894
|
+
'button',
|
|
1895
|
+
{ type: 'button', ...focusable, style: btn({ background: C.bgLayer1 }), onClick: () => load(false) },
|
|
1896
|
+
t('refresh'),
|
|
1897
|
+
),
|
|
1898
|
+
h(
|
|
1899
|
+
'button',
|
|
1900
|
+
{
|
|
1901
|
+
type: 'button',
|
|
1902
|
+
...focusable,
|
|
1903
|
+
disabled: scanning,
|
|
1904
|
+
style: btn({
|
|
1905
|
+
background: scanning ? C.bgLayer1 : ORANGE,
|
|
1906
|
+
color: scanning ? C.label2 : '#fff',
|
|
1907
|
+
border: `1px solid ${scanning ? C.border : ORANGE}`,
|
|
1908
|
+
cursor: scanning ? 'progress' : 'pointer',
|
|
1909
|
+
}),
|
|
1910
|
+
onClick: scan,
|
|
1911
|
+
},
|
|
1912
|
+
scanning ? t('shScanning') : t('shScan'),
|
|
1913
|
+
),
|
|
1914
|
+
),
|
|
1915
|
+
);
|
|
1916
|
+
|
|
1917
|
+
if (!ready) {
|
|
1918
|
+
return h('div', { style: PAGE }, header, h('div', { style: { ...muted, marginTop: 16 } }, t('loading')));
|
|
1919
|
+
}
|
|
1920
|
+
|
|
1921
|
+
if (error) {
|
|
1922
|
+
return h(
|
|
1923
|
+
'div',
|
|
1924
|
+
{ style: PAGE },
|
|
1925
|
+
header,
|
|
1926
|
+
connectionEditor,
|
|
1927
|
+
h(
|
|
1928
|
+
'div',
|
|
1929
|
+
{ role: 'alert', style: { ...card, padding: 18, marginTop: 16 } },
|
|
1930
|
+
h('div', { style: { fontSize: 14, color: C.error } }, `${t('errorPrefix')}${error}`),
|
|
1931
|
+
h('button', { type: 'button', ...focusable, style: btn({ marginTop: 12 }), onClick: () => load(true) }, t('retry')),
|
|
1932
|
+
),
|
|
1933
|
+
);
|
|
1934
|
+
}
|
|
1935
|
+
|
|
1936
|
+
/* ---- 设备详情 ---- */
|
|
1937
|
+
if (openId) {
|
|
1938
|
+
const device = devices.find((d) => d.id === openId) ?? { id: openId, name: openId };
|
|
1939
|
+
const valueOf = (cap) => {
|
|
1940
|
+
const values = detail?.values;
|
|
1941
|
+
if (!values || typeof values !== 'object') return undefined;
|
|
1942
|
+
return Object.hasOwn(values, cap.key) ? values[cap.key] : values[cap.name];
|
|
1943
|
+
};
|
|
1944
|
+
const controls = Array.isArray(detail?.controls) ? detail.controls : [];
|
|
1945
|
+
return h(
|
|
1946
|
+
'div',
|
|
1947
|
+
{ style: PAGE },
|
|
1948
|
+
h(
|
|
1949
|
+
'div',
|
|
1950
|
+
{
|
|
1951
|
+
style: {
|
|
1952
|
+
display: 'flex',
|
|
1953
|
+
alignItems: 'center',
|
|
1954
|
+
gap: 12,
|
|
1955
|
+
padding: '12px 0',
|
|
1956
|
+
borderBottom: `1px solid ${C.border}`,
|
|
1957
|
+
...stickyHeader(),
|
|
1958
|
+
},
|
|
1959
|
+
},
|
|
1960
|
+
h(
|
|
1961
|
+
'button',
|
|
1962
|
+
{ type: 'button', ...focusable, style: btn({ background: C.bgLayer1 }), onClick: () => { requestVersion.current += 1; operationVersion.current += 1; setBusy(''); setOpenId(''); setCredentialTarget('home_assistant:main'); setDetail(null); setCredentialDraft(''); } },
|
|
1963
|
+
`‹ ${t('back')}`,
|
|
1964
|
+
),
|
|
1965
|
+
h(
|
|
1966
|
+
'div',
|
|
1967
|
+
{ style: { minWidth: 0 } },
|
|
1968
|
+
h(
|
|
1969
|
+
'div',
|
|
1970
|
+
{ style: { fontSize: 15, fontWeight: 600, color: C.label } },
|
|
1971
|
+
device.name || device.id,
|
|
1972
|
+
),
|
|
1973
|
+
h(
|
|
1974
|
+
'div',
|
|
1975
|
+
{ style: { ...muted, marginTop: 2 } },
|
|
1976
|
+
[`id=${device.id}`, device.category_zh, device.protocol, device.ip].filter(Boolean).join(' · '),
|
|
1977
|
+
),
|
|
1978
|
+
),
|
|
1979
|
+
),
|
|
1980
|
+
detailError
|
|
1981
|
+
? h('div', { role: 'alert', style: { ...card, padding: 16, marginTop: 16 } }, h('div', { style: { color: C.error, fontSize: 13 } }, detailError))
|
|
1982
|
+
: null,
|
|
1983
|
+
['capability_error', 'read_error'].filter((key) => detail?.[key]).map((key) =>
|
|
1984
|
+
h('div', { key, role: 'alert', style: { ...card, color: C.error, padding: 16, marginTop: 16 } },
|
|
1985
|
+
`${t(key === 'capability_error' ? 'shCapabilityError' : 'shReadError')}: ${detail[key]}`)),
|
|
1986
|
+
detail && (detail.capability_error || detail.read_error)
|
|
1987
|
+
? h('button', { type: 'button', ...focusable, style: btn({ marginTop: 8 }), onClick: () => openDevice(device) }, t('retry'))
|
|
1988
|
+
: null,
|
|
1989
|
+
!detail && !detailError
|
|
1990
|
+
? h('div', { style: { ...muted, marginTop: 16 } }, t('loading'))
|
|
1991
|
+
: null,
|
|
1992
|
+
detail && controls.length
|
|
1993
|
+
? h(
|
|
1994
|
+
'div',
|
|
1995
|
+
{ style: { ...card, padding: '4px 16px', marginTop: 16 } },
|
|
1996
|
+
controls.map((cap) =>
|
|
1997
|
+
h(
|
|
1998
|
+
'div',
|
|
1999
|
+
{ key: cap.key, style: rowStyle },
|
|
2000
|
+
h(
|
|
2001
|
+
'div',
|
|
2002
|
+
{ style: { minWidth: 0 } },
|
|
2003
|
+
h('div', { style: { fontSize: 13, color: C.label } }, cap.zh || cap.name),
|
|
2004
|
+
h(
|
|
2005
|
+
'div',
|
|
2006
|
+
{ style: { ...muted, marginTop: 2 } },
|
|
2007
|
+
[
|
|
2008
|
+
`key=${cap.key}`, `name=${cap.name ?? ''}`, `kind=${cap.kind ?? 'unknown'}`,
|
|
2009
|
+
`readable=${cap.readable ?? 'unknown'}`, `writable=${cap.writable ?? 'unknown'}`,
|
|
2010
|
+
cap.range !== undefined ? `range=${JSON.stringify(cap.range)}` :
|
|
2011
|
+
cap.min !== undefined || cap.max !== undefined ? `range=${JSON.stringify({ min: cap.min, max: cap.max, step: cap.step })}` : null,
|
|
2012
|
+
(cap.step ?? (Array.isArray(cap.range) ? cap.range[2] : cap.range?.step)) !== undefined
|
|
2013
|
+
? `step=${cap.step ?? (Array.isArray(cap.range) ? cap.range[2] : cap.range?.step)}` : null,
|
|
2014
|
+
(cap.unit ?? cap.units) !== undefined ? `units=${JSON.stringify(cap.unit ?? cap.units)}` : null,
|
|
2015
|
+
(cap.value_list?.length || cap.values?.length) ? `enums=${JSON.stringify((cap.value_list?.length ? cap.value_list : cap.values).map((option) => option && typeof option === 'object' ? option.value : option))}` : null,
|
|
2016
|
+
].filter(Boolean).join(' · '),
|
|
2017
|
+
),
|
|
2018
|
+
),
|
|
2019
|
+
h(CapabilityControl, {
|
|
2020
|
+
'aria-label': cap.zh || cap.name || cap.key,
|
|
2021
|
+
cap,
|
|
2022
|
+
value: valueOf(cap),
|
|
2023
|
+
t,
|
|
2024
|
+
disabled: busy === `${openId}:${cap.key}`,
|
|
2025
|
+
onWrite: (next) => control(openId, { mode: 'write', name: cap.key, value: next }, cap.key),
|
|
2026
|
+
onAction: (params) => control(openId, { mode: 'action', name: cap.key, params }, cap.key),
|
|
2027
|
+
}),
|
|
2028
|
+
),
|
|
2029
|
+
),
|
|
2030
|
+
)
|
|
2031
|
+
: null,
|
|
2032
|
+
detail && !controls.length && !detail.capability_error && !detail.read_error
|
|
2033
|
+
? h(
|
|
2034
|
+
'div',
|
|
2035
|
+
{ style: { ...card, padding: 18, marginTop: 16 } },
|
|
2036
|
+
h('div', { style: { fontSize: 14, fontWeight: 600, color: C.label } }, t('shNoControls')),
|
|
2037
|
+
h('div', { style: { ...muted, marginTop: 6, lineHeight: '20px' } }, t('shNoControlsHint')),
|
|
2038
|
+
)
|
|
2039
|
+
: null,
|
|
2040
|
+
connectionEditor,
|
|
2041
|
+
toast ? h(Toast, { text: toast, t }) : null,
|
|
2042
|
+
);
|
|
2043
|
+
}
|
|
2044
|
+
|
|
2045
|
+
/* ---- 设备列表:按类别分组 ---- */
|
|
2046
|
+
const groups = new Map();
|
|
2047
|
+
for (const device of devices) {
|
|
2048
|
+
const key = device.category_zh || device.category || t('shOther');
|
|
2049
|
+
if (!groups.has(key)) groups.set(key, []);
|
|
2050
|
+
groups.get(key).push(device);
|
|
2051
|
+
}
|
|
2052
|
+
|
|
2053
|
+
const tile = (device) =>
|
|
2054
|
+
h(
|
|
2055
|
+
'button',
|
|
2056
|
+
{
|
|
2057
|
+
key: device.id,
|
|
2058
|
+
type: 'button',
|
|
2059
|
+
onClick: () => openDevice(device),
|
|
2060
|
+
...focusable,
|
|
2061
|
+
style: {
|
|
2062
|
+
...card,
|
|
2063
|
+
display: 'flex',
|
|
2064
|
+
flexDirection: 'column',
|
|
2065
|
+
alignItems: 'flex-start',
|
|
2066
|
+
gap: 4,
|
|
2067
|
+
padding: '12px 14px',
|
|
2068
|
+
textAlign: 'left',
|
|
2069
|
+
cursor: 'pointer',
|
|
2070
|
+
width: '100%',
|
|
2071
|
+
outline: '2px solid transparent',
|
|
2072
|
+
},
|
|
2073
|
+
},
|
|
2074
|
+
h(
|
|
2075
|
+
'div',
|
|
2076
|
+
{
|
|
2077
|
+
style: {
|
|
2078
|
+
fontSize: 13,
|
|
2079
|
+
fontWeight: 500,
|
|
2080
|
+
color: C.label,
|
|
2081
|
+
overflow: 'hidden',
|
|
2082
|
+
textOverflow: 'ellipsis',
|
|
2083
|
+
whiteSpace: 'nowrap',
|
|
2084
|
+
maxWidth: '100%',
|
|
2085
|
+
},
|
|
2086
|
+
},
|
|
2087
|
+
device.name || device.id,
|
|
2088
|
+
),
|
|
2089
|
+
h(
|
|
2090
|
+
'div',
|
|
2091
|
+
{ style: { ...muted, fontSize: 11 } },
|
|
2092
|
+
[device.protocol, device.ip].filter(Boolean).join(' · ') || device.id,
|
|
2093
|
+
),
|
|
2094
|
+
);
|
|
2095
|
+
|
|
2096
|
+
const deviceList = devices.length
|
|
2097
|
+
? Array.from(groups.entries()).map(([category, items]) =>
|
|
2098
|
+
h(
|
|
2099
|
+
'div',
|
|
2100
|
+
{ key: category },
|
|
2101
|
+
h('div', { style: sectionTitle }, `${category}(${items.length})`),
|
|
2102
|
+
h(
|
|
2103
|
+
'div',
|
|
2104
|
+
{
|
|
2105
|
+
style: {
|
|
2106
|
+
display: 'grid',
|
|
2107
|
+
gridTemplateColumns: 'repeat(auto-fill, minmax(150px, 1fr))',
|
|
2108
|
+
gap: 10,
|
|
2109
|
+
},
|
|
2110
|
+
},
|
|
2111
|
+
items.map(tile),
|
|
2112
|
+
),
|
|
2113
|
+
),
|
|
2114
|
+
)
|
|
2115
|
+
: h(
|
|
2116
|
+
'div',
|
|
2117
|
+
{ style: { ...card, padding: 20, marginTop: 20 } },
|
|
2118
|
+
h('div', { style: { fontSize: 14, fontWeight: 600, color: C.label } }, t('shNoDevices')),
|
|
2119
|
+
h('div', { style: { ...muted, marginTop: 6, lineHeight: '20px' } }, t('shNoDevicesHint')),
|
|
2120
|
+
);
|
|
2121
|
+
|
|
2122
|
+
const sceneReport = (scene) => {
|
|
2123
|
+
const result = sceneRunDetails[scene.id];
|
|
2124
|
+
if (!result) return null;
|
|
2125
|
+
const steps = Array.isArray(result.steps) ? result.steps : Array.isArray(result.results) ? result.results : [];
|
|
2126
|
+
const success = Number.isInteger(result.success) ? result.success : steps.filter((step) => step?.ok === true).length;
|
|
2127
|
+
const total = Number.isInteger(result.total) ? result.total : steps.length;
|
|
2128
|
+
return h('div', { role: 'status', 'aria-live': 'polite', style: { width: '100%', fontSize: 12, color: C.label2 } },
|
|
2129
|
+
h('div', null, tf(t, 'shSceneResult', { success, total })),
|
|
2130
|
+
result.error ? h('div', { style: { color: C.error } }, String(result.error)) : null,
|
|
2131
|
+
steps.map((step, index) => h('div', { key: index, style: { marginTop: 4, color: step?.ok === true ? C.label2 : C.error } },
|
|
2132
|
+
`${index + 1}. ${step?.device ?? step?.device_id ?? '?'} ${step?.mode ?? ''} · ${t(step?.ok === true ? 'shStepOK' : 'shStepFailed')}${step?.error ?? step?.result?.error ? ` · ${step.error ?? step.result.error}` : ''}`)),
|
|
2133
|
+
);
|
|
2134
|
+
};
|
|
2135
|
+
const sceneBlock = h('div', { style: { marginTop: 12 } },
|
|
2136
|
+
sceneLoadError ? h('div', { role: 'alert', style: { ...card, padding: 12, marginBottom: 12, color: C.error } },
|
|
2137
|
+
h('div', null, `${t('errorPrefix')}${sceneLoadError}`),
|
|
2138
|
+
h('button', { type: 'button', ...focusable, style: btn({ marginTop: 8 }), onClick: loadScenes }, t('shSceneRetry'))) : null,
|
|
2139
|
+
!scenesReady ? h('div', { role: 'status', style: muted }, t('loading')) : null,
|
|
2140
|
+
h('button', { type: 'button', ...focusable, style: btn(), disabled: Boolean(busy), onClick: () => {
|
|
2141
|
+
setEditingScene('new'); setSceneError('');
|
|
2142
|
+
setSceneDraft(JSON.stringify({ name: '', actions: [] }, null, 2));
|
|
2143
|
+
} }, t('shNewScene')),
|
|
2144
|
+
editingScene !== null ? h('div', { style: { ...card, padding: 16, marginTop: 12 } },
|
|
2145
|
+
h('div', { style: { ...muted, marginBottom: 8 } }, t('shSceneHelp')),
|
|
2146
|
+
h('textarea', { 'aria-label': t('shSceneJSON'), ...focusable, value: sceneDraft, rows: 12, disabled: Boolean(busy),
|
|
2147
|
+
onChange: (event) => setSceneDraft(event.target.value),
|
|
2148
|
+
style: btn({ width: '100%', boxSizing: 'border-box', fontFamily: 'monospace', resize: 'vertical', textAlign: 'left' }) }),
|
|
2149
|
+
sceneError ? h('div', { role: 'alert', style: { color: C.error, fontSize: 12, marginTop: 6 } }, sceneError) : null,
|
|
2150
|
+
h('div', { style: { display: 'flex', gap: 8, marginTop: 8 } },
|
|
2151
|
+
h('button', { type: 'button', ...focusable, style: btn(), disabled: Boolean(busy), onClick: saveScene }, t('shSaveScene')),
|
|
2152
|
+
h('button', { type: 'button', ...focusable, style: btn(), disabled: Boolean(busy), onClick: () => { setEditingScene(null); setSceneDraft(''); setSceneError(''); } }, t('shCancel')),
|
|
2153
|
+
),
|
|
2154
|
+
) : null,
|
|
2155
|
+
scenes.length ? h('div', { style: { display: 'flex', flexDirection: 'column', gap: 10, marginTop: 12 } },
|
|
2156
|
+
scenes.map((scene) => h('div', { key: scene.id, style: { ...card, padding: '14px 16px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap' } },
|
|
2157
|
+
h('div', null,
|
|
2158
|
+
h('div', { style: { fontSize: 14, fontWeight: 500, color: C.label } }, scene.name),
|
|
2159
|
+
h('div', { style: { ...muted, marginTop: 2 } }, `${Array.isArray(scene.actions) ? scene.actions.length : 0} ${t('shActions')}`),
|
|
2160
|
+
),
|
|
2161
|
+
h('div', { style: { display: 'flex', gap: 8 } },
|
|
2162
|
+
h('button', { type: 'button', ...focusable, style: btn(), disabled: Boolean(busy), onClick: () => runScene(scene) }, busy === `scene:${scene.id}` ? t('running') : t('run')),
|
|
2163
|
+
h('button', { type: 'button', ...focusable, style: btn(), disabled: Boolean(busy), onClick: () => { setEditingScene(scene.id); setSceneError(''); setSceneDraft(JSON.stringify(scene, null, 2)); } }, t('shEditScene')),
|
|
2164
|
+
h('button', { type: 'button', ...focusable, style: btn({ color: C.error }), disabled: Boolean(busy), onClick: () => deleteScene(scene) }, t('shDeleteScene')),
|
|
2165
|
+
),
|
|
2166
|
+
sceneReport(scene),
|
|
2167
|
+
)),
|
|
2168
|
+
) : scenesReady && !sceneLoadError ? h('div', { style: { ...card, padding: 20, marginTop: 20 } },
|
|
2169
|
+
h('div', { style: { fontSize: 14, fontWeight: 600, color: C.label } }, t('shNoScenes')),
|
|
2170
|
+
h('div', { style: { ...muted, marginTop: 6 } }, t('shNoScenesHint')),
|
|
2171
|
+
) : null,
|
|
2172
|
+
);
|
|
2173
|
+
|
|
2174
|
+
const tabBar = h(
|
|
2175
|
+
'div',
|
|
2176
|
+
{
|
|
2177
|
+
role: 'tablist',
|
|
2178
|
+
style: { display: 'flex', gap: 6, marginTop: 12, padding: 3, background: C.bgLayer1, borderRadius: C.radius },
|
|
2179
|
+
},
|
|
2180
|
+
[
|
|
2181
|
+
{ id: 'smart', label: t('tabDevices'), badge: devices.length },
|
|
2182
|
+
{ id: 'scenes', label: t('tabScenes'), badge: scenes.length },
|
|
2183
|
+
].map((entry) =>
|
|
2184
|
+
h(
|
|
2185
|
+
'button',
|
|
2186
|
+
{
|
|
2187
|
+
key: entry.id,
|
|
2188
|
+
type: 'button',
|
|
2189
|
+
role: 'tab',
|
|
2190
|
+
'aria-selected': mode === entry.id,
|
|
2191
|
+
onClick: () => setMode(entry.id),
|
|
2192
|
+
...focusable,
|
|
2193
|
+
style: {
|
|
2194
|
+
flex: '1 1 0',
|
|
2195
|
+
appearance: 'none',
|
|
2196
|
+
border: 'none',
|
|
2197
|
+
borderRadius: C.radius,
|
|
2198
|
+
padding: '7px 10px',
|
|
2199
|
+
fontSize: 13,
|
|
2200
|
+
fontWeight: mode === entry.id ? 600 : 400,
|
|
2201
|
+
color: mode === entry.id ? C.label : C.label2,
|
|
2202
|
+
background: mode === entry.id ? C.bgBase : 'transparent',
|
|
2203
|
+
cursor: 'pointer',
|
|
2204
|
+
outline: '2px solid transparent',
|
|
2205
|
+
},
|
|
2206
|
+
},
|
|
2207
|
+
entry.label,
|
|
2208
|
+
entry.badge ? h('span', { style: { marginLeft: 4, fontSize: 11, color: C.label3 } }, `· ${entry.badge}`) : null,
|
|
2209
|
+
),
|
|
2210
|
+
),
|
|
2211
|
+
);
|
|
2212
|
+
|
|
2213
|
+
return h(
|
|
2214
|
+
'div',
|
|
2215
|
+
{ style: PAGE },
|
|
2216
|
+
header,
|
|
2217
|
+
tabBar,
|
|
2218
|
+
mode === 'smart' ? connectionEditor : null,
|
|
2219
|
+
mode === 'smart' ? h('div', null, h('div', { style: { ...muted, marginTop: 10 } }, t('shHint')), deviceList) : null,
|
|
2220
|
+
mode === 'scenes' ? sceneBlock : null,
|
|
2221
|
+
toast ? h(Toast, { text: toast, t }) : null,
|
|
2222
|
+
);
|
|
2223
|
+
}
|
|
2224
|
+
|
|
2225
|
+
/** 底部提示条(设备/场景操作反馈)。 */
|
|
2226
|
+
function Toast({ text, t }) {
|
|
2227
|
+
return h(
|
|
2228
|
+
'div',
|
|
2229
|
+
{
|
|
2230
|
+
role: String(text).startsWith(t('errorPrefix')) ? 'alert' : 'status',
|
|
2231
|
+
'aria-live': String(text).startsWith(t('errorPrefix')) ? 'assertive' : 'polite',
|
|
2232
|
+
style: {
|
|
2233
|
+
position: 'sticky',
|
|
2234
|
+
bottom: 12,
|
|
2235
|
+
marginTop: 14,
|
|
2236
|
+
padding: '8px 14px',
|
|
2237
|
+
background: C.bgLayer2,
|
|
2238
|
+
border: `1px solid ${C.border}`,
|
|
2239
|
+
borderRadius: C.radius,
|
|
2240
|
+
fontSize: 12,
|
|
2241
|
+
color: String(text).startsWith(t('errorPrefix')) ? C.error : C.success,
|
|
2242
|
+
display: 'inline-block',
|
|
2243
|
+
},
|
|
2244
|
+
},
|
|
2245
|
+
text,
|
|
2246
|
+
);
|
|
2247
|
+
}
|
|
2248
|
+
|
|
2249
|
+
/**
|
|
2250
|
+
* 统一能力项控件。
|
|
2251
|
+
*
|
|
2252
|
+
* cap 来自 Python 的 catalog:{ key, zh, name, kind: bool|range|enum, writable,
|
|
2253
|
+
* values?, min/max/step/unit }。写入用 cap.key(统一能力名),不是原始属性名——
|
|
2254
|
+
* 适配器按能力名分发,原始名只用于读当前值。
|
|
2255
|
+
*/
|
|
2256
|
+
function CapabilityControl({ cap, value, t, disabled, onWrite, onAction, 'aria-label': ariaLabel }) {
|
|
2257
|
+
const [draft, setDraft] = useState('');
|
|
2258
|
+
const [paramsDraft, setParamsDraft] = useState('');
|
|
2259
|
+
const [paramsError, setParamsError] = useState('');
|
|
2260
|
+
const [localBusy, setLocalBusy] = useState(false);
|
|
2261
|
+
|
|
2262
|
+
useEffect(() => {
|
|
2263
|
+
setDraft(value === undefined || value === null ? '' : value);
|
|
2264
|
+
}, [value]);
|
|
2265
|
+
|
|
2266
|
+
const commit = async (next) => {
|
|
2267
|
+
setLocalBusy(true);
|
|
2268
|
+
try {
|
|
2269
|
+
await onWrite(next);
|
|
2270
|
+
} finally {
|
|
2271
|
+
setLocalBusy(false);
|
|
2272
|
+
}
|
|
2273
|
+
};
|
|
2274
|
+
|
|
2275
|
+
const off = disabled || localBusy || cap.writable === false;
|
|
2276
|
+
const boolValue = booleanState(value);
|
|
2277
|
+
|
|
2278
|
+
const label = cap.zh || cap.name || cap.key;
|
|
2279
|
+
if (cap.kind === 'action') {
|
|
2280
|
+
const inputs = cap.inputs ?? cap.in;
|
|
2281
|
+
const schema = cap.params_schema ?? (inputs && !Array.isArray(inputs) && typeof inputs === 'object' && inputs.type ? inputs : null);
|
|
2282
|
+
const validate = (input, rule, path = 'params') => {
|
|
2283
|
+
if (!rule || typeof rule !== 'object') return '';
|
|
2284
|
+
const type = rule.type;
|
|
2285
|
+
const matches = (expected) => expected === 'object' ? input !== null && typeof input === 'object' && !Array.isArray(input)
|
|
2286
|
+
: expected === 'array' ? Array.isArray(input) : expected === 'integer' ? Number.isInteger(input)
|
|
2287
|
+
: expected === 'number' ? typeof input === 'number' && Number.isFinite(input) : expected === 'null' ? input === null
|
|
2288
|
+
: ['string', 'boolean'].includes(expected) ? typeof input === expected : true;
|
|
2289
|
+
if (type && !(Array.isArray(type) ? type : [type]).some(matches))
|
|
2290
|
+
return type === 'object' ? `${path}: ${t('shObjectRequired')}` : `${path}: expected ${type}`;
|
|
2291
|
+
if (Array.isArray(rule.enum) && !rule.enum.some((option) => JSON.stringify(option) === JSON.stringify(input))) return `${path}: enum ${JSON.stringify(rule.enum)}`;
|
|
2292
|
+
if (typeof input === 'number') {
|
|
2293
|
+
if (Number.isFinite(rule.minimum) && input < rule.minimum) return `${path}: minimum ${rule.minimum}`;
|
|
2294
|
+
if (Number.isFinite(rule.maximum) && input > rule.maximum) return `${path}: maximum ${rule.maximum}`;
|
|
2295
|
+
}
|
|
2296
|
+
if (Array.isArray(input)) {
|
|
2297
|
+
if (Number.isInteger(rule.minItems) && input.length < rule.minItems) return `${path}: minItems ${rule.minItems}`;
|
|
2298
|
+
if (Number.isInteger(rule.maxItems) && input.length > rule.maxItems) return `${path}: maxItems ${rule.maxItems}`;
|
|
2299
|
+
for (const [index, item] of input.entries()) {
|
|
2300
|
+
const error = validate(item, rule.prefixItems?.[index] ?? rule.items, `${path}[${index}]`);
|
|
2301
|
+
if (error) return error;
|
|
2302
|
+
}
|
|
2303
|
+
} else if (input && typeof input === 'object') {
|
|
2304
|
+
for (const key of Array.isArray(rule.required) ? rule.required : []) if (!Object.hasOwn(input, key)) return `${path}.${key}: required`;
|
|
2305
|
+
for (const [key, item] of Object.entries(input)) {
|
|
2306
|
+
if (rule.additionalProperties === false && !Object.hasOwn(rule.properties ?? {}, key)) return `${path}.${key}: unknown field`;
|
|
2307
|
+
const error = validate(item, rule.properties?.[key], `${path}.${key}`);
|
|
2308
|
+
if (error) return error;
|
|
2309
|
+
}
|
|
2310
|
+
}
|
|
2311
|
+
return '';
|
|
2312
|
+
};
|
|
2313
|
+
const execute = async () => {
|
|
2314
|
+
if (!paramsDraft.trim()) { setParamsError(t('shActionParamsRequired')); return; }
|
|
2315
|
+
let params;
|
|
2316
|
+
try { params = JSON.parse(paramsDraft); }
|
|
2317
|
+
catch { setParamsError(t('shJSONInvalid')); return; }
|
|
2318
|
+
if (params === null || typeof params !== 'object') { setParamsError(t('shObjectRequired')); return; }
|
|
2319
|
+
const validationError = validate(params, schema);
|
|
2320
|
+
if (validationError) { setParamsError(validationError); return; }
|
|
2321
|
+
setParamsError(''); setLocalBusy(true);
|
|
2322
|
+
try { await onAction(params); }
|
|
2323
|
+
finally { setLocalBusy(false); }
|
|
2324
|
+
};
|
|
2325
|
+
return h('div', { style: { display: 'flex', flexDirection: 'column', gap: 6, maxWidth: 340 } },
|
|
2326
|
+
h('div', { style: muted }, t(schema?.type === 'object' ? 'shActionObjectHint' : schema?.type === 'array' ? 'shActionArrayHint' : 'shActionParamsHint')),
|
|
2327
|
+
schema || inputs !== undefined ? h('pre', { 'aria-label': t('shActionSchema'), style: { ...muted, whiteSpace: 'pre-wrap', overflowWrap: 'anywhere', margin: 0 } }, JSON.stringify(schema ?? inputs, null, 2)) : null,
|
|
2328
|
+
h('textarea', { 'aria-label': `${label} · ${t('shActionParams')}`, ...focusable, value: paramsDraft, disabled: off,
|
|
2329
|
+
onChange: (event) => setParamsDraft(event.target.value), rows: 3, placeholder: schema?.type === 'object' ? '{}' : '[]',
|
|
2330
|
+
style: btn({ width: '100%', resize: 'vertical', fontFamily: 'monospace', boxSizing: 'border-box' }) }),
|
|
2331
|
+
paramsError ? h('div', { role: 'alert', style: { ...muted, color: C.error } }, paramsError) : null,
|
|
2332
|
+
h('button', { type: 'button', ...focusable, style: btn(), disabled: off, onClick: execute }, t('run')),
|
|
2333
|
+
);
|
|
2334
|
+
}
|
|
2335
|
+
|
|
2336
|
+
if (cap.kind === 'bool') {
|
|
2337
|
+
if (boolValue === undefined) return unknownBoolean(t, ariaLabel || label, off, commit);
|
|
2338
|
+
return h(Switch, {
|
|
2339
|
+
checked: boolValue,
|
|
2340
|
+
disabled: off,
|
|
2341
|
+
label: cap.zh || cap.name,
|
|
2342
|
+
'aria-label': ariaLabel || label,
|
|
2343
|
+
onChange: (next) => commit(next),
|
|
2344
|
+
});
|
|
2345
|
+
}
|
|
2346
|
+
|
|
2347
|
+
const enumValues = Array.isArray(cap.values) && cap.values.length ? cap.values : cap.value_list;
|
|
2348
|
+
if (cap.kind === 'enum' && Array.isArray(enumValues) && enumValues.length) {
|
|
2349
|
+
const options = enumValues.map((entry) => entry && typeof entry === 'object' && Object.hasOwn(entry, 'value')
|
|
2350
|
+
? entry : { value: entry });
|
|
2351
|
+
const currentIndex = options.findIndex((option) => Object.is(option.value, value));
|
|
2352
|
+
if (options.length <= 5) {
|
|
2353
|
+
return h(
|
|
2354
|
+
'div',
|
|
2355
|
+
{
|
|
2356
|
+
role: 'group',
|
|
2357
|
+
'aria-label': label,
|
|
2358
|
+
style: {
|
|
2359
|
+
display: 'inline-flex',
|
|
2360
|
+
border: `1px solid ${C.border}`,
|
|
2361
|
+
borderRadius: C.radius,
|
|
2362
|
+
overflow: 'hidden',
|
|
2363
|
+
background: C.bgLayer1,
|
|
2364
|
+
},
|
|
2365
|
+
},
|
|
2366
|
+
options.map((option, index) => {
|
|
2367
|
+
const active = index === currentIndex;
|
|
2368
|
+
return h(
|
|
2369
|
+
'button',
|
|
2370
|
+
{
|
|
2371
|
+
key: `${typeof option.value}:${JSON.stringify(option.value)}`,
|
|
2372
|
+
type: 'button',
|
|
2373
|
+
'aria-pressed': active,
|
|
2374
|
+
disabled: off,
|
|
2375
|
+
...focusable,
|
|
2376
|
+
style: {
|
|
2377
|
+
appearance: 'none',
|
|
2378
|
+
border: 'none',
|
|
2379
|
+
borderLeft: index === 0 ? 'none' : `1px solid ${C.border}`,
|
|
2380
|
+
background: active ? ORANGE : 'transparent',
|
|
2381
|
+
color: active ? '#fff' : C.label2,
|
|
2382
|
+
padding: '6px 12px',
|
|
2383
|
+
fontSize: 12,
|
|
2384
|
+
cursor: off ? 'not-allowed' : 'pointer',
|
|
2385
|
+
whiteSpace: 'nowrap',
|
|
2386
|
+
opacity: off ? 0.6 : 1,
|
|
2387
|
+
outline: '2px solid transparent',
|
|
2388
|
+
},
|
|
2389
|
+
onClick: () => {
|
|
2390
|
+
setDraft(option.value);
|
|
2391
|
+
commit(option.value);
|
|
2392
|
+
},
|
|
2393
|
+
},
|
|
2394
|
+
option.zh ?? option.description ?? String(option.value),
|
|
2395
|
+
);
|
|
2396
|
+
}),
|
|
2397
|
+
);
|
|
2398
|
+
}
|
|
2399
|
+
return h(
|
|
2400
|
+
'select',
|
|
2401
|
+
{
|
|
2402
|
+
'aria-label': label,
|
|
2403
|
+
...focusable,
|
|
2404
|
+
value: currentIndex < 0 ? '' : String(currentIndex),
|
|
2405
|
+
disabled: off,
|
|
2406
|
+
style: btn({ padding: '6px 8px', minWidth: 130 }),
|
|
2407
|
+
onChange: (e) => {
|
|
2408
|
+
const index = Number(e.target.value);
|
|
2409
|
+
const hit = options[index];
|
|
2410
|
+
if (!hit) return;
|
|
2411
|
+
setDraft(hit.value);
|
|
2412
|
+
commit(hit.value);
|
|
2413
|
+
},
|
|
2414
|
+
},
|
|
2415
|
+
options.map((option, index) => h('option', {
|
|
2416
|
+
key: `${typeof option.value}:${JSON.stringify(option.value)}`,
|
|
2417
|
+
value: String(index),
|
|
2418
|
+
}, option.zh ?? option.description ?? String(option.value))),
|
|
2419
|
+
);
|
|
2420
|
+
}
|
|
2421
|
+
|
|
2422
|
+
if (cap.kind === 'range') {
|
|
2423
|
+
const range = Array.isArray(cap.range) ? { min: cap.range[0], max: cap.range[1], step: cap.range[2] }
|
|
2424
|
+
: cap.range && typeof cap.range === 'object' ? cap.range : {};
|
|
2425
|
+
const minValue = cap.min ?? range.min;
|
|
2426
|
+
const maxValue = cap.max ?? range.max;
|
|
2427
|
+
const stepValue = cap.step ?? range.step;
|
|
2428
|
+
const min = Number.isFinite(minValue) ? minValue : 0;
|
|
2429
|
+
const max = Number.isFinite(maxValue) ? maxValue : 100;
|
|
2430
|
+
const step = Number.isFinite(stepValue) && stepValue > 0 ? stepValue : 1;
|
|
2431
|
+
const number = Number(draft);
|
|
2432
|
+
const current = Number.isFinite(number) ? Math.min(max, Math.max(min, number)) : min;
|
|
2433
|
+
const unit = cap.unit || '';
|
|
2434
|
+
return h(
|
|
2435
|
+
'div',
|
|
2436
|
+
{ style: { display: 'inline-flex', alignItems: 'center', gap: 8 } },
|
|
2437
|
+
h('input', {
|
|
2438
|
+
type: 'range',
|
|
2439
|
+
'aria-label': label,
|
|
2440
|
+
...focusable,
|
|
2441
|
+
min,
|
|
2442
|
+
max,
|
|
2443
|
+
step,
|
|
2444
|
+
value: current,
|
|
2445
|
+
disabled: off,
|
|
2446
|
+
onChange: (e) => setDraft(e.target.value),
|
|
2447
|
+
onMouseUp: (e) => commit(Number(e.target.value)),
|
|
2448
|
+
onTouchEnd: (e) => commit(Number(e.target.value)),
|
|
2449
|
+
onKeyUp: (e) => {
|
|
2450
|
+
if (['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End', 'PageUp', 'PageDown'].includes(e.key))
|
|
2451
|
+
commit(Number(e.target.value));
|
|
2452
|
+
},
|
|
2453
|
+
style: { width: 120, accentColor: ORANGE },
|
|
2454
|
+
}),
|
|
2455
|
+
h(
|
|
2456
|
+
'span',
|
|
2457
|
+
{ style: { minWidth: 48, fontSize: 13, color: C.label, textAlign: 'right' } },
|
|
2458
|
+
`${value === undefined || value === null ? '—' : value}${unit}`,
|
|
2459
|
+
),
|
|
2460
|
+
);
|
|
2461
|
+
}
|
|
2462
|
+
|
|
2463
|
+
if (cap.writable === false || cap.kind === 'json') {
|
|
2464
|
+
return h('pre', { 'aria-label': label, style: { ...muted, margin: 0, maxWidth: 360, whiteSpace: 'pre-wrap', overflowWrap: 'anywhere' } },
|
|
2465
|
+
value === undefined || value === null ? t('unknown') : typeof value === 'object' ? JSON.stringify(value) : String(value));
|
|
2466
|
+
}
|
|
2467
|
+
|
|
2468
|
+
// 其它:输入框 + 确定
|
|
2469
|
+
return h(
|
|
2470
|
+
'div',
|
|
2471
|
+
{ style: { display: 'inline-flex', alignItems: 'center', gap: 6 } },
|
|
2472
|
+
h('input', {
|
|
2473
|
+
type: 'text',
|
|
2474
|
+
'aria-label': label,
|
|
2475
|
+
...focusable,
|
|
2476
|
+
value: draft,
|
|
2477
|
+
disabled: off,
|
|
2478
|
+
onChange: (e) => setDraft(e.target.value),
|
|
2479
|
+
onKeyDown: (e) => {
|
|
2480
|
+
if (e.key === 'Enter' && draft !== '') commit(draft);
|
|
2481
|
+
},
|
|
2482
|
+
style: btn({ width: 110, padding: '5px 8px' }),
|
|
2483
|
+
}),
|
|
2484
|
+
h(
|
|
2485
|
+
'button',
|
|
2486
|
+
{ type: 'button', ...focusable, disabled: off, style: btn(), onClick: () => draft !== '' && commit(draft) },
|
|
2487
|
+
t('write'),
|
|
2488
|
+
),
|
|
2489
|
+
);
|
|
2490
|
+
}
|
|
2491
|
+
|
|
2492
|
+
/** 带占位符的文案:tf(t,'shScanDone',{n:3})。 */
|
|
2493
|
+
function tf(t, key, params) {
|
|
2494
|
+
const raw = t(key);
|
|
2495
|
+
return String(raw).replace(/\{(\w+)\}/g, (_, name) => (params?.[name] !== undefined ? String(params[name]) : `{${name}}`));
|
|
2496
|
+
}
|
|
2497
|
+
|
|
1437
2498
|
function Panel({ t }) {
|
|
1438
2499
|
const [status, setStatus] = useState(null);
|
|
1439
2500
|
const [ready, setReady] = useState(false);
|
|
1440
2501
|
const [error, setError] = useState('');
|
|
2502
|
+
const [resourceErrors, setResourceErrors] = useState({});
|
|
2503
|
+
const [resourceBusy, setResourceBusy] = useState(false);
|
|
1441
2504
|
|
|
1442
2505
|
const [devices, setDevices] = useState([]);
|
|
1443
2506
|
const [homes, setHomes] = useState([]);
|
|
@@ -1454,6 +2517,8 @@ window.__ModuleLoader__.load({
|
|
|
1454
2517
|
|
|
1455
2518
|
const load = useCallback(async () => {
|
|
1456
2519
|
setError('');
|
|
2520
|
+
setResourceErrors({});
|
|
2521
|
+
setResourceBusy(true);
|
|
1457
2522
|
setReady(false);
|
|
1458
2523
|
let state = null;
|
|
1459
2524
|
try {
|
|
@@ -1461,6 +2526,7 @@ window.__ModuleLoader__.load({
|
|
|
1461
2526
|
setStatus(state);
|
|
1462
2527
|
} catch (err) {
|
|
1463
2528
|
setError(err?.body?.error ?? err.message ?? String(err));
|
|
2529
|
+
setResourceBusy(false);
|
|
1464
2530
|
setReady(true);
|
|
1465
2531
|
return;
|
|
1466
2532
|
}
|
|
@@ -1468,12 +2534,15 @@ window.__ModuleLoader__.load({
|
|
|
1468
2534
|
setReady(true);
|
|
1469
2535
|
return;
|
|
1470
2536
|
}
|
|
1471
|
-
const [
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
]);
|
|
2537
|
+
const resources = ['devices', 'homes', 'scenes', 'consumables'];
|
|
2538
|
+
const results = await Promise.all(resources.map(async (resource) => {
|
|
2539
|
+
try { return [resource, await getJSON(resource), '']; }
|
|
2540
|
+
catch (err) { return [resource, {}, err?.body?.error ?? err.message ?? String(err)]; }
|
|
2541
|
+
}));
|
|
2542
|
+
const data = Object.fromEntries(results.map(([resource, result]) => [resource, result]));
|
|
2543
|
+
const failures = Object.fromEntries(results.filter(([, , message]) => message).map(([resource, , message]) => [resource, message]));
|
|
2544
|
+
setResourceErrors(failures);
|
|
2545
|
+
const dev = data.devices ?? {}, home = data.homes ?? {}, scene = data.scenes ?? {}, cons = data.consumables ?? {};
|
|
1477
2546
|
const list = Array.isArray(dev.devices) ? dev.devices : [];
|
|
1478
2547
|
setDevices(list);
|
|
1479
2548
|
setHomes(Array.isArray(home.homes) ? home.homes : []);
|
|
@@ -1505,6 +2574,7 @@ window.__ModuleLoader__.load({
|
|
|
1505
2574
|
}
|
|
1506
2575
|
}
|
|
1507
2576
|
|
|
2577
|
+
setResourceBusy(false);
|
|
1508
2578
|
setReady(true);
|
|
1509
2579
|
}, []);
|
|
1510
2580
|
|
|
@@ -2054,6 +3124,10 @@ window.__ModuleLoader__.load({
|
|
|
2054
3124
|
{ style: PAGE },
|
|
2055
3125
|
header,
|
|
2056
3126
|
tabBar,
|
|
3127
|
+
Object.keys(resourceErrors).length ? h('div', { role: 'alert', style: { ...card, padding: 12, marginTop: 10, color: C.error } },
|
|
3128
|
+
Object.entries(resourceErrors).map(([resource, message]) => h('div', { key: resource }, `${resource}: ${message}`)),
|
|
3129
|
+
h('button', { type: 'button', ...focusable, style: btn({ marginTop: 8 }), disabled: resourceBusy, onClick: load }, t('retry')),
|
|
3130
|
+
) : null,
|
|
2057
3131
|
tab === 'devices'
|
|
2058
3132
|
? h(
|
|
2059
3133
|
'div',
|
|
@@ -2089,8 +3163,64 @@ window.__ModuleLoader__.load({
|
|
|
2089
3163
|
|
|
2090
3164
|
/* -------------------------------------------------------------- 注册 */
|
|
2091
3165
|
|
|
3166
|
+
/**
|
|
3167
|
+
* 面板外壳:两页签(米家 / 全屋)。
|
|
3168
|
+
*
|
|
3169
|
+
* 为什么合并成一个面板而不是两个侧栏项:两者是同一件事的两个层次
|
|
3170
|
+
* (账号内的米家设备 vs 局域网里的所有设备),分开放用户还得记住
|
|
3171
|
+
* 哪个设备在哪个页签。外壳只负责切页,各页自己取数。
|
|
3172
|
+
*/
|
|
2092
3173
|
function Shell({ t }) {
|
|
2093
|
-
|
|
3174
|
+
const [view, setView] = useState('smart');
|
|
3175
|
+
const tab = (id, label) =>
|
|
3176
|
+
h(
|
|
3177
|
+
'button',
|
|
3178
|
+
{
|
|
3179
|
+
key: id,
|
|
3180
|
+
type: 'button',
|
|
3181
|
+
role: 'tab',
|
|
3182
|
+
'aria-selected': view === id,
|
|
3183
|
+
onClick: () => setView(id),
|
|
3184
|
+
...focusable,
|
|
3185
|
+
style: {
|
|
3186
|
+
appearance: 'none',
|
|
3187
|
+
border: `1px solid ${view === id ? ORANGE : C.border}`,
|
|
3188
|
+
background: view === id ? 'rgba(255,106,0,.10)' : C.bgBase,
|
|
3189
|
+
color: view === id ? ORANGE : C.label2,
|
|
3190
|
+
borderRadius: C.radius,
|
|
3191
|
+
padding: '5px 14px',
|
|
3192
|
+
fontSize: 12,
|
|
3193
|
+
fontWeight: view === id ? 600 : 400,
|
|
3194
|
+
cursor: 'pointer',
|
|
3195
|
+
outline: '2px solid transparent',
|
|
3196
|
+
},
|
|
3197
|
+
},
|
|
3198
|
+
label,
|
|
3199
|
+
);
|
|
3200
|
+
|
|
3201
|
+
return h(
|
|
3202
|
+
'div',
|
|
3203
|
+
{ style: { display: 'flex', flexDirection: 'column', height: '100%', minHeight: 0 } },
|
|
3204
|
+
h(
|
|
3205
|
+
'div',
|
|
3206
|
+
{
|
|
3207
|
+
role: 'tablist',
|
|
3208
|
+
style: {
|
|
3209
|
+
display: 'flex',
|
|
3210
|
+
gap: 8,
|
|
3211
|
+
padding: '12px 20px 0',
|
|
3212
|
+
flex: '0 0 auto',
|
|
3213
|
+
},
|
|
3214
|
+
},
|
|
3215
|
+
tab('mihome', t('shTabMihome')),
|
|
3216
|
+
tab('smart', t('shTabSmart')),
|
|
3217
|
+
),
|
|
3218
|
+
h(
|
|
3219
|
+
'div',
|
|
3220
|
+
{ style: { flex: '1 1 auto', minHeight: 0, display: 'flex' } },
|
|
3221
|
+
view === 'mihome' ? h(Panel, { t }) : h(SmartHomePanel, { t }),
|
|
3222
|
+
),
|
|
3223
|
+
);
|
|
2094
3224
|
}
|
|
2095
3225
|
|
|
2096
3226
|
return {
|
|
@@ -2124,7 +3254,7 @@ window.__ModuleLoader__.load({
|
|
|
2124
3254
|
name: 'sidebar.panellist',
|
|
2125
3255
|
id: PANEL_ID,
|
|
2126
3256
|
order: 8,
|
|
2127
|
-
label: () => t('
|
|
3257
|
+
label: () => t('shNav'),
|
|
2128
3258
|
locale: NS,
|
|
2129
3259
|
},
|
|
2130
3260
|
(owner = {}) =>
|