bug改修,智家模块
This commit is contained in:
1 parent
063718f86d
commit
fcbcf07b87
52 files changed
+12563
-103
No files matched your search
@@ -214,8 +214,8 @@ Tab 收敛为 **概览 / 库 / 编辑器 / 集成**(把 v1 的「同步」并
|
|||||||
┌─ 标题栏(自绘:文档名 + 未保存点 + 窗口按钮)────────────────────────┐
|
┌─ 标题栏(自绘:文档名 + 未保存点 + 窗口按钮)────────────────────────┐
|
||||||
├─ 工具栏:保存 另存 打开 快速打开 | 格式化(.md 时) | 编码 换行 主题 ─┤
|
├─ 工具栏:保存 另存 打开 快速打开 | 格式化(.md 时) | 编码 换行 主题 ─┤
|
||||||
├────────────┬──────────────────────────────────────────┬─────────────┤
|
├────────────┬──────────────────────────────────────────┬─────────────┤
|
||||||
│ 侧栏 │ 标签页条:doc1 × | doc2 × | … │ 抽屉(可选) │
|
│ 侧栏 │ 标签栏:doc1 × | doc2 × | … │ 抽屉(可选) │
|
||||||
│ [库|目录| │ │ 大纲 / 双链 │
|
│ [库|目录| ├──────────────────────────────────────────┤ 大纲 / 双链 │
|
||||||
│ 检索|最近] │ 编辑器(CM6) │ │
|
│ 检索|最近] │ 编辑器(CM6) │ │
|
||||||
│ │ │ │
|
│ │ │ │
|
||||||
│ 树 / 结果 │ │ │
|
│ 树 / 结果 │ │ │
|
||||||
@@ -224,6 +224,20 @@ Tab 收敛为 **概览 / 库 / 编辑器 / 集成**(把 v1 的「同步」并
|
|||||||
└─────────────────────────────────────────────────────────────────────┘
|
└─────────────────────────────────────────────────────────────────────┘
|
||||||
```
|
```
|
||||||
|
|
||||||
|
**并排分屏**(标签右键 → 并排分屏)把编辑页平分为左右两列,各占一半宽:
|
||||||
|
|
||||||
|
```
|
||||||
|
├─ 工具栏(整行,不参与分屏)──────────────────────────────────────────┤
|
||||||
|
│ 标签栏:doc1 × | doc2 × │ 副文档名 × │
|
||||||
|
├──────────────────────────────┼──────────────────────────────────────┤
|
||||||
|
│ 编辑器(CM6)· 主文档 │ 编辑器(CM6)· 副文档 │
|
||||||
|
└──────────────────────────────┴──────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
- 「标签栏 + 编辑栏」整体是**左半列**,副文档是**右半列**(自带 8px 标题行与关闭按钮),
|
||||||
|
两列等宽、各自独立滚动 —— 副文档是并排的一列,**不是嵌在编辑栏内部的一块**。
|
||||||
|
从前的做法把副面板塞在编辑栏(标签栏下方)内部,看起来像"同一栏里又开了个窗口"。
|
||||||
|
- 不分屏时标签栏回到顶部、横跨整列宽度(即左半列占满),行为与基础形态一致。
|
||||||
- 侧栏可整体折叠(腾出宽度给长行代码)。
|
- 侧栏可整体折叠(腾出宽度给长行代码)。
|
||||||
- 抽屉默认关闭,`Ctrl+Shift+O` 切大纲、`Ctrl+Shift+B` 切双链。**这两个键位在实现时由 `keymap.ts` 统一声明并做冲突检测**:若与 CM6 默认键位冲突,以 CM6 默认键位优先,本功能改用 `Alt+O` / `Alt+B`(冲突检测方式沿用 v1 的 `shortcut.rs` 思路,编辑器内用 CM6 的 keymap 优先级)。
|
- 抽屉默认关闭,`Ctrl+Shift+O` 切大纲、`Ctrl+Shift+B` 切双链。**这两个键位在实现时由 `keymap.ts` 统一声明并做冲突检测**:若与 CM6 默认键位冲突,以 CM6 默认键位优先,本功能改用 `Alt+O` / `Alt+B`(冲突检测方式沿用 v1 的 `shortcut.rs` 思路,编辑器内用 CM6 的 keymap 优先级)。
|
||||||
|
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
Generated
+29
@@ -7895,8 +7895,12 @@ checksum = "edc5f74e248dc973e0dbb7b74c7e0d6fcc301c694ff50049504004ef4d0cdcd9"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"futures-util",
|
"futures-util",
|
||||||
"log",
|
"log",
|
||||||
|
"rustls",
|
||||||
|
"rustls-pki-types",
|
||||||
"tokio",
|
"tokio",
|
||||||
|
"tokio-rustls",
|
||||||
"tungstenite",
|
"tungstenite",
|
||||||
|
"webpki-roots 0.26.11",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -8032,12 +8036,17 @@ version = "0.6.11"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"
|
checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"async-compression",
|
||||||
"bitflags 2.13.2",
|
"bitflags 2.13.2",
|
||||||
"bytes",
|
"bytes",
|
||||||
|
"futures-core",
|
||||||
"futures-util",
|
"futures-util",
|
||||||
"http",
|
"http",
|
||||||
"http-body",
|
"http-body",
|
||||||
|
"http-body-util",
|
||||||
"pin-project-lite",
|
"pin-project-lite",
|
||||||
|
"tokio",
|
||||||
|
"tokio-util",
|
||||||
"tower",
|
"tower",
|
||||||
"tower-layer",
|
"tower-layer",
|
||||||
"tower-service",
|
"tower-service",
|
||||||
@@ -8139,6 +8148,8 @@ dependencies = [
|
|||||||
"httparse",
|
"httparse",
|
||||||
"log",
|
"log",
|
||||||
"rand 0.8.8",
|
"rand 0.8.8",
|
||||||
|
"rustls",
|
||||||
|
"rustls-pki-types",
|
||||||
"sha1 0.10.7",
|
"sha1 0.10.7",
|
||||||
"thiserror 1.0.69",
|
"thiserror 1.0.69",
|
||||||
"utf-8",
|
"utf-8",
|
||||||
@@ -8512,6 +8523,24 @@ dependencies = [
|
|||||||
"rustls-pki-types",
|
"rustls-pki-types",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "webpki-roots"
|
||||||
|
version = "0.26.11"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9"
|
||||||
|
dependencies = [
|
||||||
|
"webpki-roots 1.0.9",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "webpki-roots"
|
||||||
|
version = "1.0.9"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a"
|
||||||
|
dependencies = [
|
||||||
|
"rustls-pki-types",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "webview2-com"
|
name = "webview2-com"
|
||||||
version = "0.39.1"
|
version = "0.39.1"
|
||||||
|
|||||||
+19
-3
@@ -42,8 +42,14 @@ chrono = "0.4"
|
|||||||
# blocking:音乐播放引擎在**独立 std 线程**上解码(symphonia 的 MediaSource 是同步
|
# blocking:音乐播放引擎在**独立 std 线程**上解码(symphonia 的 MediaSource 是同步
|
||||||
# Read+Seek),需要同步 HTTP 客户端去按 Range 拉 NAS 音频流。放在 std 线程上用
|
# Read+Seek),需要同步 HTTP 客户端去按 Range 拉 NAS 音频流。放在 std 线程上用
|
||||||
# blocking 是安全的(在 tokio 运行时线程里用才会 panic)。
|
# blocking 是安全的(在 tokio 运行时线程里用才会 panic)。
|
||||||
reqwest = { version = "0.12", features = ["json", "stream", "multipart", "blocking"] }
|
# gzip:智能家居模块走反代(Cloudflare Tunnel)链路时,`/api/states` 是几百 KB JSON。
|
||||||
futures-util = "0.3"
|
# **默认不开压缩就不会发 Accept-Encoding**,CF 会回未压缩响应,远端首屏流量翻 5–10 倍
|
||||||
|
# (见 doc/SMART_HOME_MODULE_PLAN.md §3.7-b)。
|
||||||
|
reqwest = { version = "0.12", features = ["json", "stream", "multipart", "blocking", "gzip"] }
|
||||||
|
# `sink`:WebSocket 客户端要把流拆成读/写两半(`SinkExt` / `StreamExt`)。
|
||||||
|
# default 特性里**不含** `sink`(已核对 0.3.32 的 Cargo.toml),目前只是因为
|
||||||
|
# tokio-tungstenite 自己开了它才传递可用 —— 依赖传递特性不该被当成前提,故显式打开。
|
||||||
|
futures-util = { version = "0.3", features = ["sink"] }
|
||||||
tokio = { version = "1", features = ["io-util", "time", "rt-multi-thread", "macros", "sync", "fs", "net"] }
|
tokio = { version = "1", features = ["io-util", "time", "rt-multi-thread", "macros", "sync", "fs", "net"] }
|
||||||
axum = { version = "0.7", features = ["ws"] }
|
axum = { version = "0.7", features = ["ws"] }
|
||||||
url = "2"
|
url = "2"
|
||||||
@@ -104,7 +110,14 @@ aes = "0.8"
|
|||||||
cbc = "0.1"
|
cbc = "0.1"
|
||||||
rsa = { version = "0.9", features = ["pem"] }
|
rsa = { version = "0.9", features = ["pem"] }
|
||||||
rand = "0.8"
|
rand = "0.8"
|
||||||
tokio-tungstenite = "0.24"
|
# WebSocket 客户端(智能家居模块 P4 的实时推送 / 规则引擎)。
|
||||||
|
# `connect` 已随 default 启用(`cargo tree -e features -i tokio-tungstenite` 复核过:
|
||||||
|
# 它由本项 + axum 的 `ws` 共同引入),这里显式写出来是为了让"要连"这件事在清单里可见。
|
||||||
|
# **TLS 默认未启用** —— 反代是 HTTPS(`wss://`,D5 已定必须支持),故补
|
||||||
|
# `rustls-tls-webpki-roots`:纯 Rust、无 C 依赖,与项目姿态一致(`native-tls` 会引入系统依赖),
|
||||||
|
# 且复用依赖树里已存在的 rustls 0.23(经 russh),不新增编译单元。
|
||||||
|
# 注意:自签证书的 `wss://` 仍是缺口 —— `insecure`(危险开关)目前只覆盖 REST。
|
||||||
|
tokio-tungstenite = { version = "0.24", features = ["connect", "rustls-tls-webpki-roots"] }
|
||||||
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp"] }
|
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp"] }
|
||||||
walkdir = "2"
|
walkdir = "2"
|
||||||
notify = { version = "6", features = [] }
|
notify = { version = "6", features = [] }
|
||||||
@@ -178,6 +191,9 @@ windows = { version = "0.52", features = [
|
|||||||
"Win32_System_Ole",
|
"Win32_System_Ole",
|
||||||
"Win32_System_Variant",
|
"Win32_System_Variant",
|
||||||
"Win32_UI_Shell",
|
"Win32_UI_Shell",
|
||||||
|
# 快速面板「保存截图后定位并进入重命名」:SHParseDisplayName / SHOpenFolderAndSelectItems
|
||||||
|
# 与 ITEMIDLIST 都被 Win32_UI_Shell_Common 门控(windows 0.52 源码 cfg)
|
||||||
|
"Win32_UI_Shell_Common",
|
||||||
"Win32_UI_WindowsAndMessaging",
|
"Win32_UI_WindowsAndMessaging",
|
||||||
# 翻译模块:Windows.Media.Ocr 本地识别(WinRT)
|
# 翻译模块:Windows.Media.Ocr 本地识别(WinRT)
|
||||||
# Foundation_Collections:OcrResult.Lines / OcrEngine.AvailableRecognizerLanguages 返回 IVectorView
|
# Foundation_Collections:OcrResult.Lines / OcrEngine.AvailableRecognizerLanguages 返回 IVectorView
|
||||||
|
|||||||
@@ -178,4 +178,12 @@ pub mod events {
|
|||||||
// 进度在**发送端**按时间节流(见 diff::commands::diff_compare_dirs):整棵树可能有
|
// 进度在**发送端**按时间节流(见 diff::commands::diff_compare_dirs):整棵树可能有
|
||||||
// 上万个条目、上千次读盘,逐条 emit 会把 IPC 打满;前端只负责显示。
|
// 上万个条目、上千次读盘,逐条 emit 会把 IPC 打满;前端只负责显示。
|
||||||
pub const DIFF_SCAN_PROGRESS: &str = "diff-scan-progress";
|
pub const DIFF_SCAN_PROGRESS: &str = "diff-scan-progress";
|
||||||
|
// ===== 智能家居(Home Assistant)实时推送与本地规则(P4)=====
|
||||||
|
// 连接状态变化(含 WS):负载 `WsStatus`。前端据此显示顶部横幅与设置页诊断。
|
||||||
|
pub const SMARTHOME_CONNECTION_STATUS: &str = "smarthome-connection-status";
|
||||||
|
// 状态增量批次(**200ms 聚合后**):负载 `StateBatch`。
|
||||||
|
// 逐条 emit 会把 WebView 打爆(一次全屋变化可能几十条),聚合是硬要求。
|
||||||
|
pub const SMARTHOME_STATE_BATCH: &str = "smarthome-state-batch";
|
||||||
|
// 本地规则触发:负载 `RuleFiredEvent`。
|
||||||
|
pub const SMARTHOME_RULE_FIRED: &str = "smarthome-rule-fired";
|
||||||
}
|
}
|
||||||
+63
-2
@@ -20,6 +20,7 @@ mod screenshot;
|
|||||||
mod secrets;
|
mod secrets;
|
||||||
mod setup;
|
mod setup;
|
||||||
mod shortcut;
|
mod shortcut;
|
||||||
|
mod smarthome;
|
||||||
mod snap_fix;
|
mod snap_fix;
|
||||||
mod taskbar_identity;
|
mod taskbar_identity;
|
||||||
mod terminal;
|
mod terminal;
|
||||||
@@ -145,7 +146,8 @@ use quickpanel::{
|
|||||||
quickpanel_get_special_locations, quickpanel_hide_popup, quickpanel_init_file_index,
|
quickpanel_get_special_locations, quickpanel_hide_popup, quickpanel_init_file_index,
|
||||||
quickpanel_list_archives, quickpanel_list_dir, quickpanel_lock_screen, quickpanel_open_file,
|
quickpanel_list_archives, quickpanel_list_dir, quickpanel_lock_screen, quickpanel_open_file,
|
||||||
quickpanel_open_special, quickpanel_preview_rename, quickpanel_register_shortcut,
|
quickpanel_open_special, quickpanel_preview_rename, quickpanel_register_shortcut,
|
||||||
quickpanel_reveal_in_explorer, quickpanel_run_custom_command, quickpanel_run_system_command,
|
quickpanel_reveal_in_explorer, quickpanel_reveal_in_explorer_rename,
|
||||||
|
quickpanel_run_custom_command, quickpanel_run_system_command,
|
||||||
quickpanel_save_settings, quickpanel_scan_apps, quickpanel_search_files, quickpanel_show_popup,
|
quickpanel_save_settings, quickpanel_scan_apps, quickpanel_search_files, quickpanel_show_popup,
|
||||||
quickpanel_show_window, quickpanel_unregister_shortcut, quickpanel_focus_main_window,
|
quickpanel_show_window, quickpanel_unregister_shortcut, quickpanel_focus_main_window,
|
||||||
};
|
};
|
||||||
@@ -194,6 +196,15 @@ use terminal::commands::{
|
|||||||
};
|
};
|
||||||
use terminal::TerminalManager;
|
use terminal::TerminalManager;
|
||||||
use taskbar_identity::window_set_taskbar_identity;
|
use taskbar_identity::window_set_taskbar_identity;
|
||||||
|
use smarthome::{
|
||||||
|
smarthome_activate_connection, smarthome_call_service, smarthome_check_link,
|
||||||
|
smarthome_clear_token, smarthome_delete_connection, smarthome_delete_rule,
|
||||||
|
smarthome_get_entity, smarthome_get_settings, smarthome_list_entities, smarthome_list_registry,
|
||||||
|
smarthome_list_rules, smarthome_save_connection, smarthome_save_rule,
|
||||||
|
smarthome_save_ui_settings, smarthome_set_endpoint_mode, smarthome_set_realtime_enabled,
|
||||||
|
smarthome_set_rules_enabled, smarthome_set_token, smarthome_test_connection,
|
||||||
|
smarthome_ws_start, smarthome_ws_status, smarthome_ws_stop,
|
||||||
|
};
|
||||||
use win32_util::window_focus_window;
|
use win32_util::window_focus_window;
|
||||||
use translate::{
|
use translate::{
|
||||||
translate_abort, translate_ai_engine_remove, translate_ai_params_save, translate_apply_shortcuts,
|
translate_abort, translate_ai_engine_remove, translate_ai_params_save, translate_apply_shortcuts,
|
||||||
@@ -255,7 +266,8 @@ fn export_bindings() {
|
|||||||
quickpanel_show_window, quickpanel_lock_screen, quickpanel_init_file_index,
|
quickpanel_show_window, quickpanel_lock_screen, quickpanel_init_file_index,
|
||||||
quickpanel_build_file_index, quickpanel_search_files, quickpanel_file_index_stats,
|
quickpanel_build_file_index, quickpanel_search_files, quickpanel_file_index_stats,
|
||||||
quickpanel_scan_apps, quickpanel_get_app_icon, quickpanel_clear_app_icon_cache,
|
quickpanel_scan_apps, quickpanel_get_app_icon, quickpanel_clear_app_icon_cache,
|
||||||
quickpanel_reveal_in_explorer, quickpanel_open_file, quickpanel_get_special_locations,
|
quickpanel_reveal_in_explorer, quickpanel_reveal_in_explorer_rename,
|
||||||
|
quickpanel_open_file, quickpanel_get_special_locations,
|
||||||
quickpanel_open_special, quickpanel_delete_file, quickpanel_run_custom_command,
|
quickpanel_open_special, quickpanel_delete_file, quickpanel_run_custom_command,
|
||||||
quickpanel_run_system_command, quickpanel_list_archives, quickpanel_list_dir,
|
quickpanel_run_system_command, quickpanel_list_archives, quickpanel_list_dir,
|
||||||
quickpanel_batch_extract, quickpanel_preview_rename, quickpanel_apply_rename,
|
quickpanel_batch_extract, quickpanel_preview_rename, quickpanel_apply_rename,
|
||||||
@@ -381,6 +393,30 @@ fn export_bindings() {
|
|||||||
diff_compare_dirs,
|
diff_compare_dirs,
|
||||||
diff_get_settings,
|
diff_get_settings,
|
||||||
diff_save_settings,
|
diff_save_settings,
|
||||||
|
// 智能家居(Home Assistant):连接 / 令牌 / 端点策略 / 测试 —— 与 run() 里那份保持一致,否则 bindings.ts 缺类型
|
||||||
|
smarthome_get_settings,
|
||||||
|
smarthome_save_connection,
|
||||||
|
smarthome_set_token,
|
||||||
|
smarthome_clear_token,
|
||||||
|
smarthome_delete_connection,
|
||||||
|
smarthome_activate_connection,
|
||||||
|
smarthome_set_endpoint_mode,
|
||||||
|
smarthome_test_connection,
|
||||||
|
smarthome_check_link,
|
||||||
|
smarthome_list_entities,
|
||||||
|
smarthome_save_ui_settings,
|
||||||
|
smarthome_call_service,
|
||||||
|
smarthome_get_entity,
|
||||||
|
// 智能家居 P4:实时推送 / 注册表(房间分组)/ 本地规则
|
||||||
|
smarthome_set_realtime_enabled,
|
||||||
|
smarthome_ws_start,
|
||||||
|
smarthome_ws_stop,
|
||||||
|
smarthome_ws_status,
|
||||||
|
smarthome_list_registry,
|
||||||
|
smarthome_list_rules,
|
||||||
|
smarthome_save_rule,
|
||||||
|
smarthome_delete_rule,
|
||||||
|
smarthome_set_rules_enabled,
|
||||||
// 子窗口任务栏身份(独立 AUMID + 组合图标)
|
// 子窗口任务栏身份(独立 AUMID + 组合图标)
|
||||||
window_set_taskbar_identity,
|
window_set_taskbar_identity,
|
||||||
// 通用「显示 + 取消最小化 + 强制置前」(绕过 Windows 前台锁定)
|
// 通用「显示 + 取消最小化 + 强制置前」(绕过 Windows 前台锁定)
|
||||||
@@ -639,6 +675,7 @@ pub fn run() {
|
|||||||
quickpanel_get_app_icon,
|
quickpanel_get_app_icon,
|
||||||
quickpanel_clear_app_icon_cache,
|
quickpanel_clear_app_icon_cache,
|
||||||
quickpanel_reveal_in_explorer,
|
quickpanel_reveal_in_explorer,
|
||||||
|
quickpanel_reveal_in_explorer_rename,
|
||||||
quickpanel_open_file,
|
quickpanel_open_file,
|
||||||
quickpanel_delete_file,
|
quickpanel_delete_file,
|
||||||
quickpanel_delete_files,
|
quickpanel_delete_files,
|
||||||
@@ -916,6 +953,30 @@ pub fn run() {
|
|||||||
diff_compare_dirs,
|
diff_compare_dirs,
|
||||||
diff_get_settings,
|
diff_get_settings,
|
||||||
diff_save_settings,
|
diff_save_settings,
|
||||||
|
// 智能家居(Home Assistant):连接 / 令牌 / 端点策略 / 测试
|
||||||
|
smarthome_get_settings,
|
||||||
|
smarthome_save_connection,
|
||||||
|
smarthome_set_token,
|
||||||
|
smarthome_clear_token,
|
||||||
|
smarthome_delete_connection,
|
||||||
|
smarthome_activate_connection,
|
||||||
|
smarthome_set_endpoint_mode,
|
||||||
|
smarthome_test_connection,
|
||||||
|
smarthome_check_link,
|
||||||
|
smarthome_list_entities,
|
||||||
|
smarthome_save_ui_settings,
|
||||||
|
smarthome_call_service,
|
||||||
|
smarthome_get_entity,
|
||||||
|
// 智能家居 P4:实时推送 / 注册表(房间分组)/ 本地规则
|
||||||
|
smarthome_set_realtime_enabled,
|
||||||
|
smarthome_ws_start,
|
||||||
|
smarthome_ws_stop,
|
||||||
|
smarthome_ws_status,
|
||||||
|
smarthome_list_registry,
|
||||||
|
smarthome_list_rules,
|
||||||
|
smarthome_save_rule,
|
||||||
|
smarthome_delete_rule,
|
||||||
|
smarthome_set_rules_enabled,
|
||||||
// 子窗口任务栏身份(独立 AUMID + 组合图标)
|
// 子窗口任务栏身份(独立 AUMID + 组合图标)
|
||||||
window_set_taskbar_identity,
|
window_set_taskbar_identity,
|
||||||
// 通用「显示 + 取消最小化 + 强制置前」
|
// 通用「显示 + 取消最小化 + 强制置前」
|
||||||
|
|||||||
@@ -337,6 +337,147 @@ pub fn quickpanel_reveal_in_explorer(path: String) -> Result<(), String> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 等 Explorer 完成「定位 + 选中」再送 F2 的等待时长。
|
||||||
|
///
|
||||||
|
/// 这是纯 UI 时序:定位调用只是把一个请求交给已在运行的 Explorer 进程,
|
||||||
|
/// 它要等窗口到前台、切到目标目录、滚到条目并选中,然后才会响应 F2。
|
||||||
|
/// 给得太短会把 F2 送到当时还在前台的那个窗口上(而不是 Explorer)。
|
||||||
|
const RENAME_KEY_DELAY_MS: u64 = 450;
|
||||||
|
|
||||||
|
/// 在资源管理器中定位文件(选中)并**进入重命名编辑状态**。
|
||||||
|
///
|
||||||
|
/// # 为什么不用 `explorer.exe /select,`
|
||||||
|
///
|
||||||
|
/// 本仓原先的定位做法是 `ShellExecuteW("explorer.exe", "/select,\"path\"")`。
|
||||||
|
/// 那条命令行在 Win10/11 上**经常新开一个窗口**而不是复用用户已经打开的那个
|
||||||
|
/// (尤其目标文件夹已通过标签页 / 其他窗口打开时)—— 表现就是"点保存后又弹出
|
||||||
|
/// 一个资源管理器打开了这个文件夹"。`SHOpenFolderAndSelectItems` 才是 shell 为此
|
||||||
|
/// 提供的 API:复用已有窗口、滚到条目并选中,随后该窗口即为前台窗口。
|
||||||
|
///
|
||||||
|
/// 重命名仍然只能借 Explorer 自己的快捷键 F2 —— shell 没有"开始重命名"的 API。
|
||||||
|
///
|
||||||
|
/// `spawn_blocking`:命令里有 sleep;同时 shell 调用要求 **STA** 线程,而 async 命令
|
||||||
|
/// 跑在 tokio 工作线程(MTA)上 —— 所以在工作线程里自己
|
||||||
|
/// `CoInitializeEx(APARTMENTTHREADED)`(与 `quickpanel::explorer` 同一做法),
|
||||||
|
/// 既不占 IPC 线程,也不依赖命令所在线程的既有套间模型。
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub async fn quickpanel_reveal_in_explorer_rename(path: String) -> Result<(), String> {
|
||||||
|
tauri::async_runtime::spawn_blocking(move || -> Result<(), String> {
|
||||||
|
select_in_explorer(&path)?;
|
||||||
|
std::thread::sleep(std::time::Duration::from_millis(RENAME_KEY_DELAY_MS));
|
||||||
|
send_rename_key();
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("定位 / 重命名任务失败: {}", e))?
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 用 shell 的「打开文件夹并选中」定位文件(复用已有窗口,不新开一个)。
|
||||||
|
#[cfg(windows)]
|
||||||
|
fn select_in_explorer(path: &str) -> Result<(), String> {
|
||||||
|
use std::ffi::OsStr;
|
||||||
|
use std::os::windows::ffi::OsStrExt;
|
||||||
|
use windows::core::PCWSTR;
|
||||||
|
use windows::Win32::System::Com::{
|
||||||
|
CoInitializeEx, CoTaskMemFree, CoUninitialize, COINIT_APARTMENTTHREADED,
|
||||||
|
};
|
||||||
|
use windows::Win32::UI::Shell::Common::ITEMIDLIST;
|
||||||
|
use windows::Win32::UI::Shell::{SHOpenFolderAndSelectItems, SHParseDisplayName};
|
||||||
|
|
||||||
|
let normalized = path.replace('/', "\\");
|
||||||
|
let dir = match normalized.rfind('\\') {
|
||||||
|
Some(i) if i > 0 => &normalized[..i],
|
||||||
|
_ => return Err("路径缺少目录部分".into()),
|
||||||
|
};
|
||||||
|
|
||||||
|
let wide = |s: &str| -> Vec<u16> {
|
||||||
|
OsStr::new(s).encode_wide().chain(std::iter::once(0)).collect()
|
||||||
|
};
|
||||||
|
let dir_w = wide(dir);
|
||||||
|
let file_w = wide(&normalized);
|
||||||
|
|
||||||
|
// 首次 COM 初始化失败(例如线程已在 MTA)时,后续 shell 调用一般仍可用,忽略错误继续
|
||||||
|
let _ = unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) };
|
||||||
|
|
||||||
|
let result = unsafe {
|
||||||
|
let mut folder_pidl: *mut ITEMIDLIST = std::ptr::null_mut();
|
||||||
|
let mut file_pidl: *mut ITEMIDLIST = std::ptr::null_mut();
|
||||||
|
let attempt = (|| -> Result<(), String> {
|
||||||
|
SHParseDisplayName(PCWSTR(dir_w.as_ptr()), None, &mut folder_pidl, 0, None)
|
||||||
|
.map_err(|e| format!("解析目录失败: {}", e))?;
|
||||||
|
SHParseDisplayName(PCWSTR(file_w.as_ptr()), None, &mut file_pidl, 0, None)
|
||||||
|
.map_err(|e| format!("解析文件失败: {}", e))?;
|
||||||
|
// `apidl` 要的是**相对父目录的子 PIDL**,正是绝对 PIDL 的最后一个 ITEMID
|
||||||
|
let child = il_find_last_id(file_pidl);
|
||||||
|
SHOpenFolderAndSelectItems(folder_pidl, Some(&[child]), 0)
|
||||||
|
.map_err(|e| format!("定位文件失败: {}", e))
|
||||||
|
})();
|
||||||
|
if !folder_pidl.is_null() {
|
||||||
|
CoTaskMemFree(Some(folder_pidl as *const core::ffi::c_void));
|
||||||
|
}
|
||||||
|
if !file_pidl.is_null() {
|
||||||
|
CoTaskMemFree(Some(file_pidl as *const core::ffi::c_void));
|
||||||
|
}
|
||||||
|
attempt
|
||||||
|
};
|
||||||
|
|
||||||
|
unsafe { CoUninitialize() };
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(windows))]
|
||||||
|
fn select_in_explorer(_path: &str) -> Result<(), String> {
|
||||||
|
Err("当前平台不支持".into())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `ITEMIDLIST` 是一条「ITEMID 链」:每个 ITEMID 以 2 字节的 `cb` 开头,`cb == 0` 表示链结束。
|
||||||
|
/// 返回最后一个 ITEMID 的指针(即相对父目录的子 PIDL)。
|
||||||
|
///
|
||||||
|
/// `ILFindLastID` 在 `shlobj_core.h` 里是**内联函数**,`windows` crate 不导出,所以这里自己走一遍
|
||||||
|
/// (windows-sys 把它声明成了 shell32 导入,但本项目统一用 `windows` crate 做 shell/COM)。
|
||||||
|
#[cfg(windows)]
|
||||||
|
unsafe fn il_find_last_id(pidl: *const windows::Win32::UI::Shell::Common::ITEMIDLIST) -> *const windows::Win32::UI::Shell::Common::ITEMIDLIST {
|
||||||
|
use windows::Win32::UI::Shell::Common::ITEMIDLIST;
|
||||||
|
let mut p: *const ITEMIDLIST = pidl;
|
||||||
|
loop {
|
||||||
|
let next = p.cast::<u8>().add((*p).mkid.cb as usize).cast::<ITEMIDLIST>();
|
||||||
|
if (*next).mkid.cb == 0 {
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
p = next;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 向前台窗口发一次 F2(Explorer 的重命名快捷键)。
|
||||||
|
///
|
||||||
|
/// 用 SendInput 而不是 PostMessage:F2 要经过 Explorer 的消息泵与输入法状态,
|
||||||
|
/// 与 `clipboard::popup::simulate_paste` 同一套做法(也是同一条已知限制:
|
||||||
|
/// 目标窗口若以管理员权限运行,非提权进程的 SendInput 会被 UIPI 挡掉)。
|
||||||
|
#[cfg(windows)]
|
||||||
|
fn send_rename_key() {
|
||||||
|
use windows_sys::Win32::UI::Input::KeyboardAndMouse::{
|
||||||
|
SendInput, INPUT, INPUT_KEYBOARD, KEYBDINPUT, KEYEVENTF_KEYUP, VK_F2,
|
||||||
|
};
|
||||||
|
|
||||||
|
// 安全初始化为零值,避免未定义字段
|
||||||
|
let mut inputs: [INPUT; 2] = unsafe { std::mem::zeroed() };
|
||||||
|
|
||||||
|
inputs[0].r#type = INPUT_KEYBOARD;
|
||||||
|
inputs[0].Anonymous.ki = KEYBDINPUT { wVk: VK_F2, wScan: 0, dwFlags: 0, time: 0, dwExtraInfo: 0 };
|
||||||
|
|
||||||
|
inputs[1].r#type = INPUT_KEYBOARD;
|
||||||
|
inputs[1].Anonymous.ki =
|
||||||
|
KEYBDINPUT { wVk: VK_F2, wScan: 0, dwFlags: KEYEVENTF_KEYUP, time: 0, dwExtraInfo: 0 };
|
||||||
|
|
||||||
|
unsafe {
|
||||||
|
SendInput(2, inputs.as_ptr(), std::mem::size_of::<INPUT>() as i32);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(windows))]
|
||||||
|
fn send_rename_key() {}
|
||||||
|
|
||||||
/// 用系统默认程序打开文件/文件夹。
|
/// 用系统默认程序打开文件/文件夹。
|
||||||
/// - 目录:explorer.exe 直接打开(修复索引目录点击后未打开的问题)
|
/// - 目录:explorer.exe 直接打开(修复索引目录点击后未打开的问题)
|
||||||
/// - 文件:ShellExecuteW open,无关联应用时自动 fallback 到「打开方式」对话框(verb: openas)
|
/// - 文件:ShellExecuteW open,无关联应用时自动 fallback 到「打开方式」对话框(verb: openas)
|
||||||
|
|||||||
@@ -23,7 +23,8 @@ pub use commands::{
|
|||||||
quickpanel_get_app_icon, quickpanel_get_settings, quickpanel_get_special_locations,
|
quickpanel_get_app_icon, quickpanel_get_settings, quickpanel_get_special_locations,
|
||||||
quickpanel_hide_popup, quickpanel_init_file_index, quickpanel_lock_screen,
|
quickpanel_hide_popup, quickpanel_init_file_index, quickpanel_lock_screen,
|
||||||
quickpanel_open_file, quickpanel_open_special, quickpanel_register_shortcut,
|
quickpanel_open_file, quickpanel_open_special, quickpanel_register_shortcut,
|
||||||
quickpanel_reveal_in_explorer, quickpanel_run_custom_command, quickpanel_run_system_command,
|
quickpanel_reveal_in_explorer, quickpanel_reveal_in_explorer_rename,
|
||||||
|
quickpanel_run_custom_command, quickpanel_run_system_command,
|
||||||
quickpanel_save_settings, quickpanel_scan_apps, quickpanel_search_files, quickpanel_show_popup,
|
quickpanel_save_settings, quickpanel_scan_apps, quickpanel_search_files, quickpanel_show_popup,
|
||||||
quickpanel_show_window, quickpanel_unregister_shortcut,
|
quickpanel_show_window, quickpanel_unregister_shortcut,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ use crate::monitor_kernel::MonitorKernel;
|
|||||||
use crate::music::MusicManager;
|
use crate::music::MusicManager;
|
||||||
use crate::network_monitor::NetworkMonitor;
|
use crate::network_monitor::NetworkMonitor;
|
||||||
use crate::editor::EditorManager;
|
use crate::editor::EditorManager;
|
||||||
|
use crate::smarthome::HaManager;
|
||||||
use crate::process_manager::{ProcessManager, start_monitoring_thread};
|
use crate::process_manager::{ProcessManager, start_monitoring_thread};
|
||||||
use crate::terminal::TerminalManager;
|
use crate::terminal::TerminalManager;
|
||||||
use crate::translate::TranslateManager;
|
use crate::translate::TranslateManager;
|
||||||
@@ -101,6 +102,21 @@ pub fn init(app: &mut App<Wry>) -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
diff.init_on_launch(app.handle());
|
diff.init_on_launch(app.handle());
|
||||||
app.manage(diff);
|
app.manage(diff);
|
||||||
|
|
||||||
|
// ===== 智能家居模块:HaManager(Home Assistant 对接) =====
|
||||||
|
// 仅注册状态:连接与令牌都在命令调用时按需读取,**启动阶段不发任何网络请求**。
|
||||||
|
// 端点探测(局域网 900ms / 反代 5s)发生在首次需要发请求时,不占启动时间。
|
||||||
|
let smarthome = HaManager::new(app_data_dir.clone());
|
||||||
|
app.manage(smarthome);
|
||||||
|
// P4:用户上次开着「实时推送」或「本地规则总开关」时,启动后恢复 WS 连接。
|
||||||
|
// 放在后台任务里(不阻塞启动),且**只有用户显式开过才会连** —— 与"启动不发请求"一致。
|
||||||
|
{
|
||||||
|
let handle = app.handle().clone();
|
||||||
|
tauri::async_runtime::spawn(async move {
|
||||||
|
let manager = handle.state::<HaManager>();
|
||||||
|
manager.sync_ws(&handle).await;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// ===== 翻译模块:TranslateManager =====
|
// ===== 翻译模块:TranslateManager =====
|
||||||
// 仅注册状态:设置与密钥都在命令调用时按需读取,启动阶段不发任何网络请求
|
// 仅注册状态:设置与密钥都在命令调用时按需读取,启动阶段不发任何网络请求
|
||||||
// (模型可用性校验因此改为懒校验:首次翻译失败时解释原因 + 设置页手动拉取模型列表)。
|
// (模型可用性校验因此改为懒校验:首次翻译失败时解释原因 + 设置页手动拉取模型列表)。
|
||||||
|
|||||||
@@ -0,0 +1,549 @@
|
|||||||
|
//! 本地轻量规则引擎(P4)。
|
||||||
|
//!
|
||||||
|
//! 三段式(触发 / 条件 / 动作)线性规则,**不做嵌套树** —— 这是"简单自动化"的边界所在
|
||||||
|
//! (plan §5.4-B)。求值在 Rust 侧:WS 事件一到就匹配,不依赖前端页面是否打开。
|
||||||
|
//!
|
||||||
|
//! **必须显式告知用户的前提**(D2 已拍板):本地规则只在 Thing 运行时生效。
|
||||||
|
//! 应用退出、电脑关机后就不再触发;要 7×24 可靠就得把规则建在 HA 里。UI 有常驻警示条。
|
||||||
|
//!
|
||||||
|
//! 三条护栏(plan §5.4-B 明确要求,一条都不能省):
|
||||||
|
//! 1. **冷却时间**:`cooldownSec` 内的重复触发直接丢弃;
|
||||||
|
//! 2. **动作失败不中断**:某个动作 4xx/5xx 时记 `lastError` 并继续下一个,
|
||||||
|
//! 否则一条失败会吞掉后续所有动作;
|
||||||
|
//! 3. **循环保护**:规则动作引起的状态变化可能再次触发同一规则(A 开 B、B 关 A),
|
||||||
|
//! 冷却不足以阻断时用"突发计数"兜底(同规则 10s 内最多 5 次)。
|
||||||
|
|
||||||
|
use std::collections::{HashMap, VecDeque};
|
||||||
|
use std::path::Path;
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use chrono::{Datelike, Local, Timelike};
|
||||||
|
use tauri::{AppHandle, Emitter};
|
||||||
|
use tauri_plugin_notification::NotificationExt;
|
||||||
|
use tokio::sync::watch;
|
||||||
|
|
||||||
|
use super::client;
|
||||||
|
use super::types::{
|
||||||
|
EndpointKind, EntitySummary, Rule, RuleAction, RuleCondition, RuleFiredEvent, RuleRecord,
|
||||||
|
RuleTrigger, RulesFile, RULES_VERSION,
|
||||||
|
};
|
||||||
|
use crate::constants::events;
|
||||||
|
|
||||||
|
/// 内存里保留的运行记录条数。
|
||||||
|
pub const MAX_RECORDS: usize = 50;
|
||||||
|
/// 单个 `delay` 动作的上限(秒)。
|
||||||
|
///
|
||||||
|
/// 防的是"睡 1 小时"这种怪规则:本地规则只在 Thing 运行时生效,
|
||||||
|
/// 一条要睡一小时的动作在应用重启后就永远跑不完了。
|
||||||
|
pub const MAX_DELAY_SEC: u32 = 600;
|
||||||
|
/// 突发护栏窗口与上限(循环保护,护栏 3)。
|
||||||
|
const BURST_WINDOW: Duration = Duration::from_secs(10);
|
||||||
|
const BURST_MAX: usize = 5;
|
||||||
|
/// 触发统计落盘的最小间隔(秒)—— 去抖,见 `maybe_persist`。
|
||||||
|
const PERSIST_MIN_INTERVAL_SECS: u64 = 3;
|
||||||
|
/// `for`(持续 N 秒)触发器的巡检间隔(毫秒)。
|
||||||
|
const SWEEP_INTERVAL_MS: u64 = 500;
|
||||||
|
|
||||||
|
/// 规则求值 / 执行所需的环境(`Clone` 以便丢进后台任务)。
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct RuleEnv {
|
||||||
|
pub app: AppHandle,
|
||||||
|
/// REST 端点:动作里的服务调用走 REST(与 P2 的控制同一条路径,不另造一套)
|
||||||
|
pub base_url: String,
|
||||||
|
pub token: String,
|
||||||
|
pub insecure: bool,
|
||||||
|
pub kind: EndpointKind,
|
||||||
|
pub rules: Arc<Mutex<RulesFile>>,
|
||||||
|
pub records: Arc<Mutex<VecDeque<RuleRecord>>>,
|
||||||
|
/// 当前实体摘要(`entity_id` → 摘要),条件判断读它
|
||||||
|
pub summaries: Arc<Mutex<HashMap<String, EntitySummary>>>,
|
||||||
|
/// 最近触发时刻(内存态,只服务突发护栏)
|
||||||
|
pub recent: Arc<Mutex<VecDeque<(String, Instant)>>>,
|
||||||
|
/// `for`(持续 N 秒)触发器的槽位表:`rule_id` → 到点时刻。
|
||||||
|
///
|
||||||
|
/// 用槽位表而不是"每次事件起一个 sleep 任务":1Hz 的实体配 `for=300`
|
||||||
|
/// 会常驻几百个任务,而且那些任务不受连接切换影响(会用旧端点执行动作)。
|
||||||
|
pub pending: Arc<Mutex<HashMap<String, Instant>>>,
|
||||||
|
/// 触发统计上次落盘时刻(去抖用,见 `maybe_persist`)
|
||||||
|
pub last_persist: Arc<Mutex<Instant>>,
|
||||||
|
/// `automations.json` 路径
|
||||||
|
pub rules_path: std::path::PathBuf,
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================== 文件读写 ==============================
|
||||||
|
|
||||||
|
/// 读取规则文件(不存在 / 损坏时退化为默认值,**不报错**:规则是可选功能,
|
||||||
|
/// 不该因为它坏了导致模块打不开)。
|
||||||
|
pub fn load(path: &Path) -> RulesFile {
|
||||||
|
let mut file: RulesFile = std::fs::read_to_string(path)
|
||||||
|
.ok()
|
||||||
|
.and_then(|t| serde_json::from_str(&t).ok())
|
||||||
|
.unwrap_or_default();
|
||||||
|
if file.version != RULES_VERSION {
|
||||||
|
file.version = RULES_VERSION;
|
||||||
|
}
|
||||||
|
file
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 写入规则文件(调用方负责放到 `spawn_blocking` 里)。
|
||||||
|
pub fn save(path: &Path, file: &RulesFile) -> Result<(), String> {
|
||||||
|
let json = serde_json::to_string_pretty(file).map_err(|e| format!("序列化规则失败:{e}"))?;
|
||||||
|
std::fs::write(path, json).map_err(|e| format!("写入规则文件失败:{e}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 保存前的校验(**留在这里而不是组件里**:规则模型的知识只有一份)。
|
||||||
|
pub fn validate(rule: &Rule) -> Result<(), String> {
|
||||||
|
if rule.name.trim().is_empty() {
|
||||||
|
return Err("请填写规则名称".to_string());
|
||||||
|
}
|
||||||
|
if rule.trigger.entity_id.trim().is_empty() {
|
||||||
|
return Err("请选择触发实体".to_string());
|
||||||
|
}
|
||||||
|
if rule.actions.is_empty() {
|
||||||
|
return Err("至少需要一个动作".to_string());
|
||||||
|
}
|
||||||
|
for action in &rule.actions {
|
||||||
|
match action.kind.as_str() {
|
||||||
|
"service" => {
|
||||||
|
if action.domain.trim().is_empty()
|
||||||
|
|| action.service.trim().is_empty()
|
||||||
|
|| action.entity_id.trim().is_empty()
|
||||||
|
{
|
||||||
|
return Err("动作里的 domain / 服务 / 实体都不能为空".to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"delay" => {
|
||||||
|
if action.seconds == 0 {
|
||||||
|
return Err("延时的秒数必须大于 0".to_string());
|
||||||
|
}
|
||||||
|
if action.seconds > MAX_DELAY_SEC {
|
||||||
|
return Err(format!("延时最长 {MAX_DELAY_SEC} 秒"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================== 求值 ==============================
|
||||||
|
|
||||||
|
/// 触发条件是否成立(`old` 为 `None` 表示"首次见到该实体"或"延时复查")。
|
||||||
|
pub fn trigger_matches(
|
||||||
|
trigger: &RuleTrigger,
|
||||||
|
old: Option<&EntitySummary>,
|
||||||
|
new: &EntitySummary,
|
||||||
|
) -> bool {
|
||||||
|
if trigger.entity_id.is_empty() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if !trigger.to.is_empty() && !trigger.to.contains(&new.state) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if !trigger.from.is_empty() {
|
||||||
|
match old {
|
||||||
|
Some(o) if trigger.from.contains(&o.state) => {}
|
||||||
|
// from 非空但拿不到旧状态:不判定为命中(宁可漏一次,也不要误触)
|
||||||
|
_ => return false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !trigger.numeric_op.is_empty() {
|
||||||
|
let (Some(value), Some(threshold)) = (new.numeric, trigger.numeric_value) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
let ok = match trigger.numeric_op.as_str() {
|
||||||
|
">" => value > threshold,
|
||||||
|
">=" => value >= threshold,
|
||||||
|
"<" => value < threshold,
|
||||||
|
"<=" => value <= threshold,
|
||||||
|
"==" => (value - threshold).abs() < f64::EPSILON,
|
||||||
|
"!=" => (value - threshold).abs() >= f64::EPSILON,
|
||||||
|
_ => true,
|
||||||
|
};
|
||||||
|
if !ok {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 实体状态变化时的入口(由 `ws.rs` 的聚合任务调用,**必须是同步的**:
|
||||||
|
/// 它跑在 WS 读循环里,耗时工作都丢给后台任务)。
|
||||||
|
pub fn on_entity_changed(
|
||||||
|
env: &RuleEnv,
|
||||||
|
entity_id: &str,
|
||||||
|
old: Option<&EntitySummary>,
|
||||||
|
new: &EntitySummary,
|
||||||
|
) {
|
||||||
|
let candidates: Vec<(String, RuleTrigger)> = {
|
||||||
|
let Ok(file) = env.rules.lock() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
if !file.enabled {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
file.rules
|
||||||
|
.iter()
|
||||||
|
.filter(|r| r.enabled && r.trigger.entity_id == entity_id)
|
||||||
|
.map(|r| (r.id.clone(), r.trigger.clone()))
|
||||||
|
.collect()
|
||||||
|
};
|
||||||
|
|
||||||
|
for (rule_id, trigger) in candidates {
|
||||||
|
if trigger.for_sec == 0 {
|
||||||
|
if !trigger_matches(&trigger, old, new) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let env = env.clone();
|
||||||
|
tauri::async_runtime::spawn(async move {
|
||||||
|
fire(&env, &rule_id).await;
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// 持续 N 秒:只维护"首次满足的时刻",到点由巡检任务(`spawn_sweeper`)复查;
|
||||||
|
// 状态一旦离开满足态就把槽位撤掉。**不重置**已存在的槽位 —— 那才是
|
||||||
|
// "持续 N 秒满足"的语义(每次事件都重置会变成"静默 N 秒才触发")。
|
||||||
|
let matches = trigger_matches(&trigger, old, new);
|
||||||
|
if let Ok(mut pending) = env.pending.lock() {
|
||||||
|
if matches {
|
||||||
|
pending
|
||||||
|
.entry(rule_id)
|
||||||
|
.or_insert_with(|| Instant::now() + Duration::from_secs(trigger.for_sec as u64));
|
||||||
|
} else {
|
||||||
|
pending.remove(&rule_id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `for` 触发器的巡检任务:每 `SWEEP_INTERVAL_MS` 看一次槽位表,到点的复查后执行。
|
||||||
|
///
|
||||||
|
/// **与 WS 连接同生命周期**(收到 stop 就退出):连接换了/停了,就不会有旧定时器
|
||||||
|
/// 残留下来用旧端点、旧令牌继续执行动作。
|
||||||
|
pub fn spawn_sweeper(env: &RuleEnv, mut stop: watch::Receiver<bool>) {
|
||||||
|
let env = env.clone();
|
||||||
|
tauri::async_runtime::spawn(async move {
|
||||||
|
let mut tick = tokio::time::interval(Duration::from_millis(SWEEP_INTERVAL_MS));
|
||||||
|
loop {
|
||||||
|
tokio::select! {
|
||||||
|
_ = stop.changed() => break,
|
||||||
|
_ = tick.tick() => sweep_pending(&env),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sweep_pending(env: &RuleEnv) {
|
||||||
|
let due: Vec<String> = match env.pending.lock() {
|
||||||
|
Ok(mut pending) => {
|
||||||
|
let now = Instant::now();
|
||||||
|
let ready: Vec<String> = pending
|
||||||
|
.iter()
|
||||||
|
.filter(|entry| *entry.1 <= now)
|
||||||
|
.map(|entry| entry.0.clone())
|
||||||
|
.collect();
|
||||||
|
for id in &ready {
|
||||||
|
pending.remove(id);
|
||||||
|
}
|
||||||
|
ready
|
||||||
|
}
|
||||||
|
Err(_) => return,
|
||||||
|
};
|
||||||
|
|
||||||
|
for rule_id in due {
|
||||||
|
let (trigger, entity_id) = match env.rules.lock() {
|
||||||
|
Ok(file) if file.enabled => {
|
||||||
|
match file.rules.iter().find(|r| r.id == rule_id && r.enabled) {
|
||||||
|
Some(r) => (r.trigger.clone(), r.trigger.entity_id.clone()),
|
||||||
|
None => continue,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => continue,
|
||||||
|
};
|
||||||
|
// 复查:到点时**当前**状态仍需满足触发条件(去抖的真正含义)
|
||||||
|
let current = env
|
||||||
|
.summaries
|
||||||
|
.lock()
|
||||||
|
.ok()
|
||||||
|
.and_then(|g| g.get(&entity_id).cloned());
|
||||||
|
let Some(current) = current else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
if !trigger_matches(&trigger, None, ¤t) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let env = env.clone();
|
||||||
|
tauri::async_runtime::spawn(async move {
|
||||||
|
fire(&env, &rule_id).await;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 原子认领一次触发权:**在同一把锁里**判冷却并写下占位时间。
|
||||||
|
///
|
||||||
|
/// 为什么必须"认领"而不是"先读后写":`fire` 里的动作是 async(服务调用可能几秒),
|
||||||
|
/// 同一聚合窗口内的两条事件会各自起一个 `fire`,两个都读到同一份旧 `last_fired_at`
|
||||||
|
/// → 都通过冷却 → **同一条规则被重复执行**。占位把判定与写入收进一个临界区后,
|
||||||
|
/// 后到的那次会读到新时间戳并被冷却挡掉。
|
||||||
|
///
|
||||||
|
/// 返回 `(规则快照, 认领时刻)`。
|
||||||
|
fn claim(env: &RuleEnv, rule_id: &str) -> Option<(Rule, i64)> {
|
||||||
|
let mut file = env.rules.lock().ok()?;
|
||||||
|
if !file.enabled {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let idx = file.rules.iter().position(|r| r.id == rule_id)?;
|
||||||
|
if !file.rules[idx].enabled {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let now = chrono::Utc::now().timestamp();
|
||||||
|
let (cooldown, last) = (file.rules[idx].cooldown_sec, file.rules[idx].last_fired_at);
|
||||||
|
if cooldown > 0 && last > 0 && now - last < cooldown as i64 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
file.rules[idx].last_fired_at = now;
|
||||||
|
Some((file.rules[idx].clone(), now))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 执行一条规则(认领 → 突发护栏 → 条件 → 动作)。
|
||||||
|
async fn fire(env: &RuleEnv, rule_id: &str) {
|
||||||
|
let Some((rule, now)) = claim(env, rule_id) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 护栏 3:突发计数(冷却不足以阻断的 A→B→A 互触)
|
||||||
|
if !burst_allow(env, &rule.id) {
|
||||||
|
crate::logger::log_warn(
|
||||||
|
"smarthome",
|
||||||
|
&format!(
|
||||||
|
"规则「{}」在 {} 秒内触发超过 {} 次,已跳过(循环保护)",
|
||||||
|
rule.name,
|
||||||
|
BURST_WINDOW.as_secs(),
|
||||||
|
BURST_MAX
|
||||||
|
),
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if !conditions_ok(env, &rule) {
|
||||||
|
// 触发器确实命中了,是条件没放行:本次不执行、不计次数,
|
||||||
|
// 但冷却槽已被占用(没有动作就不该反复重试)
|
||||||
|
maybe_persist(env);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut failures: Vec<String> = Vec::new();
|
||||||
|
for action in &rule.actions {
|
||||||
|
// 护栏 2:单个动作失败**不中断**后续动作
|
||||||
|
if let Err(e) = run_action(env, action).await {
|
||||||
|
failures.push(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let ok = failures.is_empty();
|
||||||
|
let detail = if ok {
|
||||||
|
format!("已执行 {} 个动作", rule.actions.len())
|
||||||
|
} else {
|
||||||
|
failures.join(";")
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Ok(mut file) = env.rules.lock() {
|
||||||
|
if let Some(slot) = file.rules.iter_mut().find(|r| r.id == rule_id) {
|
||||||
|
if ok {
|
||||||
|
slot.fire_count = slot.fire_count.saturating_add(1);
|
||||||
|
}
|
||||||
|
slot.last_error = if ok { String::new() } else { detail.clone() };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
maybe_persist(env);
|
||||||
|
|
||||||
|
crate::logger::log_info(
|
||||||
|
"smarthome",
|
||||||
|
&format!("本地规则「{}」触发:{}", rule.name, detail),
|
||||||
|
);
|
||||||
|
push_record(
|
||||||
|
env,
|
||||||
|
RuleRecord {
|
||||||
|
rule_id: rule.id.clone(),
|
||||||
|
rule_name: rule.name.clone(),
|
||||||
|
at: now,
|
||||||
|
ok,
|
||||||
|
detail,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 触发统计的落盘去抖:内存立即更新,磁盘最多每 `PERSIST_MIN_INTERVAL_SECS` 写一次。
|
||||||
|
///
|
||||||
|
/// 规则很容易被传感器刷得勤(功率反复跳),每触发一次就整份序列化 + 写盘是纯浪费;
|
||||||
|
/// 统计字段(`lastFiredAt` / `fireCount` / `lastError`)晚几秒落盘不影响任何判断。
|
||||||
|
/// 命令层的**显式**保存(存规则 / 删规则 / 总开关)仍立即写盘 —— 那是用户动作。
|
||||||
|
fn maybe_persist(env: &RuleEnv) {
|
||||||
|
let due = match env.last_persist.lock() {
|
||||||
|
Ok(mut at) => {
|
||||||
|
if at.elapsed() >= Duration::from_secs(PERSIST_MIN_INTERVAL_SECS) {
|
||||||
|
*at = Instant::now();
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(_) => true,
|
||||||
|
};
|
||||||
|
if !due {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let Ok(file) = env.rules.lock().map(|g| g.clone()) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let path = env.rules_path.clone();
|
||||||
|
tauri::async_runtime::spawn_blocking(move || {
|
||||||
|
if let Err(e) = save(&path, &file) {
|
||||||
|
crate::logger::log_warn("smarthome", &format!("保存规则触发统计失败:{e}"));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 执行单个动作。
|
||||||
|
async fn run_action(env: &RuleEnv, action: &RuleAction) -> Result<(), String> {
|
||||||
|
match action.kind.as_str() {
|
||||||
|
"delay" => {
|
||||||
|
let secs = action.seconds.min(MAX_DELAY_SEC) as u64;
|
||||||
|
if secs > 0 {
|
||||||
|
tokio::time::sleep(Duration::from_secs(secs)).await;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
"notify" => {
|
||||||
|
let title = if action.title.trim().is_empty() {
|
||||||
|
"Thing 智能家居".to_string()
|
||||||
|
} else {
|
||||||
|
action.title.clone()
|
||||||
|
};
|
||||||
|
env.app
|
||||||
|
.notification()
|
||||||
|
.builder()
|
||||||
|
.title(title)
|
||||||
|
.body(action.message.clone())
|
||||||
|
.show()
|
||||||
|
.map_err(|e| format!("系统通知发送失败:{e}"))
|
||||||
|
}
|
||||||
|
// 默认按 service 处理(前端只给这三种 kind)
|
||||||
|
_ => {
|
||||||
|
if action.domain.trim().is_empty()
|
||||||
|
|| action.service.trim().is_empty()
|
||||||
|
|| action.entity_id.trim().is_empty()
|
||||||
|
{
|
||||||
|
return Err("动作缺少 domain / 服务 / 实体".to_string());
|
||||||
|
}
|
||||||
|
client::call_service(
|
||||||
|
&env.base_url,
|
||||||
|
&env.token,
|
||||||
|
env.insecure,
|
||||||
|
env.kind,
|
||||||
|
&action.domain,
|
||||||
|
&action.service,
|
||||||
|
&action.entity_id,
|
||||||
|
&action.params,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map(|_| ())
|
||||||
|
.map_err(|f| format!("{}:{}", action.entity_id, f.message))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 条件全部 AND(plan §5.4-B)。
|
||||||
|
fn conditions_ok(env: &RuleEnv, rule: &Rule) -> bool {
|
||||||
|
rule.conditions.iter().all(|c| match c.kind.as_str() {
|
||||||
|
"time" => time_ok(c),
|
||||||
|
_ => state_ok(env, c),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn state_ok(env: &RuleEnv, condition: &RuleCondition) -> bool {
|
||||||
|
if condition.entity_id.is_empty() || condition.state.is_empty() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
env.summaries
|
||||||
|
.lock()
|
||||||
|
.ok()
|
||||||
|
.and_then(|g| g.get(&condition.entity_id).map(|e| e.state == condition.state))
|
||||||
|
.unwrap_or(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 时间窗口条件:`weekdays`(1=周一 … 7=周日,空 = 每天)+ `HH:MM` 区间。
|
||||||
|
/// 跨零点(`to < from`)视为跨天窗口,例如 `23:00 – 06:00`。
|
||||||
|
fn time_ok(condition: &RuleCondition) -> bool {
|
||||||
|
if condition.from_time.is_empty() || condition.to_time.is_empty() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
let (Some((fh, fm)), Some((th, tm))) = (
|
||||||
|
parse_hhmm(&condition.from_time),
|
||||||
|
parse_hhmm(&condition.to_time),
|
||||||
|
) else {
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
let now = Local::now();
|
||||||
|
if !condition.weekdays.is_empty() {
|
||||||
|
let weekday = now.weekday().number_from_monday();
|
||||||
|
if !condition.weekdays.contains(&weekday) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let current = now.hour() * 60 + now.minute();
|
||||||
|
let from = fh * 60 + fm;
|
||||||
|
let to = th * 60 + tm;
|
||||||
|
if from <= to {
|
||||||
|
current >= from && current <= to
|
||||||
|
} else {
|
||||||
|
current >= from || current <= to
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_hhmm(text: &str) -> Option<(u32, u32)> {
|
||||||
|
let (h, m) = text.trim().split_once(':')?;
|
||||||
|
let hour: u32 = h.trim().parse().ok()?;
|
||||||
|
let minute: u32 = m.trim().parse().ok()?;
|
||||||
|
if hour > 23 || minute > 59 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Some((hour, minute))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 突发护栏:同规则在窗口内的触发次数上限。
|
||||||
|
///
|
||||||
|
/// 顺带把过期记录从队首清掉(队列按时间推进,天然有序)。
|
||||||
|
fn burst_allow(env: &RuleEnv, rule_id: &str) -> bool {
|
||||||
|
let Ok(mut g) = env.recent.lock() else {
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
let cutoff = Instant::now() - BURST_WINDOW;
|
||||||
|
while g.front().map(|(_, at)| *at < cutoff).unwrap_or(false) {
|
||||||
|
g.pop_front();
|
||||||
|
}
|
||||||
|
if g.iter().filter(|(id, _)| id == rule_id).count() >= BURST_MAX {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
g.push_back((rule_id.to_string(), Instant::now()));
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 记一条运行记录(内存环形)+ 推事件给前端。
|
||||||
|
fn push_record(env: &RuleEnv, record: RuleRecord) {
|
||||||
|
if let Ok(mut g) = env.records.lock() {
|
||||||
|
g.push_front(record.clone());
|
||||||
|
while g.len() > MAX_RECORDS {
|
||||||
|
g.pop_back();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let _ = env.app.emit(
|
||||||
|
events::SMARTHOME_RULE_FIRED,
|
||||||
|
RuleFiredEvent {
|
||||||
|
rule_id: record.rule_id,
|
||||||
|
rule_name: record.rule_name,
|
||||||
|
at: record.at,
|
||||||
|
ok: record.ok,
|
||||||
|
detail: record.detail,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,735 @@
|
|||||||
|
//! Home Assistant HTTP 客户端与**端点选择**。
|
||||||
|
//!
|
||||||
|
//! P0 只用到两件事:探测(`GET /api/` + `GET /api/config`)与端点选择
|
||||||
|
//! (`auto` / `local` / `remote` 三档)。设备数据与控制命令在 P1/P2 才接上来,
|
||||||
|
//! 但它们**必须复用这里的 `resolve_endpoint`**,否则在外面的每次请求都会先等
|
||||||
|
//! 局域网超时。
|
||||||
|
//!
|
||||||
|
//! 超时策略见 `SMART_HOME_MODULE_PLAN.md` §3.7:局域网探测必须短(在外会必然耗满),
|
||||||
|
//! 反代探测可以宽松(Cloudflare Tunnel 的 RTT 常在 100–400ms)。
|
||||||
|
|
||||||
|
use std::time::Instant;
|
||||||
|
|
||||||
|
use serde::Deserialize;
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
use crate::smarthome::types::{
|
||||||
|
EndpointKind, EndpointMode, EndpointProbe, EntitySummary, HaConnection, ServiceParams,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// 局域网探测超时(**必须短**)。
|
||||||
|
///
|
||||||
|
/// 在家里局域网必然 <10ms 命中;在外面,这个地址会因为 ARP / 路由不可达而
|
||||||
|
/// **必然耗满超时**。它直接决定"出门后每次冷探测有多卡"。
|
||||||
|
pub const LOCAL_PROBE_TIMEOUT_MS: u64 = 900;
|
||||||
|
/// 反代探测超时(Cloudflare Tunnel 首包可能较慢,给足余量)。
|
||||||
|
pub const REMOTE_PROBE_TIMEOUT_MS: u64 = 5000;
|
||||||
|
/// 强制模式(`local` / `remote`)下的超时:此时失败就是"真的连不上",
|
||||||
|
/// 不该因为 900ms 这种"用于探测缺失"的短超时把可用链路判死。
|
||||||
|
pub const FORCED_PROBE_TIMEOUT_MS: u64 = 5000;
|
||||||
|
/// 「测试连接」在单个地址上的总超时(要跑两个请求,给比探测更宽的预算)。
|
||||||
|
pub const TEST_LOCAL_TIMEOUT_MS: u64 = 8000;
|
||||||
|
pub const TEST_REMOTE_TIMEOUT_MS: u64 = 20000;
|
||||||
|
|
||||||
|
/// 普通数据请求的超时:局域网 8s / 反代 30s。
|
||||||
|
///
|
||||||
|
/// 反代上 `/api/states` 是几百 KB(gzip 后几十 KB),这里给的是"能成功但慢"的余量,
|
||||||
|
/// 不是"期望 30s" —— 实际体验主要由 §3.7 的链路选择与 gzip 决定。
|
||||||
|
pub const REQUEST_TIMEOUT_LOCAL_MS: u64 = 8000;
|
||||||
|
pub const REQUEST_TIMEOUT_REMOTE_MS: u64 = 30000;
|
||||||
|
|
||||||
|
/// 按链路取数据请求超时。
|
||||||
|
pub fn request_timeout(kind: EndpointKind) -> u64 {
|
||||||
|
match kind {
|
||||||
|
EndpointKind::Local => REQUEST_TIMEOUT_LOCAL_MS,
|
||||||
|
EndpointKind::Remote => REQUEST_TIMEOUT_REMOTE_MS,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 一次 HTTP 交互失败的分类结果(探测与数据/控制请求共用)。
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct ProbeFailure {
|
||||||
|
/// auth | network | notFound | badRequest | server | other
|
||||||
|
pub kind: &'static str,
|
||||||
|
pub message: String,
|
||||||
|
/// 是否属于"令牌本身无效"。
|
||||||
|
///
|
||||||
|
/// 这类失败**必须立刻放弃换端点重试**:同一个令牌在所有地址上都无效,
|
||||||
|
/// 继续试反代只会让用户多等一个超时,并把真正的原因(令牌失效)淹没在
|
||||||
|
/// "都无法连接"里。
|
||||||
|
pub fatal_auth: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ProbeFailure {
|
||||||
|
fn auth(message: impl Into<String>) -> Self {
|
||||||
|
Self {
|
||||||
|
kind: "auth",
|
||||||
|
message: message.into(),
|
||||||
|
fatal_auth: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn network(message: impl Into<String>) -> Self {
|
||||||
|
Self {
|
||||||
|
kind: "network",
|
||||||
|
message: message.into(),
|
||||||
|
fatal_auth: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn server(message: impl Into<String>) -> Self {
|
||||||
|
Self {
|
||||||
|
kind: "server",
|
||||||
|
message: message.into(),
|
||||||
|
fatal_auth: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// 实体 / 服务不存在(设备被移除、集成重载)
|
||||||
|
fn not_found(message: impl Into<String>) -> Self {
|
||||||
|
Self {
|
||||||
|
kind: "notFound",
|
||||||
|
message: message.into(),
|
||||||
|
fatal_auth: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// 参数不被该服务接受(如给不支持色温的灯传 `color_temp_kelvin`)
|
||||||
|
fn bad_request(message: impl Into<String>) -> Self {
|
||||||
|
Self {
|
||||||
|
kind: "badRequest",
|
||||||
|
message: message.into(),
|
||||||
|
fatal_auth: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 端点选择结果。
|
||||||
|
pub struct ResolvedEndpoint {
|
||||||
|
pub url: String,
|
||||||
|
pub kind: EndpointKind,
|
||||||
|
pub latency_ms: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 端点选择失败:带分类,前端据此决定是"重填令牌"还是"重试/切换地址"(§3.6)。
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct ResolveFailure {
|
||||||
|
/// auth | network | config
|
||||||
|
pub kind: &'static str,
|
||||||
|
pub message: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ResolveFailure {
|
||||||
|
fn new(kind: &'static str, message: impl Into<String>) -> Self {
|
||||||
|
Self {
|
||||||
|
kind,
|
||||||
|
message: message.into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 地址规范化:补协议(局域网默认 `http`、反代默认 `https`)、去掉结尾斜杠。
|
||||||
|
pub fn normalize_url(input: &str, prefer_https: bool) -> String {
|
||||||
|
let mut u = input.trim().to_string();
|
||||||
|
if u.is_empty() {
|
||||||
|
return u;
|
||||||
|
}
|
||||||
|
let lower = u.to_lowercase();
|
||||||
|
if !lower.starts_with("http://") && !lower.starts_with("https://") {
|
||||||
|
u = if prefer_https {
|
||||||
|
format!("https://{u}")
|
||||||
|
} else {
|
||||||
|
format!("http://{u}")
|
||||||
|
};
|
||||||
|
}
|
||||||
|
while u.ends_with('/') {
|
||||||
|
u.pop();
|
||||||
|
}
|
||||||
|
u
|
||||||
|
}
|
||||||
|
|
||||||
|
/// REST 端点 → WebSocket 端点:`http` → `ws`、`https` → `wss`,路径固定 `/api/websocket`。
|
||||||
|
///
|
||||||
|
/// **复用同一份端点选择结果**(plan §3.7-a 最后一条):WS 一旦连上就固定在所选端点,
|
||||||
|
/// 不允许同一屏数据来自两条链路(否则"更新于 x 秒前"的时间戳会来自不同链路)。
|
||||||
|
pub fn ws_url(base: &str) -> Result<String, String> {
|
||||||
|
let mut u = url::Url::parse(base).map_err(|e| format!("HA 地址不合法:{e}"))?;
|
||||||
|
let ok = match u.scheme() {
|
||||||
|
"https" => u.set_scheme("wss").is_ok(),
|
||||||
|
"http" => u.set_scheme("ws").is_ok(),
|
||||||
|
"ws" | "wss" => true,
|
||||||
|
other => return Err(format!("不支持用 {other} 建立 WebSocket 连接")),
|
||||||
|
};
|
||||||
|
if !ok {
|
||||||
|
return Err("无法把该地址转换成 WebSocket 协议".to_string());
|
||||||
|
}
|
||||||
|
u.set_path("/api/websocket");
|
||||||
|
u.set_query(None);
|
||||||
|
Ok(u.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 校验地址合法性(保存时做,**不要在请求时才失败**——那时错误信息已经离用户输入很远了)。
|
||||||
|
pub fn validate_url(url: &str, label: &str) -> Result<(), String> {
|
||||||
|
if url.trim().is_empty() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let parsed = url::Url::parse(url).map_err(|e| format!("{label}不是合法的地址:{e}"))?;
|
||||||
|
if parsed.host_str().unwrap_or("").is_empty() {
|
||||||
|
return Err(format!("{label}缺少主机名"));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn build_client(insecure: bool, timeout_ms: u64) -> Result<reqwest::Client, String> {
|
||||||
|
reqwest::Client::builder()
|
||||||
|
// 自签证书:与飞牛连接同款开关。局域网 IP 的 HA 通常是 http,用不到它;
|
||||||
|
// 反代若用 IP 直连 + 自签证书才需要。
|
||||||
|
.danger_accept_invalid_certs(insecure)
|
||||||
|
.timeout(std::time::Duration::from_millis(timeout_ms))
|
||||||
|
// 压缩交给 reqwest 自动协商(Cargo.toml 已开 `gzip` feature):
|
||||||
|
// 反代链路上 `/api/states` 是几百 KB JSON,不压缩就是白送 5–10 倍流量。
|
||||||
|
.build()
|
||||||
|
.map_err(|e| format!("构建 HTTP 客户端失败:{e}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct ApiRoot {
|
||||||
|
#[serde(default)]
|
||||||
|
message: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct HaConfig {
|
||||||
|
#[serde(default)]
|
||||||
|
version: String,
|
||||||
|
#[serde(default)]
|
||||||
|
location_name: String,
|
||||||
|
#[serde(default)]
|
||||||
|
unit_system: UnitSystem,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// HA 的系统单位制(`/api/config`)。只有温度是本模块需要的 ——
|
||||||
|
/// climate 的 `temperature` / `min_temp` / `max_temp` 都按它给值。
|
||||||
|
#[derive(Deserialize, Default)]
|
||||||
|
struct UnitSystem {
|
||||||
|
#[serde(default)]
|
||||||
|
temperature: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn describe_request_error(e: &reqwest::Error) -> String {
|
||||||
|
if e.is_timeout() {
|
||||||
|
"连接超时".to_string()
|
||||||
|
} else if e.is_connect() {
|
||||||
|
"无法建立连接".to_string()
|
||||||
|
} else {
|
||||||
|
format!("请求失败:{e}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 轻量可达性检查:`GET /api/`(地址可达 + 令牌有效 + **确实是 HA 的 API**)。
|
||||||
|
/// 返回耗时(毫秒)。
|
||||||
|
///
|
||||||
|
/// 为什么要校验响应体而不仅是状态码:反代前面若挂了访问网关(如 Cloudflare Access),
|
||||||
|
/// 未携带 Service Token 时会被重定向到一个 **200 的 HTML 登录页** —— 只看状态码会把它
|
||||||
|
/// 判成"链路正常",随后的真实请求才会莫名其妙地失败(§2.2-6)。
|
||||||
|
async fn check_reachable(
|
||||||
|
base: &str,
|
||||||
|
token: &str,
|
||||||
|
insecure: bool,
|
||||||
|
timeout_ms: u64,
|
||||||
|
) -> Result<u64, ProbeFailure> {
|
||||||
|
let client = build_client(insecure, timeout_ms).map_err(ProbeFailure::network)?;
|
||||||
|
let started = Instant::now();
|
||||||
|
let resp = client
|
||||||
|
.get(format!("{base}/api/"))
|
||||||
|
.bearer_auth(token)
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|e| ProbeFailure::network(describe_request_error(&e)))?;
|
||||||
|
|
||||||
|
let status = resp.status();
|
||||||
|
if status.as_u16() == 401 || status.as_u16() == 403 {
|
||||||
|
return Err(ProbeFailure::auth("访问令牌无效或已被吊销"));
|
||||||
|
}
|
||||||
|
if !status.is_success() {
|
||||||
|
return Err(ProbeFailure::server(format!("HTTP {}", status.as_u16())));
|
||||||
|
}
|
||||||
|
let root = resp.json::<ApiRoot>().await.map_err(|_| {
|
||||||
|
ProbeFailure::server("响应不是 Home Assistant 的 API(可能被反向代理或访问网关拦截)")
|
||||||
|
})?;
|
||||||
|
if root.message.is_empty() {
|
||||||
|
return Err(ProbeFailure::server("Home Assistant 返回了空响应"));
|
||||||
|
}
|
||||||
|
Ok(started.elapsed().as_millis() as u64)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 探测单个地址(「测试连接」用):`GET /api/` + `GET /api/config`。
|
||||||
|
///
|
||||||
|
/// 不拉 `/api/states` 统计实体数:那是几百 KB 的响应,在反代链路上会把
|
||||||
|
/// "测试连接"从 1 秒拖到 3 秒以上,而实体列表在 P1 本来就会拉一次。
|
||||||
|
pub async fn probe_url(
|
||||||
|
url: &str,
|
||||||
|
token: &str,
|
||||||
|
insecure: bool,
|
||||||
|
kind: EndpointKind,
|
||||||
|
) -> EndpointProbe {
|
||||||
|
let timeout_ms = match kind {
|
||||||
|
EndpointKind::Local => TEST_LOCAL_TIMEOUT_MS,
|
||||||
|
EndpointKind::Remote => TEST_REMOTE_TIMEOUT_MS,
|
||||||
|
};
|
||||||
|
let mut failure: Option<ProbeFailure> = None;
|
||||||
|
let started = Instant::now();
|
||||||
|
|
||||||
|
let mut ha_version = String::new();
|
||||||
|
let mut location_name = String::new();
|
||||||
|
let mut temperature_unit = String::new();
|
||||||
|
let mut ok = false;
|
||||||
|
|
||||||
|
match check_reachable(url, token, insecure, timeout_ms).await {
|
||||||
|
Ok(_) => match fetch_config(url, token, insecure, timeout_ms).await {
|
||||||
|
Ok(cfg) => {
|
||||||
|
ha_version = cfg.version;
|
||||||
|
location_name = cfg.location_name;
|
||||||
|
temperature_unit = cfg.unit_system.temperature;
|
||||||
|
ok = true;
|
||||||
|
}
|
||||||
|
Err(e) => failure = Some(e),
|
||||||
|
},
|
||||||
|
Err(e) => failure = Some(e),
|
||||||
|
}
|
||||||
|
|
||||||
|
EndpointProbe {
|
||||||
|
url: url.to_string(),
|
||||||
|
kind,
|
||||||
|
ok,
|
||||||
|
ha_version,
|
||||||
|
location_name,
|
||||||
|
temperature_unit,
|
||||||
|
elapsed_ms: started.elapsed().as_millis() as u64,
|
||||||
|
error: failure.as_ref().map(|f| f.message.clone()),
|
||||||
|
error_kind: failure.as_ref().map(|f| f.kind.to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn fetch_config(
|
||||||
|
base: &str,
|
||||||
|
token: &str,
|
||||||
|
insecure: bool,
|
||||||
|
timeout_ms: u64,
|
||||||
|
) -> Result<HaConfig, ProbeFailure> {
|
||||||
|
let client = build_client(insecure, timeout_ms).map_err(ProbeFailure::network)?;
|
||||||
|
let resp = client
|
||||||
|
.get(format!("{base}/api/config"))
|
||||||
|
.bearer_auth(token)
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|e| ProbeFailure::network(describe_request_error(&e)))?;
|
||||||
|
let status = resp.status();
|
||||||
|
if !status.is_success() {
|
||||||
|
if status.as_u16() == 401 || status.as_u16() == 403 {
|
||||||
|
return Err(ProbeFailure::auth("访问令牌无效或已被吊销"));
|
||||||
|
}
|
||||||
|
return Err(ProbeFailure::server(format!("HTTP {}", status.as_u16())));
|
||||||
|
}
|
||||||
|
resp.json::<HaConfig>()
|
||||||
|
.await
|
||||||
|
.map_err(|e| ProbeFailure::server(format!("响应解析失败:{e}")))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 逐个地址探测(顺序:局域网 → 反代),供「测试连接」使用。
|
||||||
|
pub async fn probe_all(
|
||||||
|
local_url: &str,
|
||||||
|
remote_url: &str,
|
||||||
|
token: &str,
|
||||||
|
insecure: bool,
|
||||||
|
) -> Vec<EndpointProbe> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
if !local_url.trim().is_empty() {
|
||||||
|
out.push(probe_url(local_url.trim(), token, insecure, EndpointKind::Local).await);
|
||||||
|
}
|
||||||
|
if !remote_url.trim().is_empty() {
|
||||||
|
out.push(probe_url(remote_url.trim(), token, insecure, EndpointKind::Remote).await);
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 候选端点列表:(地址, 类型, 探测超时),按尝试顺序排列。
|
||||||
|
fn candidates(conn: &HaConnection) -> Result<Vec<(&str, EndpointKind, u64)>, ResolveFailure> {
|
||||||
|
let local = conn.local_candidate();
|
||||||
|
let remote = conn.remote_candidate();
|
||||||
|
match conn.endpoint_mode {
|
||||||
|
EndpointMode::Local => match local {
|
||||||
|
Some((u, _)) => Ok(vec![(u, EndpointKind::Local, FORCED_PROBE_TIMEOUT_MS)]),
|
||||||
|
None => Err(ResolveFailure::new(
|
||||||
|
"config",
|
||||||
|
"当前连接未配置局域网地址(端点策略为「仅局域网」)",
|
||||||
|
)),
|
||||||
|
},
|
||||||
|
EndpointMode::Remote => match remote {
|
||||||
|
Some((u, _)) => Ok(vec![(u, EndpointKind::Remote, FORCED_PROBE_TIMEOUT_MS)]),
|
||||||
|
None => Err(ResolveFailure::new(
|
||||||
|
"config",
|
||||||
|
"当前连接未配置反代地址(端点策略为「仅反代」)",
|
||||||
|
)),
|
||||||
|
},
|
||||||
|
EndpointMode::Auto => {
|
||||||
|
let mut v = Vec::new();
|
||||||
|
// 局域网优先:回家时能自动切回,代价是出门后每轮冷探测多花 900ms
|
||||||
|
// (见 types::EndpointMode 的注释,这里刻意**不**把 lastOkUrl 排在最前)。
|
||||||
|
if let Some((u, k)) = local {
|
||||||
|
v.push((u, k, LOCAL_PROBE_TIMEOUT_MS));
|
||||||
|
}
|
||||||
|
if let Some((u, k)) = remote {
|
||||||
|
v.push((u, k, REMOTE_PROBE_TIMEOUT_MS));
|
||||||
|
}
|
||||||
|
if v.is_empty() {
|
||||||
|
return Err(ResolveFailure::new("config", "该连接没有配置任何地址"));
|
||||||
|
}
|
||||||
|
Ok(v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 按 `endpoint_mode` 顺序探测,返回第一个可用端点。
|
||||||
|
///
|
||||||
|
/// 失败时的错误信息**包含每个地址的尝试结果** —— 用户需要知道"是局域网不可达、
|
||||||
|
/// 还是反代也挂了",一个笼统的"连接失败"无法排障。
|
||||||
|
pub async fn resolve_endpoint(
|
||||||
|
conn: &HaConnection,
|
||||||
|
token: &str,
|
||||||
|
) -> Result<ResolvedEndpoint, ResolveFailure> {
|
||||||
|
let list = candidates(conn)?;
|
||||||
|
let mut failures: Vec<String> = Vec::new();
|
||||||
|
|
||||||
|
for (url, kind, timeout_ms) in list {
|
||||||
|
match check_reachable(url, token, conn.insecure, timeout_ms).await {
|
||||||
|
Ok(latency_ms) => {
|
||||||
|
return Ok(ResolvedEndpoint {
|
||||||
|
url: url.to_string(),
|
||||||
|
kind,
|
||||||
|
latency_ms,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Err(f) => {
|
||||||
|
// 令牌无效:换任何地址都是同一个结果,立即停止
|
||||||
|
if f.fatal_auth {
|
||||||
|
return Err(ResolveFailure::new("auth", f.message));
|
||||||
|
}
|
||||||
|
failures.push(format!("{}:{}", kind_label(kind), f.message));
|
||||||
|
crate::logger::log_warn(
|
||||||
|
"smarthome",
|
||||||
|
&format!("端点探测失败({} {}):{}", kind_label(kind), url, f.message),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Err(ResolveFailure::new(
|
||||||
|
"network",
|
||||||
|
format!("所有地址均不可达 —— {}", failures.join(";")),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn kind_label(kind: EndpointKind) -> &'static str {
|
||||||
|
match kind {
|
||||||
|
EndpointKind::Local => "局域网",
|
||||||
|
EndpointKind::Remote => "反代",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 取 HA 元信息(版本 / 实例名 / 温度单位)。
|
||||||
|
///
|
||||||
|
/// 「检测链路」与"首次拉实体时还不知道实例信息"两个场景会用到它 ——
|
||||||
|
/// 只是一个很小的 `/api/config` 请求,因此不塞进每次数据拉取里。
|
||||||
|
pub async fn fetch_meta(
|
||||||
|
base: &str,
|
||||||
|
token: &str,
|
||||||
|
insecure: bool,
|
||||||
|
kind: EndpointKind,
|
||||||
|
) -> Result<(String, String, String), ProbeFailure> {
|
||||||
|
let cfg = fetch_config(base, token, insecure, request_timeout(kind)).await?;
|
||||||
|
Ok((cfg.version, cfg.location_name, cfg.unit_system.temperature))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============ 实体状态(P1) ============
|
||||||
|
|
||||||
|
/// HA 的原始状态对象(`/api/states` 的元素,也是 WS 里 `subscribe_entities` 的形态)。
|
||||||
|
///
|
||||||
|
/// P4 起 `ws.rs` 也要用:WS 的增量是**差量更新**,必须先把 attributes 合并回一份
|
||||||
|
/// 完整的原始对象,再转 `EntitySummary` —— 所以这里不再是 P1 的私有实现细节。
|
||||||
|
#[derive(Deserialize, Default, Clone)]
|
||||||
|
pub struct RawState {
|
||||||
|
#[serde(default)]
|
||||||
|
pub entity_id: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub state: String,
|
||||||
|
/// **故意不建结构体**:attributes 的字段集合随 domain 差异极大
|
||||||
|
/// (灯 / 窗帘 / 气候 / 媒体播放器各不相同),按需白名单取用才稳。
|
||||||
|
#[serde(default)]
|
||||||
|
pub attributes: serde_json::Value,
|
||||||
|
#[serde(default)]
|
||||||
|
pub last_changed: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 拉取全量实体状态并转成精简结构。
|
||||||
|
///
|
||||||
|
/// 调用方必须先 `resolve_endpoint` 拿到可用的 `base` 与 `kind` —— 这里不做链路选择。
|
||||||
|
pub async fn fetch_entities(
|
||||||
|
base: &str,
|
||||||
|
token: &str,
|
||||||
|
insecure: bool,
|
||||||
|
kind: EndpointKind,
|
||||||
|
) -> Result<Vec<EntitySummary>, ProbeFailure> {
|
||||||
|
let client = build_client(insecure, request_timeout(kind)).map_err(ProbeFailure::network)?;
|
||||||
|
let resp = client
|
||||||
|
.get(format!("{base}/api/states"))
|
||||||
|
.bearer_auth(token)
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|e| ProbeFailure::network(describe_request_error(&e)))?;
|
||||||
|
|
||||||
|
let status = resp.status();
|
||||||
|
if status.as_u16() == 401 || status.as_u16() == 403 {
|
||||||
|
return Err(ProbeFailure::auth("访问令牌无效或已被吊销"));
|
||||||
|
}
|
||||||
|
if !status.is_success() {
|
||||||
|
return Err(ProbeFailure::server(format!("HTTP {}", status.as_u16())));
|
||||||
|
}
|
||||||
|
let raw = resp
|
||||||
|
.json::<Vec<RawState>>()
|
||||||
|
.await
|
||||||
|
.map_err(|e| ProbeFailure::server(format!("状态响应解析失败:{e}")))?;
|
||||||
|
Ok(raw.into_iter().map(to_summary).collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn attr_str(attrs: &serde_json::Value, key: &str) -> String {
|
||||||
|
attrs
|
||||||
|
.get(key)
|
||||||
|
.and_then(|v| v.as_str())
|
||||||
|
.unwrap_or_default()
|
||||||
|
.to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn attr_f64(attrs: &serde_json::Value, key: &str) -> Option<f64> {
|
||||||
|
attrs.get(key).and_then(|v| v.as_f64())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 0–255 的整数属性(亮度)。上界夹紧,避免异常集成给出超范围值反倒转换失败。
|
||||||
|
fn attr_u8(attrs: &serde_json::Value, key: &str) -> Option<u8> {
|
||||||
|
attrs
|
||||||
|
.get(key)
|
||||||
|
.and_then(|v| v.as_u64())
|
||||||
|
.map(|n| n.min(255) as u8)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 0–100 的整数属性(窗帘位置 / 风扇档位)。
|
||||||
|
fn attr_pct(attrs: &serde_json::Value, key: &str) -> Option<u8> {
|
||||||
|
attrs
|
||||||
|
.get(key)
|
||||||
|
.and_then(|v| v.as_u64())
|
||||||
|
.map(|n| n.min(100) as u8)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn attr_u32(attrs: &serde_json::Value, key: &str) -> Option<u32> {
|
||||||
|
attrs.get(key).and_then(|v| v.as_u64()).map(|n| n as u32)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 字符串数组属性(`supported_color_modes` / `hvac_modes`)
|
||||||
|
fn attr_str_list(attrs: &serde_json::Value, key: &str) -> Vec<String> {
|
||||||
|
attrs
|
||||||
|
.get(key)
|
||||||
|
.and_then(|v| v.as_array())
|
||||||
|
.map(|a| {
|
||||||
|
a.iter()
|
||||||
|
.filter_map(|x| x.as_str().map(|s| s.to_string()))
|
||||||
|
.collect()
|
||||||
|
})
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// HA 状态对象 → 精简结构。控制类命令(服务响应里带回的变化实体)也复用它,
|
||||||
|
/// P4 的 WS 增量合并后同样走这里。
|
||||||
|
pub fn to_summary(raw: RawState) -> EntitySummary {
|
||||||
|
let attrs = &raw.attributes;
|
||||||
|
let domain = raw
|
||||||
|
.entity_id
|
||||||
|
.split('.')
|
||||||
|
.next()
|
||||||
|
.unwrap_or_default()
|
||||||
|
.to_string();
|
||||||
|
let name = {
|
||||||
|
let n = attr_str(attrs, "friendly_name");
|
||||||
|
if n.is_empty() {
|
||||||
|
raw.entity_id.clone()
|
||||||
|
} else {
|
||||||
|
n
|
||||||
|
}
|
||||||
|
};
|
||||||
|
// sensor 的读数在 state 里(字符串形式的数字):能解析就顺手给前端一个数值
|
||||||
|
let numeric = raw.state.parse::<f64>().ok();
|
||||||
|
EntitySummary {
|
||||||
|
entity_id: raw.entity_id,
|
||||||
|
domain,
|
||||||
|
name,
|
||||||
|
state: raw.state,
|
||||||
|
numeric,
|
||||||
|
unit: attr_str(attrs, "unit_of_measurement"),
|
||||||
|
device_class: attr_str(attrs, "device_class"),
|
||||||
|
brightness: attr_u8(attrs, "brightness"),
|
||||||
|
// 窗帘:HA 官方集成给 `current_position`,个别集成给 `position`,两个都认
|
||||||
|
position: attr_pct(attrs, "current_position").or_else(|| attr_pct(attrs, "position")),
|
||||||
|
target_temp: attr_f64(attrs, "temperature"),
|
||||||
|
min_temp: attr_f64(attrs, "min_temp"),
|
||||||
|
max_temp: attr_f64(attrs, "max_temp"),
|
||||||
|
current_temp: attr_f64(attrs, "current_temperature"),
|
||||||
|
last_changed: raw.last_changed,
|
||||||
|
last_triggered: attr_str(attrs, "last_triggered"),
|
||||||
|
supported_features: attr_u32(attrs, "supported_features").unwrap_or(0),
|
||||||
|
supported_color_modes: attr_str_list(attrs, "supported_color_modes"),
|
||||||
|
min_color_temp_kelvin: attr_u32(attrs, "min_color_temp_kelvin"),
|
||||||
|
max_color_temp_kelvin: attr_u32(attrs, "max_color_temp_kelvin"),
|
||||||
|
color_temp_kelvin: attr_u32(attrs, "color_temp_kelvin"),
|
||||||
|
hvac_modes: attr_str_list(attrs, "hvac_modes"),
|
||||||
|
target_temp_step: attr_f64(attrs, "target_temp_step"),
|
||||||
|
volume_level: attr_f64(attrs, "volume_level"),
|
||||||
|
percentage: attr_pct(attrs, "percentage"),
|
||||||
|
min: attr_f64(attrs, "min"),
|
||||||
|
max: attr_f64(attrs, "max"),
|
||||||
|
step: attr_f64(attrs, "step"),
|
||||||
|
options: attr_str_list(attrs, "options"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============ 设备控制(P2) ============
|
||||||
|
|
||||||
|
/// 调用服务(控制设备)。
|
||||||
|
///
|
||||||
|
/// 返回 HA 在响应体里带回的**已变化实体**新状态(`200` 响应就是这些状态对象,
|
||||||
|
/// 与 `/api/states` 同构)。解析失败时返回空列表而**不是报错**:命令本身已经成功,
|
||||||
|
/// 状态只是"还没反映出来",不该因此告诉用户"控制失败"。
|
||||||
|
pub async fn call_service(
|
||||||
|
base: &str,
|
||||||
|
token: &str,
|
||||||
|
insecure: bool,
|
||||||
|
kind: EndpointKind,
|
||||||
|
domain: &str,
|
||||||
|
service: &str,
|
||||||
|
entity_id: &str,
|
||||||
|
params: &ServiceParams,
|
||||||
|
) -> Result<Vec<EntitySummary>, ProbeFailure> {
|
||||||
|
let client = build_client(insecure, request_timeout(kind)).map_err(ProbeFailure::network)?;
|
||||||
|
|
||||||
|
let mut body = serde_json::Map::new();
|
||||||
|
body.insert(
|
||||||
|
"entity_id".to_string(),
|
||||||
|
serde_json::Value::String(entity_id.to_string()),
|
||||||
|
);
|
||||||
|
// 只带真正有值的参数:HA 各服务对 `null` 的处理并不统一
|
||||||
|
if let Some(v) = params.brightness_pct {
|
||||||
|
body.insert("brightness_pct".into(), json!(v));
|
||||||
|
}
|
||||||
|
if let Some(v) = params.color_temp_kelvin {
|
||||||
|
body.insert("color_temp_kelvin".into(), json!(v));
|
||||||
|
}
|
||||||
|
if let Some(v) = params.position {
|
||||||
|
body.insert("position".into(), json!(v));
|
||||||
|
}
|
||||||
|
if let Some(v) = params.temperature {
|
||||||
|
body.insert("temperature".into(), json!(v));
|
||||||
|
}
|
||||||
|
if let Some(v) = ¶ms.hvac_mode {
|
||||||
|
body.insert("hvac_mode".into(), json!(v));
|
||||||
|
}
|
||||||
|
if let Some(v) = params.percentage {
|
||||||
|
body.insert("percentage".into(), json!(v));
|
||||||
|
}
|
||||||
|
if let Some(v) = params.volume_level {
|
||||||
|
body.insert("volume_level".into(), json!(v));
|
||||||
|
}
|
||||||
|
if let Some(v) = params.value {
|
||||||
|
body.insert("value".into(), json!(v));
|
||||||
|
}
|
||||||
|
if let Some(v) = ¶ms.option {
|
||||||
|
body.insert("option".into(), json!(v));
|
||||||
|
}
|
||||||
|
|
||||||
|
let resp = client
|
||||||
|
.post(format!("{base}/api/services/{domain}/{service}"))
|
||||||
|
.bearer_auth(token)
|
||||||
|
.json(&serde_json::Value::Object(body))
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|e| ProbeFailure::network(describe_request_error(&e)))?;
|
||||||
|
|
||||||
|
let status = resp.status();
|
||||||
|
if status.as_u16() == 401 || status.as_u16() == 403 {
|
||||||
|
return Err(ProbeFailure::auth("访问令牌无效或已被吊销"));
|
||||||
|
}
|
||||||
|
if status.as_u16() == 404 {
|
||||||
|
return Err(ProbeFailure::not_found("实体或服务不存在(设备可能已被移除)"));
|
||||||
|
}
|
||||||
|
if status.as_u16() == 400 {
|
||||||
|
// HA 对参数不支持会返回可读的中文/英文 message,原样带给用户最有用
|
||||||
|
let text = resp.text().await.unwrap_or_default();
|
||||||
|
return Err(ProbeFailure::bad_request(extract_message(&text)));
|
||||||
|
}
|
||||||
|
if !status.is_success() {
|
||||||
|
return Err(ProbeFailure::server(format!("HTTP {}", status.as_u16())));
|
||||||
|
}
|
||||||
|
Ok(resp
|
||||||
|
.json::<Vec<RawState>>()
|
||||||
|
.await
|
||||||
|
.unwrap_or_default()
|
||||||
|
.into_iter()
|
||||||
|
.map(to_summary)
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 取单个实体状态(控制后的校正用)。
|
||||||
|
///
|
||||||
|
/// 只在校正窗口到期时才调用 —— 它不是常规路径,所以单独一个命令而不是重拉全量。
|
||||||
|
pub async fn fetch_entity(
|
||||||
|
base: &str,
|
||||||
|
token: &str,
|
||||||
|
insecure: bool,
|
||||||
|
kind: EndpointKind,
|
||||||
|
entity_id: &str,
|
||||||
|
) -> Result<EntitySummary, ProbeFailure> {
|
||||||
|
let client = build_client(insecure, request_timeout(kind)).map_err(ProbeFailure::network)?;
|
||||||
|
let resp = client
|
||||||
|
.get(format!("{base}/api/states/{entity_id}"))
|
||||||
|
.bearer_auth(token)
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|e| ProbeFailure::network(describe_request_error(&e)))?;
|
||||||
|
|
||||||
|
let status = resp.status();
|
||||||
|
if status.as_u16() == 401 || status.as_u16() == 403 {
|
||||||
|
return Err(ProbeFailure::auth("访问令牌无效或已被吊销"));
|
||||||
|
}
|
||||||
|
if status.as_u16() == 404 {
|
||||||
|
return Err(ProbeFailure::not_found("该实体已不存在"));
|
||||||
|
}
|
||||||
|
if !status.is_success() {
|
||||||
|
return Err(ProbeFailure::server(format!("HTTP {}", status.as_u16())));
|
||||||
|
}
|
||||||
|
let raw = resp
|
||||||
|
.json::<RawState>()
|
||||||
|
.await
|
||||||
|
.map_err(|e| ProbeFailure::server(format!("实体响应解析失败:{e}")))?;
|
||||||
|
Ok(to_summary(raw))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 从 HA 的错误响应里抠出可读的 `message`(响应不是 JSON 时退化为原文截断)。
|
||||||
|
fn extract_message(text: &str) -> String {
|
||||||
|
let parsed = serde_json::from_str::<serde_json::Value>(text)
|
||||||
|
.ok()
|
||||||
|
.and_then(|v| v.get("message").and_then(|m| m.as_str()).map(|s| s.to_string()));
|
||||||
|
match parsed {
|
||||||
|
Some(m) if !m.is_empty() => m,
|
||||||
|
_ => {
|
||||||
|
let short: String = text.chars().take(200).collect();
|
||||||
|
if short.is_empty() {
|
||||||
|
"该服务不接受这些参数".to_string()
|
||||||
|
} else {
|
||||||
|
short
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,734 @@
|
|||||||
|
//! 智能家居模块的 Tauri 命令。
|
||||||
|
//!
|
||||||
|
//! 约定(同项目其它模块):命令名以模块前缀开头,错误用 `Result<_, String>`;
|
||||||
|
//! **没有任何命令会向前端返回明文令牌** —— 只有 `tokenMasked` 与 `hasToken`。
|
||||||
|
|
||||||
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
|
use tauri::{AppHandle, State};
|
||||||
|
|
||||||
|
use super::client;
|
||||||
|
use super::types::{
|
||||||
|
EndpointMode, EndpointProbe, EntityListResult, EntitySummary, HaApiError, HaConnection,
|
||||||
|
HaConnectionInput, HaSaveConnectionResult, HaSettingsView, HaUiSettings, LinkInfo,
|
||||||
|
RegistryResult, Rule, RuleListResult, RulesFile, ServiceCallResult, ServiceParams, WsStatus,
|
||||||
|
};
|
||||||
|
use super::{automation, registry, HaManager, InstanceMeta};
|
||||||
|
|
||||||
|
/// 读取模块设置视图(连接列表 + 偏好;令牌只有掩码)。
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub fn smarthome_get_settings(state: State<'_, HaManager>) -> Result<HaSettingsView, String> {
|
||||||
|
Ok(state.settings_view())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 新建或更新一条连接(令牌**不在**此命令里,见 `smarthome_set_token`)。
|
||||||
|
///
|
||||||
|
/// 地址可能刚被改动,已建立的实时连接仍粘在旧端点上 → 重连一次(P4)。
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub async fn smarthome_save_connection(
|
||||||
|
app: AppHandle,
|
||||||
|
state: State<'_, HaManager>,
|
||||||
|
input: HaConnectionInput,
|
||||||
|
) -> Result<HaSaveConnectionResult, String> {
|
||||||
|
let name = input.name.trim().to_string();
|
||||||
|
if name.is_empty() {
|
||||||
|
return Err("请填写名称".to_string());
|
||||||
|
}
|
||||||
|
// 局域网默认补 http(HA 的默认端口 8123 无 TLS);反代默认补 https
|
||||||
|
let local_url = client::normalize_url(&input.local_url, false);
|
||||||
|
let remote_url = client::normalize_url(&input.remote_url, true);
|
||||||
|
if local_url.is_empty() && remote_url.is_empty() {
|
||||||
|
return Err("请至少填写一个地址(局域网或反代)".to_string());
|
||||||
|
}
|
||||||
|
// 保存时就校验地址:等到请求时才失败,错误信息已经离用户输入很远了
|
||||||
|
client::validate_url(&local_url, "局域网地址")?;
|
||||||
|
client::validate_url(&remote_url, "反代地址")?;
|
||||||
|
|
||||||
|
let mut settings = state.load_settings();
|
||||||
|
let mut conn = HaConnection {
|
||||||
|
id: input.id.trim().to_string(),
|
||||||
|
name,
|
||||||
|
local_url,
|
||||||
|
remote_url,
|
||||||
|
endpoint_mode: input.endpoint_mode,
|
||||||
|
insecure: input.insecure,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
// 只配了一个地址时把策略收敛到对应模式:不必让用户理解 auto 的含义
|
||||||
|
if conn.endpoint_mode == EndpointMode::Auto {
|
||||||
|
match (conn.local_url.is_empty(), conn.remote_url.is_empty()) {
|
||||||
|
(true, false) => conn.endpoint_mode = EndpointMode::Remote,
|
||||||
|
(false, true) => conn.endpoint_mode = EndpointMode::Local,
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 强制模式与地址必须自洽:否则要到"检测链路"时才报"未配置该地址",错误离用户输入太远
|
||||||
|
if conn.endpoint_mode == EndpointMode::Local && conn.local_url.is_empty() {
|
||||||
|
return Err("端点策略选了「仅局域网」,但没填局域网地址".to_string());
|
||||||
|
}
|
||||||
|
if conn.endpoint_mode == EndpointMode::Remote && conn.remote_url.is_empty() {
|
||||||
|
return Err("端点策略选了「仅反代」,但没填反代地址".to_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
if conn.id.is_empty() {
|
||||||
|
conn.id = new_conn_id();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 运行期信息(上次成功 / HA 版本 / 实例名)不随编辑清空
|
||||||
|
if let Some(existing) = settings.connection(&conn.id) {
|
||||||
|
conn.last_ok_url = existing.last_ok_url.clone();
|
||||||
|
conn.last_ok_at = existing.last_ok_at;
|
||||||
|
conn.ha_version = existing.ha_version.clone();
|
||||||
|
conn.location_name = existing.location_name.clone();
|
||||||
|
}
|
||||||
|
|
||||||
|
let id = conn.id.clone();
|
||||||
|
let is_new = !settings.connections.iter().any(|c| c.id == id);
|
||||||
|
match settings.connections.iter_mut().find(|c| c.id == id) {
|
||||||
|
Some(slot) => *slot = conn,
|
||||||
|
None => settings.connections.push(conn),
|
||||||
|
}
|
||||||
|
if settings.active_id.is_empty() {
|
||||||
|
settings.active_id = id.clone();
|
||||||
|
}
|
||||||
|
// 首次保存连接时**默认打开实时连接**:按设备 / 按房间浏览、状态实时更新、
|
||||||
|
// 本地规则触发都依赖 WebSocket,默认关闭会让第一次打开模块的人看到一个
|
||||||
|
// "什么都点不了"的设备页。用户仍可在设置页显式关掉。
|
||||||
|
if is_new && !settings.realtime.enabled {
|
||||||
|
settings.realtime.enabled = true;
|
||||||
|
settings.realtime.last_connected_at = chrono::Utc::now().timestamp();
|
||||||
|
}
|
||||||
|
state.save_settings(settings)?;
|
||||||
|
// 地址可能刚被改动:缓存里的端点可能已经不适用了
|
||||||
|
state.clear_endpoint_cache();
|
||||||
|
restart_ws(&app, &state).await;
|
||||||
|
Ok(HaSaveConnectionResult {
|
||||||
|
id,
|
||||||
|
settings: state.settings_view(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 写入长期访问令牌(进系统凭据管理器,**不落 settings.json**)。
|
||||||
|
///
|
||||||
|
/// 令牌换了,已经建立的实时连接用的还是旧令牌 → 重连一次。
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub async fn smarthome_set_token(
|
||||||
|
app: AppHandle,
|
||||||
|
state: State<'_, HaManager>,
|
||||||
|
conn_id: String,
|
||||||
|
token: String,
|
||||||
|
) -> Result<HaSettingsView, String> {
|
||||||
|
if state.load_settings().connection(&conn_id).is_none() {
|
||||||
|
return Err("该连接不存在".to_string());
|
||||||
|
}
|
||||||
|
let t = token.trim();
|
||||||
|
if t.is_empty() {
|
||||||
|
return Err("请填写访问令牌".to_string());
|
||||||
|
}
|
||||||
|
state.set_token(&conn_id, t)?;
|
||||||
|
restart_ws(&app, &state).await;
|
||||||
|
Ok(state.settings_view())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 清除令牌(连接本身保留)。
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub async fn smarthome_clear_token(
|
||||||
|
app: AppHandle,
|
||||||
|
state: State<'_, HaManager>,
|
||||||
|
conn_id: String,
|
||||||
|
) -> Result<HaSettingsView, String> {
|
||||||
|
state.clear_token(&conn_id)?;
|
||||||
|
restart_ws(&app, &state).await;
|
||||||
|
Ok(state.settings_view())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 删除一条连接(连带清除它的令牌)。
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub async fn smarthome_delete_connection(
|
||||||
|
app: AppHandle,
|
||||||
|
state: State<'_, HaManager>,
|
||||||
|
conn_id: String,
|
||||||
|
) -> Result<HaSettingsView, String> {
|
||||||
|
let mut settings = state.load_settings();
|
||||||
|
settings.connections.retain(|c| c.id != conn_id);
|
||||||
|
if settings.active_id == conn_id {
|
||||||
|
settings.active_id = settings
|
||||||
|
.connections
|
||||||
|
.first()
|
||||||
|
.map(|c| c.id.clone())
|
||||||
|
.unwrap_or_default();
|
||||||
|
}
|
||||||
|
state.save_settings(settings)?;
|
||||||
|
// 凭据库里那条令牌也要清掉:连接都删了,留着它是纯粹的残留
|
||||||
|
if let Err(e) = state.clear_token(&conn_id) {
|
||||||
|
crate::logger::log_warn("smarthome", &format!("删除连接时清理令牌失败:{e}"));
|
||||||
|
}
|
||||||
|
state.clear_endpoint_cache();
|
||||||
|
state.clear_entities_cache();
|
||||||
|
state.clear_registry_cache();
|
||||||
|
restart_ws(&app, &state).await;
|
||||||
|
Ok(state.settings_view())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 切换激活连接。
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub async fn smarthome_activate_connection(
|
||||||
|
app: AppHandle,
|
||||||
|
state: State<'_, HaManager>,
|
||||||
|
conn_id: String,
|
||||||
|
) -> Result<HaSettingsView, String> {
|
||||||
|
let mut settings = state.load_settings();
|
||||||
|
if settings.connection(&conn_id).is_none() {
|
||||||
|
return Err("该连接不存在".to_string());
|
||||||
|
}
|
||||||
|
settings.active_id = conn_id;
|
||||||
|
state.save_settings(settings)?;
|
||||||
|
state.clear_endpoint_cache();
|
||||||
|
// 房间 / 实体都属于"上一条连接",切连接必须一并作废
|
||||||
|
state.clear_entities_cache();
|
||||||
|
state.clear_registry_cache();
|
||||||
|
restart_ws(&app, &state).await;
|
||||||
|
Ok(state.settings_view())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 修改端点选择策略(auto / local / remote)。
|
||||||
|
///
|
||||||
|
/// 策略变了,实时连接也应当按新策略重新选端点 → 重连一次。
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub async fn smarthome_set_endpoint_mode(
|
||||||
|
app: AppHandle,
|
||||||
|
state: State<'_, HaManager>,
|
||||||
|
conn_id: String,
|
||||||
|
mode: EndpointMode,
|
||||||
|
) -> Result<HaSettingsView, String> {
|
||||||
|
let mut settings = state.load_settings();
|
||||||
|
let conn = settings
|
||||||
|
.connections
|
||||||
|
.iter_mut()
|
||||||
|
.find(|c| c.id == conn_id)
|
||||||
|
.ok_or_else(|| "该连接不存在".to_string())?;
|
||||||
|
conn.endpoint_mode = mode;
|
||||||
|
state.save_settings(settings)?;
|
||||||
|
state.clear_endpoint_cache();
|
||||||
|
restart_ws(&app, &state).await;
|
||||||
|
Ok(state.settings_view())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 测试连接:**逐个地址**探测,每个地址各给一条结果。
|
||||||
|
///
|
||||||
|
/// `token` 留空时回落到该连接已存的令牌(编辑连接时不必重输)。
|
||||||
|
/// 草案也能直接测(不必先保存)——`input.id` 为空只是没有回落令牌可用。
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub async fn smarthome_test_connection(
|
||||||
|
state: State<'_, HaManager>,
|
||||||
|
input: HaConnectionInput,
|
||||||
|
token: String,
|
||||||
|
) -> Result<Vec<EndpointProbe>, String> {
|
||||||
|
let stored = if input.id.trim().is_empty() {
|
||||||
|
String::new()
|
||||||
|
} else {
|
||||||
|
state.token(input.id.trim())
|
||||||
|
};
|
||||||
|
let token = if token.trim().is_empty() {
|
||||||
|
stored
|
||||||
|
} else {
|
||||||
|
token.trim().to_string()
|
||||||
|
};
|
||||||
|
if token.is_empty() {
|
||||||
|
return Err("请填写访问令牌".to_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
let local_url = client::normalize_url(&input.local_url, false);
|
||||||
|
let remote_url = client::normalize_url(&input.remote_url, true);
|
||||||
|
if local_url.is_empty() && remote_url.is_empty() {
|
||||||
|
return Err("请至少填写一个地址(局域网或反代)".to_string());
|
||||||
|
}
|
||||||
|
client::validate_url(&local_url, "局域网地址")?;
|
||||||
|
client::validate_url(&remote_url, "反代地址")?;
|
||||||
|
|
||||||
|
let probes = client::probe_all(&local_url, &remote_url, &token, input.insecure).await;
|
||||||
|
|
||||||
|
// 测的是已保存的连接,且有一条成功 → 记下"上次成功"(含版本 / 实例名 / 温度单位)
|
||||||
|
let conn_id = input.id.trim();
|
||||||
|
if !conn_id.is_empty() {
|
||||||
|
if let Some(ok) = probes.iter().find(|p| p.ok) {
|
||||||
|
let meta = InstanceMeta {
|
||||||
|
ha_version: ok.ha_version.clone(),
|
||||||
|
location_name: ok.location_name.clone(),
|
||||||
|
temperature_unit: ok.temperature_unit.clone(),
|
||||||
|
};
|
||||||
|
if let Err(e) = state.mark_ok(conn_id, &ok.url, &meta) {
|
||||||
|
crate::logger::log_warn("smarthome", &format!("记录上次成功失败:{e}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(probes)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 检测当前链路:按端点策略**强制新探测**一次,返回实际使用的地址与耗时。
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub async fn smarthome_check_link(
|
||||||
|
state: State<'_, HaManager>,
|
||||||
|
conn_id: String,
|
||||||
|
) -> Result<LinkInfo, String> {
|
||||||
|
let conn = state
|
||||||
|
.load_settings()
|
||||||
|
.connection(&conn_id)
|
||||||
|
.cloned()
|
||||||
|
.ok_or_else(|| "该连接不存在".to_string())?;
|
||||||
|
match state.resolve_fresh(&conn).await {
|
||||||
|
Ok((url, kind, latency_ms)) => {
|
||||||
|
// 顺带取一次实例信息(版本 / 名称 / 温度单位):只有「检测链路」这个显式动作需要它,
|
||||||
|
// 取到就记进设置,设置页与设备页因此不必再单独请求 /api/config。
|
||||||
|
let meta = {
|
||||||
|
let token = state.token(&conn_id);
|
||||||
|
match client::fetch_meta(&url, &token, conn.insecure, kind).await {
|
||||||
|
Ok((version, location, unit)) => InstanceMeta {
|
||||||
|
ha_version: version,
|
||||||
|
location_name: location,
|
||||||
|
temperature_unit: unit,
|
||||||
|
},
|
||||||
|
Err(e) => {
|
||||||
|
crate::logger::log_warn(
|
||||||
|
"smarthome",
|
||||||
|
&format!("读取 HA 实例信息失败(不影响链路判定):{}", e.message),
|
||||||
|
);
|
||||||
|
InstanceMeta::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if let Err(e) = state.mark_ok(&conn_id, &url, &meta) {
|
||||||
|
crate::logger::log_warn("smarthome", &format!("记录上次成功失败:{e}"));
|
||||||
|
}
|
||||||
|
Ok(LinkInfo {
|
||||||
|
url: Some(url),
|
||||||
|
kind: Some(kind),
|
||||||
|
ok: true,
|
||||||
|
latency_ms,
|
||||||
|
error: None,
|
||||||
|
error_kind: None,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
Err(e) => Ok(LinkInfo {
|
||||||
|
url: None,
|
||||||
|
kind: None,
|
||||||
|
ok: false,
|
||||||
|
latency_ms: 0,
|
||||||
|
error: Some(e.message),
|
||||||
|
error_kind: Some(e.kind.to_string()),
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 拉取实体列表(精简视图)。
|
||||||
|
///
|
||||||
|
/// `force = false` 且内存缓存未过期(60s)时直接返回缓存 —— 在反代链路上,
|
||||||
|
/// 每次切回设备页都重新拉几百 KB 是明显的浪费(§5.2)。
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub async fn smarthome_list_entities(
|
||||||
|
state: State<'_, HaManager>,
|
||||||
|
conn_id: String,
|
||||||
|
force: bool,
|
||||||
|
) -> Result<EntityListResult, HaApiError> {
|
||||||
|
let conn = state
|
||||||
|
.load_settings()
|
||||||
|
.connection(&conn_id)
|
||||||
|
.cloned()
|
||||||
|
.ok_or_else(|| HaApiError::new("config", "该连接不存在"))?;
|
||||||
|
|
||||||
|
if !force {
|
||||||
|
if let Some((entities, fetched_at)) = state.cached_entities(&conn_id) {
|
||||||
|
return Ok(EntityListResult {
|
||||||
|
entities,
|
||||||
|
fetched_at,
|
||||||
|
from_cache: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let (url, kind, _latency) = state.resolve(&conn).await.map_err(to_api_error)?;
|
||||||
|
let token = state.token(&conn_id);
|
||||||
|
|
||||||
|
// 首次进入还不知道实例信息?顺带取一次 `/api/config`。
|
||||||
|
// 温度单位必须从实例读(`°F` 的实例上写死 `°C` 会显示成"77°C"),
|
||||||
|
// 而它只在"还不知道"时才需要这一跳;之后 `ha_version` 有了就不再请求。
|
||||||
|
if conn.ha_version.is_empty() {
|
||||||
|
match client::fetch_meta(&url, &token, conn.insecure, kind).await {
|
||||||
|
Ok((version, location, unit)) => {
|
||||||
|
let meta = InstanceMeta {
|
||||||
|
ha_version: version,
|
||||||
|
location_name: location,
|
||||||
|
temperature_unit: unit,
|
||||||
|
};
|
||||||
|
if let Err(e) = state.mark_ok(&conn_id, &url, &meta) {
|
||||||
|
crate::logger::log_warn("smarthome", &format!("记录实例信息失败:{e}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => crate::logger::log_warn(
|
||||||
|
"smarthome",
|
||||||
|
&format!("读取实例信息失败(不影响设备列表):{}", e.message),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
match client::fetch_entities(&url, &token, conn.insecure, kind).await {
|
||||||
|
Ok(entities) => {
|
||||||
|
let fetched_at = chrono::Utc::now().timestamp();
|
||||||
|
state.store_entities(&conn_id, entities.clone());
|
||||||
|
if let Err(e) = state.mark_ok(&conn_id, &url, &InstanceMeta::default()) {
|
||||||
|
crate::logger::log_warn("smarthome", &format!("记录上次成功失败:{e}"));
|
||||||
|
}
|
||||||
|
Ok(EntityListResult {
|
||||||
|
entities,
|
||||||
|
fetched_at,
|
||||||
|
from_cache: false,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
Err(f) => {
|
||||||
|
// 端点可能已经不可用(出门 / 断网 / 隧道挂了):清掉,让下次请求重新探测
|
||||||
|
state.clear_endpoint_cache();
|
||||||
|
if f.fatal_auth {
|
||||||
|
// 令牌失效时旧数据不再可信,留着会让下次把它误当成"还能用"
|
||||||
|
state.clear_entities_cache();
|
||||||
|
}
|
||||||
|
Err(HaApiError::new(f.kind, f.message))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 保存界面偏好(自动刷新间隔 / 收藏等)。
|
||||||
|
///
|
||||||
|
/// 整体覆盖写入:偏好字段少且同屏修改,没必要为每个开关单开一条命令
|
||||||
|
/// (多命令各自的字段同步反倒容易漏)。
|
||||||
|
///
|
||||||
|
/// 注意:**实时推送开关不在 `ui` 里**(它在 `settings.realtime`),
|
||||||
|
/// 因此这里不碰实时连接;收藏 / 自动刷新这类改动不该引起重连。
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub fn smarthome_save_ui_settings(
|
||||||
|
state: State<'_, HaManager>,
|
||||||
|
ui: HaUiSettings,
|
||||||
|
) -> Result<HaSettingsView, String> {
|
||||||
|
let mut settings = state.load_settings();
|
||||||
|
settings.ui = ui;
|
||||||
|
// heal 里会把非法的 autoRefreshSec 收敛回 0
|
||||||
|
state.save_settings(settings)?;
|
||||||
|
Ok(state.settings_view())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 开关实时推送(WebSocket)。
|
||||||
|
///
|
||||||
|
/// 打开 = 建立 WS(设备状态不再依赖手动刷新);关闭 = 断开。
|
||||||
|
/// **本地规则也依赖它**:只要规则总开关开着,关掉推送 Rust 侧仍会保持连接
|
||||||
|
/// (见 `HaManager::sync_ws`)—— 规则没连接永远不会触发。
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub async fn smarthome_set_realtime_enabled(
|
||||||
|
app: AppHandle,
|
||||||
|
state: State<'_, HaManager>,
|
||||||
|
enabled: bool,
|
||||||
|
) -> Result<HaSettingsView, String> {
|
||||||
|
let mut settings = state.load_settings();
|
||||||
|
if settings.realtime.enabled == enabled {
|
||||||
|
return Ok(state.settings_view());
|
||||||
|
}
|
||||||
|
settings.realtime.enabled = enabled;
|
||||||
|
if enabled {
|
||||||
|
settings.realtime.last_connected_at = chrono::Utc::now().timestamp();
|
||||||
|
}
|
||||||
|
state.save_settings(settings)?;
|
||||||
|
// 用 `sync_ws` 而不是 `restart_ws`:关掉推送但本地规则总开关还开着时,
|
||||||
|
// 连接本来就该保留 —— `sync_ws` 会据此保持不动,不会做无谓的重连。
|
||||||
|
state.sync_ws(&app).await;
|
||||||
|
Ok(state.settings_view())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `client::ResolveFailure` → 命令层错误(保留分类)。
|
||||||
|
fn to_api_error(e: client::ResolveFailure) -> HaApiError {
|
||||||
|
HaApiError::new(e.kind, e.message)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 调用设备服务(控制)。
|
||||||
|
///
|
||||||
|
/// 前端流程(§5.3):乐观更新 → 本命令 → **若响应带回新状态就直接采用**(省一次往返),
|
||||||
|
/// 否则在分级窗口后调 `smarthome_get_entity` 校正。
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub async fn smarthome_call_service(
|
||||||
|
state: State<'_, HaManager>,
|
||||||
|
conn_id: String,
|
||||||
|
domain: String,
|
||||||
|
service: String,
|
||||||
|
entity_id: String,
|
||||||
|
params: ServiceParams,
|
||||||
|
) -> Result<ServiceCallResult, HaApiError> {
|
||||||
|
let conn = state
|
||||||
|
.load_settings()
|
||||||
|
.connection(&conn_id)
|
||||||
|
.cloned()
|
||||||
|
.ok_or_else(|| HaApiError::new("config", "该连接不存在"))?;
|
||||||
|
let domain = domain.trim().to_string();
|
||||||
|
let service = service.trim().to_string();
|
||||||
|
let entity_id = entity_id.trim().to_string();
|
||||||
|
if domain.is_empty() || service.is_empty() || entity_id.is_empty() {
|
||||||
|
return Err(HaApiError::new(
|
||||||
|
"badRequest",
|
||||||
|
"domain / service / entity_id 都不能为空",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
let (url, kind, _latency) = state.resolve(&conn).await.map_err(to_api_error)?;
|
||||||
|
let token = state.token(&conn_id);
|
||||||
|
match client::call_service(
|
||||||
|
&url, &token, conn.insecure, kind, &domain, &service, &entity_id, ¶ms,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(entities) => {
|
||||||
|
// 缓存要与 UI 保持一致:带回新状态就并进去,没带回就整份作废
|
||||||
|
// (否则"开灯 → 切页 → 切回来"会看到控制前的旧状态)
|
||||||
|
if entities.is_empty() {
|
||||||
|
state.clear_entities_cache();
|
||||||
|
} else {
|
||||||
|
state.merge_entities(&conn_id, &entities);
|
||||||
|
}
|
||||||
|
if let Err(e) = state.mark_ok(&conn_id, &url, &InstanceMeta::default()) {
|
||||||
|
crate::logger::log_warn("smarthome", &format!("记录上次成功失败:{e}"));
|
||||||
|
}
|
||||||
|
Ok(ServiceCallResult { entities })
|
||||||
|
}
|
||||||
|
Err(f) => {
|
||||||
|
state.clear_endpoint_cache();
|
||||||
|
if f.fatal_auth {
|
||||||
|
state.clear_entities_cache();
|
||||||
|
}
|
||||||
|
Err(HaApiError::new(f.kind, f.message))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 取单个实体状态(控制后的校正用,不是常规路径)。
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub async fn smarthome_get_entity(
|
||||||
|
state: State<'_, HaManager>,
|
||||||
|
conn_id: String,
|
||||||
|
entity_id: String,
|
||||||
|
) -> Result<EntitySummary, HaApiError> {
|
||||||
|
let conn = state
|
||||||
|
.load_settings()
|
||||||
|
.connection(&conn_id)
|
||||||
|
.cloned()
|
||||||
|
.ok_or_else(|| HaApiError::new("config", "该连接不存在"))?;
|
||||||
|
let (url, kind, _latency) = state.resolve(&conn).await.map_err(to_api_error)?;
|
||||||
|
let token = state.token(&conn_id);
|
||||||
|
match client::fetch_entity(&url, &token, conn.insecure, kind, entity_id.trim()).await {
|
||||||
|
Ok(e) => {
|
||||||
|
state.merge_entities(&conn_id, std::slice::from_ref(&e));
|
||||||
|
Ok(e)
|
||||||
|
}
|
||||||
|
Err(f) => {
|
||||||
|
if !f.fatal_auth {
|
||||||
|
state.clear_endpoint_cache();
|
||||||
|
}
|
||||||
|
Err(HaApiError::new(f.kind, f.message))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 新建连接 id(不依赖 uuid crate,同 music 的 `new_conn_id` 做法)。
|
||||||
|
fn new_conn_id() -> String {
|
||||||
|
let n = SystemTime::now()
|
||||||
|
.duration_since(UNIX_EPOCH)
|
||||||
|
.map(|d| d.as_nanos())
|
||||||
|
.unwrap_or(0);
|
||||||
|
format!("h{n:x}")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 新建规则 id。
|
||||||
|
fn new_rule_id() -> String {
|
||||||
|
let n = SystemTime::now()
|
||||||
|
.duration_since(UNIX_EPOCH)
|
||||||
|
.map(|d| d.as_nanos())
|
||||||
|
.unwrap_or(0);
|
||||||
|
format!("r{n:x}")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 端点 / 令牌 / 连接发生变化后:先停当前的实时连接,再按需重连。
|
||||||
|
///
|
||||||
|
/// 必须"先停再起"而不是直接 `sync_ws`:`sync_ws` 对**同一个**连接是幂等的(不动它),
|
||||||
|
/// 而这里恰恰要重连 —— 换了令牌或换了链路却继续粘在旧连接上是最坏的结果
|
||||||
|
/// (UI 显示着新配置,实际走的是老链路)。
|
||||||
|
async fn restart_ws(app: &AppHandle, state: &State<'_, HaManager>) {
|
||||||
|
state.stop_ws();
|
||||||
|
state.sync_ws(app).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 落盘规则文件并更新内存。
|
||||||
|
///
|
||||||
|
/// 同步磁盘 IO 丢到阻塞线程池(编辑器模块的教训:在异步线程里直接读写文件
|
||||||
|
/// 会占住 IPC 线程)。
|
||||||
|
async fn persist_rules(state: &State<'_, HaManager>, file: RulesFile) -> Result<(), String> {
|
||||||
|
let path = state.rules_path();
|
||||||
|
let snapshot = file.clone();
|
||||||
|
tauri::async_runtime::spawn_blocking(move || automation::save(&path, &snapshot))
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("保存规则失败:{e}"))??;
|
||||||
|
state.set_rules_memory(file);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================== P4:实时连接命令 ==============================
|
||||||
|
|
||||||
|
/// 启动实时连接(显式动作)。
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub async fn smarthome_ws_start(
|
||||||
|
app: AppHandle,
|
||||||
|
state: State<'_, HaManager>,
|
||||||
|
conn_id: String,
|
||||||
|
) -> Result<WsStatus, String> {
|
||||||
|
let conn = state
|
||||||
|
.load_settings()
|
||||||
|
.connection(&conn_id)
|
||||||
|
.cloned()
|
||||||
|
.ok_or_else(|| "该连接不存在".to_string())?;
|
||||||
|
state.start_ws(&app, &conn).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 停止实时连接(**不改持久化开关**:设置页的开关走 `smarthome_set_realtime_enabled`)。
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub fn smarthome_ws_stop(state: State<'_, HaManager>) -> WsStatus {
|
||||||
|
state.stop_ws();
|
||||||
|
state.ws_status()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 当前实时连接状态(诊断用)。
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub fn smarthome_ws_status(state: State<'_, HaManager>) -> WsStatus {
|
||||||
|
state.ws_status()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================== P4:注册表(房间分组) ==============================
|
||||||
|
|
||||||
|
/// 拉取区域 / 设备 / 实体注册表,返回 `entity_id → area_id`(三级回退已算好)。
|
||||||
|
///
|
||||||
|
/// **需要实时连接**:注册表只能通过 WebSocket 查(plan §0.4),因此这里显式依赖
|
||||||
|
/// `smarthome_ws_start` 已经连上;没连上就给出可操作的错误文案(不是笼统的"失败")。
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub async fn smarthome_list_registry(
|
||||||
|
state: State<'_, HaManager>,
|
||||||
|
conn_id: String,
|
||||||
|
force: bool,
|
||||||
|
) -> Result<RegistryResult, HaApiError> {
|
||||||
|
if let Some(cached) = state.cached_registry(&conn_id, force) {
|
||||||
|
return Ok(cached);
|
||||||
|
}
|
||||||
|
let Some(handle) = state.ws_handle() else {
|
||||||
|
return Err(HaApiError::new(
|
||||||
|
"ws",
|
||||||
|
"房间分组需要实时连接:请在设置页开启「实时推送」",
|
||||||
|
));
|
||||||
|
};
|
||||||
|
if handle.conn_id != conn_id {
|
||||||
|
return Err(HaApiError::new(
|
||||||
|
"ws",
|
||||||
|
"实时连接属于另一条连接,请先切换回该连接",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let registry = registry::fetch(&handle)
|
||||||
|
.await
|
||||||
|
.map_err(|e| HaApiError::new("ws", e))?;
|
||||||
|
state.store_registry(&conn_id, registry.clone());
|
||||||
|
Ok(registry)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================== P4:本地规则命令 ==============================
|
||||||
|
|
||||||
|
/// 规则列表(含总开关与最近运行记录)。
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub fn smarthome_list_rules(state: State<'_, HaManager>) -> RuleListResult {
|
||||||
|
state.rules_result()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 新建或更新一条规则。
|
||||||
|
///
|
||||||
|
/// **动作的合法性只在 Rust 侧判定一次**(`automation::validate`):前端可以少校验,
|
||||||
|
/// 但"能不能真的执行"这套规则必须只有一份。
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub async fn smarthome_save_rule(
|
||||||
|
app: AppHandle,
|
||||||
|
state: State<'_, HaManager>,
|
||||||
|
rule: Rule,
|
||||||
|
) -> Result<RuleListResult, String> {
|
||||||
|
let mut rule = rule;
|
||||||
|
automation::validate(&rule)?;
|
||||||
|
if rule.id.trim().is_empty() {
|
||||||
|
rule.id = new_rule_id();
|
||||||
|
} else {
|
||||||
|
rule.id = rule.id.trim().to_string();
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut file = state.rules_file();
|
||||||
|
// 编辑既有规则时保留运行统计(前端提交的是"规则定义",统计属于运行期数据)
|
||||||
|
if let Some(existing) = file.rules.iter().find(|r| r.id == rule.id) {
|
||||||
|
rule.last_fired_at = existing.last_fired_at;
|
||||||
|
rule.fire_count = existing.fire_count;
|
||||||
|
rule.last_error = existing.last_error.clone();
|
||||||
|
}
|
||||||
|
match file.rules.iter_mut().find(|r| r.id == rule.id) {
|
||||||
|
Some(slot) => *slot = rule,
|
||||||
|
None => file.rules.push(rule),
|
||||||
|
}
|
||||||
|
persist_rules(&state, file).await?;
|
||||||
|
// 规则总开关开着就需要实时连接(事件驱动),幂等对齐一次
|
||||||
|
state.sync_ws(&app).await;
|
||||||
|
Ok(state.rules_result())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 删除一条规则。
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub async fn smarthome_delete_rule(
|
||||||
|
app: AppHandle,
|
||||||
|
state: State<'_, HaManager>,
|
||||||
|
rule_id: String,
|
||||||
|
) -> Result<RuleListResult, String> {
|
||||||
|
let mut file = state.rules_file();
|
||||||
|
file.rules.retain(|r| r.id != rule_id);
|
||||||
|
persist_rules(&state, file).await?;
|
||||||
|
state.sync_ws(&app).await;
|
||||||
|
Ok(state.rules_result())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 规则总开关(关掉后所有规则都不求值,规则本身保留)。
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub async fn smarthome_set_rules_enabled(
|
||||||
|
app: AppHandle,
|
||||||
|
state: State<'_, HaManager>,
|
||||||
|
enabled: bool,
|
||||||
|
) -> Result<RuleListResult, String> {
|
||||||
|
let mut file = state.rules_file();
|
||||||
|
file.enabled = enabled;
|
||||||
|
persist_rules(&state, file).await?;
|
||||||
|
// 打开总开关意味着"现在就要开始跑规则":它依赖 WS,因此强制对齐(必要时建连)
|
||||||
|
state.sync_ws(&app).await;
|
||||||
|
Ok(state.rules_result())
|
||||||
|
}
|
||||||
@@ -0,0 +1,582 @@
|
|||||||
|
//! 智能家居模块(Home Assistant):状态容器、设置持久化、会话内端点缓存。
|
||||||
|
//!
|
||||||
|
//! 分工:`types` 数据模型(specta 导出)· `client` HTTP 客户端与端点选择 · `commands` Tauri 命令。
|
||||||
|
//!
|
||||||
|
//! 目录布局(`{app_data_dir}/smarthome/`):
|
||||||
|
//! - `settings.json` 模块设置(版本号 + 自愈)
|
||||||
|
//!
|
||||||
|
//! 凭据:长期访问令牌存**系统凭据管理器**,键 `smarthome-token-<connId>`,
|
||||||
|
//! **不落 settings.json**(见 `crate::secrets` 的模块注释)。
|
||||||
|
|
||||||
|
use std::collections::VecDeque;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use tauri::AppHandle;
|
||||||
|
|
||||||
|
use types::{
|
||||||
|
EndpointKind, EntitySummary, HaConnection, HaConnectionView, HaSettings, HaSettingsView,
|
||||||
|
RegistryResult, RuleListResult, RuleRecord, RulesFile, WsStatus, SECRET_PREFIX,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub mod automation;
|
||||||
|
pub mod client;
|
||||||
|
pub mod commands;
|
||||||
|
pub mod registry;
|
||||||
|
pub mod types;
|
||||||
|
pub mod ws;
|
||||||
|
|
||||||
|
// 命令在 lib.rs 里按模块路径导入(`smarthome::smarthome_xxx`),因此在这里 re-export
|
||||||
|
pub use commands::{
|
||||||
|
smarthome_activate_connection, smarthome_call_service, smarthome_check_link,
|
||||||
|
smarthome_clear_token, smarthome_delete_connection, smarthome_delete_rule,
|
||||||
|
smarthome_get_entity, smarthome_get_settings, smarthome_list_entities, smarthome_list_registry,
|
||||||
|
smarthome_list_rules, smarthome_save_connection, smarthome_save_rule,
|
||||||
|
smarthome_save_ui_settings, smarthome_set_endpoint_mode, smarthome_set_realtime_enabled,
|
||||||
|
smarthome_set_rules_enabled, smarthome_set_token, smarthome_test_connection,
|
||||||
|
smarthome_ws_start, smarthome_ws_status, smarthome_ws_stop,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// 会话内端点缓存 TTL。
|
||||||
|
///
|
||||||
|
/// - 缓存在**局域网**上给 60s:短一点,好尽快发现"出门了"(失败也会立即重探)。
|
||||||
|
/// - 缓存在**反代**上给 300s:此时唯一的提升空间是"回家切回局域网",
|
||||||
|
/// 为它每分钟白花 900ms 去探局域网不值得。
|
||||||
|
const CACHE_TTL_LOCAL: Duration = Duration::from_secs(60);
|
||||||
|
const CACHE_TTL_REMOTE: Duration = Duration::from_secs(300);
|
||||||
|
|
||||||
|
/// 会话内端点缓存条目(**不落盘**:它表达的是"这次跑在哪个网络环境",
|
||||||
|
/// 下次启动的网络环境可能完全不同,落盘只会让人先走错一次)。
|
||||||
|
struct CachedEndpoint {
|
||||||
|
conn_id: String,
|
||||||
|
url: String,
|
||||||
|
kind: EndpointKind,
|
||||||
|
latency_ms: u64,
|
||||||
|
at: Instant,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 实体列表内存缓存(**不落盘**)。
|
||||||
|
///
|
||||||
|
/// 理由同 §3.7-c:智能家居里"显示灯已关、实际还亮着"的误导比"多等一秒"糟得多,
|
||||||
|
/// 所以不把可能过期的状态持久化。这里只是省掉"切走再切回设备页就重拉一次全量"
|
||||||
|
/// 的那次请求(在反代链路上那是几百 KB)。
|
||||||
|
struct EntityCache {
|
||||||
|
conn_id: String,
|
||||||
|
entities: Vec<EntitySummary>,
|
||||||
|
fetched_at: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 实体缓存 TTL(秒)—— 约束的是"多久之内不重新拉全量"。
|
||||||
|
const ENTITY_CACHE_TTL_SECS: i64 = 60;
|
||||||
|
|
||||||
|
/// 注册表缓存 TTL(秒)。
|
||||||
|
///
|
||||||
|
/// 房间归属变化极少(用户在 HA 里改名 / 挪设备才会变),给 5 分钟足够;
|
||||||
|
/// 而且每次查注册表在反代上是 3 个来回(约 2s),不该每次进设备页都查一遍。
|
||||||
|
const REGISTRY_CACHE_TTL_SECS: i64 = 300;
|
||||||
|
|
||||||
|
/// 一次成功通信里学到的实例信息(版本 / 实例名 / 温度单位)。
|
||||||
|
///
|
||||||
|
/// 数据请求(拉实体、调服务)只带空的那份 —— 它们不请求 `/api/config`,
|
||||||
|
/// 因此 `mark_ok` 里**空值不覆盖旧值**,免得把已经记住的元信息抹掉。
|
||||||
|
#[derive(Debug, Default, Clone)]
|
||||||
|
pub struct InstanceMeta {
|
||||||
|
pub ha_version: String,
|
||||||
|
pub location_name: String,
|
||||||
|
pub temperature_unit: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 智能家居模块管理器(Tauri State)。
|
||||||
|
pub struct HaManager {
|
||||||
|
/// 模块目录 `{app_data_dir}/smarthome`
|
||||||
|
module_dir: PathBuf,
|
||||||
|
/// 设置(内存为真相;写盘即同步)
|
||||||
|
settings: Mutex<HaSettings>,
|
||||||
|
/// 端点选择缓存
|
||||||
|
endpoint_cache: Mutex<Option<CachedEndpoint>>,
|
||||||
|
/// 实体列表缓存
|
||||||
|
entity_cache: Mutex<Option<EntityCache>>,
|
||||||
|
// ---------- P4 ----------
|
||||||
|
/// 运行中的 WebSocket 连接(生命周期归属应用,Tab 切走不关)
|
||||||
|
ws: Mutex<Option<ws::WsHandle>>,
|
||||||
|
/// 最近一次 WS 启动失败原因(没有运行中的连接时用于诊断)
|
||||||
|
ws_error: Mutex<String>,
|
||||||
|
/// 本地规则(内存为真相;与 WS 任务共享同一份 Arc)
|
||||||
|
rules: Arc<Mutex<RulesFile>>,
|
||||||
|
/// 规则运行记录(内存环形,最多 `automation::MAX_RECORDS` 条)
|
||||||
|
records: Arc<Mutex<VecDeque<RuleRecord>>>,
|
||||||
|
/// 规则突发护栏用的最近触发时刻(与 WS 任务共享)
|
||||||
|
recent: Arc<Mutex<VecDeque<(String, Instant)>>>,
|
||||||
|
/// 注册表缓存(房间分组,不落盘)。**带 connId**:房间归属是每条连接各自的,
|
||||||
|
/// 切了实例还返回上一实例的房间,用户会看到"房间名全对不上、筛选后一片空白"。
|
||||||
|
registry_cache: Mutex<Option<(String, RegistryResult)>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl HaManager {
|
||||||
|
pub fn new(app_data_dir: PathBuf) -> Self {
|
||||||
|
let module_dir = app_data_dir.join("smarthome");
|
||||||
|
if let Err(e) = std::fs::create_dir_all(&module_dir) {
|
||||||
|
crate::logger::log_warn("smarthome", &format!("创建模块目录失败:{e}"));
|
||||||
|
}
|
||||||
|
let mut settings: HaSettings = std::fs::read_to_string(module_dir.join("settings.json"))
|
||||||
|
.ok()
|
||||||
|
.and_then(|t| serde_json::from_str(&t).ok())
|
||||||
|
.unwrap_or_default();
|
||||||
|
if settings.heal() {
|
||||||
|
// 首次启动(version = 0)也走这里:落一份带版本号的默认设置
|
||||||
|
let _ = write_settings_file(&module_dir, &settings);
|
||||||
|
}
|
||||||
|
// 规则文件:**启动阶段不建文件**(还没人用过本地规则时不必产生空文件)
|
||||||
|
let rules = automation::load(&module_dir.join("automations.json"));
|
||||||
|
Self {
|
||||||
|
module_dir,
|
||||||
|
settings: Mutex::new(settings),
|
||||||
|
endpoint_cache: Mutex::new(None),
|
||||||
|
entity_cache: Mutex::new(None),
|
||||||
|
ws: Mutex::new(None),
|
||||||
|
ws_error: Mutex::new(String::new()),
|
||||||
|
rules: Arc::new(Mutex::new(rules)),
|
||||||
|
records: Arc::new(Mutex::new(VecDeque::new())),
|
||||||
|
recent: Arc::new(Mutex::new(VecDeque::new())),
|
||||||
|
registry_cache: Mutex::new(None),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 设置 ----------
|
||||||
|
|
||||||
|
pub fn load_settings(&self) -> HaSettings {
|
||||||
|
match self.settings.lock() {
|
||||||
|
Ok(s) => s.clone(),
|
||||||
|
Err(e) => {
|
||||||
|
crate::logger::log_error("smarthome", &format!("设置锁中毒:{e}"));
|
||||||
|
HaSettings::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn save_settings(&self, mut next: HaSettings) -> Result<(), String> {
|
||||||
|
next.heal();
|
||||||
|
write_settings_file(&self.module_dir, &next)?;
|
||||||
|
if let Ok(mut s) = self.settings.lock() {
|
||||||
|
*s = next;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 令牌(系统凭据管理器) ----------
|
||||||
|
|
||||||
|
fn token_key(conn_id: &str) -> String {
|
||||||
|
format!("{SECRET_PREFIX}{conn_id}")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 读取明文令牌,失败/未配置一律退化为空串(调用方无需区分两者)。
|
||||||
|
pub fn token(&self, conn_id: &str) -> String {
|
||||||
|
crate::secrets::read_or_empty(&Self::token_key(conn_id))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_token(&self, conn_id: &str, token: &str) -> Result<(), String> {
|
||||||
|
crate::secrets::secret_write(&Self::token_key(conn_id), token)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn clear_token(&self, conn_id: &str) -> Result<(), String> {
|
||||||
|
crate::secrets::secret_delete(&Self::token_key(conn_id))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 视图 ----------
|
||||||
|
|
||||||
|
pub fn connection_view(&self, conn: &HaConnection) -> HaConnectionView {
|
||||||
|
let token = self.token(&conn.id);
|
||||||
|
let cached = self.cached_endpoint(&conn.id);
|
||||||
|
HaConnectionView {
|
||||||
|
id: conn.id.clone(),
|
||||||
|
name: conn.name.clone(),
|
||||||
|
local_url: conn.local_url.clone(),
|
||||||
|
remote_url: conn.remote_url.clone(),
|
||||||
|
endpoint_mode: conn.endpoint_mode,
|
||||||
|
insecure: conn.insecure,
|
||||||
|
has_token: !token.is_empty(),
|
||||||
|
token_masked: crate::secrets::mask(&token),
|
||||||
|
last_ok_url: conn.last_ok_url.clone(),
|
||||||
|
last_ok_at: conn.last_ok_at,
|
||||||
|
ha_version: conn.ha_version.clone(),
|
||||||
|
location_name: conn.location_name.clone(),
|
||||||
|
temperature_unit: conn.temperature_unit.clone(),
|
||||||
|
endpoint_url: cached.as_ref().map(|c| c.0.clone()),
|
||||||
|
endpoint_kind: cached.as_ref().map(|c| c.1),
|
||||||
|
endpoint_latency_ms: cached.as_ref().map(|c| c.2),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn settings_view(&self) -> HaSettingsView {
|
||||||
|
let s = self.load_settings();
|
||||||
|
HaSettingsView {
|
||||||
|
version: s.version,
|
||||||
|
active_id: s.active_id.clone(),
|
||||||
|
connections: s
|
||||||
|
.connections
|
||||||
|
.iter()
|
||||||
|
.map(|c| self.connection_view(c))
|
||||||
|
.collect(),
|
||||||
|
ui: s.ui.clone(),
|
||||||
|
realtime: s.realtime.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 端点缓存 ----------
|
||||||
|
|
||||||
|
pub fn cached_endpoint(&self, conn_id: &str) -> Option<(String, EndpointKind, u64)> {
|
||||||
|
let guard = self.endpoint_cache.lock().ok()?;
|
||||||
|
let c = guard.as_ref()?;
|
||||||
|
if c.conn_id != conn_id {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let ttl = if c.kind == EndpointKind::Local {
|
||||||
|
CACHE_TTL_LOCAL
|
||||||
|
} else {
|
||||||
|
CACHE_TTL_REMOTE
|
||||||
|
};
|
||||||
|
if c.at.elapsed() > ttl {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Some((c.url.clone(), c.kind, c.latency_ms))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn store_endpoint(&self, conn_id: &str, url: &str, kind: EndpointKind, latency_ms: u64) {
|
||||||
|
if let Ok(mut c) = self.endpoint_cache.lock() {
|
||||||
|
*c = Some(CachedEndpoint {
|
||||||
|
conn_id: conn_id.to_string(),
|
||||||
|
url: url.to_string(),
|
||||||
|
kind,
|
||||||
|
latency_ms,
|
||||||
|
at: Instant::now(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 失效端点缓存。触发点:地址被改动、请求失败、用户手动重探。
|
||||||
|
pub fn clear_endpoint_cache(&self) {
|
||||||
|
if let Ok(mut c) = self.endpoint_cache.lock() {
|
||||||
|
*c = None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 实体缓存 ----------
|
||||||
|
|
||||||
|
/// 读取**未过期**的实体缓存(过期视为未命中)。
|
||||||
|
pub fn cached_entities(&self, conn_id: &str) -> Option<(Vec<EntitySummary>, i64)> {
|
||||||
|
let guard = self.entity_cache.lock().ok()?;
|
||||||
|
let c = guard.as_ref()?;
|
||||||
|
if c.conn_id != conn_id {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
if chrono::Utc::now().timestamp() - c.fetched_at > ENTITY_CACHE_TTL_SECS {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Some((c.entities.clone(), c.fetched_at))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn store_entities(&self, conn_id: &str, entities: Vec<EntitySummary>) {
|
||||||
|
if let Ok(mut c) = self.entity_cache.lock() {
|
||||||
|
*c = Some(EntityCache {
|
||||||
|
conn_id: conn_id.to_string(),
|
||||||
|
entities,
|
||||||
|
fetched_at: chrono::Utc::now().timestamp(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 清空实体缓存。触发点:令牌失效(旧数据不再可信)、删除连接。
|
||||||
|
pub fn clear_entities_cache(&self) {
|
||||||
|
if let Ok(mut c) = self.entity_cache.lock() {
|
||||||
|
*c = None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 把控制命令带回的新状态并进缓存。
|
||||||
|
///
|
||||||
|
/// 必须做,否则会出现这种误导:开灯 → 切到设置页 → 切回设备页(60s 内命中缓存)
|
||||||
|
/// → 又显示"灯是关的"。响应没带回状态时(部分云端集成)调用方应改为清缓存。
|
||||||
|
pub fn merge_entities(&self, conn_id: &str, changed: &[EntitySummary]) {
|
||||||
|
if changed.is_empty() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let Ok(mut guard) = self.entity_cache.lock() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let Some(cache) = guard.as_mut() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
if cache.conn_id != conn_id {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for e in changed {
|
||||||
|
match cache.entities.iter_mut().find(|x| x.entity_id == e.entity_id) {
|
||||||
|
Some(slot) => *slot = e.clone(),
|
||||||
|
None => cache.entities.push(e.clone()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 解析当前端点(命中会话缓存则不再探测)。
|
||||||
|
///
|
||||||
|
/// 数据请求走这里;**失败时必须调用 `clear_endpoint_cache()`**,
|
||||||
|
/// 否则会一直粘在一个已经不可用的端点上。
|
||||||
|
pub async fn resolve(
|
||||||
|
&self,
|
||||||
|
conn: &HaConnection,
|
||||||
|
) -> Result<(String, EndpointKind, u64), client::ResolveFailure> {
|
||||||
|
if let Some(hit) = self.cached_endpoint(&conn.id) {
|
||||||
|
return Ok(hit);
|
||||||
|
}
|
||||||
|
self.resolve_fresh(conn).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 强制重新探测(「检测链路」按钮、以及缓存未命中时)。
|
||||||
|
pub async fn resolve_fresh(
|
||||||
|
&self,
|
||||||
|
conn: &HaConnection,
|
||||||
|
) -> Result<(String, EndpointKind, u64), client::ResolveFailure> {
|
||||||
|
let token = self.token(&conn.id);
|
||||||
|
if token.is_empty() {
|
||||||
|
return Err(client::ResolveFailure {
|
||||||
|
kind: "auth",
|
||||||
|
message: "尚未配置访问令牌".to_string(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let r = client::resolve_endpoint(conn, &token).await?;
|
||||||
|
self.store_endpoint(&conn.id, &r.url, r.kind, r.latency_ms);
|
||||||
|
Ok((r.url, r.kind, r.latency_ms))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 记录一次成功通信的结果(供设置页展示"上次成功 / HA 版本 / 实例名 / 温度单位")。
|
||||||
|
pub fn mark_ok(
|
||||||
|
&self,
|
||||||
|
conn_id: &str,
|
||||||
|
url: &str,
|
||||||
|
meta: &InstanceMeta,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
let mut s = self.load_settings();
|
||||||
|
let Some(conn) = s.connections.iter_mut().find(|c| c.id == conn_id) else {
|
||||||
|
return Ok(());
|
||||||
|
};
|
||||||
|
conn.last_ok_url = url.to_string();
|
||||||
|
conn.last_ok_at = chrono::Utc::now().timestamp();
|
||||||
|
// 空值不覆盖:数据请求带的是空 meta,不能因此把已记住的版本 / 单位抹掉
|
||||||
|
if !meta.ha_version.is_empty() {
|
||||||
|
conn.ha_version = meta.ha_version.clone();
|
||||||
|
}
|
||||||
|
if !meta.location_name.is_empty() {
|
||||||
|
conn.location_name = meta.location_name.clone();
|
||||||
|
}
|
||||||
|
if !meta.temperature_unit.is_empty() {
|
||||||
|
conn.temperature_unit = meta.temperature_unit.clone();
|
||||||
|
}
|
||||||
|
self.save_settings(s)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 本地规则(P4) ----------
|
||||||
|
|
||||||
|
pub fn rules_path(&self) -> PathBuf {
|
||||||
|
self.module_dir.join("automations.json")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 当前规则文件快照。
|
||||||
|
pub fn rules_file(&self) -> RulesFile {
|
||||||
|
match self.rules.lock() {
|
||||||
|
Ok(g) => g.clone(),
|
||||||
|
Err(e) => {
|
||||||
|
crate::logger::log_error("smarthome", &format!("规则锁中毒:{e}"));
|
||||||
|
RulesFile::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 规则列表视图(含总开关与最近运行记录)。
|
||||||
|
pub fn rules_result(&self) -> RuleListResult {
|
||||||
|
let file = self.rules_file();
|
||||||
|
let records = self
|
||||||
|
.records
|
||||||
|
.lock()
|
||||||
|
.map(|g| g.iter().cloned().collect())
|
||||||
|
.unwrap_or_default();
|
||||||
|
RuleListResult {
|
||||||
|
enabled: file.enabled,
|
||||||
|
rules: file.rules,
|
||||||
|
records,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 更新内存里的规则(写盘由调用方在 `spawn_blocking` 里做)。
|
||||||
|
pub fn set_rules_memory(&self, file: RulesFile) {
|
||||||
|
if let Ok(mut g) = self.rules.lock() {
|
||||||
|
*g = file;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 实时连接(P4) ----------
|
||||||
|
|
||||||
|
pub fn ws_handle(&self) -> Option<ws::WsHandle> {
|
||||||
|
self.ws.lock().ok().and_then(|g| g.as_ref().cloned())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_ws_error(&self, message: &str) {
|
||||||
|
if let Ok(mut g) = self.ws_error.lock() {
|
||||||
|
*g = message.to_string();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 当前实时连接状态(没有运行中的连接时,用最近一次失败原因作诊断信息)。
|
||||||
|
pub fn ws_status(&self) -> WsStatus {
|
||||||
|
if let Some(handle) = self.ws_handle() {
|
||||||
|
return handle.status();
|
||||||
|
}
|
||||||
|
let detail = self.ws_error.lock().map(|g| g.clone()).unwrap_or_default();
|
||||||
|
let conn_id = self.load_settings().active_id;
|
||||||
|
let mut status = WsStatus::new(
|
||||||
|
&conn_id,
|
||||||
|
if detail.is_empty() { "idle" } else { "disconnected" },
|
||||||
|
);
|
||||||
|
status.detail = detail;
|
||||||
|
status
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 停止实时连接(幂等)。
|
||||||
|
pub fn stop_ws(&self) {
|
||||||
|
let taken = self.ws.lock().ok().and_then(|mut g| g.take());
|
||||||
|
if let Some(handle) = taken {
|
||||||
|
handle.stop();
|
||||||
|
}
|
||||||
|
self.set_ws_error("");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 启动实时连接:复用 P0 的端点选择(`resolve`),把所选端点换成 `ws(s)://`。
|
||||||
|
///
|
||||||
|
/// **一旦连上就固定在该端点**(plan §3.7-a):不允许同一屏数据来自两条链路。
|
||||||
|
/// 幂等:同一条连接已经连着 / 正在连时直接返回它的状态,不重复建连。
|
||||||
|
pub async fn start_ws(
|
||||||
|
&self,
|
||||||
|
app: &AppHandle,
|
||||||
|
conn: &HaConnection,
|
||||||
|
) -> Result<WsStatus, String> {
|
||||||
|
if let Some(handle) = self.ws_handle() {
|
||||||
|
if handle.conn_id == conn.id {
|
||||||
|
let status = handle.status();
|
||||||
|
if status.state == "connected" || status.state == "connecting" {
|
||||||
|
return Ok(status);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let result = self.start_ws_fresh(app, conn).await;
|
||||||
|
if let Err(e) = &result {
|
||||||
|
self.set_ws_error(e);
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn start_ws_fresh(
|
||||||
|
&self,
|
||||||
|
app: &AppHandle,
|
||||||
|
conn: &HaConnection,
|
||||||
|
) -> Result<WsStatus, String> {
|
||||||
|
// 已有句柄但连接不可用(断线 / 鉴权失败):先彻底停掉,避免留下第二个任务
|
||||||
|
self.stop_ws();
|
||||||
|
let token = self.token(&conn.id);
|
||||||
|
if token.is_empty() {
|
||||||
|
return Err("尚未配置访问令牌".to_string());
|
||||||
|
}
|
||||||
|
let (url, kind, _latency) = self.resolve(conn).await.map_err(|e| e.message)?;
|
||||||
|
let ws_url = client::ws_url(&url)?;
|
||||||
|
let cfg = ws::WsTaskConfig {
|
||||||
|
conn_id: conn.id.clone(),
|
||||||
|
app: app.clone(),
|
||||||
|
base_url: url,
|
||||||
|
ws_url,
|
||||||
|
token,
|
||||||
|
insecure: conn.insecure,
|
||||||
|
kind,
|
||||||
|
rules: self.rules.clone(),
|
||||||
|
records: self.records.clone(),
|
||||||
|
recent: self.recent.clone(),
|
||||||
|
rules_path: self.rules_path(),
|
||||||
|
};
|
||||||
|
let handle = ws::spawn(cfg);
|
||||||
|
if let Ok(mut g) = self.ws.lock() {
|
||||||
|
*g = Some(handle);
|
||||||
|
}
|
||||||
|
self.set_ws_error("");
|
||||||
|
Ok(self.ws_status())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 按"该不该有实时连接"对齐运行状态(幂等)。
|
||||||
|
///
|
||||||
|
/// 触发条件:**实时推送开关开着**,或**本地规则总开关开着** ——
|
||||||
|
/// 后者是硬依赖:规则靠 WS 事件驱动,没有实时连接它永远不会触发。
|
||||||
|
/// 调用点:启动时、保存界面偏好 / 连接 / 规则之后。
|
||||||
|
pub async fn sync_ws(&self, app: &AppHandle) {
|
||||||
|
let settings = self.load_settings();
|
||||||
|
let want = settings.realtime.enabled || self.rules_file().enabled;
|
||||||
|
let conn = settings.connection(&settings.active_id).cloned();
|
||||||
|
|
||||||
|
if !want {
|
||||||
|
self.stop_ws();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let Some(conn) = conn else {
|
||||||
|
self.stop_ws();
|
||||||
|
self.set_ws_error("没有可用的连接(请先在设置页配置 Home Assistant)");
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
// 已经连着同一个连接:不动它(避免切个设置页就重连一次)。
|
||||||
|
// 但 **authFailed 例外**:那种句柄是"永久放弃重连"的状态(§3.3 要求不刷日志),
|
||||||
|
// 若用户刚补了新令牌,这里必须给它一次重新尝试的机会。
|
||||||
|
if let Some(handle) = self.ws_handle() {
|
||||||
|
if handle.conn_id == conn.id && handle.status().state != "authFailed" {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.stop_ws();
|
||||||
|
if let Err(e) = self.start_ws(app, &conn).await {
|
||||||
|
crate::logger::log_warn("smarthome", &format!("启动实时连接失败:{e}"));
|
||||||
|
self.set_ws_error(&e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 注册表(房间分组,P4) ----------
|
||||||
|
|
||||||
|
/// 命中缓存的前提:**是同一个连接**且未超过 TTL。
|
||||||
|
pub fn cached_registry(&self, conn_id: &str, force: bool) -> Option<RegistryResult> {
|
||||||
|
if force {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let guard = self.registry_cache.lock().ok()?;
|
||||||
|
let (cached_conn, cached) = guard.as_ref()?;
|
||||||
|
if cached_conn != conn_id {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
if chrono::Utc::now().timestamp() - cached.fetched_at > REGISTRY_CACHE_TTL_SECS {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Some(cached.clone())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn store_registry(&self, conn_id: &str, registry: RegistryResult) {
|
||||||
|
if let Ok(mut g) = self.registry_cache.lock() {
|
||||||
|
*g = Some((conn_id.to_string(), registry));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 失效注册表缓存。触发点:切换/删除连接(房间归属跟着连接走)。
|
||||||
|
pub fn clear_registry_cache(&self) {
|
||||||
|
if let Ok(mut g) = self.registry_cache.lock() {
|
||||||
|
*g = None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write_settings_file(module_dir: &Path, settings: &HaSettings) -> Result<(), String> {
|
||||||
|
let json = serde_json::to_string_pretty(settings)
|
||||||
|
.map_err(|e| format!("序列化智能家居设置失败:{e}"))?;
|
||||||
|
std::fs::write(module_dir.join("settings.json"), json)
|
||||||
|
.map_err(|e| format!("写入智能家居设置失败:{e}"))
|
||||||
|
}
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
//! 区域 / 设备 / 实体注册表查询(P4)。
|
||||||
|
//!
|
||||||
|
//! **房间分组的唯一来源**:纯 REST 拿不到 area(plan §0.4),注册表只能走 WebSocket 的
|
||||||
|
//! `config/area_registry/list` 等命令。
|
||||||
|
//!
|
||||||
|
//! **真机修正(§9.5-1)**:目标实例上实体级 `area_id` **全空**(606 条 0 条),
|
||||||
|
//! 房间归属在**设备**上(36 设备 / 27 有 area)。照原计划只读实体的 `area_id`
|
||||||
|
//! 会得到"一间房都没有",因此这里必须做三级回退:
|
||||||
|
//! `entity.area_id` → `device.area_id` → 归入「未分配房间」(前端负责这一档)。
|
||||||
|
//! 这个"未分配"分组是**必需的**而不是兜底:那台实例上 9 个设备确实没有房间。
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
use serde_json::{json, Value};
|
||||||
|
|
||||||
|
use super::types::{EntityRegistryEntry, HaArea, HaDevice, RegistryResult};
|
||||||
|
use super::ws::WsHandle;
|
||||||
|
|
||||||
|
/// 拉取三张注册表并算出 `entity_id → area_id` 映射 + 设备聚合所需的实体注册表。
|
||||||
|
pub async fn fetch(ws: &WsHandle) -> Result<RegistryResult, String> {
|
||||||
|
let timeout = super::ws::request_timeout();
|
||||||
|
let areas = ws
|
||||||
|
.request(json!({ "type": "config/area_registry/list" }), timeout)
|
||||||
|
.await?;
|
||||||
|
let devices = ws
|
||||||
|
.request(json!({ "type": "config/device_registry/list" }), timeout)
|
||||||
|
.await?;
|
||||||
|
let entities = ws
|
||||||
|
.request(json!({ "type": "config/entity_registry/list" }), timeout)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let area_list: Vec<HaArea> = items(&areas)
|
||||||
|
.iter()
|
||||||
|
.map(|a| HaArea {
|
||||||
|
area_id: text(a, "area_id"),
|
||||||
|
name: text(a, "name"),
|
||||||
|
})
|
||||||
|
.filter(|a| !a.area_id.is_empty())
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let device_list: Vec<HaDevice> = items(&devices)
|
||||||
|
.iter()
|
||||||
|
.map(|d| HaDevice {
|
||||||
|
id: text(d, "id"),
|
||||||
|
name: text(d, "name"),
|
||||||
|
name_by_user: text(d, "name_by_user"),
|
||||||
|
area_id: text(d, "area_id"),
|
||||||
|
manufacturer: text(d, "manufacturer"),
|
||||||
|
model: text(d, "model"),
|
||||||
|
})
|
||||||
|
.filter(|d| !d.id.is_empty())
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
// 设备级房间(真机上房间归属实际就在这一层)
|
||||||
|
let device_area: HashMap<&str, &str> = device_list
|
||||||
|
.iter()
|
||||||
|
.filter(|d| !d.area_id.is_empty())
|
||||||
|
.map(|d| (d.id.as_str(), d.area_id.as_str()))
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let mut entity_areas: HashMap<String, String> = HashMap::new();
|
||||||
|
let mut entity_registry: Vec<EntityRegistryEntry> = Vec::new();
|
||||||
|
for e in items(&entities) {
|
||||||
|
let entity_id = text(e, "entity_id");
|
||||||
|
if entity_id.is_empty() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let device_id = text(e, "device_id");
|
||||||
|
let direct = text(e, "area_id");
|
||||||
|
let area = if !direct.is_empty() {
|
||||||
|
direct
|
||||||
|
} else {
|
||||||
|
device_area
|
||||||
|
.get(device_id.as_str())
|
||||||
|
.map(|a| a.to_string())
|
||||||
|
.unwrap_or_default()
|
||||||
|
};
|
||||||
|
// 三级都拿不到 → 不进表;前端把它归入「未分配房间」
|
||||||
|
if !area.is_empty() {
|
||||||
|
entity_areas.insert(entity_id.clone(), area);
|
||||||
|
}
|
||||||
|
entity_registry.push(EntityRegistryEntry {
|
||||||
|
entity_id,
|
||||||
|
device_id,
|
||||||
|
name: text(e, "name"),
|
||||||
|
original_name: text(e, "original_name"),
|
||||||
|
entity_category: text(e, "entity_category"),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(RegistryResult {
|
||||||
|
areas: area_list,
|
||||||
|
devices: device_list,
|
||||||
|
entity_areas,
|
||||||
|
entity_registry,
|
||||||
|
fetched_at: chrono::Utc::now().timestamp(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn items(v: &Value) -> &[Value] {
|
||||||
|
v.as_array().map(|a| a.as_slice()).unwrap_or(&[])
|
||||||
|
}
|
||||||
|
|
||||||
|
fn text(v: &Value, key: &str) -> String {
|
||||||
|
v.get(key)
|
||||||
|
.and_then(|x| x.as_str())
|
||||||
|
.unwrap_or_default()
|
||||||
|
.to_string()
|
||||||
|
}
|
||||||
@@ -0,0 +1,699 @@
|
|||||||
|
//! 智能家居(Home Assistant)模块的数据模型。
|
||||||
|
//!
|
||||||
|
//! 全部走 specta 导出到 `src/lib/bindings.ts`,字段 camelCase。
|
||||||
|
//!
|
||||||
|
//! 持久化:`{app_data_dir}/smarthome/settings.json`(范式同 dsh / editor / terminal)。
|
||||||
|
//! **长期访问令牌不在这里** —— 它只进系统凭据管理器(`crate::secrets`),
|
||||||
|
//! 键名 `smarthome-token-<connId>`;前端拿到的永远是掩码。
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use specta::Type;
|
||||||
|
|
||||||
|
/// 设置结构版本号(自愈用;**只补增量、不清空**,避免误删用户配置)。
|
||||||
|
pub const SETTINGS_VERSION: u32 = 1;
|
||||||
|
|
||||||
|
/// 凭据键前缀:`smarthome-token-<connId>`。
|
||||||
|
pub const SECRET_PREFIX: &str = "smarthome-token-";
|
||||||
|
|
||||||
|
/// 允许的自动刷新间隔(秒),0 = 关闭。远端(反代)链路下强制为 0,见 §3.7-b。
|
||||||
|
pub const AUTO_REFRESH_OPTIONS: [u32; 4] = [0, 5, 10, 30];
|
||||||
|
|
||||||
|
/// 端点(链路)类型。
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
pub enum EndpointKind {
|
||||||
|
/// 局域网直连
|
||||||
|
Local,
|
||||||
|
/// 反代(Cloudflare Tunnel 等)
|
||||||
|
Remote,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 端点选择策略。
|
||||||
|
///
|
||||||
|
/// 探测顺序与超时见 `client.rs` 的常量;`auto` 是「先短超时试局域网、失败再试反代」,
|
||||||
|
/// 而不是「优先上次成功的端点」—— 后者会把人困在反代上:回家后反代仍然可用,
|
||||||
|
/// 就永远不会切回局域网(§3.7-a)。
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, Type)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
pub enum EndpointMode {
|
||||||
|
/// 自动(局域网优先,反代兜底)
|
||||||
|
#[default]
|
||||||
|
Auto,
|
||||||
|
/// 强制局域网
|
||||||
|
Local,
|
||||||
|
/// 强制反代
|
||||||
|
Remote,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 一条 Home Assistant 连接。
|
||||||
|
///
|
||||||
|
/// 支持**两个地址**:局域网直连(在家、快)+ 反代(在外面、慢但可达)。
|
||||||
|
/// 两者至少填一个;只填一个时 `endpoint_mode` 退化为对应模式。
|
||||||
|
#[derive(Debug, Clone, Default, Serialize, Deserialize, Type)]
|
||||||
|
#[serde(rename_all = "camelCase", default)]
|
||||||
|
pub struct HaConnection {
|
||||||
|
pub id: String,
|
||||||
|
pub name: String,
|
||||||
|
/// 局域网地址,如 `http://192.168.1.10:8123`(可空)
|
||||||
|
pub local_url: String,
|
||||||
|
/// 反代地址,如 `https://ha.example.com`(可空)
|
||||||
|
pub remote_url: String,
|
||||||
|
/// 端点选择策略
|
||||||
|
pub endpoint_mode: EndpointMode,
|
||||||
|
/// 忽略 HTTPS 证书校验(自签证书时勾选)
|
||||||
|
pub insecure: bool,
|
||||||
|
/// 上次成功的地址(**仅用于展示**;不参与探测排序,理由见 `EndpointMode` 注释)
|
||||||
|
pub last_ok_url: String,
|
||||||
|
/// 上次成功时间(unix 秒,0 = 从未)
|
||||||
|
pub last_ok_at: i64,
|
||||||
|
/// HA 版本(`GET /api/config` 的 `version`)
|
||||||
|
pub ha_version: String,
|
||||||
|
/// HA 实例名(`GET /api/config` 的 `location_name`)
|
||||||
|
pub location_name: String,
|
||||||
|
/// 温度单位(`GET /api/config` 的 `unit_system.temperature`,如 `°C` / `°F`)。
|
||||||
|
///
|
||||||
|
/// **必须从实例读**:HA 的 `climate.temperature` / `min_temp` / `max_temp` 都按
|
||||||
|
/// 系统单位制给值,写死 `°C` 在美制实例上会显示成"77°C"。
|
||||||
|
pub temperature_unit: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl HaConnection {
|
||||||
|
/// 局域网候选(空串表示未配置)。
|
||||||
|
pub fn local_candidate(&self) -> Option<(&str, EndpointKind)> {
|
||||||
|
let u = self.local_url.trim();
|
||||||
|
if u.is_empty() {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
Some((u, EndpointKind::Local))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 反代候选(空串表示未配置)。
|
||||||
|
pub fn remote_candidate(&self) -> Option<(&str, EndpointKind)> {
|
||||||
|
let u = self.remote_url.trim();
|
||||||
|
if u.is_empty() {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
Some((u, EndpointKind::Remote))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 界面与行为偏好。
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||||
|
#[serde(rename_all = "camelCase", default)]
|
||||||
|
pub struct HaUiSettings {
|
||||||
|
/// 自动刷新间隔(秒),0 = 关闭
|
||||||
|
pub auto_refresh_sec: u32,
|
||||||
|
/// 不展示的 domain(如 `sensor` 太多时可隐藏)
|
||||||
|
pub hidden_domains: Vec<String>,
|
||||||
|
/// 不展示的具体实体
|
||||||
|
pub hidden_entity_ids: Vec<String>,
|
||||||
|
/// 收藏(置顶)
|
||||||
|
pub favorite_entity_ids: Vec<String>,
|
||||||
|
/// 危险操作(解锁 / 开门 / 全开)二次确认
|
||||||
|
pub confirm_dangerous: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for HaUiSettings {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
auto_refresh_sec: 0,
|
||||||
|
hidden_domains: Vec::new(),
|
||||||
|
hidden_entity_ids: Vec::new(),
|
||||||
|
favorite_entity_ids: Vec::new(),
|
||||||
|
// 默认开启:这是有实际后果的操作(开锁 / 开门),宁可多一次确认
|
||||||
|
confirm_dangerous: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 实时推送配置(P4 才真正使用;P0 只落字段,避免以后升级设置结构)。
|
||||||
|
#[derive(Debug, Clone, Default, Serialize, Deserialize, Type)]
|
||||||
|
#[serde(rename_all = "camelCase", default)]
|
||||||
|
pub struct HaRealtimeSettings {
|
||||||
|
/// 是否启用 WebSocket 实时推送
|
||||||
|
pub enabled: bool,
|
||||||
|
/// 上次连接成功时间(unix 秒,0 = 从未)
|
||||||
|
pub last_connected_at: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 模块设置(`{app_data}/smarthome/settings.json`)。
|
||||||
|
#[derive(Debug, Clone, Default, Serialize, Deserialize, Type)]
|
||||||
|
#[serde(rename_all = "camelCase", default)]
|
||||||
|
pub struct HaSettings {
|
||||||
|
pub version: u32,
|
||||||
|
/// 激活连接 id(空 = 未选择)
|
||||||
|
pub active_id: String,
|
||||||
|
pub connections: Vec<HaConnection>,
|
||||||
|
pub ui: HaUiSettings,
|
||||||
|
pub realtime: HaRealtimeSettings,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl HaSettings {
|
||||||
|
/// 自愈:补版本号、校正激活连接、收敛非法的自动刷新间隔。返回「是否发生过修改」。
|
||||||
|
pub fn heal(&mut self) -> bool {
|
||||||
|
let mut changed = false;
|
||||||
|
if self.version != SETTINGS_VERSION {
|
||||||
|
self.version = SETTINGS_VERSION;
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
// 激活连接指向一个已不存在的 id(删连接后旧快照回写等):回落到第一条
|
||||||
|
let active_ok = self.connections.iter().any(|c| c.id == self.active_id);
|
||||||
|
if !active_ok {
|
||||||
|
let next = self.connections.first().map(|c| c.id.clone()).unwrap_or_default();
|
||||||
|
if next != self.active_id {
|
||||||
|
self.active_id = next;
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !AUTO_REFRESH_OPTIONS.contains(&self.ui.auto_refresh_sec) {
|
||||||
|
self.ui.auto_refresh_sec = 0;
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
changed
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn connection(&self, id: &str) -> Option<&HaConnection> {
|
||||||
|
self.connections.iter().find(|c| c.id == id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 前端提交的连接草案(新建或编辑)。令牌**不在此结构里**,走独立命令写入凭据库。
|
||||||
|
#[derive(Debug, Clone, Default, Serialize, Deserialize, Type)]
|
||||||
|
#[serde(rename_all = "camelCase", default)]
|
||||||
|
pub struct HaConnectionInput {
|
||||||
|
/// 空 = 新建
|
||||||
|
pub id: String,
|
||||||
|
pub name: String,
|
||||||
|
pub local_url: String,
|
||||||
|
pub remote_url: String,
|
||||||
|
pub endpoint_mode: EndpointMode,
|
||||||
|
pub insecure: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 发给前端的连接视图:**不含明文令牌**,只有掩码与"是否已配置"。
|
||||||
|
#[derive(Debug, Clone, Serialize, Type)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct HaConnectionView {
|
||||||
|
pub id: String,
|
||||||
|
pub name: String,
|
||||||
|
pub local_url: String,
|
||||||
|
pub remote_url: String,
|
||||||
|
pub endpoint_mode: EndpointMode,
|
||||||
|
pub insecure: bool,
|
||||||
|
pub has_token: bool,
|
||||||
|
/// 掩码(`secrets::mask`):长度不足 8 时整串打码,绝不泄露完整明文
|
||||||
|
pub token_masked: String,
|
||||||
|
pub last_ok_url: String,
|
||||||
|
pub last_ok_at: i64,
|
||||||
|
pub ha_version: String,
|
||||||
|
pub location_name: String,
|
||||||
|
/// 温度单位(`°C` / `°F`)—— climate 的温度显示必须用它
|
||||||
|
pub temperature_unit: String,
|
||||||
|
/// 本次会话实际使用的端点(未探测过为 null)
|
||||||
|
pub endpoint_url: Option<String>,
|
||||||
|
pub endpoint_kind: Option<EndpointKind>,
|
||||||
|
/// 该端点最近一次实测耗时(毫秒)
|
||||||
|
pub endpoint_latency_ms: Option<u64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 模块设置视图。
|
||||||
|
#[derive(Debug, Clone, Serialize, Type)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct HaSettingsView {
|
||||||
|
pub version: u32,
|
||||||
|
pub active_id: String,
|
||||||
|
pub connections: Vec<HaConnectionView>,
|
||||||
|
pub ui: HaUiSettings,
|
||||||
|
pub realtime: HaRealtimeSettings,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 保存连接的结果:**回传 id**(新建时前端要靠它接着写令牌,按名称/地址反查不可靠),
|
||||||
|
/// 外加刷新后的整份视图。
|
||||||
|
#[derive(Debug, Clone, Serialize, Type)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct HaSaveConnectionResult {
|
||||||
|
pub id: String,
|
||||||
|
pub settings: HaSettingsView,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 单个地址的探测结果(「测试连接」逐地址返回)。
|
||||||
|
///
|
||||||
|
/// 逐地址给结果而不是一个笼统的成功/失败:用户在外面测时,局域网失败是**预期内**的,
|
||||||
|
/// 只有把两条链路的结果分开呈现,这个信息才有用(§5.1)。
|
||||||
|
#[derive(Debug, Clone, Serialize, Type)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct EndpointProbe {
|
||||||
|
pub url: String,
|
||||||
|
pub kind: EndpointKind,
|
||||||
|
pub ok: bool,
|
||||||
|
pub ha_version: String,
|
||||||
|
pub location_name: String,
|
||||||
|
/// 实例的温度单位(见 `HaConnection::temperature_unit`)
|
||||||
|
pub temperature_unit: String,
|
||||||
|
/// 耗时(毫秒):既是诊断信息,也是"反代比局域网慢多少"的直觉来源
|
||||||
|
pub elapsed_ms: u64,
|
||||||
|
/// 失败原因(中文可读)
|
||||||
|
pub error: Option<String>,
|
||||||
|
/// 失败分类:auth | network | server | other(前端据此决定是否提示"重填令牌")
|
||||||
|
pub error_kind: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 当前链路信息(诊断区)。
|
||||||
|
///
|
||||||
|
/// 失败时 `url` / `kind` 也可能为空 —— 例如 `auto` 模式下两个地址都不可达,
|
||||||
|
/// 这时没有"当前链路"可言,只能把失败原因(包含每个地址的尝试结果)交给前端展示。
|
||||||
|
#[derive(Debug, Clone, Serialize, Type)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct LinkInfo {
|
||||||
|
pub url: Option<String>,
|
||||||
|
pub kind: Option<EndpointKind>,
|
||||||
|
pub ok: bool,
|
||||||
|
/// 成功时:该端点实测耗时(毫秒)。失败时为 0
|
||||||
|
pub latency_ms: u64,
|
||||||
|
/// 失败原因(含各候选地址的尝试结果)
|
||||||
|
pub error: Option<String>,
|
||||||
|
/// 失败分类:auth | network | config(前端据此决定提示"重填令牌"还是"重试")
|
||||||
|
pub error_kind: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 实体摘要(发给前端的**精简结构**)。
|
||||||
|
///
|
||||||
|
/// 只带前端**要显示**的字段。完整 `attributes` 因 domain 而异(灯有
|
||||||
|
/// `supported_color_modes`、窗帘有 `current_position`、气候有 `hvac_modes`…),
|
||||||
|
/// 几百个实体整份过 IPC 会让序列化与前端响应式都明显变重(§6.1)。
|
||||||
|
///
|
||||||
|
/// 「是否可控 / 分组 / 图标 / 状态文案」这类**表现层语义由前端 `format.ts` 决定**,
|
||||||
|
/// 不在这里算 —— Rust 侧只负责"协议 → 数据的忠实搬运"。
|
||||||
|
#[derive(Debug, Clone, Serialize, Type)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct EntitySummary {
|
||||||
|
pub entity_id: String,
|
||||||
|
/// `entity_id` 的前半段(light / switch / sensor…)
|
||||||
|
pub domain: String,
|
||||||
|
/// `friendly_name`,缺失时回落 `entity_id`
|
||||||
|
pub name: String,
|
||||||
|
/// 原始状态字符串:`on` / `off` / `24.5` / `unavailable` / `unknown` …
|
||||||
|
pub state: String,
|
||||||
|
/// `state` 可解析为数字时的数值(sensor 这类读数就在 `state` 里)
|
||||||
|
pub numeric: Option<f64>,
|
||||||
|
/// `unit_of_measurement`
|
||||||
|
pub unit: String,
|
||||||
|
/// `device_class`(binary_sensor / sensor 的语义细分)
|
||||||
|
pub device_class: String,
|
||||||
|
/// 灯亮度 0–255
|
||||||
|
pub brightness: Option<u8>,
|
||||||
|
/// 窗帘当前位置 0–100
|
||||||
|
pub position: Option<u8>,
|
||||||
|
/// 空调目标温度
|
||||||
|
pub target_temp: Option<f64>,
|
||||||
|
/// 空调可设的上下限(**单位随系统单位制**,如美制是 61–86 °F)。
|
||||||
|
/// 控件必须用它,不能自己写死 5–35 —— 美制下 77 会被钳成 35(真机踩到过)。
|
||||||
|
pub min_temp: Option<f64>,
|
||||||
|
pub max_temp: Option<f64>,
|
||||||
|
/// 空调当前温度(室温)
|
||||||
|
pub current_temp: Option<f64>,
|
||||||
|
/// 最后变化时间(HA 的 ISO8601 串,前端格式化成相对时间)
|
||||||
|
pub last_changed: String,
|
||||||
|
/// `attributes.last_triggered` —— 自动化 / 脚本的"上次触发时间"(空 = 从未触发)。
|
||||||
|
/// P3 的自动化列表要靠它回答"这条规则最近到底跑没跑"。
|
||||||
|
pub last_triggered: String,
|
||||||
|
// ---- 以下为 P2 控制所需的能力位与参数(同一次拉取里拿到,不必为控制再请求一次)----
|
||||||
|
/// HA 的 `supported_features` 位掩码。**语义按 domain 不同**(窗帘 OPEN/CLOSE/…、
|
||||||
|
/// 气候 TARGET_TEMPERATURE/…),因此这里原样透传,由前端按 domain 解释。
|
||||||
|
pub supported_features: u32,
|
||||||
|
/// 灯的 `supported_color_modes`(`onoff` / `brightness` / `color_temp` / `hs` …)。
|
||||||
|
/// 判断"能不能调亮度 / 色温"必须用它,而不是 `supported_features` 的旧位约定。
|
||||||
|
pub supported_color_modes: Vec<String>,
|
||||||
|
/// 色温可调范围(灯)
|
||||||
|
pub min_color_temp_kelvin: Option<u32>,
|
||||||
|
pub max_color_temp_kelvin: Option<u32>,
|
||||||
|
/// 当前色温(灯)。**必须有**:没有它,色温滑杆只能猜一个初始位置,
|
||||||
|
/// 那就成了一个会骗人的控件。
|
||||||
|
pub color_temp_kelvin: Option<u32>,
|
||||||
|
/// 空调可选模式(cool / heat / off / auto …)
|
||||||
|
pub hvac_modes: Vec<String>,
|
||||||
|
/// 空调温度步进(0.5 / 1)
|
||||||
|
pub target_temp_step: Option<f64>,
|
||||||
|
/// 媒体播放器音量 0.0–1.0
|
||||||
|
pub volume_level: Option<f64>,
|
||||||
|
/// 风扇档位 0–100
|
||||||
|
pub percentage: Option<u8>,
|
||||||
|
// ---- 通用域(`number` / `select` / `button`):这三类能覆盖最多"能控但没控件"的实体 ----
|
||||||
|
/// `number` 实体的可设上下限与步长(各集成差异极大:0–100 音量、10–90 变焦、步长 180 的翻转角)
|
||||||
|
pub min: Option<f64>,
|
||||||
|
pub max: Option<f64>,
|
||||||
|
pub step: Option<f64>,
|
||||||
|
/// `select` 实体的可选项
|
||||||
|
pub options: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 服务调用的可选参数。
|
||||||
|
///
|
||||||
|
/// **用固定字段而不是 `serde_json::Value`**:specta 无法为 `Value` 生成类型
|
||||||
|
/// (见 lib.rs 的豁免清单);而且固定字段顺带把"能传什么参数"限死了,
|
||||||
|
/// 前端不可能把任意键塞进 HA 的 `service_data`。
|
||||||
|
#[derive(Debug, Clone, Default, Serialize, Deserialize, Type)]
|
||||||
|
#[serde(rename_all = "camelCase", default)]
|
||||||
|
pub struct ServiceParams {
|
||||||
|
/// 灯亮度百分比 0–100(HA 侧换算成 `brightness`)
|
||||||
|
pub brightness_pct: Option<u8>,
|
||||||
|
/// 色温(开尔文)
|
||||||
|
pub color_temp_kelvin: Option<u32>,
|
||||||
|
/// 窗帘位置 0–100
|
||||||
|
pub position: Option<u8>,
|
||||||
|
/// 空调目标温度
|
||||||
|
pub temperature: Option<f64>,
|
||||||
|
/// 空调模式(`cool` / `heat` / `off` …)
|
||||||
|
pub hvac_mode: Option<String>,
|
||||||
|
/// 风扇档位 0–100
|
||||||
|
pub percentage: Option<u8>,
|
||||||
|
/// 媒体音量 0.0–1.0
|
||||||
|
pub volume_level: Option<f64>,
|
||||||
|
/// `number.set_value` 的目标值
|
||||||
|
pub value: Option<f64>,
|
||||||
|
/// `select.select_option` 的目标项
|
||||||
|
pub option: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 服务调用结果。
|
||||||
|
#[derive(Debug, Clone, Serialize, Type)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct ServiceCallResult {
|
||||||
|
/// HA 在 `200` 响应体里带回的**已变化实体**新状态(已转成精简结构)。
|
||||||
|
///
|
||||||
|
/// **可能为空**:部分集成(尤其走云端的设备)是"发完就返回",状态要稍后才反映。
|
||||||
|
/// 前端据此决定"直接采用服务端结果"还是"等分级窗口后重拉一次"(§9.3)。
|
||||||
|
pub entities: Vec<EntitySummary>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 实体列表结果。
|
||||||
|
#[derive(Debug, Clone, Serialize, Type)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct EntityListResult {
|
||||||
|
pub entities: Vec<EntitySummary>,
|
||||||
|
/// 抓取时间(unix 秒)。"更新于 x 秒前"必须用它 —— 那是**服务端数据的时刻**,
|
||||||
|
/// 而不是前端收到响应的时刻。
|
||||||
|
pub fetched_at: i64,
|
||||||
|
/// true = 命中内存缓存,未重新请求
|
||||||
|
pub from_cache: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================== P4:实时推送 ==============================
|
||||||
|
|
||||||
|
/// WebSocket 连接状态(`smarthome_ws_status` 的返回,也是 `smarthome-connection-status` 的载荷)。
|
||||||
|
#[derive(Debug, Clone, Serialize, Type)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct WsStatus {
|
||||||
|
pub conn_id: String,
|
||||||
|
/// idle | connecting | connected | authFailed | disconnected
|
||||||
|
pub state: String,
|
||||||
|
/// 失败原因 / 补充说明(正常时为空)
|
||||||
|
pub detail: String,
|
||||||
|
/// 本次连上的时间(unix 秒,0 = 未连上)
|
||||||
|
pub connected_at: i64,
|
||||||
|
/// 最近一次收到服务端消息的时间(unix 秒)—— 半开连接靠它判断
|
||||||
|
pub last_event_at: i64,
|
||||||
|
/// 已订阅到的实体数(`subscribe_entities` 首帧后写入)
|
||||||
|
pub entity_count: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WsStatus {
|
||||||
|
pub fn new(conn_id: &str, state: &str) -> Self {
|
||||||
|
Self {
|
||||||
|
conn_id: conn_id.to_string(),
|
||||||
|
state: state.to_string(),
|
||||||
|
detail: String::new(),
|
||||||
|
connected_at: 0,
|
||||||
|
last_event_at: 0,
|
||||||
|
entity_count: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 状态变化时重置"连上时间 / 事件时间"(只有 connected 才重新计时)。
|
||||||
|
pub fn set(&mut self, state: &str, detail: impl Into<String>) {
|
||||||
|
self.state = state.to_string();
|
||||||
|
self.detail = detail.into();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `smarthome-state-batch` 事件的载荷。
|
||||||
|
///
|
||||||
|
/// **200ms 聚合后**才发(plan §6.5):一次全屋状态变化(HA 重启恢复、场景切换)
|
||||||
|
/// 会造成数十条消息,逐条 IPC 会把 WebView 卡住。窗口内的多次变更按 `entity_id`
|
||||||
|
/// 合并,只发最终值。
|
||||||
|
#[derive(Debug, Clone, Serialize, Type)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct StateBatch {
|
||||||
|
pub conn_id: String,
|
||||||
|
/// 本次窗口内新出现的实体(含首次订阅的全量快照)
|
||||||
|
pub added: Vec<EntitySummary>,
|
||||||
|
/// 本次窗口内发生变化的实体(只带最终值)
|
||||||
|
pub changed: Vec<EntitySummary>,
|
||||||
|
/// 本次窗口内被移除的实体 id
|
||||||
|
pub removed: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 规则列表结果(含总开关与最近运行记录)。
|
||||||
|
///
|
||||||
|
/// 计划 §6.2 只列了 `Rule[]`,这里把「总开关 + 最近记录」并进同一个返回:
|
||||||
|
/// 自动化页进来就要用这三样,拆成三条命令只是多两次往返。
|
||||||
|
#[derive(Debug, Clone, Serialize, Type)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct RuleListResult {
|
||||||
|
/// 规则总开关(关掉后所有规则都不求值)
|
||||||
|
pub enabled: bool,
|
||||||
|
pub rules: Vec<Rule>,
|
||||||
|
/// 最近运行记录(新的在前,最多 `automation::MAX_RECORDS` 条;仅本次运行期内有)
|
||||||
|
pub records: Vec<RuleRecord>,
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================== P4:注册表(房间分组) ==============================
|
||||||
|
|
||||||
|
/// 区域(房间)。
|
||||||
|
#[derive(Debug, Clone, Serialize, Type)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct HaArea {
|
||||||
|
pub area_id: String,
|
||||||
|
pub name: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 设备(设备聚合与详情页头部所需的最小字段集合)。
|
||||||
|
#[derive(Debug, Clone, Serialize, Type)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct HaDevice {
|
||||||
|
pub id: String,
|
||||||
|
pub name: String,
|
||||||
|
/// 用户在 HA 里改过的名字(为空时用 `name`)
|
||||||
|
pub name_by_user: String,
|
||||||
|
/// 空 = 未分配房间
|
||||||
|
pub area_id: String,
|
||||||
|
/// 厂商 / 型号(详情页头部显示,便于认出是哪台设备)
|
||||||
|
pub manufacturer: String,
|
||||||
|
pub model: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 实体注册表条目(**设备聚合的唯一来源**:REST 的 `/api/states` 里没有 device_id)。
|
||||||
|
#[derive(Debug, Clone, Serialize, Type)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct EntityRegistryEntry {
|
||||||
|
pub entity_id: String,
|
||||||
|
/// 空 = 未归组到设备(真机上是 `person` / `todo` 这类)
|
||||||
|
pub device_id: String,
|
||||||
|
/// 注册表里的名字(小米集成上**大量为空**,因此只作兜底)
|
||||||
|
pub name: String,
|
||||||
|
/// 集成给的原始名字
|
||||||
|
pub original_name: String,
|
||||||
|
/// `""` | `config` | `diagnostic` —— HA 官方标记的"高级 / 配置"类实体。
|
||||||
|
///
|
||||||
|
/// 真机上只有 30/606 条有值,所以它只是"三级"的**判据之一**,不是全部。
|
||||||
|
pub entity_category: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 注册表查询结果(房间分组 + 设备聚合的唯一来源)。
|
||||||
|
///
|
||||||
|
/// **真机修正(§9.5-1)**:目标实例上实体级 `area_id` 全空,房间归属在设备上,
|
||||||
|
/// 因此 `entity_areas` 已按「实体 → 设备 → 区域」三级回退算好;仍未解析到的不进表
|
||||||
|
/// (前端把它归入「未分配房间」,这是必需的分组而不是兜底)。
|
||||||
|
#[derive(Debug, Clone, Serialize, Type)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct RegistryResult {
|
||||||
|
pub areas: Vec<HaArea>,
|
||||||
|
pub devices: Vec<HaDevice>,
|
||||||
|
/// `entity_id` → `area_id`
|
||||||
|
pub entity_areas: HashMap<String, String>,
|
||||||
|
/// 实体注册表(`entity_id` → 设备 / 名字 / 分类)
|
||||||
|
pub entity_registry: Vec<EntityRegistryEntry>,
|
||||||
|
/// 抓取时间(unix 秒)
|
||||||
|
pub fetched_at: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================== P4:本地规则 ==============================
|
||||||
|
|
||||||
|
/// 规则触发段(线性三段式的第一段)。
|
||||||
|
#[derive(Debug, Clone, Default, Serialize, Deserialize, Type)]
|
||||||
|
#[serde(rename_all = "camelCase", default)]
|
||||||
|
pub struct RuleTrigger {
|
||||||
|
pub entity_id: String,
|
||||||
|
/// 命中这些状态才触发(空 = 任意变化)
|
||||||
|
pub to: Vec<String>,
|
||||||
|
/// 仅当从这些状态变化而来(空 = 不限)
|
||||||
|
pub from: Vec<String>,
|
||||||
|
/// 持续 N 秒仍然满足才触发(0 = 立即;用于去抖)
|
||||||
|
pub for_sec: u32,
|
||||||
|
/// 数值比较运算符(空 = 不做数值判断;否则 `>` `>=` `<` `<=` `==` `!=`)
|
||||||
|
pub numeric_op: String,
|
||||||
|
/// 数值比较的阈值
|
||||||
|
pub numeric_value: Option<f64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 规则条件段(全部 AND)。
|
||||||
|
#[derive(Debug, Clone, Default, Serialize, Deserialize, Type)]
|
||||||
|
#[serde(rename_all = "camelCase", default)]
|
||||||
|
pub struct RuleCondition {
|
||||||
|
/// state | time
|
||||||
|
pub kind: String,
|
||||||
|
/// `state` 条件:实体 id
|
||||||
|
pub entity_id: String,
|
||||||
|
/// `state` 条件:要求的状态
|
||||||
|
pub state: String,
|
||||||
|
/// `time` 条件:起始 `HH:MM`
|
||||||
|
pub from_time: String,
|
||||||
|
/// `time` 条件:结束 `HH:MM`(跨零点时 `to < from` 视为跨天)
|
||||||
|
pub to_time: String,
|
||||||
|
/// `time` 条件:星期(1=周一 … 7=周日;空 = 每天)
|
||||||
|
pub weekdays: Vec<u32>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 规则动作段(顺序执行)。
|
||||||
|
#[derive(Debug, Clone, Default, Serialize, Deserialize, Type)]
|
||||||
|
#[serde(rename_all = "camelCase", default)]
|
||||||
|
pub struct RuleAction {
|
||||||
|
/// service | delay | notify
|
||||||
|
pub kind: String,
|
||||||
|
/// `service`:domain / service / 目标实体
|
||||||
|
pub domain: String,
|
||||||
|
pub service: String,
|
||||||
|
pub entity_id: String,
|
||||||
|
pub params: ServiceParams,
|
||||||
|
/// `delay`:秒(上限见 `automation::MAX_DELAY_SEC`)
|
||||||
|
pub seconds: u32,
|
||||||
|
/// `notify`:标题与正文
|
||||||
|
pub title: String,
|
||||||
|
pub message: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 一条本地规则。
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||||
|
#[serde(rename_all = "camelCase", default)]
|
||||||
|
pub struct Rule {
|
||||||
|
pub id: String,
|
||||||
|
pub name: String,
|
||||||
|
pub enabled: bool,
|
||||||
|
pub trigger: RuleTrigger,
|
||||||
|
pub conditions: Vec<RuleCondition>,
|
||||||
|
pub actions: Vec<RuleAction>,
|
||||||
|
/// 冷却秒数:窗口内的重复触发直接丢弃(护栏 1)
|
||||||
|
pub cooldown_sec: u32,
|
||||||
|
/// 上次触发时间(unix 秒,0 = 从未)
|
||||||
|
pub last_fired_at: i64,
|
||||||
|
/// 累计触发次数
|
||||||
|
pub fire_count: u32,
|
||||||
|
/// 上次失败原因(空 = 上次正常)
|
||||||
|
pub last_error: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for Rule {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
id: String::new(),
|
||||||
|
name: String::new(),
|
||||||
|
enabled: true,
|
||||||
|
trigger: RuleTrigger::default(),
|
||||||
|
conditions: Vec::new(),
|
||||||
|
actions: Vec::new(),
|
||||||
|
// 默认 30s:小米设备的状态抖动(如功率传感器反复跳)很容易把规则刷爆
|
||||||
|
cooldown_sec: 30,
|
||||||
|
last_fired_at: 0,
|
||||||
|
fire_count: 0,
|
||||||
|
last_error: String::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 规则运行记录(内存里保留最近 `automation::MAX_RECORDS` 条)。
|
||||||
|
#[derive(Debug, Clone, Serialize, Type)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct RuleRecord {
|
||||||
|
pub rule_id: String,
|
||||||
|
pub rule_name: String,
|
||||||
|
pub at: i64,
|
||||||
|
pub ok: bool,
|
||||||
|
pub detail: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `smarthome-rule-fired` 事件的载荷(与 `RuleRecord` 同构,但字段名对齐计划 §6.3)。
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct RuleFiredEvent {
|
||||||
|
pub rule_id: String,
|
||||||
|
pub rule_name: String,
|
||||||
|
pub at: i64,
|
||||||
|
pub ok: bool,
|
||||||
|
pub detail: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 规则文件(`{app_data}/smarthome/automations.json`)。
|
||||||
|
///
|
||||||
|
/// `enabled` 是**总开关**:关掉后所有规则都不求值(但规则本身保留)。
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase", default)]
|
||||||
|
pub struct RulesFile {
|
||||||
|
pub version: u32,
|
||||||
|
pub enabled: bool,
|
||||||
|
pub rules: Vec<Rule>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for RulesFile {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
version: RULES_VERSION,
|
||||||
|
enabled: false,
|
||||||
|
rules: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 规则文件版本号(自愈用)。
|
||||||
|
pub const RULES_VERSION: u32 = 1;
|
||||||
|
|
||||||
|
/// 命令层错误:带分类。
|
||||||
|
///
|
||||||
|
/// 前端据此区分"重填令牌"(`auth`,重试无意义)与"重试 / 检查地址"
|
||||||
|
/// (`network` / `config`)—— **分类判定留在 Rust 侧**,不让前端靠匹配错误文案猜(§3.6)。
|
||||||
|
/// 这是本项目第一个不用 `String` 作错误类型的命令模块;理由见 §9.1。
|
||||||
|
#[derive(Debug, Clone, Serialize, Type)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct HaApiError {
|
||||||
|
/// auth | network | config | server | other
|
||||||
|
pub kind: String,
|
||||||
|
pub message: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl HaApiError {
|
||||||
|
pub fn new(kind: &str, message: impl Into<String>) -> Self {
|
||||||
|
Self {
|
||||||
|
kind: kind.to_string(),
|
||||||
|
message: message.into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Display for HaApiError {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
f.write_str(&self.message)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,768 @@
|
|||||||
|
//! Home Assistant WebSocket 实时客户端(P4)。
|
||||||
|
//!
|
||||||
|
//! 职责(plan §3.3 / §6.1):握手鉴权 → `subscribe_entities` → 增量合并 → 200ms 聚合后
|
||||||
|
//! 发 `smarthome-state-batch`;顺带把状态变化喂给本地规则引擎(`automation`)。
|
||||||
|
//! 还提供「请求 / 应答」通道,供 `registry` 拉区域 / 实体 / 设备注册表。
|
||||||
|
//!
|
||||||
|
//! 生命周期归属**应用**而非页面:连接由 Rust 侧持有(后台任务),模块 Tab 切走不关连接;
|
||||||
|
//! 只有用户显式关掉实时、规则总开关关闭、或应用退出才断(plan §3.3 第一条)。
|
||||||
|
//!
|
||||||
|
//! 真机实测前提(§9.5):
|
||||||
|
//! - 握手 `auth_required` → `auth` → `auth_ok`,HA 2026.10.1;
|
||||||
|
//! - `subscribe_entities` 首帧是**一条大消息**(577 实体 / 152 KB / 2.23s),
|
||||||
|
//! 之后 30 秒仅 2 个增量事件 —— 这就是"实时优于轮询"的量化依据;
|
||||||
|
//! - `ping/pong` 往返 617ms(反代),心跳与聚合窗口按它设计;
|
||||||
|
//! - **`c`(changed)里的 attributes 可能是差量**(`{"+": {...}, "-": [...]}`),
|
||||||
|
//! 因此必须维护一份原始 attributes 再合并,然后重新推导 `EntitySummary`,
|
||||||
|
//! 不能整份替换(整份替换会在下一次事件把未变化的字段抹掉)。
|
||||||
|
|
||||||
|
use std::collections::{HashMap, HashSet};
|
||||||
|
use std::sync::atomic::{AtomicU64, Ordering};
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use futures_util::{SinkExt, StreamExt};
|
||||||
|
use serde_json::{json, Map, Value};
|
||||||
|
use tauri::{AppHandle, Emitter};
|
||||||
|
use tokio::sync::{mpsc, oneshot, watch};
|
||||||
|
use tokio_tungstenite::tungstenite::Message;
|
||||||
|
|
||||||
|
use super::automation::{self, RuleEnv};
|
||||||
|
use super::client::{self, RawState};
|
||||||
|
use super::types::{EntitySummary, StateBatch, WsStatus};
|
||||||
|
use crate::constants::events;
|
||||||
|
|
||||||
|
/// 心跳间隔(秒)。
|
||||||
|
///
|
||||||
|
/// 反代链路上的 `ping/pong` 实测 **617ms**(§9.5),25s 足够保活,也给 Cloudflare
|
||||||
|
/// 约 100s 的空闲超时留足余量。**必须主动发**:不能只依赖 TCP keepalive,
|
||||||
|
/// 路由器 / NAT 把连接悄悄丢掉时 TCP 是不会有反应的。
|
||||||
|
const PING_SECS: u64 = 25;
|
||||||
|
/// 超过这么久没收到任何入站消息 → 判定半开连接,主动断开重连。
|
||||||
|
const STALE_SECS: u64 = PING_SECS * 3;
|
||||||
|
/// 聚合窗口(毫秒)—— **硬要求**(plan §6.5):一次全屋变化会有数十条消息。
|
||||||
|
const AGG_MS: u64 = 200;
|
||||||
|
/// 重连退避上限(秒)。
|
||||||
|
const MAX_BACKOFF_SECS: u64 = 30;
|
||||||
|
/// 握手 / 鉴权等待超时(秒)。反代上首帧可能慢,给足。
|
||||||
|
const HANDSHAKE_TIMEOUT_SECS: u64 = 20;
|
||||||
|
/// 连上后至少活这么久才认为"这次连接是成功的",从而把退避重置回 1s
|
||||||
|
/// (否则"连上即断"会退化成 1s 一次的重连风暴)。
|
||||||
|
const STABLE_CONNECT_SECS: u64 = 5;
|
||||||
|
/// 实时命令(注册表查询)的等待超时(秒)。
|
||||||
|
const REQUEST_TIMEOUT_SECS: u64 = 20;
|
||||||
|
|
||||||
|
/// 应答等待表:`id` → 一次性回执。
|
||||||
|
type Pending = Arc<Mutex<HashMap<u64, oneshot::Sender<Result<Value, String>>>>>;
|
||||||
|
|
||||||
|
/// 客户端连接的具体类型(`MaybeTlsStream` 在开了 `rustls-tls-webpki-roots` 后
|
||||||
|
/// 会带上 TLS 分支,因此必须用具名别名而不是泛型参数)。
|
||||||
|
type WsStream = tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>;
|
||||||
|
|
||||||
|
/// 传给后台任务的配置。
|
||||||
|
pub struct WsTaskConfig {
|
||||||
|
pub conn_id: String,
|
||||||
|
pub app: AppHandle,
|
||||||
|
/// REST 端点(规则动作走 REST 下发;不重造一份"WS 版 call_service")
|
||||||
|
pub base_url: String,
|
||||||
|
/// WebSocket 端点(由 `client::ws_url` 从 REST 端点推出来)
|
||||||
|
pub ws_url: String,
|
||||||
|
pub token: String,
|
||||||
|
pub insecure: bool,
|
||||||
|
pub kind: super::types::EndpointKind,
|
||||||
|
pub rules: Arc<Mutex<super::types::RulesFile>>,
|
||||||
|
pub records: Arc<Mutex<std::collections::VecDeque<super::types::RuleRecord>>>,
|
||||||
|
pub recent: Arc<Mutex<std::collections::VecDeque<(String, Instant)>>>,
|
||||||
|
pub rules_path: std::path::PathBuf,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 运行中的 WS 连接的句柄(克隆是廉价的:内部全是 Arc / channel)。
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct WsHandle {
|
||||||
|
pub conn_id: String,
|
||||||
|
out: mpsc::UnboundedSender<String>,
|
||||||
|
pending: Pending,
|
||||||
|
next_id: Arc<AtomicU64>,
|
||||||
|
stop: watch::Sender<bool>,
|
||||||
|
status: Arc<Mutex<WsStatus>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WsHandle {
|
||||||
|
/// 当前状态快照。
|
||||||
|
pub fn status(&self) -> WsStatus {
|
||||||
|
match self.status.lock() {
|
||||||
|
Ok(g) => g.clone(),
|
||||||
|
Err(e) => {
|
||||||
|
crate::logger::log_error("smarthome", &format!("WS 状态锁中毒:{e}"));
|
||||||
|
WsStatus::new(&self.conn_id, "disconnected")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 请求停止(任务会在下一个 select 轮次退出)。
|
||||||
|
pub fn stop(&self) {
|
||||||
|
let _ = self.stop.send(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 发一条实时命令并等应答(注册表查询用它)。
|
||||||
|
///
|
||||||
|
/// 超时后要把等待表里的条目删掉 —— 否则应答迟到时会往一个已丢弃的 oneshot
|
||||||
|
/// 里写(无害但会泄漏一条记录)。
|
||||||
|
pub async fn request(&self, mut payload: Value, timeout: Duration) -> Result<Value, String> {
|
||||||
|
let id = self.next_id.fetch_add(1, Ordering::Relaxed);
|
||||||
|
match payload.as_object_mut() {
|
||||||
|
Some(o) => {
|
||||||
|
o.insert("id".to_string(), json!(id));
|
||||||
|
}
|
||||||
|
None => return Err("内部错误:实时命令载荷不是对象".to_string()),
|
||||||
|
}
|
||||||
|
let (tx, rx) = oneshot::channel();
|
||||||
|
if let Ok(mut g) = self.pending.lock() {
|
||||||
|
g.insert(id, tx);
|
||||||
|
}
|
||||||
|
self.out
|
||||||
|
.send(payload.to_string())
|
||||||
|
.map_err(|_| "实时连接已断开".to_string())?;
|
||||||
|
match tokio::time::timeout(timeout, rx).await {
|
||||||
|
Ok(Ok(v)) => v,
|
||||||
|
Ok(Err(_)) => Err("实时连接已断开".to_string()),
|
||||||
|
Err(_) => {
|
||||||
|
if let Ok(mut g) = self.pending.lock() {
|
||||||
|
g.remove(&id);
|
||||||
|
}
|
||||||
|
Err("Home Assistant 未在预期时间内应答".to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 启动一条实时连接,返回句柄(**不阻塞**:连接建立与重连都在后台任务里)。
|
||||||
|
pub fn spawn(cfg: WsTaskConfig) -> WsHandle {
|
||||||
|
let status = Arc::new(Mutex::new(WsStatus::new(&cfg.conn_id, "connecting")));
|
||||||
|
let (out_tx, out_rx) = mpsc::unbounded_channel::<String>();
|
||||||
|
let pending: Pending = Arc::new(Mutex::new(HashMap::new()));
|
||||||
|
let next_id = Arc::new(AtomicU64::new(1));
|
||||||
|
let (stop_tx, stop_rx) = watch::channel(false);
|
||||||
|
let summaries: Arc<Mutex<HashMap<String, EntitySummary>>> = Arc::new(Mutex::new(HashMap::new()));
|
||||||
|
|
||||||
|
let rule_env = RuleEnv {
|
||||||
|
app: cfg.app.clone(),
|
||||||
|
base_url: cfg.base_url.clone(),
|
||||||
|
token: cfg.token.clone(),
|
||||||
|
insecure: cfg.insecure,
|
||||||
|
kind: cfg.kind,
|
||||||
|
rules: cfg.rules.clone(),
|
||||||
|
records: cfg.records.clone(),
|
||||||
|
recent: cfg.recent.clone(),
|
||||||
|
pending: Arc::new(Mutex::new(HashMap::new())),
|
||||||
|
last_persist: Arc::new(Mutex::new(Instant::now())),
|
||||||
|
rules_path: cfg.rules_path.clone(),
|
||||||
|
summaries: summaries.clone(),
|
||||||
|
};
|
||||||
|
let session = Session {
|
||||||
|
cfg,
|
||||||
|
pending: pending.clone(),
|
||||||
|
next_id: next_id.clone(),
|
||||||
|
status: status.clone(),
|
||||||
|
summaries,
|
||||||
|
rule_env,
|
||||||
|
raw: HashMap::new(),
|
||||||
|
added: HashSet::new(),
|
||||||
|
changed: HashSet::new(),
|
||||||
|
removed: HashSet::new(),
|
||||||
|
};
|
||||||
|
// `for`(持续 N 秒)触发器的巡检任务:与连接同生共死(stop 信号一响就退出),
|
||||||
|
// 因此不会有"连接已经换了、旧定时器还在跑旧端点"的残留(见自动化模块注释)
|
||||||
|
automation::spawn_sweeper(&session.rule_env, stop_rx.clone());
|
||||||
|
let handle = WsHandle {
|
||||||
|
conn_id: session.cfg.conn_id.clone(),
|
||||||
|
out: out_tx,
|
||||||
|
pending,
|
||||||
|
next_id,
|
||||||
|
stop: stop_tx,
|
||||||
|
status,
|
||||||
|
};
|
||||||
|
tauri::async_runtime::spawn(run(session, out_rx, stop_rx));
|
||||||
|
handle
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================== 任务主体 ==============================
|
||||||
|
|
||||||
|
/// 任务内部状态。
|
||||||
|
struct Session {
|
||||||
|
cfg: WsTaskConfig,
|
||||||
|
pending: Pending,
|
||||||
|
next_id: Arc<AtomicU64>,
|
||||||
|
status: Arc<Mutex<WsStatus>>,
|
||||||
|
/// 原始实体状态(**差量合并的基准**,见文件头注释)
|
||||||
|
raw: HashMap<String, RawEntity>,
|
||||||
|
/// 当前摘要(与规则引擎共享同一份 Arc,条件判断直接读它)
|
||||||
|
summaries: Arc<Mutex<HashMap<String, EntitySummary>>>,
|
||||||
|
rule_env: RuleEnv,
|
||||||
|
added: HashSet<String>,
|
||||||
|
changed: HashSet<String>,
|
||||||
|
removed: HashSet<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 合并基准:一份完整的原始状态。
|
||||||
|
struct RawEntity {
|
||||||
|
state: String,
|
||||||
|
attrs: Map<String, Value>,
|
||||||
|
last_changed: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Session {
|
||||||
|
/// 更新状态并推给前端(同状态同原因不重复推)。
|
||||||
|
fn push_status(&mut self, state: &str, detail: impl Into<String>) {
|
||||||
|
let detail = detail.into();
|
||||||
|
let Ok(mut g) = self.status.lock() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
if g.state == state && g.detail == detail {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
g.set(state, detail);
|
||||||
|
if state == "connected" {
|
||||||
|
g.connected_at = now_secs();
|
||||||
|
} else if state == "idle" || state == "disconnected" || state == "authFailed" {
|
||||||
|
// 断开/停止后"连上时间"不再有效,别让它在那儿假装还连着
|
||||||
|
g.connected_at = 0;
|
||||||
|
}
|
||||||
|
let payload = g.clone();
|
||||||
|
drop(g);
|
||||||
|
let _ = self
|
||||||
|
.cfg
|
||||||
|
.app
|
||||||
|
.emit(events::SMARTHOME_CONNECTION_STATUS, payload);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 记一次"收到服务端消息"的时刻(诊断用,不推事件:状态本身没变)。
|
||||||
|
fn note_event(&mut self) {
|
||||||
|
if let Ok(mut g) = self.status.lock() {
|
||||||
|
g.last_event_at = now_secs();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 断线后清空本地状态:增量已经丢了,重连时 `subscribe_entities` 会给全量快照。
|
||||||
|
fn reset_state(&mut self) {
|
||||||
|
self.raw.clear();
|
||||||
|
if let Ok(mut g) = self.summaries.lock() {
|
||||||
|
g.clear();
|
||||||
|
}
|
||||||
|
self.added.clear();
|
||||||
|
self.changed.clear();
|
||||||
|
self.removed.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 分配一个自增 id 并直接发送(不等应答:订阅与心跳的结果不参与流程)。
|
||||||
|
async fn send_fire_and_forget(
|
||||||
|
&mut self,
|
||||||
|
write: &mut futures_util::stream::SplitSink<WsStream, Message>,
|
||||||
|
mut payload: Value,
|
||||||
|
) {
|
||||||
|
let id = self.next_id.fetch_add(1, Ordering::Relaxed);
|
||||||
|
if let Some(o) = payload.as_object_mut() {
|
||||||
|
o.insert("id".to_string(), json!(id));
|
||||||
|
}
|
||||||
|
if let Err(e) = write.send(Message::Text(payload.to_string())).await {
|
||||||
|
crate::logger::log_warn("smarthome", &format!("发送实时命令失败:{e}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 收到一条文本消息:先路由应答,再处理事件。
|
||||||
|
fn on_text(&mut self, text: &str) {
|
||||||
|
let v: Value = match serde_json::from_str(text) {
|
||||||
|
Ok(v) => v,
|
||||||
|
Err(e) => {
|
||||||
|
crate::logger::log_warn("smarthome", &format!("忽略无法解析的实时消息:{e}"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 1) 应答路由(订阅 / 心跳 / 注册表查询都带 id)
|
||||||
|
if let Some(id) = v.get("id").and_then(|x| x.as_u64()) {
|
||||||
|
let ty = v.get("type").and_then(|x| x.as_str()).unwrap_or("");
|
||||||
|
if ty == "result" || ty == "pong" {
|
||||||
|
let sender = self.pending.lock().ok().and_then(|mut g| g.remove(&id));
|
||||||
|
if let Some(tx) = sender {
|
||||||
|
let outcome = if ty == "pong" {
|
||||||
|
Ok(Value::Null)
|
||||||
|
} else if v.get("success").and_then(|x| x.as_bool()).unwrap_or(false) {
|
||||||
|
Ok(v.get("result").cloned().unwrap_or(Value::Null))
|
||||||
|
} else {
|
||||||
|
Err(error_message(&v))
|
||||||
|
};
|
||||||
|
let _ = tx.send(outcome);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2) 事件(只订阅了 subscribe_entities)
|
||||||
|
if v.get("type").and_then(|x| x.as_str()) == Some("event") {
|
||||||
|
if let Some(ev) = v.get("event") {
|
||||||
|
self.apply_event(ev);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `subscribe_entities` 的事件:`a` 新增全量 / `c` 变化(可能是差量)/ `r` 移除。
|
||||||
|
fn apply_event(&mut self, ev: &Value) {
|
||||||
|
if let Some(map) = ev.get("a").and_then(|x| x.as_object()) {
|
||||||
|
let first = self.summaries.lock().map(|g| g.is_empty()).unwrap_or(false);
|
||||||
|
if first && !map.is_empty() {
|
||||||
|
// 首帧是一条大消息:记下实际大小(plan §2.2-3 要求把它记进日志)
|
||||||
|
crate::logger::log_info(
|
||||||
|
"smarthome",
|
||||||
|
&format!("实时订阅首帧:{} 个实体(约 {} KB)", map.len(), approx_kb(ev)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
for (entity_id, obj) in map {
|
||||||
|
self.upsert_full(entity_id, obj);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(map) = ev.get("c").and_then(|x| x.as_object()) {
|
||||||
|
for (entity_id, obj) in map {
|
||||||
|
self.apply_change(entity_id, obj);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(list) = ev.get("r").and_then(|x| x.as_array()) {
|
||||||
|
for item in list {
|
||||||
|
if let Some(id) = item.as_str() {
|
||||||
|
self.remove_entity(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 全量状态(`a` 段,或变化数据里带了完整状态时)。
|
||||||
|
fn upsert_full(&mut self, entity_id: &str, obj: &Value) {
|
||||||
|
let raw = RawEntity {
|
||||||
|
state: obj
|
||||||
|
.get("s")
|
||||||
|
.and_then(|x| x.as_str())
|
||||||
|
.unwrap_or_default()
|
||||||
|
.to_string(),
|
||||||
|
attrs: obj
|
||||||
|
.get("a")
|
||||||
|
.and_then(|x| x.as_object())
|
||||||
|
.cloned()
|
||||||
|
.unwrap_or_default(),
|
||||||
|
last_changed: last_changed_of(obj),
|
||||||
|
};
|
||||||
|
self.commit(entity_id, raw);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 差量变化(`c` 段):**先合并回原始对象再推导摘要**,绝不整份替换。
|
||||||
|
fn apply_change(&mut self, entity_id: &str, obj: &Value) {
|
||||||
|
match self.raw.get_mut(entity_id) {
|
||||||
|
Some(stored) => {
|
||||||
|
if let Some(s) = obj.get("s").and_then(|x| x.as_str()) {
|
||||||
|
stored.state = s.to_string();
|
||||||
|
}
|
||||||
|
if let Some(a) = obj.get("a").and_then(|x| x.as_object()) {
|
||||||
|
// 差量形态:`+` 是要补的键、`-` 是要删的键;其余键按普通属性合并
|
||||||
|
if let Some(plus) = a.get("+").and_then(|x| x.as_object()) {
|
||||||
|
for (k, v) in plus {
|
||||||
|
stored.attrs.insert(k.clone(), v.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(minus) = a.get("-").and_then(|x| x.as_array()) {
|
||||||
|
for k in minus {
|
||||||
|
if let Some(k) = k.as_str() {
|
||||||
|
stored.attrs.remove(k);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (k, v) in a {
|
||||||
|
if k == "+" || k == "-" {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
stored.attrs.insert(k.clone(), v.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let lc = last_changed_of(obj);
|
||||||
|
if !lc.is_empty() {
|
||||||
|
stored.last_changed = lc;
|
||||||
|
}
|
||||||
|
let raw = RawEntity {
|
||||||
|
state: stored.state.clone(),
|
||||||
|
attrs: stored.attrs.clone(),
|
||||||
|
last_changed: stored.last_changed.clone(),
|
||||||
|
};
|
||||||
|
self.commit(entity_id, raw);
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
// 没见过这个实体(订阅之后才出现的实体理论上会先走 `a`):
|
||||||
|
// 用这条变化消息构造一份(属性可能不全),下一次全量会补齐
|
||||||
|
self.upsert_full(entity_id, obj);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn remove_entity(&mut self, entity_id: &str) {
|
||||||
|
self.raw.remove(entity_id);
|
||||||
|
if let Ok(mut g) = self.summaries.lock() {
|
||||||
|
g.remove(entity_id);
|
||||||
|
}
|
||||||
|
self.added.remove(entity_id);
|
||||||
|
self.changed.remove(entity_id);
|
||||||
|
self.removed.insert(entity_id.to_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 落一份新状态:算摘要、标记批次、喂规则引擎。
|
||||||
|
fn commit(&mut self, entity_id: &str, raw: RawEntity) {
|
||||||
|
let summary = summary_of(entity_id, &raw);
|
||||||
|
let previous = self
|
||||||
|
.summaries
|
||||||
|
.lock()
|
||||||
|
.ok()
|
||||||
|
.and_then(|mut g| g.insert(entity_id.to_string(), summary.clone()));
|
||||||
|
self.raw.insert(entity_id.to_string(), raw);
|
||||||
|
self.removed.remove(entity_id);
|
||||||
|
match previous {
|
||||||
|
Some(prev) => {
|
||||||
|
self.changed.insert(entity_id.to_string());
|
||||||
|
if prev.state != summary.state || prev.numeric != summary.numeric {
|
||||||
|
automation::on_entity_changed(&self.rule_env, entity_id, Some(&prev), &summary);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
// **首次见到不触发规则。**
|
||||||
|
// `subscribe_entities` 的首帧就是全量快照,重连后也会重放一遍 ——
|
||||||
|
// 把快照当成"状态变化"会让只配了「变化为 on」的边沿触发规则在每次
|
||||||
|
// 连接/重连时凭空执行一次(门开着 → 每次都重新锁门)。
|
||||||
|
// 订阅之后**新出现**的实体同样走这条路径,代价是"实体一出现就触发"
|
||||||
|
// 这种玩法不支持 —— 那本来也不是"状态变化"。
|
||||||
|
self.added.insert(entity_id.to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 聚合窗口到点:把窗口内累计的变化合并成一批发出去。
|
||||||
|
fn flush(&mut self) {
|
||||||
|
if self.added.is_empty() && self.changed.is_empty() && self.removed.is_empty() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let removed: Vec<String> = self.removed.drain().collect();
|
||||||
|
let removed_set: HashSet<String> = removed.iter().cloned().collect();
|
||||||
|
|
||||||
|
let mut added = Vec::new();
|
||||||
|
let mut changed = Vec::new();
|
||||||
|
// 一次锁住摘要表把两批都取出来:首帧是 577 个实体,逐个 lock/clone 没必要
|
||||||
|
match self.summaries.lock() {
|
||||||
|
Ok(summaries) => {
|
||||||
|
for id in self.added.drain() {
|
||||||
|
if removed_set.contains(&id) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if let Some(s) = summaries.get(&id) {
|
||||||
|
added.push(s.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for id in self.changed.drain() {
|
||||||
|
if removed_set.contains(&id) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if let Some(s) = summaries.get(&id) {
|
||||||
|
changed.push(s.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
crate::logger::log_error("smarthome", &format!("实体摘要锁中毒:{e}"));
|
||||||
|
self.added.clear();
|
||||||
|
self.changed.clear();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 实体数变了要**推一次状态**:否则设置页的「实时连接」永远显示
|
||||||
|
// "已连接(0 个实体实时同步)」—— 那个数字只存在 Rust 内存里没人看得到
|
||||||
|
let payload = match self.status.lock() {
|
||||||
|
Ok(mut g) => {
|
||||||
|
let total = self.summaries.lock().map(|m| m.len()).unwrap_or(0) as u32;
|
||||||
|
if g.entity_count != total {
|
||||||
|
g.entity_count = total;
|
||||||
|
Some(g.clone())
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(_) => None,
|
||||||
|
};
|
||||||
|
if let Some(payload) = payload {
|
||||||
|
let _ = self
|
||||||
|
.cfg
|
||||||
|
.app
|
||||||
|
.emit(events::SMARTHOME_CONNECTION_STATUS, payload);
|
||||||
|
}
|
||||||
|
|
||||||
|
let _ = self.cfg.app.emit(
|
||||||
|
events::SMARTHOME_STATE_BATCH,
|
||||||
|
StateBatch {
|
||||||
|
conn_id: self.cfg.conn_id.clone(),
|
||||||
|
added,
|
||||||
|
changed,
|
||||||
|
removed,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
enum Outcome {
|
||||||
|
/// 用户主动停止
|
||||||
|
Stopped,
|
||||||
|
/// 令牌无效:**停止重连**(继续试只会刷爆日志,见 plan §3.3)
|
||||||
|
AuthFailed(String),
|
||||||
|
/// 链路断开:指数退避后重连
|
||||||
|
Lost(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn run(
|
||||||
|
mut session: Session,
|
||||||
|
mut rx: mpsc::UnboundedReceiver<String>,
|
||||||
|
mut stop_rx: watch::Receiver<bool>,
|
||||||
|
) {
|
||||||
|
let mut backoff = Duration::from_secs(1);
|
||||||
|
loop {
|
||||||
|
if *stop_rx.borrow() {
|
||||||
|
session.push_status("idle", "");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
session.push_status("connecting", "");
|
||||||
|
match connect_and_run(&mut session, &mut rx, &mut stop_rx, &mut backoff).await {
|
||||||
|
Outcome::Stopped => {
|
||||||
|
session.push_status("idle", "");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Outcome::AuthFailed(msg) => {
|
||||||
|
crate::logger::log_error("smarthome", &format!("实时连接鉴权失败:{msg}"));
|
||||||
|
session.push_status("authFailed", msg);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Outcome::Lost(msg) => {
|
||||||
|
crate::logger::log_warn("smarthome", &format!("实时连接断开:{msg}"));
|
||||||
|
session.push_status("disconnected", msg);
|
||||||
|
session.reset_state();
|
||||||
|
tokio::select! {
|
||||||
|
_ = stop_rx.changed() => {}
|
||||||
|
_ = tokio::time::sleep(backoff) => {}
|
||||||
|
}
|
||||||
|
backoff = std::cmp::min(backoff * 2, Duration::from_secs(MAX_BACKOFF_SECS));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn connect_and_run(
|
||||||
|
session: &mut Session,
|
||||||
|
rx: &mut mpsc::UnboundedReceiver<String>,
|
||||||
|
stop_rx: &mut watch::Receiver<bool>,
|
||||||
|
backoff: &mut Duration,
|
||||||
|
) -> Outcome {
|
||||||
|
let started = Instant::now();
|
||||||
|
let mut stream: WsStream = match tokio_tungstenite::connect_async(session.cfg.ws_url.as_str())
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok((s, _resp)) => s,
|
||||||
|
Err(e) => return Outcome::Lost(format!("建立 WebSocket 失败:{e}")),
|
||||||
|
};
|
||||||
|
|
||||||
|
// ---- 握手:等 auth_required ----
|
||||||
|
let hello = match timeout_json(
|
||||||
|
wait_for_type(&mut stream, "auth_required"),
|
||||||
|
HANDSHAKE_TIMEOUT_SECS,
|
||||||
|
"等待 Home Assistant 握手",
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(Ok(v)) => v,
|
||||||
|
Ok(Err(e)) | Err(e) => return Outcome::Lost(e),
|
||||||
|
};
|
||||||
|
if hello.get("type").and_then(|x| x.as_str()) != Some("auth_required") {
|
||||||
|
return Outcome::Lost("握手消息类型异常".to_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- 鉴权 ----
|
||||||
|
let auth = json!({ "type": "auth", "access_token": session.cfg.token });
|
||||||
|
if let Err(e) = stream.send(Message::Text(auth.to_string())).await {
|
||||||
|
return Outcome::Lost(format!("发送鉴权消息失败:{e}"));
|
||||||
|
}
|
||||||
|
let result = match timeout_json(
|
||||||
|
wait_for_any(&mut stream, &["auth_ok", "auth_invalid"]),
|
||||||
|
HANDSHAKE_TIMEOUT_SECS,
|
||||||
|
"等待鉴权结果",
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(Ok(v)) => v,
|
||||||
|
Ok(Err(e)) | Err(e) => return Outcome::Lost(e),
|
||||||
|
};
|
||||||
|
match result.get("type").and_then(|x| x.as_str()) {
|
||||||
|
Some("auth_ok") => {}
|
||||||
|
Some("auth_invalid") => {
|
||||||
|
return Outcome::AuthFailed(error_message(&result));
|
||||||
|
}
|
||||||
|
_ => return Outcome::Lost("鉴权应答类型异常".to_string()),
|
||||||
|
}
|
||||||
|
|
||||||
|
session.push_status("connected", "");
|
||||||
|
crate::logger::log_info("smarthome", "实时连接已建立(WebSocket 已鉴权)");
|
||||||
|
|
||||||
|
// ---- 拆分读写两半,进入主循环 ----
|
||||||
|
let (mut write, mut read) = stream.split();
|
||||||
|
|
||||||
|
// 订阅全实体(省略 entity_ids = 全量;首帧就是完整快照)
|
||||||
|
session
|
||||||
|
.send_fire_and_forget(&mut write, json!({ "type": "subscribe_entities" }))
|
||||||
|
.await;
|
||||||
|
|
||||||
|
let mut ping_at = tokio::time::Instant::now() + Duration::from_secs(PING_SECS);
|
||||||
|
let mut flush_at = tokio::time::Instant::now() + Duration::from_millis(AGG_MS);
|
||||||
|
let mut last_rx = tokio::time::Instant::now();
|
||||||
|
|
||||||
|
let outcome = loop {
|
||||||
|
tokio::select! {
|
||||||
|
_ = stop_rx.changed() => break Outcome::Stopped,
|
||||||
|
out = rx.recv() => match out {
|
||||||
|
Some(text) => {
|
||||||
|
if let Err(e) = write.send(Message::Text(text)).await {
|
||||||
|
break Outcome::Lost(format!("发送实时命令失败:{e}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None => break Outcome::Stopped,
|
||||||
|
},
|
||||||
|
msg = read.next() => match msg {
|
||||||
|
Some(Ok(Message::Text(text))) => {
|
||||||
|
last_rx = tokio::time::Instant::now();
|
||||||
|
session.note_event();
|
||||||
|
session.on_text(&text);
|
||||||
|
}
|
||||||
|
Some(Ok(Message::Binary(_))) => {}
|
||||||
|
Some(Ok(Message::Ping(payload))) => {
|
||||||
|
// 协议级 ping 必须回 pong,否则服务端会判为死连接
|
||||||
|
let _ = write.send(Message::Pong(payload)).await;
|
||||||
|
}
|
||||||
|
Some(Ok(Message::Close(_))) => break Outcome::Lost("服务端关闭了连接".to_string()),
|
||||||
|
Some(Ok(_)) => {}
|
||||||
|
Some(Err(e)) => break Outcome::Lost(format!("WebSocket 读取失败:{e}")),
|
||||||
|
None => break Outcome::Lost("WebSocket 已断开".to_string()),
|
||||||
|
},
|
||||||
|
_ = tokio::time::sleep_until(ping_at) => {
|
||||||
|
ping_at += Duration::from_secs(PING_SECS);
|
||||||
|
session.send_fire_and_forget(&mut write, json!({ "type": "ping" })).await;
|
||||||
|
if last_rx.elapsed() > Duration::from_secs(STALE_SECS) {
|
||||||
|
break Outcome::Lost(format!(
|
||||||
|
"{} 秒未收到任何消息(连接可能已被中间设备半开)",
|
||||||
|
STALE_SECS
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ = tokio::time::sleep_until(flush_at) => {
|
||||||
|
flush_at += Duration::from_millis(AGG_MS);
|
||||||
|
session.flush();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 连上后稳定存活过一段时间才算"这次连接是成功的":否则"连上即断"会变成
|
||||||
|
// 1s 一次的重连风暴(真机上半开连接就是这种表现)
|
||||||
|
if started.elapsed() >= Duration::from_secs(STABLE_CONNECT_SECS) {
|
||||||
|
*backoff = Duration::from_secs(1);
|
||||||
|
}
|
||||||
|
outcome
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================== 小工具 ==============================
|
||||||
|
|
||||||
|
fn now_secs() -> i64 {
|
||||||
|
chrono::Utc::now().timestamp()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 事件 / 应答里的可读错误信息。
|
||||||
|
fn error_message(v: &Value) -> String {
|
||||||
|
v.get("error")
|
||||||
|
.and_then(|e| e.get("message"))
|
||||||
|
.and_then(|m| m.as_str())
|
||||||
|
.or_else(|| v.get("message").and_then(|m| m.as_str()))
|
||||||
|
.map(|s| s.to_string())
|
||||||
|
.unwrap_or_else(|| "Home Assistant 拒绝了这条实时命令".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 粗略估算一条消息的 KB 数(只用于日志,不值得精确序列化)。
|
||||||
|
fn approx_kb(v: &Value) -> usize {
|
||||||
|
v.to_string().len() / 1024
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 紧凑状态里的时间戳。
|
||||||
|
///
|
||||||
|
/// HA 的紧凑形态是 `c` = `last_changed`、`lc` = `last_updated`;
|
||||||
|
/// 个别版本在变化帧里只带 `lc`,所以这里按 `c` → `lc` → `lu` 兜底取用。
|
||||||
|
/// 两者都是时间戳,最坏情况是"x 分钟前"差一点,不影响状态本身。
|
||||||
|
fn last_changed_of(obj: &Value) -> String {
|
||||||
|
for key in ["c", "lc", "lu"] {
|
||||||
|
if let Some(s) = obj.get(key).and_then(|x| x.as_str()) {
|
||||||
|
if !s.is_empty() {
|
||||||
|
return s.to_string();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
String::new()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 原始状态 → 精简摘要(与 REST 路径共用同一份推导逻辑,见 `client::to_summary`)。
|
||||||
|
fn summary_of(entity_id: &str, raw: &RawEntity) -> EntitySummary {
|
||||||
|
client::to_summary(RawState {
|
||||||
|
entity_id: entity_id.to_string(),
|
||||||
|
state: raw.state.clone(),
|
||||||
|
attributes: Value::Object(raw.attrs.clone()),
|
||||||
|
last_changed: raw.last_changed.clone(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 带超时的等待(把两个 Result 层级压平成一个)。
|
||||||
|
async fn timeout_json(
|
||||||
|
fut: impl std::future::Future<Output = Result<Value, String>>,
|
||||||
|
secs: u64,
|
||||||
|
what: &str,
|
||||||
|
) -> Result<Result<Value, String>, String> {
|
||||||
|
match tokio::time::timeout(Duration::from_secs(secs), fut).await {
|
||||||
|
Ok(r) => Ok(r),
|
||||||
|
Err(_) => Err(format!("{what}超时")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 读到指定 `type` 的消息为止(其余消息按协议回 pong / 跳过)。
|
||||||
|
async fn wait_for_type(stream: &mut WsStream, want: &str) -> Result<Value, String> {
|
||||||
|
wait_for_any(stream, &[want]).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn wait_for_any(stream: &mut WsStream, want: &[&str]) -> Result<Value, String> {
|
||||||
|
loop {
|
||||||
|
match stream.next().await {
|
||||||
|
Some(Ok(Message::Text(text))) => {
|
||||||
|
let Ok(v) = serde_json::from_str::<Value>(&text) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let ty = v.get("type").and_then(|x| x.as_str()).unwrap_or("");
|
||||||
|
if want.contains(&ty) {
|
||||||
|
return Ok(v);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some(Ok(Message::Ping(payload))) => {
|
||||||
|
let _ = stream.send(Message::Pong(payload)).await;
|
||||||
|
}
|
||||||
|
Some(Ok(Message::Close(_))) | None => {
|
||||||
|
return Err("连接被服务端关闭".to_string());
|
||||||
|
}
|
||||||
|
Some(Err(e)) => return Err(format!("WebSocket 读取失败:{e}")),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 供 `commands` 复用的等待超时。
|
||||||
|
pub fn request_timeout() -> Duration {
|
||||||
|
Duration::from_secs(REQUEST_TIMEOUT_SECS)
|
||||||
|
}
|
||||||
@@ -24,7 +24,9 @@ const displayModules = computed(() => {
|
|||||||
class="w-17 shrink-0 flex flex-col items-center py-4 border-r border-border transition-[background-color,border-color] duration-300"
|
class="w-17 shrink-0 flex flex-col items-center py-4 border-r border-border transition-[background-color,border-color] duration-300"
|
||||||
:style="{ backgroundColor: 'var(--effect-bg)', backdropFilter: 'var(--effect-blur)' }"
|
:style="{ backgroundColor: 'var(--effect-bg)', backdropFilter: 'var(--effect-blur)' }"
|
||||||
>
|
>
|
||||||
<div class="flex flex-col gap-1">
|
<!-- 模块列表:超出侧边栏高度时可滚动(隐藏滚动条),避免把底部的「常规设置」挤出视口 -->
|
||||||
|
<div class="sidebar-scroll w-full flex-1 min-h-0 overflow-y-auto">
|
||||||
|
<div class="flex flex-col items-center gap-1">
|
||||||
<div v-for="module in displayModules" :key="module.id">
|
<div v-for="module in displayModules" :key="module.id">
|
||||||
<Tooltip>
|
<Tooltip>
|
||||||
<TooltipTrigger as-child>
|
<TooltipTrigger as-child>
|
||||||
@@ -47,9 +49,10 @@ const displayModules = computed(() => {
|
|||||||
</Tooltip>
|
</Tooltip>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="flex-1"></div>
|
<!-- 常规设置:固定在底部,不参与滚动 -->
|
||||||
|
<div class="shrink-0 pt-1">
|
||||||
<Tooltip>
|
<Tooltip>
|
||||||
<TooltipTrigger as-child>
|
<TooltipTrigger as-child>
|
||||||
<Button
|
<Button
|
||||||
@@ -69,5 +72,17 @@ const displayModules = computed(() => {
|
|||||||
<p>常规设置</p>
|
<p>常规设置</p>
|
||||||
</TooltipContent>
|
</TooltipContent>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
|
</div>
|
||||||
</aside>
|
</aside>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
/* 模块列表滚动条隐藏(Firefox + Chromium),滚动仍可用 */
|
||||||
|
.sidebar-scroll {
|
||||||
|
scrollbar-width: none;
|
||||||
|
}
|
||||||
|
.sidebar-scroll::-webkit-scrollbar {
|
||||||
|
width: 0;
|
||||||
|
height: 0;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -98,6 +98,25 @@ export const commands = {
|
|||||||
quickpanelClearAppIconCache: () => __TAURI_INVOKE<null>("quickpanel_clear_app_icon_cache"),
|
quickpanelClearAppIconCache: () => __TAURI_INVOKE<null>("quickpanel_clear_app_icon_cache"),
|
||||||
/** 在资源管理器中显示文件(选中) */
|
/** 在资源管理器中显示文件(选中) */
|
||||||
quickpanelRevealInExplorer: (path: string) => __TAURI_INVOKE<null>("quickpanel_reveal_in_explorer", { path }),
|
quickpanelRevealInExplorer: (path: string) => __TAURI_INVOKE<null>("quickpanel_reveal_in_explorer", { path }),
|
||||||
|
/**
|
||||||
|
* 在资源管理器中定位文件(选中)并**进入重命名编辑状态**。
|
||||||
|
*
|
||||||
|
* # 为什么不用 `explorer.exe /select,`
|
||||||
|
*
|
||||||
|
* 本仓原先的定位做法是 `ShellExecuteW("explorer.exe", "/select,\"path\"")`。
|
||||||
|
* 那条命令行在 Win10/11 上**经常新开一个窗口**而不是复用用户已经打开的那个
|
||||||
|
* (尤其目标文件夹已通过标签页 / 其他窗口打开时)—— 表现就是"点保存后又弹出
|
||||||
|
* 一个资源管理器打开了这个文件夹"。`SHOpenFolderAndSelectItems` 才是 shell 为此
|
||||||
|
* 提供的 API:复用已有窗口、滚到条目并选中,随后该窗口即为前台窗口。
|
||||||
|
*
|
||||||
|
* 重命名仍然只能借 Explorer 自己的快捷键 F2 —— shell 没有"开始重命名"的 API。
|
||||||
|
*
|
||||||
|
* `spawn_blocking`:命令里有 sleep;同时 shell 调用要求 **STA** 线程,而 async 命令
|
||||||
|
* 跑在 tokio 工作线程(MTA)上 —— 所以在工作线程里自己
|
||||||
|
* `CoInitializeEx(APARTMENTTHREADED)`(与 `quickpanel::explorer` 同一做法),
|
||||||
|
* 既不占 IPC 线程,也不依赖命令所在线程的既有套间模型。
|
||||||
|
*/
|
||||||
|
quickpanelRevealInExplorerRename: (path: string) => __TAURI_INVOKE<null>("quickpanel_reveal_in_explorer_rename", { path }),
|
||||||
/**
|
/**
|
||||||
* 用系统默认程序打开文件/文件夹。
|
* 用系统默认程序打开文件/文件夹。
|
||||||
* - 目录:explorer.exe 直接打开(修复索引目录点击后未打开的问题)
|
* - 目录:explorer.exe 直接打开(修复索引目录点击后未打开的问题)
|
||||||
@@ -1164,6 +1183,101 @@ export const commands = {
|
|||||||
* 「清空快捷键」也能通过传空串生效)—— 同 `editor_save_settings`。
|
* 「清空快捷键」也能通过传空串生效)—— 同 `editor_save_settings`。
|
||||||
*/
|
*/
|
||||||
diffSaveSettings: (settings: DiffSettings) => __TAURI_INVOKE<DiffSettings>("diff_save_settings", { settings }),
|
diffSaveSettings: (settings: DiffSettings) => __TAURI_INVOKE<DiffSettings>("diff_save_settings", { settings }),
|
||||||
|
/** 读取模块设置视图(连接列表 + 偏好;令牌只有掩码)。 */
|
||||||
|
smarthomeGetSettings: () => __TAURI_INVOKE<HaSettingsView>("smarthome_get_settings"),
|
||||||
|
/**
|
||||||
|
* 新建或更新一条连接(令牌**不在**此命令里,见 `smarthome_set_token`)。
|
||||||
|
*
|
||||||
|
* 地址可能刚被改动,已建立的实时连接仍粘在旧端点上 → 重连一次(P4)。
|
||||||
|
*/
|
||||||
|
smarthomeSaveConnection: (input: HaConnectionInput) => __TAURI_INVOKE<HaSaveConnectionResult>("smarthome_save_connection", { input }),
|
||||||
|
/**
|
||||||
|
* 写入长期访问令牌(进系统凭据管理器,**不落 settings.json**)。
|
||||||
|
*
|
||||||
|
* 令牌换了,已经建立的实时连接用的还是旧令牌 → 重连一次。
|
||||||
|
*/
|
||||||
|
smarthomeSetToken: (connId: string, token: string) => __TAURI_INVOKE<HaSettingsView>("smarthome_set_token", { connId, token }),
|
||||||
|
/** 清除令牌(连接本身保留)。 */
|
||||||
|
smarthomeClearToken: (connId: string) => __TAURI_INVOKE<HaSettingsView>("smarthome_clear_token", { connId }),
|
||||||
|
/** 删除一条连接(连带清除它的令牌)。 */
|
||||||
|
smarthomeDeleteConnection: (connId: string) => __TAURI_INVOKE<HaSettingsView>("smarthome_delete_connection", { connId }),
|
||||||
|
/** 切换激活连接。 */
|
||||||
|
smarthomeActivateConnection: (connId: string) => __TAURI_INVOKE<HaSettingsView>("smarthome_activate_connection", { connId }),
|
||||||
|
/**
|
||||||
|
* 修改端点选择策略(auto / local / remote)。
|
||||||
|
*
|
||||||
|
* 策略变了,实时连接也应当按新策略重新选端点 → 重连一次。
|
||||||
|
*/
|
||||||
|
smarthomeSetEndpointMode: (connId: string, mode: EndpointMode) => __TAURI_INVOKE<HaSettingsView>("smarthome_set_endpoint_mode", { connId, mode }),
|
||||||
|
/**
|
||||||
|
* 测试连接:**逐个地址**探测,每个地址各给一条结果。
|
||||||
|
*
|
||||||
|
* `token` 留空时回落到该连接已存的令牌(编辑连接时不必重输)。
|
||||||
|
* 草案也能直接测(不必先保存)——`input.id` 为空只是没有回落令牌可用。
|
||||||
|
*/
|
||||||
|
smarthomeTestConnection: (input: HaConnectionInput, token: string) => __TAURI_INVOKE<EndpointProbe[]>("smarthome_test_connection", { input, token }),
|
||||||
|
/** 检测当前链路:按端点策略**强制新探测**一次,返回实际使用的地址与耗时。 */
|
||||||
|
smarthomeCheckLink: (connId: string) => __TAURI_INVOKE<LinkInfo>("smarthome_check_link", { connId }),
|
||||||
|
/**
|
||||||
|
* 拉取实体列表(精简视图)。
|
||||||
|
*
|
||||||
|
* `force = false` 且内存缓存未过期(60s)时直接返回缓存 —— 在反代链路上,
|
||||||
|
* 每次切回设备页都重新拉几百 KB 是明显的浪费(§5.2)。
|
||||||
|
*/
|
||||||
|
smarthomeListEntities: (connId: string, force: boolean) => __TAURI_INVOKE<EntityListResult>("smarthome_list_entities", { connId, force }),
|
||||||
|
/**
|
||||||
|
* 保存界面偏好(自动刷新间隔 / 收藏等)。
|
||||||
|
*
|
||||||
|
* 整体覆盖写入:偏好字段少且同屏修改,没必要为每个开关单开一条命令
|
||||||
|
* (多命令各自的字段同步反倒容易漏)。
|
||||||
|
*
|
||||||
|
* 注意:**实时推送开关不在 `ui` 里**(它在 `settings.realtime`),
|
||||||
|
* 因此这里不碰实时连接;收藏 / 自动刷新这类改动不该引起重连。
|
||||||
|
*/
|
||||||
|
smarthomeSaveUiSettings: (ui: HaUiSettings) => __TAURI_INVOKE<HaSettingsView>("smarthome_save_ui_settings", { ui }),
|
||||||
|
/**
|
||||||
|
* 调用设备服务(控制)。
|
||||||
|
*
|
||||||
|
* 前端流程(§5.3):乐观更新 → 本命令 → **若响应带回新状态就直接采用**(省一次往返),
|
||||||
|
* 否则在分级窗口后调 `smarthome_get_entity` 校正。
|
||||||
|
*/
|
||||||
|
smarthomeCallService: (connId: string, domain: string, service: string, entityId: string, params: ServiceParams) => __TAURI_INVOKE<ServiceCallResult>("smarthome_call_service", { connId, domain, service, entityId, params }),
|
||||||
|
/** 取单个实体状态(控制后的校正用,不是常规路径)。 */
|
||||||
|
smarthomeGetEntity: (connId: string, entityId: string) => __TAURI_INVOKE<EntitySummary>("smarthome_get_entity", { connId, entityId }),
|
||||||
|
/**
|
||||||
|
* 开关实时推送(WebSocket)。
|
||||||
|
*
|
||||||
|
* 打开 = 建立 WS(设备状态不再依赖手动刷新);关闭 = 断开。
|
||||||
|
* **本地规则也依赖它**:只要规则总开关开着,关掉推送 Rust 侧仍会保持连接
|
||||||
|
* (见 `HaManager::sync_ws`)—— 规则没连接永远不会触发。
|
||||||
|
*/
|
||||||
|
smarthomeSetRealtimeEnabled: (enabled: boolean) => __TAURI_INVOKE<HaSettingsView>("smarthome_set_realtime_enabled", { enabled }),
|
||||||
|
/** 启动实时连接(显式动作)。 */
|
||||||
|
smarthomeWsStart: (connId: string) => __TAURI_INVOKE<WsStatus>("smarthome_ws_start", { connId }),
|
||||||
|
/** 停止实时连接(**不改持久化开关**:设置页的开关走 `smarthome_set_realtime_enabled`)。 */
|
||||||
|
smarthomeWsStop: () => __TAURI_INVOKE<WsStatus>("smarthome_ws_stop"),
|
||||||
|
/** 当前实时连接状态(诊断用)。 */
|
||||||
|
smarthomeWsStatus: () => __TAURI_INVOKE<WsStatus>("smarthome_ws_status"),
|
||||||
|
/**
|
||||||
|
* 拉取区域 / 设备 / 实体注册表,返回 `entity_id → area_id`(三级回退已算好)。
|
||||||
|
*
|
||||||
|
* **需要实时连接**:注册表只能通过 WebSocket 查(plan §0.4),因此这里显式依赖
|
||||||
|
* `smarthome_ws_start` 已经连上;没连上就给出可操作的错误文案(不是笼统的"失败")。
|
||||||
|
*/
|
||||||
|
smarthomeListRegistry: (connId: string, force: boolean) => __TAURI_INVOKE<RegistryResult>("smarthome_list_registry", { connId, force }),
|
||||||
|
/** 规则列表(含总开关与最近运行记录)。 */
|
||||||
|
smarthomeListRules: () => __TAURI_INVOKE<RuleListResult>("smarthome_list_rules"),
|
||||||
|
/**
|
||||||
|
* 新建或更新一条规则。
|
||||||
|
*
|
||||||
|
* **动作的合法性只在 Rust 侧判定一次**(`automation::validate`):前端可以少校验,
|
||||||
|
* 但"能不能真的执行"这套规则必须只有一份。
|
||||||
|
*/
|
||||||
|
smarthomeSaveRule: (rule: Rule) => __TAURI_INVOKE<RuleListResult>("smarthome_save_rule", { rule }),
|
||||||
|
/** 删除一条规则。 */
|
||||||
|
smarthomeDeleteRule: (ruleId: string) => __TAURI_INVOKE<RuleListResult>("smarthome_delete_rule", { ruleId }),
|
||||||
|
/** 规则总开关(关掉后所有规则都不求值,规则本身保留)。 */
|
||||||
|
smarthomeSetRulesEnabled: (enabled: boolean) => __TAURI_INVOKE<RuleListResult>("smarthome_set_rules_enabled", { enabled }),
|
||||||
/**
|
/**
|
||||||
* 设置某个窗口的任务栏身份(独立 AUMID + 组合图标)。
|
* 设置某个窗口的任务栏身份(独立 AUMID + 组合图标)。
|
||||||
*
|
*
|
||||||
@@ -2045,6 +2159,50 @@ export type EditorSettings = {
|
|||||||
recentFolders?: RecentEntry[],
|
recentFolders?: RecentEntry[],
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** 端点(链路)类型。 */
|
||||||
|
export type EndpointKind =
|
||||||
|
/** 局域网直连 */
|
||||||
|
"local" |
|
||||||
|
/** 反代(Cloudflare Tunnel 等) */
|
||||||
|
"remote";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 端点选择策略。
|
||||||
|
*
|
||||||
|
* 探测顺序与超时见 `client.rs` 的常量;`auto` 是「先短超时试局域网、失败再试反代」,
|
||||||
|
* 而不是「优先上次成功的端点」—— 后者会把人困在反代上:回家后反代仍然可用,
|
||||||
|
* 就永远不会切回局域网(§3.7-a)。
|
||||||
|
*/
|
||||||
|
export type EndpointMode =
|
||||||
|
/** 自动(局域网优先,反代兜底) */
|
||||||
|
"auto" |
|
||||||
|
/** 强制局域网 */
|
||||||
|
"local" |
|
||||||
|
/** 强制反代 */
|
||||||
|
"remote";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 单个地址的探测结果(「测试连接」逐地址返回)。
|
||||||
|
*
|
||||||
|
* 逐地址给结果而不是一个笼统的成功/失败:用户在外面测时,局域网失败是**预期内**的,
|
||||||
|
* 只有把两条链路的结果分开呈现,这个信息才有用(§5.1)。
|
||||||
|
*/
|
||||||
|
export type EndpointProbe = {
|
||||||
|
url: string,
|
||||||
|
kind: EndpointKind,
|
||||||
|
ok: boolean,
|
||||||
|
haVersion: string,
|
||||||
|
locationName: string,
|
||||||
|
/** 实例的温度单位(见 `HaConnection::temperature_unit`) */
|
||||||
|
temperatureUnit: string,
|
||||||
|
/** 耗时(毫秒):既是诊断信息,也是"反代比局域网慢多少"的直觉来源 */
|
||||||
|
elapsedMs: number,
|
||||||
|
/** 失败原因(中文可读) */
|
||||||
|
error: string | null,
|
||||||
|
/** 失败分类:auth | network | server | other(前端据此决定是否提示"重填令牌") */
|
||||||
|
errorKind: string | null,
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 引擎连通性自检结果。
|
* 引擎连通性自检结果。
|
||||||
*
|
*
|
||||||
@@ -2079,6 +2237,114 @@ export type EngineView = {
|
|||||||
issue: string | null,
|
issue: string | null,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** 实体列表结果。 */
|
||||||
|
export type EntityListResult = {
|
||||||
|
entities: EntitySummary[],
|
||||||
|
/**
|
||||||
|
* 抓取时间(unix 秒)。"更新于 x 秒前"必须用它 —— 那是**服务端数据的时刻**,
|
||||||
|
* 而不是前端收到响应的时刻。
|
||||||
|
*/
|
||||||
|
fetchedAt: number,
|
||||||
|
/** true = 命中内存缓存,未重新请求 */
|
||||||
|
fromCache: boolean,
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 实体注册表条目(**设备聚合的唯一来源**:REST 的 `/api/states` 里没有 device_id)。 */
|
||||||
|
export type EntityRegistryEntry = {
|
||||||
|
entityId: string,
|
||||||
|
/** 空 = 未归组到设备(真机上是 `person` / `todo` 这类) */
|
||||||
|
deviceId: string,
|
||||||
|
/** 注册表里的名字(小米集成上**大量为空**,因此只作兜底) */
|
||||||
|
name: string,
|
||||||
|
/** 集成给的原始名字 */
|
||||||
|
originalName: string,
|
||||||
|
/**
|
||||||
|
* `""` | `config` | `diagnostic` —— HA 官方标记的"高级 / 配置"类实体。
|
||||||
|
*
|
||||||
|
* 真机上只有 30/606 条有值,所以它只是"三级"的**判据之一**,不是全部。
|
||||||
|
*/
|
||||||
|
entityCategory: string,
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 实体摘要(发给前端的**精简结构**)。
|
||||||
|
*
|
||||||
|
* 只带前端**要显示**的字段。完整 `attributes` 因 domain 而异(灯有
|
||||||
|
* `supported_color_modes`、窗帘有 `current_position`、气候有 `hvac_modes`…),
|
||||||
|
* 几百个实体整份过 IPC 会让序列化与前端响应式都明显变重(§6.1)。
|
||||||
|
*
|
||||||
|
* 「是否可控 / 分组 / 图标 / 状态文案」这类**表现层语义由前端 `format.ts` 决定**,
|
||||||
|
* 不在这里算 —— Rust 侧只负责"协议 → 数据的忠实搬运"。
|
||||||
|
*/
|
||||||
|
export type EntitySummary = {
|
||||||
|
entityId: string,
|
||||||
|
/** `entity_id` 的前半段(light / switch / sensor…) */
|
||||||
|
domain: string,
|
||||||
|
/** `friendly_name`,缺失时回落 `entity_id` */
|
||||||
|
name: string,
|
||||||
|
/** 原始状态字符串:`on` / `off` / `24.5` / `unavailable` / `unknown` … */
|
||||||
|
state: string,
|
||||||
|
/** `state` 可解析为数字时的数值(sensor 这类读数就在 `state` 里) */
|
||||||
|
numeric: number | null,
|
||||||
|
/** `unit_of_measurement` */
|
||||||
|
unit: string,
|
||||||
|
/** `device_class`(binary_sensor / sensor 的语义细分) */
|
||||||
|
deviceClass: string,
|
||||||
|
/** 灯亮度 0–255 */
|
||||||
|
brightness: number | null,
|
||||||
|
/** 窗帘当前位置 0–100 */
|
||||||
|
position: number | null,
|
||||||
|
/** 空调目标温度 */
|
||||||
|
targetTemp: number | null,
|
||||||
|
/**
|
||||||
|
* 空调可设的上下限(**单位随系统单位制**,如美制是 61–86 °F)。
|
||||||
|
* 控件必须用它,不能自己写死 5–35 —— 美制下 77 会被钳成 35(真机踩到过)。
|
||||||
|
*/
|
||||||
|
minTemp: number | null,
|
||||||
|
maxTemp: number | null,
|
||||||
|
/** 空调当前温度(室温) */
|
||||||
|
currentTemp: number | null,
|
||||||
|
/** 最后变化时间(HA 的 ISO8601 串,前端格式化成相对时间) */
|
||||||
|
lastChanged: string,
|
||||||
|
/**
|
||||||
|
* `attributes.last_triggered` —— 自动化 / 脚本的"上次触发时间"(空 = 从未触发)。
|
||||||
|
* P3 的自动化列表要靠它回答"这条规则最近到底跑没跑"。
|
||||||
|
*/
|
||||||
|
lastTriggered: string,
|
||||||
|
/**
|
||||||
|
* HA 的 `supported_features` 位掩码。**语义按 domain 不同**(窗帘 OPEN/CLOSE/…、
|
||||||
|
* 气候 TARGET_TEMPERATURE/…),因此这里原样透传,由前端按 domain 解释。
|
||||||
|
*/
|
||||||
|
supportedFeatures: number,
|
||||||
|
/**
|
||||||
|
* 灯的 `supported_color_modes`(`onoff` / `brightness` / `color_temp` / `hs` …)。
|
||||||
|
* 判断"能不能调亮度 / 色温"必须用它,而不是 `supported_features` 的旧位约定。
|
||||||
|
*/
|
||||||
|
supportedColorModes: string[],
|
||||||
|
/** 色温可调范围(灯) */
|
||||||
|
minColorTempKelvin: number | null,
|
||||||
|
maxColorTempKelvin: number | null,
|
||||||
|
/**
|
||||||
|
* 当前色温(灯)。**必须有**:没有它,色温滑杆只能猜一个初始位置,
|
||||||
|
* 那就成了一个会骗人的控件。
|
||||||
|
*/
|
||||||
|
colorTempKelvin: number | null,
|
||||||
|
/** 空调可选模式(cool / heat / off / auto …) */
|
||||||
|
hvacModes: string[],
|
||||||
|
/** 空调温度步进(0.5 / 1) */
|
||||||
|
targetTempStep: number | null,
|
||||||
|
/** 媒体播放器音量 0.0–1.0 */
|
||||||
|
volumeLevel: number | null,
|
||||||
|
/** 风扇档位 0–100 */
|
||||||
|
percentage: number | null,
|
||||||
|
/** `number` 实体的可设上下限与步长(各集成差异极大:0–100 音量、10–90 变焦、步长 180 的翻转角) */
|
||||||
|
min: number | null,
|
||||||
|
max: number | null,
|
||||||
|
step: number | null,
|
||||||
|
/** `select` 实体的可选项 */
|
||||||
|
options: string[],
|
||||||
|
};
|
||||||
|
|
||||||
export type EnvVar = {
|
export type EnvVar = {
|
||||||
key?: string,
|
key?: string,
|
||||||
value?: string,
|
value?: string,
|
||||||
@@ -2194,6 +2460,113 @@ export type FingerprintChange = {
|
|||||||
accepted?: boolean,
|
accepted?: boolean,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 命令层错误:带分类。
|
||||||
|
*
|
||||||
|
* 前端据此区分"重填令牌"(`auth`,重试无意义)与"重试 / 检查地址"
|
||||||
|
* (`network` / `config`)—— **分类判定留在 Rust 侧**,不让前端靠匹配错误文案猜(§3.6)。
|
||||||
|
* 这是本项目第一个不用 `String` 作错误类型的命令模块;理由见 §9.1。
|
||||||
|
*/
|
||||||
|
export type HaApiError = {
|
||||||
|
/** auth | network | config | server | other */
|
||||||
|
kind: string,
|
||||||
|
message: string,
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 区域(房间)。 */
|
||||||
|
export type HaArea = {
|
||||||
|
areaId: string,
|
||||||
|
name: string,
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 前端提交的连接草案(新建或编辑)。令牌**不在此结构里**,走独立命令写入凭据库。 */
|
||||||
|
export type HaConnectionInput = {
|
||||||
|
/** 空 = 新建 */
|
||||||
|
id?: string,
|
||||||
|
name?: string,
|
||||||
|
localUrl?: string,
|
||||||
|
remoteUrl?: string,
|
||||||
|
endpointMode?: EndpointMode,
|
||||||
|
insecure?: boolean,
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 发给前端的连接视图:**不含明文令牌**,只有掩码与"是否已配置"。 */
|
||||||
|
export type HaConnectionView = {
|
||||||
|
id: string,
|
||||||
|
name: string,
|
||||||
|
localUrl: string,
|
||||||
|
remoteUrl: string,
|
||||||
|
endpointMode: EndpointMode,
|
||||||
|
insecure: boolean,
|
||||||
|
hasToken: boolean,
|
||||||
|
/** 掩码(`secrets::mask`):长度不足 8 时整串打码,绝不泄露完整明文 */
|
||||||
|
tokenMasked: string,
|
||||||
|
lastOkUrl: string,
|
||||||
|
lastOkAt: number,
|
||||||
|
haVersion: string,
|
||||||
|
locationName: string,
|
||||||
|
/** 温度单位(`°C` / `°F`)—— climate 的温度显示必须用它 */
|
||||||
|
temperatureUnit: string,
|
||||||
|
/** 本次会话实际使用的端点(未探测过为 null) */
|
||||||
|
endpointUrl: string | null,
|
||||||
|
endpointKind: EndpointKind | null,
|
||||||
|
/** 该端点最近一次实测耗时(毫秒) */
|
||||||
|
endpointLatencyMs: number | null,
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 设备(设备聚合与详情页头部所需的最小字段集合)。 */
|
||||||
|
export type HaDevice = {
|
||||||
|
id: string,
|
||||||
|
name: string,
|
||||||
|
/** 用户在 HA 里改过的名字(为空时用 `name`) */
|
||||||
|
nameByUser: string,
|
||||||
|
/** 空 = 未分配房间 */
|
||||||
|
areaId: string,
|
||||||
|
/** 厂商 / 型号(详情页头部显示,便于认出是哪台设备) */
|
||||||
|
manufacturer: string,
|
||||||
|
model: string,
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 实时推送配置(P4 才真正使用;P0 只落字段,避免以后升级设置结构)。 */
|
||||||
|
export type HaRealtimeSettings = {
|
||||||
|
/** 是否启用 WebSocket 实时推送 */
|
||||||
|
enabled?: boolean,
|
||||||
|
/** 上次连接成功时间(unix 秒,0 = 从未) */
|
||||||
|
lastConnectedAt?: number,
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 保存连接的结果:**回传 id**(新建时前端要靠它接着写令牌,按名称/地址反查不可靠),
|
||||||
|
* 外加刷新后的整份视图。
|
||||||
|
*/
|
||||||
|
export type HaSaveConnectionResult = {
|
||||||
|
id: string,
|
||||||
|
settings: HaSettingsView,
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 模块设置视图。 */
|
||||||
|
export type HaSettingsView = {
|
||||||
|
version: number,
|
||||||
|
activeId: string,
|
||||||
|
connections: HaConnectionView[],
|
||||||
|
ui: HaUiSettings,
|
||||||
|
realtime: HaRealtimeSettings,
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 界面与行为偏好。 */
|
||||||
|
export type HaUiSettings = {
|
||||||
|
/** 自动刷新间隔(秒),0 = 关闭 */
|
||||||
|
autoRefreshSec?: number,
|
||||||
|
/** 不展示的 domain(如 `sensor` 太多时可隐藏) */
|
||||||
|
hiddenDomains?: string[],
|
||||||
|
/** 不展示的具体实体 */
|
||||||
|
hiddenEntityIds?: string[],
|
||||||
|
/** 收藏(置顶) */
|
||||||
|
favoriteEntityIds?: string[],
|
||||||
|
/** 危险操作(解锁 / 开门 / 全开)二次确认 */
|
||||||
|
confirmDangerous?: boolean,
|
||||||
|
};
|
||||||
|
|
||||||
/** 一条历史记录 */
|
/** 一条历史记录 */
|
||||||
export type HistoryItem = {
|
export type HistoryItem = {
|
||||||
id: number,
|
id: number,
|
||||||
@@ -2444,6 +2817,24 @@ export type LinkEdge = {
|
|||||||
to: string,
|
to: string,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 当前链路信息(诊断区)。
|
||||||
|
*
|
||||||
|
* 失败时 `url` / `kind` 也可能为空 —— 例如 `auto` 模式下两个地址都不可达,
|
||||||
|
* 这时没有"当前链路"可言,只能把失败原因(包含每个地址的尝试结果)交给前端展示。
|
||||||
|
*/
|
||||||
|
export type LinkInfo = {
|
||||||
|
url: string | null,
|
||||||
|
kind: EndpointKind | null,
|
||||||
|
ok: boolean,
|
||||||
|
/** 成功时:该端点实测耗时(毫秒)。失败时为 0 */
|
||||||
|
latencyMs: number,
|
||||||
|
/** 失败原因(含各候选地址的尝试结果) */
|
||||||
|
error: string | null,
|
||||||
|
/** 失败分类:auth | network | config(前端据此决定提示"重填令牌"还是"重试") */
|
||||||
|
errorKind: string | null,
|
||||||
|
};
|
||||||
|
|
||||||
/** 目录列举结果。 */
|
/** 目录列举结果。 */
|
||||||
export type LocalDir = {
|
export type LocalDir = {
|
||||||
/** 规范化之后的目录(`canonicalize` 结果,已去掉 Windows 的 `\\?\` 前缀) */
|
/** 规范化之后的目录(`canonicalize` 结果,已去掉 Windows 的 `\\?\` 前缀) */
|
||||||
@@ -2965,6 +3356,24 @@ export type RecentEntry = {
|
|||||||
exists?: boolean,
|
exists?: boolean,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 注册表查询结果(房间分组 + 设备聚合的唯一来源)。
|
||||||
|
*
|
||||||
|
* **真机修正(§9.5-1)**:目标实例上实体级 `area_id` 全空,房间归属在设备上,
|
||||||
|
* 因此 `entity_areas` 已按「实体 → 设备 → 区域」三级回退算好;仍未解析到的不进表
|
||||||
|
* (前端把它归入「未分配房间」,这是必需的分组而不是兜底)。
|
||||||
|
*/
|
||||||
|
export type RegistryResult = {
|
||||||
|
areas: HaArea[],
|
||||||
|
devices: HaDevice[],
|
||||||
|
/** `entity_id` → `area_id` */
|
||||||
|
entityAreas: { [key in string]: string },
|
||||||
|
/** 实体注册表(`entity_id` → 设备 / 名字 / 分类) */
|
||||||
|
entityRegistry: EntityRegistryEntry[],
|
||||||
|
/** 抓取时间(unix 秒) */
|
||||||
|
fetchedAt: number,
|
||||||
|
};
|
||||||
|
|
||||||
/** 远程配置(§5.1 命令 `remote_get_config` / `remote_set_enabled`)。 */
|
/** 远程配置(§5.1 命令 `remote_get_config` / `remote_set_enabled`)。 */
|
||||||
export type RemoteConfig = {
|
export type RemoteConfig = {
|
||||||
/** 开关(持久化) */
|
/** 开关(持久化) */
|
||||||
@@ -3031,6 +3440,94 @@ export type RenameResult = {
|
|||||||
error: string,
|
error: string,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** 一条本地规则。 */
|
||||||
|
export type Rule = {
|
||||||
|
id?: string,
|
||||||
|
name?: string,
|
||||||
|
enabled?: boolean,
|
||||||
|
trigger?: RuleTrigger,
|
||||||
|
conditions?: RuleCondition[],
|
||||||
|
actions?: RuleAction[],
|
||||||
|
/** 冷却秒数:窗口内的重复触发直接丢弃(护栏 1) */
|
||||||
|
cooldownSec?: number,
|
||||||
|
/** 上次触发时间(unix 秒,0 = 从未) */
|
||||||
|
lastFiredAt?: number,
|
||||||
|
/** 累计触发次数 */
|
||||||
|
fireCount?: number,
|
||||||
|
/** 上次失败原因(空 = 上次正常) */
|
||||||
|
lastError?: string,
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 规则动作段(顺序执行)。 */
|
||||||
|
export type RuleAction = {
|
||||||
|
/** service | delay | notify */
|
||||||
|
kind?: string,
|
||||||
|
/** `service`:domain / service / 目标实体 */
|
||||||
|
domain?: string,
|
||||||
|
service?: string,
|
||||||
|
entityId?: string,
|
||||||
|
params?: ServiceParams,
|
||||||
|
/** `delay`:秒(上限见 `automation::MAX_DELAY_SEC`) */
|
||||||
|
seconds?: number,
|
||||||
|
/** `notify`:标题与正文 */
|
||||||
|
title?: string,
|
||||||
|
message?: string,
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 规则条件段(全部 AND)。 */
|
||||||
|
export type RuleCondition = {
|
||||||
|
/** state | time */
|
||||||
|
kind?: string,
|
||||||
|
/** `state` 条件:实体 id */
|
||||||
|
entityId?: string,
|
||||||
|
/** `state` 条件:要求的状态 */
|
||||||
|
state?: string,
|
||||||
|
/** `time` 条件:起始 `HH:MM` */
|
||||||
|
fromTime?: string,
|
||||||
|
/** `time` 条件:结束 `HH:MM`(跨零点时 `to < from` 视为跨天) */
|
||||||
|
toTime?: string,
|
||||||
|
/** `time` 条件:星期(1=周一 … 7=周日;空 = 每天) */
|
||||||
|
weekdays?: number[],
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 规则列表结果(含总开关与最近运行记录)。
|
||||||
|
*
|
||||||
|
* 计划 §6.2 只列了 `Rule[]`,这里把「总开关 + 最近记录」并进同一个返回:
|
||||||
|
* 自动化页进来就要用这三样,拆成三条命令只是多两次往返。
|
||||||
|
*/
|
||||||
|
export type RuleListResult = {
|
||||||
|
/** 规则总开关(关掉后所有规则都不求值) */
|
||||||
|
enabled: boolean,
|
||||||
|
rules: Rule[],
|
||||||
|
/** 最近运行记录(新的在前,最多 `automation::MAX_RECORDS` 条;仅本次运行期内有) */
|
||||||
|
records: RuleRecord[],
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 规则运行记录(内存里保留最近 `automation::MAX_RECORDS` 条)。 */
|
||||||
|
export type RuleRecord = {
|
||||||
|
ruleId: string,
|
||||||
|
ruleName: string,
|
||||||
|
at: number,
|
||||||
|
ok: boolean,
|
||||||
|
detail: string,
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 规则触发段(线性三段式的第一段)。 */
|
||||||
|
export type RuleTrigger = {
|
||||||
|
entityId?: string,
|
||||||
|
/** 命中这些状态才触发(空 = 任意变化) */
|
||||||
|
to?: string[],
|
||||||
|
/** 仅当从这些状态变化而来(空 = 不限) */
|
||||||
|
from?: string[],
|
||||||
|
/** 持续 N 秒仍然满足才触发(0 = 立即;用于去抖) */
|
||||||
|
forSec?: number,
|
||||||
|
/** 数值比较运算符(空 = 不做数值判断;否则 `>` `>=` `<` `<=` `==` `!=`) */
|
||||||
|
numericOp?: string,
|
||||||
|
/** 数值比较的阈值 */
|
||||||
|
numericValue?: number | null,
|
||||||
|
};
|
||||||
|
|
||||||
/** `music_decrypt_scan` 的返回(前端零手写类型) */
|
/** `music_decrypt_scan` 的返回(前端零手写类型) */
|
||||||
export type ScanSummary = {
|
export type ScanSummary = {
|
||||||
total: number,
|
total: number,
|
||||||
@@ -3149,6 +3646,45 @@ export type SelectionSettings = {
|
|||||||
blacklist?: string[],
|
blacklist?: string[],
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** 服务调用结果。 */
|
||||||
|
export type ServiceCallResult = {
|
||||||
|
/**
|
||||||
|
* HA 在 `200` 响应体里带回的**已变化实体**新状态(已转成精简结构)。
|
||||||
|
*
|
||||||
|
* **可能为空**:部分集成(尤其走云端的设备)是"发完就返回",状态要稍后才反映。
|
||||||
|
* 前端据此决定"直接采用服务端结果"还是"等分级窗口后重拉一次"(§9.3)。
|
||||||
|
*/
|
||||||
|
entities: EntitySummary[],
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 服务调用的可选参数。
|
||||||
|
*
|
||||||
|
* **用固定字段而不是 `serde_json::Value`**:specta 无法为 `Value` 生成类型
|
||||||
|
* (见 lib.rs 的豁免清单);而且固定字段顺带把"能传什么参数"限死了,
|
||||||
|
* 前端不可能把任意键塞进 HA 的 `service_data`。
|
||||||
|
*/
|
||||||
|
export type ServiceParams = {
|
||||||
|
/** 灯亮度百分比 0–100(HA 侧换算成 `brightness`) */
|
||||||
|
brightnessPct?: number | null,
|
||||||
|
/** 色温(开尔文) */
|
||||||
|
colorTempKelvin?: number | null,
|
||||||
|
/** 窗帘位置 0–100 */
|
||||||
|
position?: number | null,
|
||||||
|
/** 空调目标温度 */
|
||||||
|
temperature?: number | null,
|
||||||
|
/** 空调模式(`cool` / `heat` / `off` …) */
|
||||||
|
hvacMode?: string | null,
|
||||||
|
/** 风扇档位 0–100 */
|
||||||
|
percentage?: number | null,
|
||||||
|
/** 媒体音量 0.0–1.0 */
|
||||||
|
volumeLevel?: number | null,
|
||||||
|
/** `number.set_value` 的目标值 */
|
||||||
|
value?: number | null,
|
||||||
|
/** `select.select_option` 的目标项 */
|
||||||
|
option?: string | null,
|
||||||
|
};
|
||||||
|
|
||||||
/** 会话元信息(回传前端;**不含任何 I/O 句柄**)。 */
|
/** 会话元信息(回传前端;**不含任何 I/O 句柄**)。 */
|
||||||
export type SessionInfo = {
|
export type SessionInfo = {
|
||||||
id: string,
|
id: string,
|
||||||
@@ -3742,3 +4278,18 @@ export type WindowInfo = {
|
|||||||
visualRect: ScreenRect | null,
|
visualRect: ScreenRect | null,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** WebSocket 连接状态(`smarthome_ws_status` 的返回,也是 `smarthome-connection-status` 的载荷)。 */
|
||||||
|
export type WsStatus = {
|
||||||
|
connId: string,
|
||||||
|
/** idle | connecting | connected | authFailed | disconnected */
|
||||||
|
state: string,
|
||||||
|
/** 失败原因 / 补充说明(正常时为空) */
|
||||||
|
detail: string,
|
||||||
|
/** 本次连上的时间(unix 秒,0 = 未连上) */
|
||||||
|
connectedAt: number,
|
||||||
|
/** 最近一次收到服务端消息的时间(unix 秒)—— 半开连接靠它判断 */
|
||||||
|
lastEventAt: number,
|
||||||
|
/** 已订阅到的实体数(`subscribe_entities` 首帧后写入) */
|
||||||
|
entityCount: number,
|
||||||
|
};
|
||||||
|
|
||||||
@@ -1119,7 +1119,7 @@ async function saveThenRedecode(): Promise<void> {
|
|||||||
</TooltipProvider>
|
</TooltipProvider>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<!-- 主体:侧栏自导航行起贯通到底;导航行 / 标签栏 / 编辑器同处右侧「编辑列」 -->
|
<!-- 主体:侧栏自导航行起贯通到底;导航行 / 搜索栏 / 编辑区同处右侧「编辑列」 -->
|
||||||
<div class="flex min-h-0 flex-1">
|
<div class="flex min-h-0 flex-1">
|
||||||
<LibrarySidebar v-if="sidebarVisible" ref="sidebarRef" @open="store.openNote($event)" />
|
<LibrarySidebar v-if="sidebarVisible" ref="sidebarRef" @open="store.openNote($event)" />
|
||||||
|
|
||||||
@@ -1141,19 +1141,6 @@ async function saveThenRedecode(): Promise<void> {
|
|||||||
@open-search="openSearch(searchDir ? 'dir' : 'library')"
|
@open-search="openSearch(searchDir ? 'dir' : 'library')"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<!-- 文档标签栏(多文档) -->
|
|
||||||
<EditorTabs
|
|
||||||
v-if="store.tabs.length"
|
|
||||||
:preview-ids="previewIds"
|
|
||||||
@close="requestCloseTab"
|
|
||||||
@toggle-preview="togglePreview"
|
|
||||||
@close-others="requestCloseTabs(tabIdsExcept($event))"
|
|
||||||
@close-left="requestCloseTabs(tabIdsLeftOf($event))"
|
|
||||||
@close-right="requestCloseTabs(tabIdsRightOf($event))"
|
|
||||||
@close-all="requestCloseTabs(store.tabs.map(t => t.id))"
|
|
||||||
@split="openSplit"
|
|
||||||
/>
|
|
||||||
|
|
||||||
<!-- 外部改动提示(有未保存改动时才会出现) -->
|
<!-- 外部改动提示(有未保存改动时才会出现) -->
|
||||||
<div
|
<div
|
||||||
v-if="store.externalChange"
|
v-if="store.externalChange"
|
||||||
@@ -1191,6 +1178,24 @@ async function saveThenRedecode(): Promise<void> {
|
|||||||
@replaced="onPathReplaced"
|
@replaced="onPathReplaced"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
<!-- 「并排分屏」行:不分屏时整行占满;分屏时左右各半 ——
|
||||||
|
左半是「标签栏 + 编辑栏」,右半是副文档(各带自己的 8px 标题行)。
|
||||||
|
副文档是**并排的一列**,不是嵌在编辑栏内部的一块。 -->
|
||||||
|
<div class="flex min-h-0 min-w-0 flex-1">
|
||||||
|
<div class="flex min-h-0 min-w-0 flex-col" :class="splitTab ? 'w-1/2' : 'flex-1'">
|
||||||
|
<!-- 文档标签栏(多文档):属于左半这一列 -->
|
||||||
|
<EditorTabs
|
||||||
|
v-if="store.tabs.length"
|
||||||
|
:preview-ids="previewIds"
|
||||||
|
@close="requestCloseTab"
|
||||||
|
@toggle-preview="togglePreview"
|
||||||
|
@close-others="requestCloseTabs(tabIdsExcept($event))"
|
||||||
|
@close-left="requestCloseTabs(tabIdsLeftOf($event))"
|
||||||
|
@close-right="requestCloseTabs(tabIdsRightOf($event))"
|
||||||
|
@close-all="requestCloseTabs(store.tabs.map(t => t.id))"
|
||||||
|
@split="openSplit"
|
||||||
|
/>
|
||||||
|
|
||||||
<main class="flex min-h-0 min-w-0 flex-1">
|
<main class="flex min-h-0 min-w-0 flex-1">
|
||||||
<div class="relative flex min-h-0 min-w-0 flex-1 flex-col">
|
<div class="relative flex min-h-0 min-w-0 flex-1 flex-col">
|
||||||
<div v-if="!store.hasDocument" class="flex min-h-0 flex-1 items-center justify-center">
|
<div v-if="!store.hasDocument" class="flex min-h-0 flex-1 items-center justify-center">
|
||||||
@@ -1255,13 +1260,16 @@ async function saveThenRedecode(): Promise<void> {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
|
||||||
<!--
|
<!--
|
||||||
并排副面板:与主编辑列等宽,绑定**另一个标签**自己的缓冲(见 EditorHost 的 tabId)。
|
并排副栏:与「标签栏 + 编辑栏」这一列等宽,绑定**另一个标签**自己的缓冲
|
||||||
`:key` 保证换目标时整块重建(编辑器实例不可跨文档复用)。
|
(见 EditorHost 的 tabId)。`:key` 保证换目标时整块重建(编辑器实例不可跨文档复用)。
|
||||||
-->
|
-->
|
||||||
<div
|
<div
|
||||||
v-if="splitTab"
|
v-if="splitTab"
|
||||||
class="relative flex min-h-0 w-1/2 min-w-0 flex-col border-l border-border"
|
class="relative flex min-h-0 min-w-0 w-1/2 flex-col border-l border-border"
|
||||||
>
|
>
|
||||||
<div class="flex h-8 shrink-0 items-center gap-1.5 border-b border-border px-2 text-xs">
|
<div class="flex h-8 shrink-0 items-center gap-1.5 border-b border-border px-2 text-xs">
|
||||||
<FileText v-if="splitTab.kind === 'note'" class="size-3.5 shrink-0 opacity-70" />
|
<FileText v-if="splitTab.kind === 'note'" class="size-3.5 shrink-0 opacity-70" />
|
||||||
@@ -1285,8 +1293,7 @@ async function saveThenRedecode(): Promise<void> {
|
|||||||
class="min-h-0 flex-1"
|
class="min-h-0 flex-1"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
</main>
|
|
||||||
|
|
||||||
<!-- 目录 / 库检索结果面板:编辑列底部(IDE 的「Find in Path」工具窗位置) -->
|
<!-- 目录 / 库检索结果面板:编辑列底部(IDE 的「Find in Path」工具窗位置) -->
|
||||||
<SearchResultsPanel @open-file="onSearchOpenFile" />
|
<SearchResultsPanel @open-file="onSearchOpenFile" />
|
||||||
|
|||||||
@@ -30,14 +30,13 @@ import {
|
|||||||
createEditorState,
|
createEditorState,
|
||||||
jumpToPosition,
|
jumpToPosition,
|
||||||
reconfigureEditor,
|
reconfigureEditor,
|
||||||
replaceDoc,
|
|
||||||
setLanguageExtension,
|
setLanguageExtension,
|
||||||
type EditorConfig
|
type EditorConfig
|
||||||
} from '../editor/core'
|
} from '../editor/core'
|
||||||
import { editorBackground } from '../editor/themes'
|
import { editorBackground } from '../editor/themes'
|
||||||
import { createLogger } from '@/lib/logger'
|
import { createLogger } from '@/lib/logger'
|
||||||
import type { LanguageLoader } from '../editor/languages'
|
import type { LanguageLoader } from '../editor/languages'
|
||||||
import type { Extension } from '@codemirror/state'
|
import type { EditorState, Extension } from '@codemirror/state'
|
||||||
|
|
||||||
const logger = createLogger('editor')
|
const logger = createLogger('editor')
|
||||||
|
|
||||||
@@ -104,13 +103,29 @@ const hostBackground = computed(() =>
|
|||||||
|
|
||||||
let view: EditorView | null = null
|
let view: EditorView | null = null
|
||||||
let autosaveTimer: ReturnType<typeof setTimeout> | null = null
|
let autosaveTimer: ReturnType<typeof setTimeout> | null = null
|
||||||
/** 程序化替换文档期间抑制「变更 → 置脏」 */
|
|
||||||
let applyingDoc = false
|
|
||||||
/** 已应用的文档版本,避免重复整篇替换 */
|
/** 已应用的文档版本,避免重复整篇替换 */
|
||||||
let appliedRevision = -1
|
let appliedRevision = -1
|
||||||
/** 语言令牌:丢弃过期的异步加载结果(与 store 里的令牌是两层保险) */
|
/** 语言令牌:丢弃过期的异步加载结果(与 store 里的令牌是两层保险) */
|
||||||
let languageSeq = 0
|
let languageSeq = 0
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 每个标签自己的 EditorState(撤销历史随标签保留)。
|
||||||
|
*
|
||||||
|
* CM6 的撤销历史挂在 **EditorState 的字段**上,没有「只导出历史」的公开 API,因此
|
||||||
|
* 「按标签保存撤销历史」就等于「按标签保存整个 state」:切换标签时把当前 state
|
||||||
|
* 收进缓存、把目标标签的 state 装回同一个 `EditorView`。缓存只保留仍打开的标签
|
||||||
|
* (见下方按标签集合的清理 watch),关闭标签即释放。
|
||||||
|
*/
|
||||||
|
const stateCache = new Map<string, EditorState>()
|
||||||
|
/** 当前 view 装载的是哪个标签的 state(空串 = 未绑定)。 */
|
||||||
|
let boundKey = ''
|
||||||
|
|
||||||
|
/** 当前面板的缓存键:主面板 = 活动标签,副面板 = 它绑定的标签。 */
|
||||||
|
function paneKey(): string {
|
||||||
|
if (isPane.value) return props.tabId ?? ''
|
||||||
|
return store.activeTabId || ''
|
||||||
|
}
|
||||||
|
|
||||||
function currentConfig(): EditorConfig {
|
function currentConfig(): EditorConfig {
|
||||||
const s = store.settings
|
const s = store.settings
|
||||||
const large = paneLarge.value
|
const large = paneLarge.value
|
||||||
@@ -139,6 +154,35 @@ function currentConfig(): EditorConfig {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构造一个**全新的**编辑器状态(初次装配 / 无法复用缓存时)。
|
||||||
|
*
|
||||||
|
* # 为什么整篇装载必须换 state,而不是 dispatch 一次替换
|
||||||
|
*
|
||||||
|
* CM6 的撤销历史是 `history()` 里的状态字段,按**同一个 EditorState** 记录。
|
||||||
|
* 若用 `dispatch({changes: 全文替换})` 装载另一个文件,新文档会继承上一份文档的
|
||||||
|
* 撤销栈:随后的 Ctrl+Z 就会把别的文件的历史改动「回退」进当前标签页。
|
||||||
|
* `EditorView.setState` 会连同历史字段一起换成新的状态(焦点保留)。
|
||||||
|
*
|
||||||
|
* 可复用的标签状态由 `stateCache` 提供(见上方);这里只负责「缓存不可用」的情形:
|
||||||
|
* 首次打开、或该标签的内容已在别处被改过(并排副面板编辑 / 外部重载)。
|
||||||
|
*/
|
||||||
|
function buildState(doc: string): EditorState {
|
||||||
|
return createEditorState({
|
||||||
|
doc,
|
||||||
|
config: currentConfig(),
|
||||||
|
onDocChanged: next => {
|
||||||
|
if (isPane.value && props.tabId) store.setTabContent(props.tabId, next)
|
||||||
|
else store.setContent(next)
|
||||||
|
scheduleAutosave()
|
||||||
|
},
|
||||||
|
// 副面板的光标不该覆盖状态栏(状态栏跟随活动文档)
|
||||||
|
onSelectionChanged: (line, column) => {
|
||||||
|
if (!isPane.value) emit('cursor-moved', line, column)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
function scheduleAutosave(): void {
|
function scheduleAutosave(): void {
|
||||||
const ms = store.settings.autosaveMs
|
const ms = store.settings.autosaveMs
|
||||||
if (!ms) return
|
if (!ms) return
|
||||||
@@ -180,29 +224,23 @@ onMounted(() => {
|
|||||||
if (!hostRef.value) return
|
if (!hostRef.value) return
|
||||||
view = new EditorView({
|
view = new EditorView({
|
||||||
parent: hostRef.value,
|
parent: hostRef.value,
|
||||||
state: createEditorState({
|
state: buildState(paneContent.value)
|
||||||
doc: paneContent.value,
|
|
||||||
config: currentConfig(),
|
|
||||||
onDocChanged: doc => {
|
|
||||||
if (applyingDoc) return
|
|
||||||
if (isPane.value && props.tabId) store.setTabContent(props.tabId, doc)
|
|
||||||
else store.setContent(doc)
|
|
||||||
scheduleAutosave()
|
|
||||||
},
|
|
||||||
// 副面板的光标不该覆盖状态栏(状态栏跟随活动文档)
|
|
||||||
onSelectionChanged: (line, column) => {
|
|
||||||
if (!isPane.value) emit('cursor-moved', line, column)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
boundKey = paneKey()
|
||||||
|
if (boundKey) stateCache.set(boundKey, view.state)
|
||||||
appliedRevision = paneRevision.value
|
appliedRevision = paneRevision.value
|
||||||
void applyLanguage(++languageSeq)
|
void applyLanguage(++languageSeq)
|
||||||
})
|
})
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 整篇装载(打开笔记 / 打开文件 / 重载):替换文档。
|
* 整篇装载(切标签 / 打开笔记 / 打开文件 / 重载):换入目标文档的状态。
|
||||||
*
|
*
|
||||||
* 用 `docRevision` 而不是路径:重载同一篇时路径没变,但内容必须被换掉。
|
* 用 `docRevision` 而不是路径:重载同一篇时路径没变,但内容必须被换掉。
|
||||||
|
*
|
||||||
|
* 两条路:
|
||||||
|
* - **切标签**(缓存键变了)且该标签的缓存内容与当前内容一致 → 装回缓存 state,
|
||||||
|
* 撤销历史 / 选区随之保留;
|
||||||
|
* - 否则(首次打开、同标签重载、内容已在别处被改过)→ 重建全新 state。
|
||||||
*/
|
*/
|
||||||
watch(
|
watch(
|
||||||
paneRevision,
|
paneRevision,
|
||||||
@@ -214,22 +252,63 @@ watch(
|
|||||||
}
|
}
|
||||||
if (appliedRevision === revision) return
|
if (appliedRevision === revision) return
|
||||||
appliedRevision = revision
|
appliedRevision = revision
|
||||||
// 目标光标行要在 replaceDoc **之前**取:替换会派发 selection 变化,
|
|
||||||
// updateListener 随即把 store.cursorLine 覆盖成 1,之后再读就只剩第 1 行了。
|
const key = paneKey()
|
||||||
|
const switching = key !== boundKey
|
||||||
|
// 离开当前文档前把它的 state 收回缓存(撤销历史 + 选区都在里面)
|
||||||
|
if (boundKey && switching) stateCache.set(boundKey, view.state)
|
||||||
|
|
||||||
|
// 只复用「换到另一个标签」且内容对得上的缓存。内容不一致说明该标签在别处
|
||||||
|
// 被改过(并排副面板编辑 / 外部重载),旧 state 的文档与撤销历史都不能再用。
|
||||||
|
const cached = switching && key ? stateCache.get(key) : undefined
|
||||||
|
if (cached && cached.doc.toString() === paneContent.value) {
|
||||||
|
view.setState(cached)
|
||||||
|
boundKey = key
|
||||||
|
// 缓存期间设置可能变过:主题 / 排版 / Live Preview / wikilink 重新配置。
|
||||||
|
// 语言不进 reconfigure(见 currentConfig 的注释),由下面的 applyLanguage 负责。
|
||||||
|
try {
|
||||||
|
reconfigureEditor(view, currentConfig())
|
||||||
|
} catch (e) {
|
||||||
|
logger.error(`恢复标签状态后重配置失败:${String(e)}`)
|
||||||
|
}
|
||||||
|
void applyLanguage(++languageSeq)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 目标光标行要在 setState **之前**取:新状态的 selection 变化会被
|
||||||
|
// updateListener 回写成 1,之后再读就只剩第 1 行了。
|
||||||
const restoreLine = isPane.value ? 1 : store.cursorLine
|
const restoreLine = isPane.value ? 1 : store.cursorLine
|
||||||
applyingDoc = true
|
// 重建状态而不是 dispatch 整篇替换:撤销历史必须随文档隔离(见 buildState)
|
||||||
replaceDoc(view, paneContent.value)
|
view.setState(buildState(paneContent.value))
|
||||||
|
boundKey = key
|
||||||
|
if (key) stateCache.set(key, view.state)
|
||||||
// 标签切换 / 会话恢复:按 store.cursorLine 复位光标(默认第 1 行不动)
|
// 标签切换 / 会话恢复:按 store.cursorLine 复位光标(默认第 1 行不动)
|
||||||
if (restoreLine > 1) {
|
if (restoreLine > 1) {
|
||||||
const line = Math.min(restoreLine, view.state.doc.lines)
|
const line = Math.min(restoreLine, view.state.doc.lines)
|
||||||
const pos = view.state.doc.line(line).from
|
const pos = view.state.doc.line(line).from
|
||||||
view.dispatch({ selection: { anchor: pos }, scrollIntoView: false })
|
view.dispatch({ selection: { anchor: pos }, scrollIntoView: false })
|
||||||
}
|
}
|
||||||
applyingDoc = false
|
|
||||||
void applyLanguage(++languageSeq)
|
void applyLanguage(++languageSeq)
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 标签集合变化时丢掉已关闭标签的状态。
|
||||||
|
*
|
||||||
|
* 每个缓存项持有一整份文档 + 撤销栈,不清理会随「开过多少文件」一直增长。
|
||||||
|
* 副面板的缓存只有它自己绑定的那一个标签,同样随标签关闭失效。
|
||||||
|
*/
|
||||||
|
watch(
|
||||||
|
() => store.tabs.map(t => t.id).join('\u0000'),
|
||||||
|
() => {
|
||||||
|
if (!stateCache.size) return
|
||||||
|
const alive = new Set(store.tabs.map(t => t.id))
|
||||||
|
for (const key of stateCache.keys()) {
|
||||||
|
if (!alive.has(key)) stateCache.delete(key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
/** 语言变化(异步加载完成 / 切换到另一种语言)。 */
|
/** 语言变化(异步加载完成 / 切换到另一种语言)。 */
|
||||||
watch(paneLanguage, () => {
|
watch(paneLanguage, () => {
|
||||||
void applyLanguage(++languageSeq)
|
void applyLanguage(++languageSeq)
|
||||||
@@ -269,6 +348,8 @@ onBeforeUnmount(() => {
|
|||||||
flushAutosave()
|
flushAutosave()
|
||||||
view?.destroy()
|
view?.destroy()
|
||||||
view = null
|
view = null
|
||||||
|
stateCache.clear()
|
||||||
|
boundKey = ''
|
||||||
})
|
})
|
||||||
|
|
||||||
defineExpose({
|
defineExpose({
|
||||||
|
|||||||
@@ -230,15 +230,6 @@ export function setLanguageExtension(view: EditorView, extension: Extension | nu
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 用新文档整体替换(切换笔记 / 打开文件时)。 */
|
|
||||||
export function replaceDoc(view: EditorView, doc: string): void {
|
|
||||||
view.dispatch({
|
|
||||||
changes: { from: 0, to: view.state.doc.length, insert: doc },
|
|
||||||
selection: { anchor: 0 },
|
|
||||||
scrollIntoView: true
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 把光标移到某个字符偏移并滚动到可见位置(大纲点击跳转用)。
|
* 把光标移到某个字符偏移并滚动到可见位置(大纲点击跳转用)。
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -13,7 +13,8 @@ import {
|
|||||||
SquareTerminal,
|
SquareTerminal,
|
||||||
Bot,
|
Bot,
|
||||||
FileCode2,
|
FileCode2,
|
||||||
Diff
|
Diff,
|
||||||
|
House
|
||||||
} from '@lucide/vue'
|
} from '@lucide/vue'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -37,7 +38,8 @@ export const moduleIconMap: Record<string, Component> = {
|
|||||||
terminal: SquareTerminal,
|
terminal: SquareTerminal,
|
||||||
dsh: Bot,
|
dsh: Bot,
|
||||||
editor: FileCode2,
|
editor: FileCode2,
|
||||||
diff: Diff
|
diff: Diff,
|
||||||
|
smarthome: House
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 获取模块图标组件,未找到时回退到 Settings 图标 */
|
/** 获取模块图标组件,未找到时回退到 Settings 图标 */
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ import { moduleConfig as terminal } from './terminal'
|
|||||||
import { moduleConfig as dsh } from './dsh'
|
import { moduleConfig as dsh } from './dsh'
|
||||||
import { moduleConfig as editor } from './editor'
|
import { moduleConfig as editor } from './editor'
|
||||||
import { moduleConfig as diff } from './diff'
|
import { moduleConfig as diff } from './diff'
|
||||||
|
import { moduleConfig as smarthome } from './smarthome'
|
||||||
|
|
||||||
const allModules: ModuleConfig[] = [
|
const allModules: ModuleConfig[] = [
|
||||||
proxy,
|
proxy,
|
||||||
@@ -31,7 +32,8 @@ const allModules: ModuleConfig[] = [
|
|||||||
terminal,
|
terminal,
|
||||||
dsh,
|
dsh,
|
||||||
editor,
|
editor,
|
||||||
diff
|
diff,
|
||||||
|
smarthome
|
||||||
]
|
]
|
||||||
|
|
||||||
// 启动时注册所有模块
|
// 启动时注册所有模块
|
||||||
|
|||||||
@@ -5,11 +5,12 @@ import { getCurrentWindow, LogicalSize, Effect, EffectState } from '@tauri-apps/
|
|||||||
// Rust 端通过 tauri-specta 生成的命令绑定(bindings.ts)
|
// Rust 端通过 tauri-specta 生成的命令绑定(bindings.ts)
|
||||||
import { commands } from '@/lib/bindings'
|
import { commands } from '@/lib/bindings'
|
||||||
import type { ArchiveInfo, DeleteResult, ExtractResult, FileEntry, RenamePreview, RenameResult } from '@/lib/bindings'
|
import type { ArchiveInfo, DeleteResult, ExtractResult, FileEntry, RenamePreview, RenameResult } from '@/lib/bindings'
|
||||||
import { Search, Command, Loader2, CornerDownLeft, Calculator, Globe, Lock, ChevronRight, ChevronLeft, ChevronDown, History, FolderOpen, Ruler, Trash2, Terminal, Archive as ArchiveIcon, Regex, FileText, Settings } from '@lucide/vue'
|
import { Search, Command, Loader2, CornerDownLeft, Calculator, Globe, Lock, ChevronRight, ChevronLeft, ChevronDown, History, FolderOpen, Ruler, Trash2, Terminal, Archive as ArchiveIcon, Regex, FileText, Settings, ImageDown, CircleAlert } from '@lucide/vue'
|
||||||
import { TooltipProvider, Tooltip, TooltipTrigger, TooltipContent } from '@/components/ui/tooltip'
|
import { TooltipProvider, Tooltip, TooltipTrigger, TooltipContent } from '@/components/ui/tooltip'
|
||||||
import { Switch } from '@/components/ui/switch'
|
import { Switch } from '@/components/ui/switch'
|
||||||
import { aggregateSearch, loadAppIconsForResults, recordHistoryItem, getAllHistoryItems, setFileIndexReady, type QPItem, type QPSubAction } from './providers'
|
import { aggregateSearch, loadAppIconsForResults, recordHistoryItem, getAllHistoryItems, setFileIndexReady, type QPItem, type QPSubAction } from './providers'
|
||||||
import { EVENTS, STORAGE_KEYS } from '@/lib/constants'
|
import { EVENTS, STORAGE_KEYS } from '@/lib/constants'
|
||||||
|
import { latestCaptureCachePath, screenshotFileName } from '@/stores/screenshotStore'
|
||||||
import { applyStoredAccent } from '@/lib/theme'
|
import { applyStoredAccent } from '@/lib/theme'
|
||||||
import HistoryPicker from './HistoryPicker.vue'
|
import HistoryPicker from './HistoryPicker.vue'
|
||||||
|
|
||||||
@@ -143,8 +144,14 @@ const renameResults = ref<RenameResult[] | null>(null)
|
|||||||
const renameOkCount = ref(0)
|
const renameOkCount = ref(0)
|
||||||
let renameTimer: ReturnType<typeof setTimeout> | null = null
|
let renameTimer: ReturnType<typeof setTimeout> | null = null
|
||||||
|
|
||||||
|
// ===== 保存截图(联动截图模块) =====
|
||||||
|
// 源是"最近一张截图"的历史缓存(完整 PNG 落盘在截图缓存目录,历史里只有缩略图),
|
||||||
|
// 目标目录就是资源管理器当前打开的文件夹 —— 与三个目录操作项同一个上下文。
|
||||||
|
const savingShot = ref(false)
|
||||||
|
const saveShotError = ref('')
|
||||||
|
|
||||||
// ===== 结果分区(从 results 中分离历史项与其他结果) =====
|
// ===== 结果分区(从 results 中分离历史项与其他结果) =====
|
||||||
// 展示顺序:目录操作(批量解压/重命名/删除)> 历史(折叠分组)> 其他
|
// 展示顺序:目录操作(保存截图/批量解压/重命名/删除)> 历史(折叠分组)> 其他
|
||||||
// 目录操作为置顶行为项;历史在空查询时置顶但默认折叠,按 Tab 展开
|
// 目录操作为置顶行为项;历史在空查询时置顶但默认折叠,按 Tab 展开
|
||||||
const dirActionItems = ref<QPItem[]>([])
|
const dirActionItems = ref<QPItem[]>([])
|
||||||
const otherItems = computed(() => results.value)
|
const otherItems = computed(() => results.value)
|
||||||
@@ -263,11 +270,56 @@ watch(query, () => {
|
|||||||
searchTimer = setTimeout(doSearch, 120)
|
searchTimer = setTimeout(doSearch, 120)
|
||||||
})
|
})
|
||||||
|
|
||||||
// ===== 当前目录文件操作(批量解压 / 批量重命名) =====
|
// ===== 当前目录文件操作(批量解压 / 批量重命名 / 保存截图) =====
|
||||||
|
/**
|
||||||
|
* 把最近一张截图保存成文件(**不弹任何对话框**,直接落到资源管理器当前目录),
|
||||||
|
* 随后在资源管理器里定位到它并**进入重命名编辑状态** —— 落盘之后最常见的下一步就是改名。
|
||||||
|
*
|
||||||
|
* 文件名在项生成时就定下来(`screenshotFileName()`,与截图编辑栏「保存」同一规则),
|
||||||
|
* 这样列表上显示的名字与实际写下的**必然一致**。保存用截图模块现成的两条命令
|
||||||
|
* (`screenshot_load_cache`:历史只留缩略图,完整 PNG 按需读 + `screenshot_save_png`)。
|
||||||
|
*
|
||||||
|
* 顺序不能反:**先收起面板**再让资源管理器到前台 —— 面板仍盖在屏幕上时就送 F2,
|
||||||
|
* 那个键会打到面板自己身上。
|
||||||
|
*/
|
||||||
|
async function saveLatestShot(srcPath: string, fileName: string) {
|
||||||
|
if (savingShot.value) return
|
||||||
|
savingShot.value = true
|
||||||
|
try {
|
||||||
|
const pngBase64 = await commands.screenshotLoadCache(srcPath)
|
||||||
|
const dir = explorerDir.value.replace(/[\\/]+$/, '')
|
||||||
|
const savedPath = `${dir}\\${fileName}`
|
||||||
|
await commands.screenshotSavePng(pngBase64, savedPath)
|
||||||
|
await hideWindow()
|
||||||
|
await commands.quickpanelRevealInExplorerRename(savedPath)
|
||||||
|
} catch (e) {
|
||||||
|
console.error('[quickpanel] 保存截图失败:', e)
|
||||||
|
saveShotError.value = String(e)
|
||||||
|
} finally {
|
||||||
|
savingShot.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** 空查询时注入到结果顶部的目录操作项 */
|
/** 空查询时注入到结果顶部的目录操作项 */
|
||||||
function getExplorerActions(): QPItem[] {
|
function getExplorerActions(): QPItem[] {
|
||||||
if (!explorerDir.value) return []
|
if (!explorerDir.value) return []
|
||||||
|
// 「保存截图」排在最前:它是唯一"点一下就有结果"的项(其余三项都要先进子面板)。
|
||||||
|
// 只在确实有截图历史时才出现 —— 没有截图时这个项没有任何意义。
|
||||||
|
const shotPath = latestCaptureCachePath()
|
||||||
|
const shotItems: QPItem[] = []
|
||||||
|
if (shotPath) {
|
||||||
|
const fileName = screenshotFileName()
|
||||||
|
shotItems.push({
|
||||||
|
id: 'fa-save-shot',
|
||||||
|
title: '保存截图',
|
||||||
|
subtitle: `最近一张 · ${fileName}`,
|
||||||
|
group: '截图',
|
||||||
|
score: 100001,
|
||||||
|
action: () => saveLatestShot(shotPath, fileName),
|
||||||
|
})
|
||||||
|
}
|
||||||
return [
|
return [
|
||||||
|
...shotItems,
|
||||||
{
|
{
|
||||||
id: 'fa-extract',
|
id: 'fa-extract',
|
||||||
title: '批量解压',
|
title: '批量解压',
|
||||||
@@ -650,8 +702,9 @@ async function openSettings() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function executeItem(item: QPItem) {
|
async function executeItem(item: QPItem) {
|
||||||
// 目录操作(批量解压/重命名):进入面板模式,不关闭窗口
|
// 目录操作组(`fa-` 前缀:保存截图/批量解压/重命名/删除):或自行收尾、或进入面板模式,
|
||||||
if (item.id === 'fa-extract' || item.id === 'fa-rename' || item.id === 'fa-delete') {
|
// 一律不在这里关窗口(保存截图成功时由 saveLatestShot 自己关)
|
||||||
|
if (item.id.startsWith('fa-')) {
|
||||||
await item.action()
|
await item.action()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -847,6 +900,7 @@ const groupIcon = (group: string) => {
|
|||||||
if (group === '快捷') return FolderOpen
|
if (group === '快捷') return FolderOpen
|
||||||
if (group === '换算') return Ruler
|
if (group === '换算') return Ruler
|
||||||
if (group === '目录操作') return FolderOpen
|
if (group === '目录操作') return FolderOpen
|
||||||
|
if (group === '截图') return ImageDown
|
||||||
return Search
|
return Search
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -861,6 +915,7 @@ const GROUP_COLORS: Record<string, string> = {
|
|||||||
快捷: 'bg-info-soft text-info-text',
|
快捷: 'bg-info-soft text-info-text',
|
||||||
换算: 'bg-success-soft text-success-text',
|
换算: 'bg-success-soft text-success-text',
|
||||||
目录操作: 'bg-info-soft text-info-text',
|
目录操作: 'bg-info-soft text-info-text',
|
||||||
|
截图: 'bg-info-soft text-info-text',
|
||||||
应用: 'bg-info-soft text-info-text',
|
应用: 'bg-info-soft text-info-text',
|
||||||
文件: 'bg-success-soft text-success-text',
|
文件: 'bg-success-soft text-success-text',
|
||||||
剪贴板: 'bg-success-soft text-success-text',
|
剪贴板: 'bg-success-soft text-success-text',
|
||||||
@@ -1565,6 +1620,19 @@ onUnmounted(() => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<!-- 保存截图失败提示(成功时窗口已关闭,这里只在失败后留窗说明原因) -->
|
||||||
|
<div v-if="saveShotError" class="qp-confirm-mask" @click.self="saveShotError = ''">
|
||||||
|
<div class="qp-confirm-box" role="alertdialog" aria-modal="true">
|
||||||
|
<div class="qp-confirm-head">
|
||||||
|
<CircleAlert class="size-4 shrink-0 text-destructive" />
|
||||||
|
<p class="qp-confirm-title">保存截图失败</p>
|
||||||
|
</div>
|
||||||
|
<p class="qp-confirm-tip break-words">{{ saveShotError }}</p>
|
||||||
|
<div class="flex items-center justify-end gap-2 mt-4">
|
||||||
|
<button class="qp-confirm-btn" @click="saveShotError = ''">知道了</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</TooltipProvider>
|
</TooltipProvider>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -0,0 +1,60 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { onMounted, ref } from 'vue'
|
||||||
|
import { Tabs, TabsContent } from '@/components/ui/tabs'
|
||||||
|
import { useModuleTabs } from '@/lib/use-module-tabs'
|
||||||
|
import { useSmartHomeStore } from '@/stores/smartHomeStore'
|
||||||
|
import HaStatusBanner from './components/HaStatusBanner.vue'
|
||||||
|
import DevicePane from './components/DevicePane.vue'
|
||||||
|
import AutomationPane from './components/AutomationPane.vue'
|
||||||
|
import SettingsPane from './components/SettingsPane.vue'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 智能家居模块外壳。
|
||||||
|
*
|
||||||
|
* 三个 Tab(设备 / 自动化 / 设置)注册到 TitleBar 的浮动切换器(`alwaysVisible`,
|
||||||
|
* 模块自身不渲染 TabsList —— 与 monitor 一致,内容区纵向空间最大化)。
|
||||||
|
*/
|
||||||
|
const store = useSmartHomeStore()
|
||||||
|
|
||||||
|
const activeTab = ref('devices')
|
||||||
|
useModuleTabs(
|
||||||
|
'smarthome',
|
||||||
|
activeTab,
|
||||||
|
[
|
||||||
|
{ value: 'devices', label: '设备' },
|
||||||
|
{ value: 'automations', label: '自动化' },
|
||||||
|
{ value: 'settings', label: '设置' }
|
||||||
|
],
|
||||||
|
{ alwaysVisible: true }
|
||||||
|
)
|
||||||
|
|
||||||
|
void store.refresh()
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
// 事件监听只注册一次(模块可能被反复挂载):WS 增量 / 连接状态 / 规则触发都靠它。
|
||||||
|
// 「确保实时连接」不在这里做 —— 那一刻设置还没读完,见 store 里的注释。
|
||||||
|
void store.initListeners()
|
||||||
|
})
|
||||||
|
|
||||||
|
function goSettings() {
|
||||||
|
activeTab.value = 'settings'
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="min-h-full p-5">
|
||||||
|
<HaStatusBanner @open-settings="goSettings" />
|
||||||
|
|
||||||
|
<Tabs v-model="activeTab" class="flex flex-col">
|
||||||
|
<TabsContent value="devices" class="flex-1 tab-animate">
|
||||||
|
<DevicePane @open-settings="goSettings" />
|
||||||
|
</TabsContent>
|
||||||
|
<TabsContent value="automations" class="flex-1 tab-animate">
|
||||||
|
<AutomationPane />
|
||||||
|
</TabsContent>
|
||||||
|
<TabsContent value="settings" class="flex-1 tab-animate">
|
||||||
|
<SettingsPane />
|
||||||
|
</TabsContent>
|
||||||
|
</Tabs>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,407 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, ref } from 'vue'
|
||||||
|
import { toast } from 'vue-sonner'
|
||||||
|
import {
|
||||||
|
AlertTriangle,
|
||||||
|
CircleAlert,
|
||||||
|
CircleCheck,
|
||||||
|
ExternalLink,
|
||||||
|
History,
|
||||||
|
Loader2,
|
||||||
|
Pencil,
|
||||||
|
Play,
|
||||||
|
Plus,
|
||||||
|
RefreshCw,
|
||||||
|
Trash2,
|
||||||
|
Workflow,
|
||||||
|
Zap
|
||||||
|
} from '@lucide/vue'
|
||||||
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||||
|
import { Switch } from '@/components/ui/switch'
|
||||||
|
import { ConfirmDialog, StateBlock, StatusDot } from '@/components/common'
|
||||||
|
import { useSmartHomeStore, type EntitySummary, type Rule } from '@/stores/smartHomeStore'
|
||||||
|
import { compareByName, relativeTime, relativeTimeFromSec, ruleSummary } from '../format'
|
||||||
|
import { controlFail } from './controls/shared'
|
||||||
|
import RuleEditorDialog from './RuleEditorDialog.vue'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 自动化页:上半区管 HA 已有的自动化与脚本(P3),下半区是**本地规则**(P4)。
|
||||||
|
*
|
||||||
|
* 数据源就是**已有的实体列表**(`automation.*` / `script.*`),因此不需要新命令:
|
||||||
|
* 启停走 `automation.turn_on|turn_off`,立即运行走 `automation.trigger` /
|
||||||
|
* `script.turn_on` —— 全都由 P2 的 `smarthome_call_service` 下发。
|
||||||
|
*
|
||||||
|
* 本地规则是另一回事:它由 Rust 侧的 WS 事件驱动(`automation.rs`),
|
||||||
|
* **只在 Thing 运行时生效** —— 因此这片区域顶部有常驻警示条。
|
||||||
|
*/
|
||||||
|
const store = useSmartHomeStore()
|
||||||
|
|
||||||
|
/** 正在运行的实体 id(一次只允许一个,避免连点刷出多条触发) */
|
||||||
|
const running = ref<string | null>(null)
|
||||||
|
/** 规则编辑器(null = 关闭) */
|
||||||
|
const editing = ref<Rule | null>(null)
|
||||||
|
const editorOpen = ref(false)
|
||||||
|
const deleting = ref<Rule | null>(null)
|
||||||
|
|
||||||
|
const items = computed(() =>
|
||||||
|
store.entities
|
||||||
|
.filter((e) => e.domain === 'automation' || e.domain === 'script')
|
||||||
|
.sort(compareByName)
|
||||||
|
)
|
||||||
|
|
||||||
|
const loading = computed(
|
||||||
|
() => !store.ready || (store.entitiesLoading && store.entities.length === 0)
|
||||||
|
)
|
||||||
|
|
||||||
|
/** 自动化是"能开关的规则",脚本只有"运行"这一个动作 */
|
||||||
|
function isAutomation(e: EntitySummary): boolean {
|
||||||
|
return e.domain === 'automation'
|
||||||
|
}
|
||||||
|
|
||||||
|
function lastFired(e: EntitySummary): string {
|
||||||
|
return e.lastTriggered ? `上次触发:${relativeTime(e.lastTriggered)}` : '尚未触发过'
|
||||||
|
}
|
||||||
|
|
||||||
|
function stateLabel(e: EntitySummary): string {
|
||||||
|
if (e.state === 'unavailable') return '离线'
|
||||||
|
if (!isAutomation(e)) return e.state === 'on' ? '运行中' : '空闲'
|
||||||
|
return e.state === 'on' ? '已启用' : '已停用'
|
||||||
|
}
|
||||||
|
|
||||||
|
function dotState(e: EntitySummary): 'success' | 'warning' | 'neutral' {
|
||||||
|
if (e.state === 'unavailable') return 'warning'
|
||||||
|
return e.state === 'on' ? 'success' : 'neutral'
|
||||||
|
}
|
||||||
|
|
||||||
|
async function setEnabled(e: EntitySummary, on: boolean) {
|
||||||
|
try {
|
||||||
|
await store.control(e, on ? 'turn_on' : 'turn_off', {}, { state: on ? 'on' : 'off' })
|
||||||
|
} catch (err) {
|
||||||
|
controlFail(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runNow(e: EntitySummary) {
|
||||||
|
if (running.value) return
|
||||||
|
running.value = e.entityId
|
||||||
|
try {
|
||||||
|
// `automation.trigger` 的 `skip_condition` 默认 false(HA 语义):照常走条件判断。
|
||||||
|
// 乐观状态传空对象 —— 触发不会让这条实体自身产生可预期的状态变化,
|
||||||
|
// 否则 store 会拿"状态没变"去冤枉一次成功触发(§5.3 的例外分支)。
|
||||||
|
await store.control(e, isAutomation(e) ? 'trigger' : 'turn_on', {}, {})
|
||||||
|
toast.success(`已触发「${e.name}」`)
|
||||||
|
} catch (err) {
|
||||||
|
controlFail(err)
|
||||||
|
} finally {
|
||||||
|
running.value = null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================== 本地规则(P4) ==============================
|
||||||
|
|
||||||
|
function openNew() {
|
||||||
|
editing.value = null
|
||||||
|
editorOpen.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
function openEdit(rule: Rule) {
|
||||||
|
editing.value = rule
|
||||||
|
editorOpen.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
async function setRulesMaster(on: boolean) {
|
||||||
|
try {
|
||||||
|
await store.setRulesEnabled(on)
|
||||||
|
toast.success(on ? '本地规则已启用' : '本地规则已停用')
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(`切换失败:${(e as { message?: string }).message ?? String(e)}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function toggleRule(rule: Rule, on: boolean) {
|
||||||
|
try {
|
||||||
|
await store.saveRule({ ...rule, enabled: on })
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(`保存失败:${(e as { message?: string }).message ?? String(e)}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function confirmDelete() {
|
||||||
|
const rule = deleting.value
|
||||||
|
if (!rule) return
|
||||||
|
try {
|
||||||
|
await store.deleteRule(rule.id)
|
||||||
|
toast.success(`已删除「${rule.name}」`)
|
||||||
|
deleting.value = null
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(`删除失败:${(e as { message?: string }).message ?? String(e)}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function ruleLastFired(rule: Rule): string {
|
||||||
|
if (!rule.lastFiredAt) return '尚未触发过'
|
||||||
|
return `上次触发:${relativeTimeFromSec(rule.lastFiredAt)}(共 ${rule.fireCount} 次)`
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="flex flex-col gap-4">
|
||||||
|
<!-- 本地规则的限制说明:决定"这条规则该建在哪"的关键信息,常驻 -->
|
||||||
|
<div
|
||||||
|
class="flex items-start gap-2.5 rounded-lg border border-warning bg-warning-soft px-4 py-3"
|
||||||
|
>
|
||||||
|
<AlertTriangle class="mt-0.5 size-4 shrink-0 text-warning" :stroke-width="1.75" />
|
||||||
|
<p class="text-xs text-warning-text">
|
||||||
|
本地规则只在 Thing 运行时生效 —— 应用退出或电脑关机后不再触发。
|
||||||
|
需要 7×24 稳定执行的自动化,请建在 Home Assistant 里。
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- ===== Home Assistant 自动化与脚本 ===== -->
|
||||||
|
<Card class="!py-0 !gap-0">
|
||||||
|
<CardHeader class="flex flex-row items-center justify-between gap-2 px-4 py-3">
|
||||||
|
<CardTitle class="flex min-w-0 items-center gap-2 text-base">
|
||||||
|
<Workflow class="size-5 shrink-0 text-fg-secondary" :stroke-width="1.75" />
|
||||||
|
<span class="truncate">Home Assistant 自动化与脚本</span>
|
||||||
|
<span class="shrink-0 text-xs font-normal text-muted-foreground"
|
||||||
|
>({{ items.length }})</span
|
||||||
|
>
|
||||||
|
</CardTitle>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
class="shrink-0"
|
||||||
|
@click="store.openHaPage('/config/automation')"
|
||||||
|
>
|
||||||
|
<ExternalLink class="size-4" />在 HA 中管理
|
||||||
|
</Button>
|
||||||
|
</CardHeader>
|
||||||
|
|
||||||
|
<CardContent class="!px-4">
|
||||||
|
<StateBlock
|
||||||
|
v-if="loading"
|
||||||
|
variant="loading"
|
||||||
|
title="正在读取自动化…"
|
||||||
|
:min-height="160"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<StateBlock
|
||||||
|
v-else-if="store.entitiesError && store.entities.length === 0"
|
||||||
|
variant="error"
|
||||||
|
title="读取失败"
|
||||||
|
:description="store.entitiesError.message"
|
||||||
|
:min-height="160"
|
||||||
|
>
|
||||||
|
<template #action>
|
||||||
|
<Button variant="outline" size="sm" @click="store.loadEntities(true)">
|
||||||
|
<RefreshCw class="size-4" />重试
|
||||||
|
</Button>
|
||||||
|
</template>
|
||||||
|
</StateBlock>
|
||||||
|
|
||||||
|
<StateBlock
|
||||||
|
v-else-if="items.length === 0"
|
||||||
|
variant="empty"
|
||||||
|
title="Home Assistant 里还没有自动化或脚本"
|
||||||
|
description="HA 的「设置 → 自动化与场景」里创建后,这里会自动出现。"
|
||||||
|
:min-height="160"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div v-else class="flex flex-col divide-y divide-divider">
|
||||||
|
<div
|
||||||
|
v-for="e in items"
|
||||||
|
:key="e.entityId"
|
||||||
|
class="flex items-center gap-3 py-2.5"
|
||||||
|
:class="e.state === 'unavailable' && 'opacity-60'"
|
||||||
|
>
|
||||||
|
<StatusDot :state="dotState(e)" :label="stateLabel(e)" />
|
||||||
|
|
||||||
|
<div class="min-w-0 flex-1">
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<span class="truncate text-[13px] text-foreground">{{ e.name }}</span>
|
||||||
|
<Badge variant="secondary" class="shrink-0 text-[10px]">{{
|
||||||
|
isAutomation(e) ? '自动化' : '脚本'
|
||||||
|
}}</Badge>
|
||||||
|
</div>
|
||||||
|
<p class="truncate text-[11px] text-muted-foreground">{{ lastFired(e) }}</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
class="shrink-0"
|
||||||
|
:disabled="running !== null || e.state === 'unavailable'"
|
||||||
|
@click="runNow(e)"
|
||||||
|
>
|
||||||
|
<Loader2 v-if="running === e.entityId" class="size-3.5 animate-spin" />
|
||||||
|
<Play v-else class="size-3.5" />运行
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<Switch
|
||||||
|
v-if="isAutomation(e)"
|
||||||
|
class="shrink-0"
|
||||||
|
:model-value="e.state === 'on'"
|
||||||
|
:disabled="e.state === 'unavailable'"
|
||||||
|
:aria-label="e.state === 'on' ? '停用自动化' : '启用自动化'"
|
||||||
|
@update:model-value="(v: boolean | 'indeterminate') => setEnabled(e, v === true)"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<!-- ===== 本地规则(P4) ===== -->
|
||||||
|
<Card class="!py-0 !gap-0">
|
||||||
|
<CardHeader class="flex flex-row items-center justify-between gap-2 px-4 py-3">
|
||||||
|
<CardTitle class="flex min-w-0 items-center gap-2 text-base">
|
||||||
|
<Zap class="size-5 shrink-0 text-fg-secondary" :stroke-width="1.75" />
|
||||||
|
<span class="truncate">本地规则</span>
|
||||||
|
<span class="shrink-0 text-xs font-normal text-muted-foreground"
|
||||||
|
>({{ store.rules.length }})</span
|
||||||
|
>
|
||||||
|
<!-- 实时连接状态:规则靠 WS 事件驱动,没连上等于不会触发 -->
|
||||||
|
<Badge
|
||||||
|
v-if="!store.wsConnected"
|
||||||
|
variant="secondary"
|
||||||
|
class="shrink-0 text-[10px] text-warning-text"
|
||||||
|
>
|
||||||
|
实时连接未就绪
|
||||||
|
</Badge>
|
||||||
|
</CardTitle>
|
||||||
|
<div class="flex shrink-0 items-center gap-3">
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<span class="text-xs text-fg-secondary">总开关</span>
|
||||||
|
<Switch
|
||||||
|
:model-value="store.rulesEnabled"
|
||||||
|
aria-label="本地规则总开关"
|
||||||
|
@update:model-value="(v: boolean | 'indeterminate') => setRulesMaster(v === true)"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<Button variant="outline" size="sm" @click="openNew">
|
||||||
|
<Plus class="size-4" />新建规则
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</CardHeader>
|
||||||
|
|
||||||
|
<CardContent class="!px-4">
|
||||||
|
<p v-if="!store.rulesEnabled && store.rules.length > 0" class="pb-2 text-[11.5px] text-muted-foreground">
|
||||||
|
总开关已关闭:下面的规则不会被求值。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<StateBlock
|
||||||
|
v-if="store.rulesLoading && store.rules.length === 0"
|
||||||
|
variant="loading"
|
||||||
|
title="正在读取本地规则…"
|
||||||
|
:min-height="150"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<StateBlock
|
||||||
|
v-else-if="store.rules.length === 0"
|
||||||
|
variant="empty"
|
||||||
|
title="还没有本地规则"
|
||||||
|
description="本地规则是「触发 → 条件 → 动作」的三段式:例如「门厅门磁 开 → 开 门厅灯」。它由实时推送驱动,只在 Thing 运行时生效。"
|
||||||
|
:min-height="150"
|
||||||
|
>
|
||||||
|
<template #action>
|
||||||
|
<Button size="sm" @click="openNew"><Plus class="size-4" />新建规则</Button>
|
||||||
|
</template>
|
||||||
|
</StateBlock>
|
||||||
|
|
||||||
|
<div v-else class="flex flex-col divide-y divide-divider">
|
||||||
|
<div v-for="rule in store.rules" :key="rule.id" class="flex items-center gap-3 py-2.5">
|
||||||
|
<StatusDot
|
||||||
|
:state="rule.lastError ? 'warning' : rule.enabled ? 'success' : 'neutral'"
|
||||||
|
:label="rule.enabled ? (rule.lastError ? '上次失败' : '已启用') : '已停用'"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div class="min-w-0 flex-1">
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<span class="truncate text-[13px] text-foreground">{{ rule.name }}</span>
|
||||||
|
<Badge v-if="rule.conditions.length" variant="secondary" class="shrink-0 text-[10px]">
|
||||||
|
{{ rule.conditions.length }} 个条件
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
<p class="truncate text-[11px] text-muted-foreground">
|
||||||
|
{{ ruleSummary(rule, store.entityLabel) }}
|
||||||
|
</p>
|
||||||
|
<p class="truncate text-[11px] text-muted-foreground">
|
||||||
|
{{ ruleLastFired(rule) }}
|
||||||
|
<span v-if="rule.lastError" class="text-warning-text">· {{ rule.lastError }}</span>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
class="size-8 shrink-0"
|
||||||
|
title="编辑规则"
|
||||||
|
aria-label="编辑规则"
|
||||||
|
@click="openEdit(rule)"
|
||||||
|
>
|
||||||
|
<Pencil class="size-4" />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
class="size-8 shrink-0 text-destructive"
|
||||||
|
title="删除规则"
|
||||||
|
aria-label="删除规则"
|
||||||
|
@click="deleting = rule"
|
||||||
|
>
|
||||||
|
<Trash2 class="size-4" />
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<Switch
|
||||||
|
class="shrink-0"
|
||||||
|
:model-value="rule.enabled"
|
||||||
|
:aria-label="rule.enabled ? '停用规则' : '启用规则'"
|
||||||
|
@update:model-value="(v: boolean | 'indeterminate') => toggleRule(rule, v === true)"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 运行记录(内存里最近 50 条):回答"这条规则到底跑没跑" -->
|
||||||
|
<div v-if="store.ruleRecords.length" class="mt-3 border-t border-divider pt-3">
|
||||||
|
<div class="mb-1.5 flex items-center gap-1.5">
|
||||||
|
<History class="size-3.5 text-fg-secondary" :stroke-width="1.75" />
|
||||||
|
<span class="text-[11px] font-medium tracking-wide text-fg-secondary">运行记录</span>
|
||||||
|
</div>
|
||||||
|
<div class="flex flex-col gap-1">
|
||||||
|
<div
|
||||||
|
v-for="(record, i) in store.ruleRecords.slice(0, 5)"
|
||||||
|
:key="`${record.at}-${i}`"
|
||||||
|
class="flex items-center gap-2 text-[11.5px]"
|
||||||
|
>
|
||||||
|
<component
|
||||||
|
:is="record.ok ? CircleCheck : CircleAlert"
|
||||||
|
class="size-3.5 shrink-0"
|
||||||
|
:class="record.ok ? 'text-success' : 'text-warning'"
|
||||||
|
:stroke-width="1.75"
|
||||||
|
/>
|
||||||
|
<span class="shrink-0 tabular-nums text-muted-foreground">
|
||||||
|
{{ relativeTimeFromSec(record.at) }}
|
||||||
|
</span>
|
||||||
|
<span class="min-w-0 truncate text-fg-secondary">
|
||||||
|
{{ record.ruleName }} · {{ record.detail }}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<RuleEditorDialog v-model:open="editorOpen" :rule="editing" />
|
||||||
|
|
||||||
|
<ConfirmDialog
|
||||||
|
:open="!!deleting"
|
||||||
|
variant="danger"
|
||||||
|
title="删除这条规则?"
|
||||||
|
:description="deleting ? `「${deleting.name}」将被移除,且不可恢复。` : ''"
|
||||||
|
confirm-text="删除"
|
||||||
|
@update:open="(v) => !v && (deleting = null)"
|
||||||
|
@confirm="confirmDelete"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,245 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, ref, watch } from 'vue'
|
||||||
|
import { toast } from 'vue-sonner'
|
||||||
|
import { Loader2 } from '@lucide/vue'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import { Switch } from '@/components/ui/switch'
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle
|
||||||
|
} from '@/components/ui/dialog'
|
||||||
|
import {
|
||||||
|
useSmartHomeStore,
|
||||||
|
type EndpointMode,
|
||||||
|
type EndpointProbe,
|
||||||
|
type HaConnectionInput,
|
||||||
|
type HaConnectionView
|
||||||
|
} from '@/stores/smartHomeStore'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 新建 / 编辑连接对话框。
|
||||||
|
*
|
||||||
|
* 两个关键设计:
|
||||||
|
* 1. **地址可以同时填两个**(局域网 + 反代),对应"在家"与"在外面"两种场景。
|
||||||
|
* 2. **测试按钮逐个地址出结果** —— 在外面测时局域网失败是预期内的,
|
||||||
|
* 笼统的"成功/失败"会把这条最有用的信息丢掉。
|
||||||
|
*/
|
||||||
|
const props = defineProps<{
|
||||||
|
open: boolean
|
||||||
|
connection?: HaConnectionView | null
|
||||||
|
}>()
|
||||||
|
const emit = defineEmits<{ 'update:open': [boolean] }>()
|
||||||
|
|
||||||
|
const store = useSmartHomeStore()
|
||||||
|
|
||||||
|
const form = ref<HaConnectionInput>(blank())
|
||||||
|
const token = ref('')
|
||||||
|
const testing = ref(false)
|
||||||
|
const saving = ref(false)
|
||||||
|
const probes = ref<EndpointProbe[]>([])
|
||||||
|
|
||||||
|
const MODES: { value: EndpointMode; label: string; hint: string }[] = [
|
||||||
|
{ value: 'auto', label: '自动', hint: '先短超时试局域网,失败再用反代;回家会自己切回来' },
|
||||||
|
{ value: 'local', label: '仅局域网', hint: '只用局域网地址(在外会连不上,进不去家门)' },
|
||||||
|
{ value: 'remote', label: '仅反代', hint: '只用反代地址(出门前可用它验证隧道是否通)' }
|
||||||
|
]
|
||||||
|
|
||||||
|
const hasStoredToken = computed(() => !!props.connection?.hasToken)
|
||||||
|
const isEdit = computed(() => !!props.connection?.id)
|
||||||
|
const modeHint = computed(() => MODES.find((m) => m.value === form.value.endpointMode)?.hint ?? '')
|
||||||
|
|
||||||
|
function blank(): HaConnectionInput {
|
||||||
|
return {
|
||||||
|
id: '',
|
||||||
|
name: '',
|
||||||
|
localUrl: '',
|
||||||
|
remoteUrl: '',
|
||||||
|
endpointMode: 'auto',
|
||||||
|
insecure: false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
watch(
|
||||||
|
() => props.open,
|
||||||
|
(v) => {
|
||||||
|
if (!v) return
|
||||||
|
const c = props.connection
|
||||||
|
form.value = c
|
||||||
|
? {
|
||||||
|
id: c.id,
|
||||||
|
name: c.name,
|
||||||
|
localUrl: c.localUrl,
|
||||||
|
remoteUrl: c.remoteUrl,
|
||||||
|
endpointMode: c.endpointMode,
|
||||||
|
insecure: c.insecure
|
||||||
|
}
|
||||||
|
: blank()
|
||||||
|
token.value = ''
|
||||||
|
probes.value = []
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
async function test() {
|
||||||
|
if (testing.value) return
|
||||||
|
if (!token.value.trim() && !hasStoredToken.value) {
|
||||||
|
toast.error('请先填写访问令牌')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!form.value.localUrl.trim() && !form.value.remoteUrl.trim()) {
|
||||||
|
toast.error('请至少填写一个地址')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
testing.value = true
|
||||||
|
probes.value = []
|
||||||
|
try {
|
||||||
|
probes.value = await store.testConnection({ ...form.value }, token.value)
|
||||||
|
const ok = probes.value.filter((p) => p.ok).length
|
||||||
|
if (ok === 0) toast.error('两个地址都连不上')
|
||||||
|
else toast.success(`${ok} 个地址可用`)
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(String(e))
|
||||||
|
} finally {
|
||||||
|
testing.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function save() {
|
||||||
|
if (saving.value) return
|
||||||
|
if (!form.value.name.trim()) {
|
||||||
|
toast.error('请填写名称')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!form.value.localUrl.trim() && !form.value.remoteUrl.trim()) {
|
||||||
|
toast.error('请至少填写一个地址')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
saving.value = true
|
||||||
|
try {
|
||||||
|
// 保存与写令牌分两步:令牌走凭据库,连接字段走 settings.json
|
||||||
|
const id = await store.saveConnection({ ...form.value })
|
||||||
|
const t = token.value.trim()
|
||||||
|
if (t) await store.setToken(id, t)
|
||||||
|
token.value = ''
|
||||||
|
emit('update:open', false)
|
||||||
|
toast.success(isEdit.value ? '已保存' : '已创建连接')
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(String(e))
|
||||||
|
} finally {
|
||||||
|
saving.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<Dialog :open="open" @update:open="emit('update:open', $event)">
|
||||||
|
<DialogContent class="sm:max-w-lg">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>{{ isEdit ? '编辑连接' : '新建连接' }}</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
长期访问令牌在 Home Assistant 的「个人资料 → 安全 → 长期访问令牌」里创建
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<div class="flex flex-col gap-3">
|
||||||
|
<div class="space-y-1.5">
|
||||||
|
<Label>名称</Label>
|
||||||
|
<Input v-model="form.name" placeholder="如:家里" spellcheck="false" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="space-y-1.5">
|
||||||
|
<Label>局域网地址</Label>
|
||||||
|
<Input
|
||||||
|
v-model="form.localUrl"
|
||||||
|
placeholder="http://192.168.1.10:8123"
|
||||||
|
spellcheck="false"
|
||||||
|
/>
|
||||||
|
<p class="text-xs text-muted-foreground">在家使用;省略协议时自动补 http://</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="space-y-1.5">
|
||||||
|
<Label>反代地址</Label>
|
||||||
|
<Input
|
||||||
|
v-model="form.remoteUrl"
|
||||||
|
placeholder="https://ha.example.com"
|
||||||
|
spellcheck="false"
|
||||||
|
/>
|
||||||
|
<p class="text-xs text-muted-foreground">
|
||||||
|
在外面使用,如 Cloudflare Tunnel 的域名;省略协议时自动补 https://
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="space-y-1.5">
|
||||||
|
<Label>端点策略</Label>
|
||||||
|
<div class="flex gap-2">
|
||||||
|
<Button
|
||||||
|
v-for="m in MODES"
|
||||||
|
:key="m.value"
|
||||||
|
type="button"
|
||||||
|
size="sm"
|
||||||
|
:variant="form.endpointMode === m.value ? 'default' : 'outline'"
|
||||||
|
@click="form.endpointMode = m.value"
|
||||||
|
>
|
||||||
|
{{ m.label }}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
<p class="text-xs text-muted-foreground">{{ modeHint }}</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="space-y-1.5">
|
||||||
|
<Label>长期访问令牌{{ hasStoredToken ? '(留空则保留已存令牌)' : '' }}</Label>
|
||||||
|
<Input
|
||||||
|
v-model="token"
|
||||||
|
type="password"
|
||||||
|
:placeholder="
|
||||||
|
hasStoredToken ? `当前:${props.connection?.tokenMasked ?? ''}` : 'eyJhbGciOi...'
|
||||||
|
"
|
||||||
|
spellcheck="false"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<Label class="text-muted-foreground">忽略 HTTPS 证书校验(自签证书时勾选)</Label>
|
||||||
|
<Switch v-model:model-value="form.insecure" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 逐地址探测结果 -->
|
||||||
|
<div v-if="probes.length" class="flex flex-col gap-2 rounded-lg border bg-subtle px-3 py-2">
|
||||||
|
<div v-for="p in probes" :key="p.url" class="flex items-start gap-2">
|
||||||
|
<span
|
||||||
|
class="mt-1.5 size-1.5 shrink-0 rounded-full"
|
||||||
|
:class="p.ok ? 'bg-success' : 'bg-danger'"
|
||||||
|
/>
|
||||||
|
<div class="min-w-0 flex-1 text-xs">
|
||||||
|
<div class="flex flex-wrap items-center gap-x-1.5">
|
||||||
|
<span class="text-fg-secondary">{{ p.kind === 'local' ? '局域网' : '反代' }}</span>
|
||||||
|
<span class="font-mono text-foreground">{{ p.url }}</span>
|
||||||
|
<span class="tabular-nums text-muted-foreground">{{ p.elapsedMs }}ms</span>
|
||||||
|
</div>
|
||||||
|
<p v-if="p.ok" class="text-success-text">
|
||||||
|
连接成功{{ p.haVersion ? ` · ${p.haVersion}` : ''
|
||||||
|
}}{{ p.locationName ? ` · ${p.locationName}` : ''
|
||||||
|
}}{{ p.temperatureUnit ? ` · ${p.temperatureUnit}` : '' }}
|
||||||
|
</p>
|
||||||
|
<p v-else class="text-danger-text">{{ p.error }}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<DialogFooter class="gap-2">
|
||||||
|
<Button variant="outline" :disabled="testing || saving" @click="test">
|
||||||
|
<Loader2 v-if="testing" class="size-4 animate-spin" />测试
|
||||||
|
</Button>
|
||||||
|
<Button :disabled="saving" @click="save">
|
||||||
|
<Loader2 v-if="saving" class="size-4 animate-spin" />保存
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed } from 'vue'
|
||||||
|
import { toast } from 'vue-sonner'
|
||||||
|
import { ChevronRight, Star } from '@lucide/vue'
|
||||||
|
import { Card, CardContent } from '@/components/ui/card'
|
||||||
|
import { StatusDot } from '@/components/common'
|
||||||
|
import { useSmartHomeStore } from '@/stores/smartHomeStore'
|
||||||
|
import {
|
||||||
|
deviceIcon,
|
||||||
|
deviceTypeLabel,
|
||||||
|
favoriteTargetOf,
|
||||||
|
primaryDisplay,
|
||||||
|
readingLabel,
|
||||||
|
readingValue,
|
||||||
|
statusState,
|
||||||
|
type DeviceView
|
||||||
|
} from '../format'
|
||||||
|
import { controlFor } from './controls'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* **设备卡片**(一级首页的唯一元素)。
|
||||||
|
*
|
||||||
|
* 为什么不再一张实体一张卡(plan §9.9 的根因):真机上 37 个设备挂着 577 个实体
|
||||||
|
* (中位数 9、摄像机 110),平铺之后"厨房插座"会被拆成 6+ 张卡,
|
||||||
|
* 真正的开关还被埋在"故障""开关状态切换"里。
|
||||||
|
*
|
||||||
|
* 卡片只露三样东西(按用户要求):
|
||||||
|
* 1. **名字**(设备名 + 房间 · 类型)
|
||||||
|
* 2. **主控**(该设备的主实体,复用 `controls/`:插座就是开关、灯就是开关+亮度)
|
||||||
|
* 3. **关键读数**(最多 2 个,插座就是功率 + 耗电)
|
||||||
|
*
|
||||||
|
* 其余一切(配置项、诊断项、事件、扩展功能)都进二级详情页,不在这里露头。
|
||||||
|
*/
|
||||||
|
const props = defineProps<{ device: DeviceView }>()
|
||||||
|
const emit = defineEmits<{ open: [] }>()
|
||||||
|
const store = useSmartHomeStore()
|
||||||
|
|
||||||
|
const icon = computed(() => deviceIcon(props.device))
|
||||||
|
const typeLabel = computed(() => deviceTypeLabel(props.device))
|
||||||
|
const favorite = computed(() => store.isFavorite(favoriteTargetOf(props.device)))
|
||||||
|
const offline = computed(() => !props.device.online)
|
||||||
|
const primary = computed(() => props.device.primary)
|
||||||
|
const control = computed(() =>
|
||||||
|
primary.value && primary.value.domain ? controlFor(primary.value.domain) : null
|
||||||
|
)
|
||||||
|
const dotState = computed(() =>
|
||||||
|
primary.value ? statusState(primary.value) : offline.value ? 'warning' : 'neutral'
|
||||||
|
)
|
||||||
|
const statusText = computed(() => (primary.value ? primaryDisplay(primary.value).text : ''))
|
||||||
|
|
||||||
|
const readings = computed(() =>
|
||||||
|
props.device.readings.map((e) => ({ id: e.entityId, label: readingLabel(e), ...readingValue(e) }))
|
||||||
|
)
|
||||||
|
|
||||||
|
/** 副标题:房间 · 类型(两者都可能缺失) */
|
||||||
|
const caption = computed(() =>
|
||||||
|
[props.device.areaName, typeLabel.value].filter(Boolean).join(' · ')
|
||||||
|
)
|
||||||
|
|
||||||
|
async function toggleFavorite() {
|
||||||
|
const target = favoriteTargetOf(props.device)
|
||||||
|
if (!target) return
|
||||||
|
try {
|
||||||
|
await store.toggleFavorite(target)
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(`收藏失败:${(e as { message?: string }).message ?? String(e)}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<Card
|
||||||
|
class="group h-full cursor-pointer gap-0 !py-0 transition-colors hover:border-border-strong hover:shadow-md"
|
||||||
|
:class="offline && 'opacity-60'"
|
||||||
|
@click="emit('open')"
|
||||||
|
>
|
||||||
|
<CardContent class="flex h-full flex-col gap-2.5 !px-3.5 py-3">
|
||||||
|
<!-- 图标 + 名字 + 房间·类型 + 收藏 -->
|
||||||
|
<div class="flex items-start gap-2.5">
|
||||||
|
<span class="flex size-8 shrink-0 items-center justify-center rounded-lg bg-muted">
|
||||||
|
<component :is="icon" class="size-4 text-fg-secondary" :stroke-width="1.75" />
|
||||||
|
</span>
|
||||||
|
<div class="min-w-0 flex-1">
|
||||||
|
<div class="truncate text-[13px] leading-4 font-medium text-foreground">
|
||||||
|
{{ device.name }}
|
||||||
|
</div>
|
||||||
|
<div class="mt-0.5 truncate text-[11px] leading-4 text-muted-foreground">
|
||||||
|
{{ caption }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="-mt-0.5 -mr-1 shrink-0 rounded-sm p-1 transition-colors hover:bg-hover"
|
||||||
|
:title="favorite ? '取消收藏' : '收藏(置顶)'"
|
||||||
|
:aria-label="favorite ? '取消收藏' : '收藏'"
|
||||||
|
@click.stop="toggleFavorite"
|
||||||
|
>
|
||||||
|
<Star
|
||||||
|
class="size-3.5"
|
||||||
|
:class="favorite ? 'text-warning' : 'text-fg-disabled'"
|
||||||
|
:fill="favorite ? 'currentColor' : 'none'"
|
||||||
|
:stroke-width="1.75"
|
||||||
|
/>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 主控:插座=开关、灯=开关+亮度、空调=模式+温度 -->
|
||||||
|
<div v-if="control && primary" @click.stop>
|
||||||
|
<component :is="control" :entity="primary" :disabled="offline" />
|
||||||
|
</div>
|
||||||
|
<div v-else class="flex items-center gap-2">
|
||||||
|
<StatusDot :state="dotState" :label="statusText || (offline ? '离线' : '只读')" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 关键读数:插座就是功率 + 耗电 -->
|
||||||
|
<div v-if="readings.length" class="flex flex-wrap items-baseline gap-x-3.5 gap-y-1">
|
||||||
|
<span v-for="r in readings" :key="r.id" class="flex items-baseline gap-1">
|
||||||
|
<span class="text-[11px] text-muted-foreground">{{ r.label }}</span>
|
||||||
|
<span class="text-[13px] font-medium tabular-nums text-foreground">{{ r.text }}</span>
|
||||||
|
<span v-if="r.unit" class="text-[10px] text-muted-foreground">{{ r.unit }}</span>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 底部:项数 + 进详情(`mt-auto` 让同一行的卡片底边对齐) -->
|
||||||
|
<div
|
||||||
|
class="mt-auto flex items-center justify-between gap-2 border-t border-divider pt-2.5 text-muted-foreground"
|
||||||
|
>
|
||||||
|
<span class="truncate text-[11px]">
|
||||||
|
{{ device.entities.length }} 项<span v-if="device.advancedCount > 0"
|
||||||
|
>({{ device.advancedCount }} 高级)</span
|
||||||
|
>
|
||||||
|
</span>
|
||||||
|
<span
|
||||||
|
class="flex shrink-0 items-center gap-0.5 text-[11px] transition-colors group-hover:text-primary"
|
||||||
|
>
|
||||||
|
详情
|
||||||
|
<ChevronRight class="size-3" :stroke-width="1.75" />
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,253 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, ref, watch } from 'vue'
|
||||||
|
import { ChevronDown, ChevronLeft, ExternalLink } from '@lucide/vue'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Card, CardContent } from '@/components/ui/card'
|
||||||
|
import { StatusDot } from '@/components/common'
|
||||||
|
import { useSmartHomeStore, type RegistryResult } from '@/stores/smartHomeStore'
|
||||||
|
import {
|
||||||
|
buildRegistryIndex,
|
||||||
|
deviceIcon,
|
||||||
|
deviceTypeLabel,
|
||||||
|
primaryDisplay,
|
||||||
|
readingLabel,
|
||||||
|
readingValue,
|
||||||
|
splitDevice,
|
||||||
|
statusState,
|
||||||
|
type DeviceView,
|
||||||
|
type EntityGroup
|
||||||
|
} from '../format'
|
||||||
|
import { controlFor } from './controls'
|
||||||
|
import EntityRow from './EntityRow.vue'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* **设备详情页**(二级)+ 高级项(三级)。
|
||||||
|
*
|
||||||
|
* 层级(与用户 2026-10-19 拍板的设计一致):
|
||||||
|
* - 一级:设备网格(`DeviceCard`)——只露名字 / 主控 / 关键读数
|
||||||
|
* - 二级:本页——主控 + 「常用」功能组(每组内的可控项给控件、只读项给一行值)
|
||||||
|
* - 三级:本页底部的「高级设置」折叠区——配置项、诊断项、集成标记的扩展功能(`*`)、
|
||||||
|
* 事件 / 通知 / 文本类。**默认收起**,展开后仍按功能组归拢并视觉降级。
|
||||||
|
*
|
||||||
|
* 为什么不做成弹窗 / 独立三级路由:摄像机一个设备就有 110 个实体(真机数据),
|
||||||
|
* 弹窗放不下嵌套控件,而多一层路由会让"看一个高级项"变成两次导航。见 plan §9.9。
|
||||||
|
*/
|
||||||
|
const props = defineProps<{
|
||||||
|
device: DeviceView
|
||||||
|
registry: RegistryResult | null
|
||||||
|
}>()
|
||||||
|
const emit = defineEmits<{ back: [] }>()
|
||||||
|
|
||||||
|
const store = useSmartHomeStore()
|
||||||
|
const advancedOpen = ref(false)
|
||||||
|
/** 常用功能组的展开覆盖(`undefined` = 用默认:含主控的组与第一组默认展开) */
|
||||||
|
const groupOverride = ref<Record<string, boolean>>({})
|
||||||
|
|
||||||
|
const index = computed(() => buildRegistryIndex(props.registry))
|
||||||
|
const groups = computed(() => splitDevice(props.device, index.value))
|
||||||
|
const icon = computed(() => deviceIcon(props.device))
|
||||||
|
const typeLabel = computed(() => deviceTypeLabel(props.device))
|
||||||
|
const primary = computed(() => props.device.primary)
|
||||||
|
const control = computed(() =>
|
||||||
|
primary.value && primary.value.domain ? controlFor(primary.value.domain) : null
|
||||||
|
)
|
||||||
|
const offline = computed(() => !props.device.online)
|
||||||
|
const dotState = computed(() =>
|
||||||
|
primary.value ? statusState(primary.value) : offline.value ? 'warning' : 'neutral'
|
||||||
|
)
|
||||||
|
const statusText = computed(() => (primary.value ? primaryDisplay(primary.value).text : ''))
|
||||||
|
|
||||||
|
/** 换了设备就重置展开状态(否则上一台设备的折叠状态会串到下一台) */
|
||||||
|
watch(
|
||||||
|
() => props.device.id,
|
||||||
|
() => {
|
||||||
|
advancedOpen.value = false
|
||||||
|
groupOverride.value = {}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
function groupHasPrimary(group: EntityGroup): boolean {
|
||||||
|
const id = primary.value?.entityId
|
||||||
|
return !!id && group.items.some((i) => i.entity.entityId === id)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 常用功能组是否展开。
|
||||||
|
*
|
||||||
|
* **默认只展开"含主控的那个组"与第一组**:摄像机这类设备有 8 个功能组、75 个常用项,
|
||||||
|
* 全展开等于把详情页变回一堵墙;折叠后一眼能看完分组,再点开具体项。
|
||||||
|
*/
|
||||||
|
function isGroupOpen(group: EntityGroup, idx: number): boolean {
|
||||||
|
const override = groupOverride.value[group.key]
|
||||||
|
if (override !== undefined) return override
|
||||||
|
return groupHasPrimary(group) || idx === 0
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleGroup(group: EntityGroup, idx: number) {
|
||||||
|
groupOverride.value = { ...groupOverride.value, [group.key]: !isGroupOpen(group, idx) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 厂商 + 型号(详情页头部用来认出是哪台设备) */
|
||||||
|
const identity = computed(() =>
|
||||||
|
[props.device.manufacturer, props.device.model].filter(Boolean).join(' ')
|
||||||
|
)
|
||||||
|
const caption = computed(
|
||||||
|
() => [props.device.areaName, typeLabel.value, identity.value].filter(Boolean).join(' · ')
|
||||||
|
)
|
||||||
|
|
||||||
|
/** 读数汇总:常用里的数值型读数(卡片只放 2 个,这里给到 6 个) */
|
||||||
|
const readings = computed(() => {
|
||||||
|
const primaryId = primary.value?.entityId
|
||||||
|
const advancedIds = new Set(
|
||||||
|
groups.value.advanced.flatMap((g) => g.items.map((i) => i.entity.entityId))
|
||||||
|
)
|
||||||
|
return props.device.entities
|
||||||
|
.filter((e) => e.entityId !== primaryId && !advancedIds.has(e.entityId))
|
||||||
|
.filter((e) => e.numeric != null || e.domain === 'binary_sensor' || e.domain === 'person')
|
||||||
|
.slice(0, 6)
|
||||||
|
.map((e) => ({
|
||||||
|
id: e.entityId,
|
||||||
|
label: readingLabel(e),
|
||||||
|
value: readingValue(e)
|
||||||
|
}))
|
||||||
|
})
|
||||||
|
|
||||||
|
const advancedCount = computed(() =>
|
||||||
|
groups.value.advanced.reduce((n, g) => n + g.items.length, 0)
|
||||||
|
)
|
||||||
|
|
||||||
|
function groupTitle(group: EntityGroup): string {
|
||||||
|
return group.label
|
||||||
|
}
|
||||||
|
|
||||||
|
function openInHa() {
|
||||||
|
void store.openHaPage(`/config/devices/device/${props.device.id}`)
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="flex flex-col gap-4">
|
||||||
|
<!-- 返回 + 在 HA 中打开 -->
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<Button variant="ghost" size="sm" class="shrink-0" @click="emit('back')">
|
||||||
|
<ChevronLeft class="size-4" />设备列表
|
||||||
|
</Button>
|
||||||
|
<span class="min-w-0 flex-1 truncate text-xs text-muted-foreground">{{ device.name }}</span>
|
||||||
|
<Button
|
||||||
|
v-if="!device.id.startsWith('solo:')"
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
class="shrink-0"
|
||||||
|
title="在 Home Assistant 里打开这台设备"
|
||||||
|
@click="openInHa"
|
||||||
|
>
|
||||||
|
<ExternalLink class="size-4" />在 HA 中查看
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 头部:身份 + 主控 -->
|
||||||
|
<Card class="!py-0 !gap-0">
|
||||||
|
<CardContent class="flex flex-col gap-3 !px-4 py-3.5">
|
||||||
|
<div class="flex items-center gap-2.5">
|
||||||
|
<component :is="icon" class="size-5 shrink-0 text-fg-secondary" :stroke-width="1.75" />
|
||||||
|
<div class="min-w-0 flex-1">
|
||||||
|
<div class="truncate text-[15px] font-semibold text-foreground">{{ device.name }}</div>
|
||||||
|
<div class="truncate text-[11px] text-muted-foreground">{{ caption }}</div>
|
||||||
|
</div>
|
||||||
|
<StatusDot :state="dotState" :label="statusText || (offline ? '离线' : '只读')" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="control && primary" :title="offline ? '设备离线,暂时无法控制' : undefined">
|
||||||
|
<component :is="control" :entity="primary" :disabled="offline" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 读数汇总(只读实体:不占控件空间,平铺成一行行) -->
|
||||||
|
<div v-if="readings.length" class="flex flex-wrap gap-x-5 gap-y-1.5">
|
||||||
|
<span v-for="r in readings" :key="r.id" class="flex items-baseline gap-1">
|
||||||
|
<span class="text-[11px] text-muted-foreground">{{ r.label }}</span>
|
||||||
|
<span class="text-[13px] font-medium tabular-nums text-foreground">{{
|
||||||
|
r.value.text
|
||||||
|
}}</span>
|
||||||
|
<span v-if="r.value.unit" class="text-[10px] text-muted-foreground">{{
|
||||||
|
r.value.unit
|
||||||
|
}}</span>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<!-- 常用:按功能组归拢(默认只展开含主控的组与第一组) -->
|
||||||
|
<Card v-for="(group, gi) in groups.common" :key="group.key" class="!py-0 !gap-0">
|
||||||
|
<CardContent class="!px-4">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="flex w-full items-center gap-2 py-3 text-left"
|
||||||
|
:aria-expanded="isGroupOpen(group, gi)"
|
||||||
|
@click="toggleGroup(group, gi)"
|
||||||
|
>
|
||||||
|
<ChevronDown
|
||||||
|
class="size-4 shrink-0 text-fg-secondary transition-transform"
|
||||||
|
:class="isGroupOpen(group, gi) && 'rotate-180'"
|
||||||
|
:stroke-width="1.75"
|
||||||
|
/>
|
||||||
|
<span class="min-w-0 flex-1 truncate text-[12.5px] font-medium text-foreground">{{
|
||||||
|
groupTitle(group)
|
||||||
|
}}</span>
|
||||||
|
<span class="shrink-0 text-[11px] text-muted-foreground">{{ group.items.length }}</span>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<div v-if="isGroupOpen(group, gi)" class="pb-2">
|
||||||
|
<EntityRow
|
||||||
|
v-for="item in group.items"
|
||||||
|
:key="item.entity.entityId"
|
||||||
|
:entity="item.entity"
|
||||||
|
:label="item.item"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<!-- 三级:高级设置(默认收起) -->
|
||||||
|
<Card v-if="advancedCount > 0" class="!py-0 !gap-0">
|
||||||
|
<CardContent class="!px-4">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="flex w-full items-center gap-2 py-3 text-left"
|
||||||
|
:aria-expanded="advancedOpen"
|
||||||
|
@click="advancedOpen = !advancedOpen"
|
||||||
|
>
|
||||||
|
<ChevronDown
|
||||||
|
class="size-4 shrink-0 text-fg-secondary transition-transform"
|
||||||
|
:class="advancedOpen && 'rotate-180'"
|
||||||
|
:stroke-width="1.75"
|
||||||
|
/>
|
||||||
|
<span class="text-[12.5px] font-medium text-fg-secondary">高级设置</span>
|
||||||
|
<span class="text-[11px] text-muted-foreground">{{ advancedCount }} 项</span>
|
||||||
|
<span class="ml-auto truncate text-[11px] text-fg-disabled">
|
||||||
|
配置 · 诊断 · 扩展功能
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<div v-if="advancedOpen" class="pb-2">
|
||||||
|
<div v-for="group in groups.advanced" :key="group.key" class="pt-2">
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<span class="text-[11.5px] font-medium text-fg-secondary">{{ group.label }}</span>
|
||||||
|
<span class="text-[11px] text-fg-disabled">{{ group.items.length }}</span>
|
||||||
|
</div>
|
||||||
|
<EntityRow
|
||||||
|
v-for="item in group.items"
|
||||||
|
:key="item.entity.entityId"
|
||||||
|
:entity="item.entity"
|
||||||
|
:label="item.item"
|
||||||
|
muted
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<p v-else class="text-[11px] text-muted-foreground">
|
||||||
|
这台设备没有配置 / 诊断类的高级项。
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,512 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
|
||||||
|
import { toast } from 'vue-sonner'
|
||||||
|
import { Activity, Loader2, PlugZap, Plus, RefreshCw, Search } from '@lucide/vue'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Card, CardContent } from '@/components/ui/card'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||||
|
import { Switch } from '@/components/ui/switch'
|
||||||
|
import { StateBlock, StatusDot } from '@/components/common'
|
||||||
|
import { useSmartHomeStore } from '@/stores/smartHomeStore'
|
||||||
|
import {
|
||||||
|
DEVICE_GROUPS,
|
||||||
|
NO_AREA,
|
||||||
|
buildDevices,
|
||||||
|
buildRegistryIndex,
|
||||||
|
compareText,
|
||||||
|
deviceGroupKey,
|
||||||
|
favoriteTargetOf,
|
||||||
|
relativeTimeFromSec,
|
||||||
|
type DeviceView
|
||||||
|
} from '../format'
|
||||||
|
import DeviceCard from './DeviceCard.vue'
|
||||||
|
import DeviceDetail from './DeviceDetail.vue'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 设备页(一级:**设备网格**;二级:设备详情)。
|
||||||
|
*
|
||||||
|
* 真机普查(plan §9.9)决定了两件事:
|
||||||
|
* 1. **必须按设备聚合**:577 个实体挂在 37 个设备下(中位数 9、摄像机 110),
|
||||||
|
* 平铺会让"厨房插座"变成 6+ 张卡,真正的开关被埋进诊断项里;
|
||||||
|
* 2. **聚合只能靠 WS 注册表**:REST 的 `/api/states` 里没有 `device_id`。
|
||||||
|
* 因此没有实时连接时这里不做"降级的平铺视图"(那正是用户要摆脱的东西),
|
||||||
|
* 而是给一个说明 + 一键开启实时连接。
|
||||||
|
*
|
||||||
|
* 分类(顶部横排按钮 / 搜索 / 房间 / 三个过滤开关)全部作用在**设备**上:
|
||||||
|
* 搜索同时匹配设备名与其任一实体名("搜到某个实体就知道它属于哪台设备")。
|
||||||
|
*/
|
||||||
|
const emit = defineEmits<{ 'open-settings': [] }>()
|
||||||
|
const store = useSmartHomeStore()
|
||||||
|
|
||||||
|
/** 让"更新于 x 分钟前"自己走时(否则会一直停在"刚刚"直到下次刷新) */
|
||||||
|
const nowMs = ref(Date.now())
|
||||||
|
let tickTimer: number | null = null
|
||||||
|
/** 自动刷新定时器(只在本页挂载期间跑) */
|
||||||
|
let refreshTimer: number | null = null
|
||||||
|
|
||||||
|
/** 注册表索引(`entity_id` → 设备 / 分类) */
|
||||||
|
const index = computed(() => buildRegistryIndex(store.registry))
|
||||||
|
/** 具备"按设备浏览"的条件(设备映射来自 WS 注册表) */
|
||||||
|
const deviceMode = computed(() => !!store.registry)
|
||||||
|
const allDevices = computed<DeviceView[]>(() => buildDevices(store.entities, index.value))
|
||||||
|
|
||||||
|
/** 房间键(未分配用哨兵值) */
|
||||||
|
function areaKeyOf(device: DeviceView): string {
|
||||||
|
return device.areaId ?? NO_AREA
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 先应用"隐藏离线 / 只显示可控 / 隐不隐系统设备",后面的过滤都在它之上叠加 —— 数字才和看到的条数一致 */
|
||||||
|
const baseDevices = computed<DeviceView[]>(() =>
|
||||||
|
allDevices.value.filter((d) => {
|
||||||
|
if (store.hideUnavailable && !d.online) return false
|
||||||
|
if (store.onlyControllable && !d.controllable) return false
|
||||||
|
if (!store.showSystemDevices && d.systemOnly) return false
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
)
|
||||||
|
|
||||||
|
/** 被"显示无控件设备"开关排除掉的数量(给个提示,别让用户以为设备丢了) */
|
||||||
|
const hiddenSystemCount = computed(
|
||||||
|
() => (store.showSystemDevices ? 0 : allDevices.value.filter((d) => d.systemOnly).length)
|
||||||
|
)
|
||||||
|
|
||||||
|
function inCurrentRoom(device: DeviceView): boolean {
|
||||||
|
if (store.filterRoom === 'all') return true
|
||||||
|
return areaKeyOf(device) === store.filterRoom
|
||||||
|
}
|
||||||
|
|
||||||
|
function isFavoriteDevice(device: DeviceView): boolean {
|
||||||
|
const target = favoriteTargetOf(device)
|
||||||
|
return !!target && store.isFavorite(target)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 房间 + 离线/可控(不含分组与搜索):分组计数在它上面统计 */
|
||||||
|
const roomScoped = computed<DeviceView[]>(() => baseDevices.value.filter(inCurrentRoom))
|
||||||
|
|
||||||
|
const groupCounts = computed<Record<string, number>>(() => {
|
||||||
|
const counts: Record<string, number> = { all: roomScoped.value.length, fav: 0 }
|
||||||
|
for (const g of DEVICE_GROUPS) counts[g.value] = 0
|
||||||
|
for (const d of roomScoped.value) {
|
||||||
|
const key = deviceGroupKey(d)
|
||||||
|
counts[key] = (counts[key] ?? 0) + 1
|
||||||
|
if (isFavoriteDevice(d)) counts.fav += 1
|
||||||
|
}
|
||||||
|
return counts
|
||||||
|
})
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 顶部横排的分类按钮。
|
||||||
|
*
|
||||||
|
* **只列"确实有设备"的分类**:真机 36 台设备里 `影音` / `窗帘` / `门锁` 目前为空,
|
||||||
|
* 空分类占位只会让分类条变长。`全部` / `收藏` 常驻。计数见 `groupCounts`。
|
||||||
|
*/
|
||||||
|
const groupItems = computed(() => [
|
||||||
|
{ value: 'all', label: '全部' },
|
||||||
|
{ value: 'fav', label: '收藏' },
|
||||||
|
...DEVICE_GROUPS.filter((g) => (groupCounts.value[g.value] ?? 0) > 0).map((g) => ({
|
||||||
|
value: g.value,
|
||||||
|
label: g.label
|
||||||
|
}))
|
||||||
|
])
|
||||||
|
|
||||||
|
/** 分组 + 搜索(不含房间):房间计数在它上面统计 */
|
||||||
|
const groupScoped = computed<DeviceView[]>(() => {
|
||||||
|
const q = store.searchQuery.trim().toLowerCase()
|
||||||
|
let list = baseDevices.value
|
||||||
|
if (store.filterGroup === 'fav') list = list.filter(isFavoriteDevice)
|
||||||
|
else if (store.filterGroup !== 'all') list = list.filter((d) => deviceGroupKey(d) === store.filterGroup)
|
||||||
|
if (q) {
|
||||||
|
list = list.filter(
|
||||||
|
(d) =>
|
||||||
|
d.name.toLowerCase().includes(q) ||
|
||||||
|
d.entities.some(
|
||||||
|
(e) => e.name.toLowerCase().includes(q) || e.entityId.toLowerCase().includes(q)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return list
|
||||||
|
})
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 房间分段(含「未分配房间」)。
|
||||||
|
*
|
||||||
|
* 只列当前分组/搜索下**确实有设备**的房间:真机上 Room 会只挂着别的类型的设备,
|
||||||
|
* 点进去空白比不显示更让人困惑;「未分配房间」不是兜底(真机 9 个设备没有区域)。
|
||||||
|
*/
|
||||||
|
const roomItems = computed(() => {
|
||||||
|
if (!store.registry) return []
|
||||||
|
const counts = new Map<string, number>()
|
||||||
|
for (const d of groupScoped.value) {
|
||||||
|
const key = areaKeyOf(d)
|
||||||
|
counts.set(key, (counts.get(key) ?? 0) + 1)
|
||||||
|
}
|
||||||
|
const items = store.registry.areas
|
||||||
|
.map((a) => ({ value: a.areaId, label: a.name, count: counts.get(a.areaId) ?? 0 }))
|
||||||
|
.filter((r) => r.count > 0)
|
||||||
|
const unassigned = counts.get(NO_AREA) ?? 0
|
||||||
|
if (unassigned > 0) items.push({ value: NO_AREA, label: '未分配房间', count: unassigned })
|
||||||
|
return items.sort((a, b) => compareText(a.label, b.label))
|
||||||
|
})
|
||||||
|
|
||||||
|
const visibleDevices = computed<DeviceView[]>(() => {
|
||||||
|
const list = groupScoped.value.filter(inCurrentRoom)
|
||||||
|
// 收藏置顶,其余按中文名
|
||||||
|
return [...list].sort((a, b) => {
|
||||||
|
const fa = isFavoriteDevice(a) ? 0 : 1
|
||||||
|
const fb = isFavoriteDevice(b) ? 0 : 1
|
||||||
|
if (fa !== fb) return fa - fb
|
||||||
|
return compareText(a.name, b.name)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
/** 当前打开的详情(设备被移除 / 换连接后自动回落到列表) */
|
||||||
|
const selectedDevice = computed<DeviceView | null>(
|
||||||
|
() => allDevices.value.find((d) => d.id === store.selectedDeviceId) ?? null
|
||||||
|
)
|
||||||
|
|
||||||
|
/** 令牌失效这类错误:不保留旧数据(见 store.loadEntities 的注释) */
|
||||||
|
const fatalError = computed(() => store.entitiesError?.kind === 'auth')
|
||||||
|
const softError = computed(() => !!store.entitiesError && !fatalError.value)
|
||||||
|
const firstLoading = computed(
|
||||||
|
() => !store.ready || (store.entitiesLoading && store.entities.length === 0)
|
||||||
|
)
|
||||||
|
|
||||||
|
const linkLabel = computed(() => {
|
||||||
|
const c = store.activeConnection
|
||||||
|
if (c?.endpointUrl) {
|
||||||
|
const kind = c.endpointKind === 'local' ? '局域网' : '远程(反代)'
|
||||||
|
return `${kind} · ${c.endpointLatencyMs ?? 0}ms`
|
||||||
|
}
|
||||||
|
return '尚未探测'
|
||||||
|
})
|
||||||
|
const linkState = computed<'success' | 'warning' | 'neutral'>(() => {
|
||||||
|
if (store.activeConnection?.endpointUrl) return 'success'
|
||||||
|
return store.entitiesError ? 'warning' : 'neutral'
|
||||||
|
})
|
||||||
|
const updatedLabel = computed(() => relativeTimeFromSec(store.fetchedAt, nowMs.value))
|
||||||
|
|
||||||
|
const hasFilter = computed(
|
||||||
|
() =>
|
||||||
|
!!store.searchQuery.trim() ||
|
||||||
|
store.onlyControllable ||
|
||||||
|
store.hideUnavailable ||
|
||||||
|
store.filterGroup !== 'all' ||
|
||||||
|
store.filterRoom !== 'all'
|
||||||
|
)
|
||||||
|
|
||||||
|
function clearFilters() {
|
||||||
|
store.searchQuery = ''
|
||||||
|
store.onlyControllable = false
|
||||||
|
store.hideUnavailable = false
|
||||||
|
store.filterGroup = 'all'
|
||||||
|
store.filterRoom = 'all'
|
||||||
|
}
|
||||||
|
|
||||||
|
async function reload() {
|
||||||
|
await store.loadEntities(true)
|
||||||
|
if (store.entitiesError) {
|
||||||
|
toast.error(store.entitiesError.message)
|
||||||
|
} else {
|
||||||
|
toast.success(`已刷新 ${allDevices.value.length} 台设备 / ${store.entities.length} 个实体`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 开启实时连接(设备聚合 + 房间 + 实时状态的前提) */
|
||||||
|
async function enableRealtime() {
|
||||||
|
try {
|
||||||
|
await store.setRealtimeEnabled(true)
|
||||||
|
toast.success('已开启实时连接')
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(`开启失败:${(e as { message?: string }).message ?? String(e)}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function stopAutoRefresh() {
|
||||||
|
if (refreshTimer !== null) {
|
||||||
|
window.clearInterval(refreshTimer)
|
||||||
|
refreshTimer = null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 自动刷新:**远端链路与实时推送下都不启用**(plan §5.2)。
|
||||||
|
*
|
||||||
|
* - 反代:每次自动刷新都是几百 KB 的全量拉取,应当改用实时连接
|
||||||
|
* - 实时已连上:状态本来就是推送来的,再周期性拉全量是纯浪费、还会让"更新于"抖动
|
||||||
|
*/
|
||||||
|
function startAutoRefresh() {
|
||||||
|
stopAutoRefresh()
|
||||||
|
const sec = store.autoRefreshSec
|
||||||
|
if (!sec || store.isRemoteLink || store.wsConnected) return
|
||||||
|
refreshTimer = window.setInterval(() => {
|
||||||
|
void store.loadEntities(true)
|
||||||
|
}, sec * 1000)
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
tickTimer = window.setInterval(() => {
|
||||||
|
nowMs.value = Date.now()
|
||||||
|
}, 30_000)
|
||||||
|
startAutoRefresh()
|
||||||
|
})
|
||||||
|
|
||||||
|
onUnmounted(() => {
|
||||||
|
if (tickTimer !== null) window.clearInterval(tickTimer)
|
||||||
|
stopAutoRefresh()
|
||||||
|
})
|
||||||
|
|
||||||
|
// 首次拉取的触发在 store 里(等设置就绪 + 并发守卫),见 smartHomeStore 的注释
|
||||||
|
watch(
|
||||||
|
() => [store.autoRefreshSec, store.isRemoteLink, store.wsConnected] as const,
|
||||||
|
startAutoRefresh
|
||||||
|
)
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="flex flex-col gap-4">
|
||||||
|
<!-- ===== 空态:还没配置任何连接 ===== -->
|
||||||
|
<Card v-if="store.ready && !store.configured">
|
||||||
|
<CardContent class="!px-4">
|
||||||
|
<StateBlock
|
||||||
|
variant="empty"
|
||||||
|
title="还没有连接 Home Assistant"
|
||||||
|
description="填写局域网地址(在家用)和/或反代地址(在外面用,如 Cloudflare Tunnel),再粘贴长期访问令牌。令牌会存进系统凭据管理器。"
|
||||||
|
:min-height="220"
|
||||||
|
>
|
||||||
|
<template #action>
|
||||||
|
<Button size="sm" @click="emit('open-settings')">
|
||||||
|
<Plus class="size-4" />连接 Home Assistant
|
||||||
|
</Button>
|
||||||
|
</template>
|
||||||
|
</StateBlock>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<!-- ===== 二级:设备详情 ===== -->
|
||||||
|
<DeviceDetail
|
||||||
|
v-else-if="selectedDevice"
|
||||||
|
:device="selectedDevice"
|
||||||
|
:registry="store.registry"
|
||||||
|
@back="store.closeDevice()"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<template v-else>
|
||||||
|
<!-- ===== 没有实时连接:按设备浏览的前提不成立 ===== -->
|
||||||
|
<Card v-if="!deviceMode && store.ready">
|
||||||
|
<CardContent class="!px-4">
|
||||||
|
<StateBlock
|
||||||
|
variant="empty"
|
||||||
|
title="按设备浏览需要实时连接"
|
||||||
|
description="Home Assistant 的接口只在设备注册表里记录「实体属于哪台设备」,而注册表只能通过 WebSocket 读取。开启后会同时带来状态实时更新与房间分组。"
|
||||||
|
:min-height="220"
|
||||||
|
>
|
||||||
|
<template #action>
|
||||||
|
<Button size="sm" :disabled="store.wsBusy" @click="enableRealtime">
|
||||||
|
<Loader2 v-if="store.wsBusy" class="size-4 animate-spin" />
|
||||||
|
<PlugZap v-else class="size-4" />开启实时连接
|
||||||
|
</Button>
|
||||||
|
</template>
|
||||||
|
</StateBlock>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<template v-else>
|
||||||
|
<!-- ===== 工具条:链路 → 实时状态 → 更新时间 → 刷新 ===== -->
|
||||||
|
<div class="flex flex-wrap items-center gap-x-4 gap-y-2">
|
||||||
|
<StatusDot :state="linkState" :label="linkLabel" :pulse="store.entitiesLoading" />
|
||||||
|
<span
|
||||||
|
v-if="store.realtimeWanted"
|
||||||
|
class="flex items-center gap-1.5 text-xs"
|
||||||
|
:class="store.wsConnected ? 'text-success-text' : 'text-muted-foreground'"
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
class="size-1.5 rounded-full"
|
||||||
|
:class="store.wsConnected ? 'bg-success' : 'bg-fg-disabled'"
|
||||||
|
/>
|
||||||
|
{{ store.wsConnected ? '实时同步中' : '实时连接未就绪' }}
|
||||||
|
</span>
|
||||||
|
<span class="text-xs text-muted-foreground">更新于 {{ updatedLabel }}</span>
|
||||||
|
<span class="text-xs text-muted-foreground">
|
||||||
|
{{ allDevices.length }} 台设备 / {{ store.entities.length }} 个实体
|
||||||
|
</span>
|
||||||
|
<div class="ml-auto flex items-center gap-2">
|
||||||
|
<Button size="sm" variant="outline" :disabled="store.entitiesLoading" @click="reload">
|
||||||
|
<Loader2 v-if="store.entitiesLoading" class="size-4 animate-spin" />
|
||||||
|
<RefreshCw v-else class="size-4" />刷新
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- ===== 非致命错误:保留已有数据,只加提示 ===== -->
|
||||||
|
<div
|
||||||
|
v-if="softError"
|
||||||
|
class="flex items-start gap-2.5 rounded-lg border border-warning bg-warning-soft px-4 py-2.5"
|
||||||
|
>
|
||||||
|
<Activity class="mt-0.5 size-4 shrink-0 text-warning" :stroke-width="1.75" />
|
||||||
|
<p class="min-w-0 flex-1 text-xs break-words text-warning-text">
|
||||||
|
刷新失败:{{ store.entitiesError?.message }}(下面显示的是上次成功的数据)
|
||||||
|
</p>
|
||||||
|
<Button size="sm" variant="outline" class="shrink-0" @click="reload">重试</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- ===== 分类:顶部横排按钮(只列"确实有设备"的类别)===== -->
|
||||||
|
<div class="-mx-0.5 flex items-center gap-1.5 overflow-x-auto px-0.5 pb-0.5" role="tablist" aria-label="设备分类">
|
||||||
|
<button
|
||||||
|
v-for="g in groupItems"
|
||||||
|
:key="g.value"
|
||||||
|
type="button"
|
||||||
|
role="tab"
|
||||||
|
:aria-selected="store.filterGroup === g.value"
|
||||||
|
class="flex shrink-0 items-center gap-1.5 rounded-full px-3 py-1.5 text-[12.5px] transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring/40"
|
||||||
|
:class="
|
||||||
|
store.filterGroup === g.value
|
||||||
|
? 'bg-primary-soft font-medium text-primary-soft-text'
|
||||||
|
: 'bg-subtle text-fg-secondary hover:bg-hover hover:text-foreground'
|
||||||
|
"
|
||||||
|
@click="store.filterGroup = g.value"
|
||||||
|
>
|
||||||
|
<span class="truncate">{{ g.label }}</span>
|
||||||
|
<span
|
||||||
|
class="shrink-0 rounded-full px-1.5 text-[10px] tabular-nums"
|
||||||
|
:class="
|
||||||
|
store.filterGroup === g.value
|
||||||
|
? 'bg-primary-soft-text/15 text-primary-soft-text'
|
||||||
|
: 'bg-card/70 text-fg-secondary'
|
||||||
|
"
|
||||||
|
>
|
||||||
|
{{ groupCounts[g.value] ?? 0 }}
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- ===== 过滤行:搜索 + 房间 + 三个开关 ===== -->
|
||||||
|
<div class="flex flex-wrap items-center gap-x-3 gap-y-2">
|
||||||
|
<div class="relative w-full sm:w-64">
|
||||||
|
<Search
|
||||||
|
class="pointer-events-none absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2 text-muted-foreground"
|
||||||
|
:stroke-width="1.75"
|
||||||
|
/>
|
||||||
|
<Input
|
||||||
|
v-model="store.searchQuery"
|
||||||
|
placeholder="搜索设备 / 实体"
|
||||||
|
class="h-8 pl-8"
|
||||||
|
spellcheck="false"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 房间:单实例上(真机只有 1 个区域)几乎用不到,没有房间时干脆不占位 -->
|
||||||
|
<Select
|
||||||
|
v-if="roomItems.length > 0"
|
||||||
|
:model-value="store.filterRoom"
|
||||||
|
@update:model-value="(v) => (store.filterRoom = String(v))"
|
||||||
|
>
|
||||||
|
<SelectTrigger size="sm" class="w-40" aria-label="房间分组">
|
||||||
|
<SelectValue />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="all">全部房间</SelectItem>
|
||||||
|
<SelectItem v-for="r in roomItems" :key="r.value" :value="r.value">
|
||||||
|
{{ r.label }} · {{ r.count }}
|
||||||
|
</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
|
||||||
|
<div class="flex flex-wrap items-center gap-x-4 gap-y-2">
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<Switch id="sh-only-controllable" v-model:model-value="store.onlyControllable" />
|
||||||
|
<Label for="sh-only-controllable" class="cursor-pointer text-xs text-fg-secondary">
|
||||||
|
只显示可控设备
|
||||||
|
</Label>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<Switch id="sh-hide-unavailable" v-model:model-value="store.hideUnavailable" />
|
||||||
|
<Label for="sh-hide-unavailable" class="cursor-pointer text-xs text-fg-secondary">
|
||||||
|
隐藏离线设备
|
||||||
|
</Label>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<Switch id="sh-show-system" v-model:model-value="store.showSystemDevices" />
|
||||||
|
<Label for="sh-show-system" class="cursor-pointer text-xs text-fg-secondary">
|
||||||
|
显示无控件设备
|
||||||
|
</Label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<span v-if="hiddenSystemCount > 0" class="text-[11px] text-muted-foreground">
|
||||||
|
已隐藏 {{ hiddenSystemCount }} 个无可控项也无读数的设备
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- ===== 设备网格:一层平铺(卡片靠 stretch 对齐行高)===== -->
|
||||||
|
<StateBlock
|
||||||
|
v-if="firstLoading"
|
||||||
|
variant="loading"
|
||||||
|
title="正在读取设备…"
|
||||||
|
:description="store.isRemoteLink ? '通过远程连接加载,可能需要几秒' : undefined"
|
||||||
|
:min-height="260"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<StateBlock
|
||||||
|
v-else-if="fatalError"
|
||||||
|
variant="error"
|
||||||
|
title="访问令牌无效或已被吊销"
|
||||||
|
:description="store.entitiesError?.message"
|
||||||
|
:min-height="260"
|
||||||
|
>
|
||||||
|
<template #action>
|
||||||
|
<Button size="sm" @click="emit('open-settings')">重新填写令牌</Button>
|
||||||
|
</template>
|
||||||
|
</StateBlock>
|
||||||
|
|
||||||
|
<StateBlock
|
||||||
|
v-else-if="store.entitiesError && store.entities.length === 0"
|
||||||
|
variant="error"
|
||||||
|
title="加载设备状态失败"
|
||||||
|
:description="store.entitiesError.message"
|
||||||
|
:min-height="260"
|
||||||
|
>
|
||||||
|
<template #action>
|
||||||
|
<Button size="sm" variant="outline" @click="reload">重试</Button>
|
||||||
|
</template>
|
||||||
|
</StateBlock>
|
||||||
|
|
||||||
|
<StateBlock
|
||||||
|
v-else-if="allDevices.length === 0"
|
||||||
|
variant="empty"
|
||||||
|
title="Home Assistant 里没有可用实体"
|
||||||
|
description="请确认集成已加载、设备已出现在 HA 的「设置 → 设备与服务」中。"
|
||||||
|
:min-height="260"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<StateBlock
|
||||||
|
v-else-if="visibleDevices.length === 0"
|
||||||
|
variant="empty"
|
||||||
|
title="没有匹配的设备"
|
||||||
|
description="当前分类 / 房间 / 搜索 / 过滤条件把结果都排除了。"
|
||||||
|
:min-height="260"
|
||||||
|
>
|
||||||
|
<template #action>
|
||||||
|
<Button v-if="hasFilter" size="sm" variant="outline" @click="clearFilters">
|
||||||
|
清除筛选条件
|
||||||
|
</Button>
|
||||||
|
</template>
|
||||||
|
</StateBlock>
|
||||||
|
|
||||||
|
<div
|
||||||
|
v-else
|
||||||
|
class="grid grid-cols-1 items-stretch gap-3 sm:grid-cols-2 lg:grid-cols-3"
|
||||||
|
>
|
||||||
|
<DeviceCard
|
||||||
|
v-for="d in visibleDevices"
|
||||||
|
:key="d.id"
|
||||||
|
:device="d"
|
||||||
|
@open="store.openDevice(d.id)"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
/**
|
||||||
|
* 实体选择器(可搜索下拉)。
|
||||||
|
*
|
||||||
|
* 规则编辑器里"触发实体 / 动作实体"都用它。数据源就是设备页那份
|
||||||
|
* `store.entities`(P1 已缓存),因此不需要新命令。
|
||||||
|
*
|
||||||
|
* 与 `music/SourcePicker` 同一套写法:Popover + 搜索框 + ScrollArea 列表;
|
||||||
|
* 不做虚拟滚动 —— 真机 577 个实体、搜索框收敛后可见集很小(plan §10 已说明
|
||||||
|
* 数量级问题靠分组/搜索解决而不是虚拟滚动)。
|
||||||
|
*/
|
||||||
|
import { computed, ref } from 'vue'
|
||||||
|
import { ChevronDown, Search } from '@lucide/vue'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
|
||||||
|
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||||
|
import { useSmartHomeStore, type EntitySummary } from '@/stores/smartHomeStore'
|
||||||
|
import { compareByName, domainIcon, domainOf, isControllable, isOffline } from '../format'
|
||||||
|
|
||||||
|
const props = withDefaults(
|
||||||
|
defineProps<{
|
||||||
|
modelValue: string
|
||||||
|
placeholder?: string
|
||||||
|
/** 只列这些 domain(空 = 全部) */
|
||||||
|
domains?: string[]
|
||||||
|
/** 是否只列可控实体(动作实体默认要可控) */
|
||||||
|
controllableOnly?: boolean
|
||||||
|
disabled?: boolean
|
||||||
|
class?: string
|
||||||
|
}>(),
|
||||||
|
{ placeholder: '选择实体', domains: () => [], controllableOnly: false, disabled: false }
|
||||||
|
)
|
||||||
|
const emit = defineEmits<{ 'update:model-value': [string] }>()
|
||||||
|
|
||||||
|
const store = useSmartHomeStore()
|
||||||
|
const open = ref(false)
|
||||||
|
const query = ref('')
|
||||||
|
|
||||||
|
const label = computed(() => {
|
||||||
|
if (!props.modelValue) return props.placeholder
|
||||||
|
return store.entityLabel(props.modelValue)
|
||||||
|
})
|
||||||
|
|
||||||
|
const options = computed<EntitySummary[]>(() => {
|
||||||
|
const q = query.value.trim().toLowerCase()
|
||||||
|
return store.entities
|
||||||
|
.filter((e) => {
|
||||||
|
if (props.domains.length && !props.domains.includes(e.domain)) return false
|
||||||
|
// 动作的目标实体必须真能控制(`format.ts` 的 `isControllable` 与控件渲染同一口径)
|
||||||
|
if (props.controllableOnly && !isControllable(e)) return false
|
||||||
|
if (q && !e.name.toLowerCase().includes(q) && !e.entityId.toLowerCase().includes(q))
|
||||||
|
return false
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
.sort(compareByName)
|
||||||
|
})
|
||||||
|
|
||||||
|
function pick(entityId: string) {
|
||||||
|
emit('update:model-value', entityId)
|
||||||
|
open.value = false
|
||||||
|
query.value = ''
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 离线实体仍可选(规则可能在设备离线时被配置),但要标出来 */
|
||||||
|
function optionCaption(e: EntitySummary): string {
|
||||||
|
const parts = [domainOf(e.entityId)]
|
||||||
|
if (isOffline(e)) parts.push('离线')
|
||||||
|
return parts.join(' · ')
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<Popover v-model:open="open">
|
||||||
|
<PopoverTrigger as-child>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
class="h-9 justify-between font-normal"
|
||||||
|
:class="[props.class, !modelValue && 'text-muted-foreground']"
|
||||||
|
:disabled="disabled"
|
||||||
|
>
|
||||||
|
<span class="truncate">{{ label }}</span>
|
||||||
|
<ChevronDown class="size-3.5 shrink-0 opacity-50" />
|
||||||
|
</Button>
|
||||||
|
</PopoverTrigger>
|
||||||
|
<PopoverContent class="w-80 p-2" align="start">
|
||||||
|
<div class="relative mb-2">
|
||||||
|
<Search
|
||||||
|
class="pointer-events-none absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2 text-muted-foreground"
|
||||||
|
:stroke-width="1.75"
|
||||||
|
/>
|
||||||
|
<Input v-model="query" placeholder="搜索名称 / 实体 ID" class="h-8 pl-8" spellcheck="false" />
|
||||||
|
</div>
|
||||||
|
<!-- ScrollArea 的 viewport 为 h-full,根节点要有确定高度才能滚动 -->
|
||||||
|
<ScrollArea class="h-72">
|
||||||
|
<div class="space-y-0.5 pr-2">
|
||||||
|
<button
|
||||||
|
v-for="e in options"
|
||||||
|
:key="e.entityId"
|
||||||
|
type="button"
|
||||||
|
class="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors hover:bg-row-hover"
|
||||||
|
:class="e.entityId === modelValue && 'bg-primary-soft'"
|
||||||
|
@click="pick(e.entityId)"
|
||||||
|
>
|
||||||
|
<component
|
||||||
|
:is="domainIcon(e)"
|
||||||
|
class="size-3.5 shrink-0 text-fg-secondary"
|
||||||
|
:stroke-width="1.75"
|
||||||
|
/>
|
||||||
|
<span class="min-w-0 flex-1 truncate text-[13px]">{{ e.name }}</span>
|
||||||
|
<span class="shrink-0 text-[11px] text-muted-foreground">{{ optionCaption(e) }}</span>
|
||||||
|
</button>
|
||||||
|
<p v-if="options.length === 0" class="px-2 py-3 text-[11.5px] text-muted-foreground">
|
||||||
|
没有匹配的实体(先在设备页确认实体已加载)。
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</ScrollArea>
|
||||||
|
</PopoverContent>
|
||||||
|
</Popover>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed } from 'vue'
|
||||||
|
import { StatusDot } from '@/components/common'
|
||||||
|
import {
|
||||||
|
domainIcon,
|
||||||
|
isControllable,
|
||||||
|
isOffline,
|
||||||
|
primaryDisplay,
|
||||||
|
readingValue,
|
||||||
|
relativeTime,
|
||||||
|
statusState
|
||||||
|
} from '../format'
|
||||||
|
import type { EntitySummary } from '../format'
|
||||||
|
import { controlFor } from './controls'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 设备详情页里的一行实体。
|
||||||
|
*
|
||||||
|
* 一条行同时承担两种形态(这是"详情页"能容下几十项的关键):
|
||||||
|
* - **可控项** → 渲染对应 domain 的控件(复用 `controls/`,与一级卡片同一套)
|
||||||
|
* - **只读项** → 只显示「名称 + 值 + 单位 + 变化时间」,不占控件的纵向空间
|
||||||
|
*
|
||||||
|
* `muted` 用于高级区(三级):视觉降级,并露出原始 `entity_id` 便于去 HA 排查。
|
||||||
|
*/
|
||||||
|
const props = defineProps<{
|
||||||
|
entity: EntitySummary
|
||||||
|
/** 功能组内的项名(如「电功率」「云台校准」) */
|
||||||
|
label: string
|
||||||
|
muted?: boolean
|
||||||
|
}>()
|
||||||
|
|
||||||
|
const icon = computed(() => domainIcon(props.entity))
|
||||||
|
const offline = computed(() => isOffline(props.entity))
|
||||||
|
const control = computed(() =>
|
||||||
|
isControllable(props.entity) ? controlFor(props.entity.domain) : null
|
||||||
|
)
|
||||||
|
const value = computed(() => readingValue(props.entity))
|
||||||
|
const text = computed(() => primaryDisplay(props.entity).text)
|
||||||
|
const dotState = computed(() => statusState(props.entity))
|
||||||
|
const changed = computed(() => relativeTime(props.entity.lastChanged))
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div
|
||||||
|
class="flex flex-col gap-2 border-b border-divider py-2.5 last:border-b-0"
|
||||||
|
:class="offline && 'opacity-60'"
|
||||||
|
>
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<component
|
||||||
|
:is="icon"
|
||||||
|
class="size-3.5 shrink-0"
|
||||||
|
:class="muted ? 'text-fg-disabled' : 'text-fg-secondary'"
|
||||||
|
:stroke-width="1.75"
|
||||||
|
/>
|
||||||
|
<span
|
||||||
|
class="min-w-0 flex-1 truncate text-[12.5px]"
|
||||||
|
:class="muted ? 'text-fg-secondary' : 'text-foreground'"
|
||||||
|
>
|
||||||
|
{{ label }}
|
||||||
|
</span>
|
||||||
|
|
||||||
|
<!-- 只读项:值就放在这一行;可控项的值由控件自己表达 -->
|
||||||
|
<template v-if="!control">
|
||||||
|
<span
|
||||||
|
class="shrink-0 text-[12.5px] tabular-nums"
|
||||||
|
:class="muted ? 'text-fg-secondary' : 'text-foreground'"
|
||||||
|
>
|
||||||
|
{{ value.text }}<span v-if="value.unit" class="ml-0.5 text-[10px] text-muted-foreground">{{ value.unit }}</span>
|
||||||
|
</span>
|
||||||
|
</template>
|
||||||
|
<StatusDot v-else :state="dotState" :label="text" />
|
||||||
|
|
||||||
|
<span class="shrink-0 text-[11px] text-muted-foreground">{{ changed }}</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="control" :title="offline ? '设备离线,暂时无法控制' : undefined">
|
||||||
|
<component :is="control" :entity="entity" :disabled="offline" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 高级项露出实体 id:三级的意义就是"能查到原始项" -->
|
||||||
|
<p v-if="muted" class="truncate font-mono text-[10px] text-fg-disabled">{{ entity.entityId }}</p>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed } from 'vue'
|
||||||
|
import { AlertTriangle, KeyRound, Loader2, Unplug } from '@lucide/vue'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { useSmartHomeStore } from '@/stores/smartHomeStore'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 顶部状态横幅:**只在出问题时占位**(未配置连接由设备页的空态负责,不在这里重复)。
|
||||||
|
*
|
||||||
|
* 两类问题必须区分(§3.6):
|
||||||
|
* - 令牌无效(auth):应当"重新填写令牌",**重试没有意义**
|
||||||
|
* - 地址不可达(network / config):应当"重新检测 / 去检查地址"
|
||||||
|
*
|
||||||
|
* P4 增加一类:**实时连接的自身问题**(鉴权失败 / 断开重连中)。它与链路问题是
|
||||||
|
* 两件事 —— 链路可能是好的(REST 还能用),但推送断了,设备状态会停在最后一次推送。
|
||||||
|
*/
|
||||||
|
const emit = defineEmits<{ 'open-settings': [] }>()
|
||||||
|
const store = useSmartHomeStore()
|
||||||
|
|
||||||
|
const failed = computed(() => store.link ?? null)
|
||||||
|
const visible = computed(() => !!failed.value && !failed.value.ok)
|
||||||
|
const isAuth = computed(() => failed.value?.errorKind === 'auth')
|
||||||
|
|
||||||
|
/**
|
||||||
|
* WS 自身的问题(只在用户确实想要实时连接时才提示:关掉实时推送的人
|
||||||
|
* 不该被"实时连接已断开"打扰)。
|
||||||
|
*/
|
||||||
|
const wsIssue = computed(() => {
|
||||||
|
if (!store.realtimeWanted) return null
|
||||||
|
const status = store.wsStatus
|
||||||
|
if (!status) return null
|
||||||
|
if (status.state === 'authFailed') {
|
||||||
|
return { kind: 'auth' as const, title: '实时连接鉴权失败', detail: status.detail }
|
||||||
|
}
|
||||||
|
if (status.state === 'disconnected') {
|
||||||
|
return { kind: 'net' as const, title: '实时连接已断开(正在重连)', detail: status.detail }
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<!-- 两条横幅都不出现时整个容器不渲染:否则会白留 16px 的间距 -->
|
||||||
|
<div v-if="visible || wsIssue" class="mb-4 flex flex-col gap-3">
|
||||||
|
<div
|
||||||
|
v-if="visible"
|
||||||
|
class="flex items-start gap-2.5 rounded-lg border px-4 py-3"
|
||||||
|
:class="isAuth ? 'border-danger bg-danger-soft' : 'border-warning bg-warning-soft'"
|
||||||
|
>
|
||||||
|
<component
|
||||||
|
:is="isAuth ? KeyRound : AlertTriangle"
|
||||||
|
class="mt-0.5 size-4 shrink-0"
|
||||||
|
:class="isAuth ? 'text-danger' : 'text-warning'"
|
||||||
|
:stroke-width="1.75"
|
||||||
|
/>
|
||||||
|
<div class="min-w-0 flex-1">
|
||||||
|
<p
|
||||||
|
class="text-[13px] font-medium"
|
||||||
|
:class="isAuth ? 'text-danger-text' : 'text-warning-text'"
|
||||||
|
>
|
||||||
|
{{ isAuth ? '访问令牌无效或已被吊销' : '无法连接 Home Assistant' }}
|
||||||
|
</p>
|
||||||
|
<p
|
||||||
|
class="mt-0.5 text-xs break-words"
|
||||||
|
:class="isAuth ? 'text-danger-text' : 'text-warning-text'"
|
||||||
|
>
|
||||||
|
{{ failed?.error }}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
class="shrink-0"
|
||||||
|
:disabled="store.linkChecking"
|
||||||
|
@click="emit('open-settings')"
|
||||||
|
>
|
||||||
|
<Loader2 v-if="store.linkChecking" class="size-4 animate-spin" />
|
||||||
|
{{ isAuth ? '重新填写令牌' : '检查连接' }}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 实时连接自身的问题(链路可能是好的,但推送断了) -->
|
||||||
|
<div
|
||||||
|
v-if="wsIssue"
|
||||||
|
class="flex items-start gap-2.5 rounded-lg border px-4 py-3"
|
||||||
|
:class="
|
||||||
|
wsIssue.kind === 'auth' ? 'border-danger bg-danger-soft' : 'border-warning bg-warning-soft'
|
||||||
|
"
|
||||||
|
>
|
||||||
|
<Unplug
|
||||||
|
class="mt-0.5 size-4 shrink-0"
|
||||||
|
:class="wsIssue.kind === 'auth' ? 'text-danger' : 'text-warning'"
|
||||||
|
:stroke-width="1.75"
|
||||||
|
/>
|
||||||
|
<div class="min-w-0 flex-1">
|
||||||
|
<p
|
||||||
|
class="text-[13px] font-medium"
|
||||||
|
:class="wsIssue.kind === 'auth' ? 'text-danger-text' : 'text-warning-text'"
|
||||||
|
>
|
||||||
|
{{ wsIssue.title }}
|
||||||
|
</p>
|
||||||
|
<p
|
||||||
|
v-if="wsIssue.detail"
|
||||||
|
class="mt-0.5 text-xs break-words"
|
||||||
|
:class="wsIssue.kind === 'auth' ? 'text-danger-text' : 'text-warning-text'"
|
||||||
|
>
|
||||||
|
{{ wsIssue.detail }}
|
||||||
|
</p>
|
||||||
|
<p
|
||||||
|
class="mt-0.5 text-xs"
|
||||||
|
:class="wsIssue.kind === 'auth' ? 'text-danger-text' : 'text-warning-text'"
|
||||||
|
>
|
||||||
|
{{ wsIssue.kind === 'auth' ? '请到设置页重新填写访问令牌。' : '设备状态会停在最后一次推送。' }}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
v-if="wsIssue.kind === 'net'"
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
class="shrink-0"
|
||||||
|
:disabled="store.wsBusy"
|
||||||
|
@click="store.startRealtime()"
|
||||||
|
>
|
||||||
|
<Loader2 v-if="store.wsBusy" class="size-4 animate-spin" />重连
|
||||||
|
</Button>
|
||||||
|
<Button v-else size="sm" variant="outline" class="shrink-0" @click="emit('open-settings')">
|
||||||
|
重新填写令牌
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,584 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
/**
|
||||||
|
* 本地规则编辑器(三段式:触发 / 条件 / 动作)。
|
||||||
|
*
|
||||||
|
* 设计取舍(与 plan §7.3 一致):
|
||||||
|
* - **线性三段式,不做嵌套树**;条件之间是 AND(多条件不支持 OR —— 需要 OR 就建两条规则);
|
||||||
|
* - 服务下拉只给每个 domain 的**常用几个**,不是 HA 的全部服务:那是几百个枚举,
|
||||||
|
* 让用户在里挑只会配错。**也不提供**"手填 domain/service"的自定义入口 —— 与"简单
|
||||||
|
* 自动化"的边界一致:冷门/带复杂参数的服务请直接在 HA 里建自动化;
|
||||||
|
* - 保存前给出**一句话预览**(`ruleSummary`),避免用户配错灯。
|
||||||
|
*
|
||||||
|
* 校验分两层:这里做即时提示(名称 / 至少一个动作),Rust 侧 `automation::validate`
|
||||||
|
* 是最终关口(两边口径一致,见该函数注释)。
|
||||||
|
*/
|
||||||
|
import { computed, ref, watch } from 'vue'
|
||||||
|
import { toast } from 'vue-sonner'
|
||||||
|
import { Plus, Trash2, ArrowUp, ArrowDown, Info } from '@lucide/vue'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogScrollContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle
|
||||||
|
} from '@/components/ui/dialog'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue
|
||||||
|
} from '@/components/ui/select'
|
||||||
|
import { Switch } from '@/components/ui/switch'
|
||||||
|
import { ConfirmDialog } from '@/components/common'
|
||||||
|
import {
|
||||||
|
useSmartHomeStore,
|
||||||
|
emptyAction,
|
||||||
|
emptyRule,
|
||||||
|
type Rule,
|
||||||
|
type RuleAction,
|
||||||
|
type RuleCondition
|
||||||
|
} from '@/stores/smartHomeStore'
|
||||||
|
import {
|
||||||
|
PARAM_LABEL,
|
||||||
|
domainOf,
|
||||||
|
ruleSummary,
|
||||||
|
servicePresets,
|
||||||
|
type ParamKey
|
||||||
|
} from '../format'
|
||||||
|
import EntityPicker from './EntityPicker.vue'
|
||||||
|
|
||||||
|
const props = defineProps<{
|
||||||
|
open: boolean
|
||||||
|
/** null = 新建 */
|
||||||
|
rule: Rule | null
|
||||||
|
}>()
|
||||||
|
const emit = defineEmits<{ 'update:open': [boolean]; saved: [] }>()
|
||||||
|
|
||||||
|
const store = useSmartHomeStore()
|
||||||
|
const saving = ref(false)
|
||||||
|
|
||||||
|
/** 新建规则:默认值来自 store 的 `emptyRule()`(与 Rust `Rule::default()` 同源),
|
||||||
|
* 再挂一个空动作(一条没有动作的规则保存不了,直接给一个省一次点击)。 */
|
||||||
|
function newRule(): Rule {
|
||||||
|
const rule = emptyRule()
|
||||||
|
rule.actions = [emptyAction()]
|
||||||
|
return rule
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 草稿(编辑 = 深拷贝 prop,避免未保存的编辑污染列表) */
|
||||||
|
const draft = ref<Rule>(newRule())
|
||||||
|
|
||||||
|
const WEEKDAYS = [
|
||||||
|
{ value: 1, label: '一' },
|
||||||
|
{ value: 2, label: '二' },
|
||||||
|
{ value: 3, label: '三' },
|
||||||
|
{ value: 4, label: '四' },
|
||||||
|
{ value: 5, label: '五' },
|
||||||
|
{ value: 6, label: '六' },
|
||||||
|
{ value: 7, label: '日' }
|
||||||
|
]
|
||||||
|
|
||||||
|
// 打开时从 prop 载入草稿(编辑 = 深拷贝;新建 = 空规则)
|
||||||
|
watch(
|
||||||
|
() => props.open,
|
||||||
|
(open) => {
|
||||||
|
if (!open) return
|
||||||
|
draft.value = props.rule ? (JSON.parse(JSON.stringify(props.rule)) as Rule) : newRule()
|
||||||
|
},
|
||||||
|
{ immediate: true }
|
||||||
|
)
|
||||||
|
|
||||||
|
const preview = computed(() => ruleSummary(draft.value, store.entityLabel))
|
||||||
|
|
||||||
|
/** 触发状态的快速填充(真机上 99% 的触发是 on / off) */
|
||||||
|
function setToStates(value: string) {
|
||||||
|
draft.value.trigger.to = value ? value.split(',').map((s) => s.trim()).filter(Boolean) : []
|
||||||
|
}
|
||||||
|
|
||||||
|
const toStatesText = computed({
|
||||||
|
get: () => draft.value.trigger.to.join(','),
|
||||||
|
set: (v: string) => setToStates(v)
|
||||||
|
})
|
||||||
|
|
||||||
|
// ---------- 条件 ----------
|
||||||
|
|
||||||
|
function addCondition(kind: 'state' | 'time') {
|
||||||
|
draft.value.conditions.push({
|
||||||
|
kind,
|
||||||
|
entityId: '',
|
||||||
|
state: '',
|
||||||
|
fromTime: kind === 'time' ? '18:00' : '',
|
||||||
|
toTime: kind === 'time' ? '23:59' : '',
|
||||||
|
weekdays: []
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleWeekday(condition: RuleCondition, day: number) {
|
||||||
|
const i = condition.weekdays.indexOf(day)
|
||||||
|
if (i >= 0) condition.weekdays.splice(i, 1)
|
||||||
|
else condition.weekdays.push(day)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 动作 ----------
|
||||||
|
|
||||||
|
function addAction(kind: 'service' | 'delay' | 'notify') {
|
||||||
|
const action = emptyAction()
|
||||||
|
action.kind = kind
|
||||||
|
if (kind === 'delay') action.seconds = 10
|
||||||
|
draft.value.actions.push(action)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 动作所属实体的 domain(服务下拉据此选预设) */
|
||||||
|
function actionDomain(action: RuleAction): string {
|
||||||
|
return domainOf(action.entityId)
|
||||||
|
}
|
||||||
|
|
||||||
|
function actionPresets(action: RuleAction) {
|
||||||
|
return servicePresets(actionDomain(action))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 当前服务需要填的参数 */
|
||||||
|
function actionParams(action: RuleAction): ParamKey[] {
|
||||||
|
return actionPresets(action).find((p) => p.value === action.service)?.params ?? []
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 实体或服务变了:清掉不再需要的参数,免得把亮度塞给一个开关 */
|
||||||
|
function clearStaleParams(action: RuleAction) {
|
||||||
|
const allowed = new Set<string>(actionParams(action))
|
||||||
|
const params = action.params as Record<string, number | string | undefined>
|
||||||
|
for (const key of Object.keys(params)) {
|
||||||
|
if (!allowed.has(key)) delete params[key]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function onActionEntity(action: RuleAction, entityId: string) {
|
||||||
|
action.entityId = entityId
|
||||||
|
action.domain = domainOf(entityId)
|
||||||
|
const presets = actionPresets(action)
|
||||||
|
if (!presets.some((p) => p.value === action.service)) action.service = presets[0]?.value ?? ''
|
||||||
|
clearStaleParams(action)
|
||||||
|
}
|
||||||
|
|
||||||
|
function onActionService(action: RuleAction, service: string) {
|
||||||
|
action.service = service
|
||||||
|
action.domain = actionDomain(action)
|
||||||
|
clearStaleParams(action)
|
||||||
|
}
|
||||||
|
|
||||||
|
function paramText(action: RuleAction, key: ParamKey): string {
|
||||||
|
const v = (action.params as Record<string, number | string | undefined>)[key]
|
||||||
|
return v === undefined || v === null ? '' : String(v)
|
||||||
|
}
|
||||||
|
|
||||||
|
function setParam(action: RuleAction, key: ParamKey, text: string) {
|
||||||
|
const params = action.params as Record<string, number | string | undefined>
|
||||||
|
if (text.trim() === '') {
|
||||||
|
delete params[key]
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (key === 'option') params[key] = text
|
||||||
|
else params[key] = Number(text)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `option` 参数的候选值来自所选实体(HA 的 `options`),不猜 */
|
||||||
|
function optionChoices(action: RuleAction): string[] {
|
||||||
|
return store.entities.find((e) => e.entityId === action.entityId)?.options ?? []
|
||||||
|
}
|
||||||
|
|
||||||
|
function moveAction(index: number, delta: number) {
|
||||||
|
const next = index + delta
|
||||||
|
if (next < 0 || next >= draft.value.actions.length) return
|
||||||
|
const [item] = draft.value.actions.splice(index, 1)
|
||||||
|
draft.value.actions.splice(next, 0, item)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 保存 ----------
|
||||||
|
|
||||||
|
const deleting = ref<Rule | null>(null)
|
||||||
|
|
||||||
|
async function save() {
|
||||||
|
if (!draft.value.name.trim()) {
|
||||||
|
toast.error('请填写规则名称')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!draft.value.trigger.entityId) {
|
||||||
|
toast.error('请选择触发实体')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (draft.value.actions.length === 0) {
|
||||||
|
toast.error('至少需要一个动作')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
saving.value = true
|
||||||
|
try {
|
||||||
|
await store.saveRule(draft.value)
|
||||||
|
toast.success('规则已保存')
|
||||||
|
emit('saved')
|
||||||
|
emit('update:open', false)
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(`保存失败:${(e as { message?: string }).message ?? String(e)}`)
|
||||||
|
} finally {
|
||||||
|
saving.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function confirmDelete() {
|
||||||
|
const rule = deleting.value
|
||||||
|
if (!rule) return
|
||||||
|
try {
|
||||||
|
await store.deleteRule(rule.id)
|
||||||
|
toast.success(`已删除「${rule.name}」`)
|
||||||
|
deleting.value = null
|
||||||
|
emit('saved')
|
||||||
|
emit('update:open', false)
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(`删除失败:${(e as { message?: string }).message ?? String(e)}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<Dialog :open="props.open" @update:open="(v: boolean) => emit('update:open', v)">
|
||||||
|
<DialogScrollContent class="max-w-2xl">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>{{ draft.id ? '编辑规则' : '新建规则' }}</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
触发 → 条件 → 动作,线性执行;条件之间是「同时满足」。本地规则只在 Thing 运行时生效。
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<div class="flex flex-col gap-5 py-1">
|
||||||
|
<!-- ===== 基本信息 ===== -->
|
||||||
|
<div class="flex items-end gap-3">
|
||||||
|
<div class="flex min-w-0 flex-1 flex-col gap-1.5">
|
||||||
|
<Label>规则名称</Label>
|
||||||
|
<Input v-model="draft.name" placeholder="例如:回家开灯" class="h-9" />
|
||||||
|
</div>
|
||||||
|
<div class="flex shrink-0 items-center gap-2 pb-1.5">
|
||||||
|
<Label class="text-[13px] text-fg-secondary">启用</Label>
|
||||||
|
<Switch v-model:model-value="draft.enabled" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- ===== 触发 ===== -->
|
||||||
|
<section class="flex flex-col gap-3 rounded-lg border border-divider p-3">
|
||||||
|
<h3 class="text-[13px] font-medium text-foreground">触发(满足即开始判定)</h3>
|
||||||
|
|
||||||
|
<div class="flex flex-wrap items-center gap-2">
|
||||||
|
<EntityPicker
|
||||||
|
:model-value="draft.trigger.entityId"
|
||||||
|
placeholder="选择触发实体"
|
||||||
|
class="w-64"
|
||||||
|
@update:model-value="(v) => (draft.trigger.entityId = v)"
|
||||||
|
/>
|
||||||
|
<span class="text-xs text-muted-foreground">变化为</span>
|
||||||
|
<Input
|
||||||
|
v-model="toStatesText"
|
||||||
|
placeholder="留空 = 任意(如 on,off)"
|
||||||
|
class="h-9 w-48"
|
||||||
|
spellcheck="false"
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
class="h-8"
|
||||||
|
@click="draft.trigger.to = ['on']"
|
||||||
|
>
|
||||||
|
开 / 有人
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
class="h-8"
|
||||||
|
@click="draft.trigger.to = ['off']"
|
||||||
|
>
|
||||||
|
关 / 无人
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex flex-wrap items-center gap-2">
|
||||||
|
<span class="text-xs text-muted-foreground">持续</span>
|
||||||
|
<Input
|
||||||
|
v-model.number="draft.trigger.forSec"
|
||||||
|
type="number"
|
||||||
|
min="0"
|
||||||
|
class="h-9 w-24"
|
||||||
|
/>
|
||||||
|
<span class="text-xs text-muted-foreground">秒后仍满足才触发(0 = 立即;用于去抖)</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex flex-wrap items-center gap-2">
|
||||||
|
<span class="text-xs text-muted-foreground">数值条件</span>
|
||||||
|
<Select
|
||||||
|
:model-value="draft.trigger.numericOp || 'none'"
|
||||||
|
@update:model-value="(v) => (draft.trigger.numericOp = String(v) === 'none' ? '' : String(v))"
|
||||||
|
>
|
||||||
|
<SelectTrigger class="h-9 w-28"><SelectValue /></SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="none">不使用</SelectItem>
|
||||||
|
<SelectItem value=">">大于</SelectItem>
|
||||||
|
<SelectItem value=">=">大于等于</SelectItem>
|
||||||
|
<SelectItem value="<">小于</SelectItem>
|
||||||
|
<SelectItem value="<=">小于等于</SelectItem>
|
||||||
|
<SelectItem value="==">等于</SelectItem>
|
||||||
|
<SelectItem value="!=">不等于</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
<Input
|
||||||
|
v-if="draft.trigger.numericOp"
|
||||||
|
:model-value="draft.trigger.numericValue ?? ''"
|
||||||
|
type="number"
|
||||||
|
class="h-9 w-28"
|
||||||
|
@update:model-value="(v) => (draft.trigger.numericValue = v === '' ? null : Number(v))"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- ===== 条件 ===== -->
|
||||||
|
<section class="flex flex-col gap-3 rounded-lg border border-divider p-3">
|
||||||
|
<div class="flex items-center justify-between gap-2">
|
||||||
|
<h3 class="text-[13px] font-medium text-foreground">条件(全部满足才执行)</h3>
|
||||||
|
<div class="flex items-center gap-1">
|
||||||
|
<Button variant="ghost" size="sm" @click="addCondition('time')">
|
||||||
|
<Plus class="size-3.5" />时间窗口
|
||||||
|
</Button>
|
||||||
|
<Button variant="ghost" size="sm" @click="addCondition('state')">
|
||||||
|
<Plus class="size-3.5" />实体状态
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p v-if="draft.conditions.length === 0" class="text-[11.5px] text-muted-foreground">
|
||||||
|
没有条件 = 触发即执行。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div
|
||||||
|
v-for="(c, i) in draft.conditions"
|
||||||
|
:key="`c${i}`"
|
||||||
|
class="flex flex-wrap items-center gap-2 rounded-md bg-subtle px-2.5 py-2"
|
||||||
|
>
|
||||||
|
<template v-if="c.kind === 'time'">
|
||||||
|
<Input v-model="c.fromTime" type="time" class="h-8 w-28" aria-label="起始时间" />
|
||||||
|
<span class="text-xs text-muted-foreground">至</span>
|
||||||
|
<Input v-model="c.toTime" type="time" class="h-8 w-28" aria-label="结束时间" />
|
||||||
|
<div class="flex items-center gap-1">
|
||||||
|
<button
|
||||||
|
v-for="d in WEEKDAYS"
|
||||||
|
:key="d.value"
|
||||||
|
type="button"
|
||||||
|
class="size-7 rounded-md text-[11px] transition-colors"
|
||||||
|
:class="
|
||||||
|
c.weekdays.includes(d.value)
|
||||||
|
? 'bg-primary-soft text-primary-soft-text'
|
||||||
|
: 'text-fg-secondary hover:bg-hover'
|
||||||
|
"
|
||||||
|
:aria-label="`周${d.label}`"
|
||||||
|
:aria-pressed="c.weekdays.includes(d.value)"
|
||||||
|
@click="toggleWeekday(c, d.value)"
|
||||||
|
>
|
||||||
|
{{ d.label }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<span class="text-[11px] text-muted-foreground">不选星期 = 每天</span>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<template v-else>
|
||||||
|
<EntityPicker
|
||||||
|
:model-value="c.entityId"
|
||||||
|
placeholder="选择实体"
|
||||||
|
class="w-56"
|
||||||
|
@update:model-value="(v) => (c.entityId = v)"
|
||||||
|
/>
|
||||||
|
<span class="text-xs text-muted-foreground">状态为</span>
|
||||||
|
<Input v-model="c.state" placeholder="on / off / home…" class="h-8 w-36" />
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
class="ml-auto size-8 text-destructive"
|
||||||
|
aria-label="删除条件"
|
||||||
|
@click="draft.conditions.splice(i, 1)"
|
||||||
|
>
|
||||||
|
<Trash2 class="size-3.5" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- ===== 动作 ===== -->
|
||||||
|
<section class="flex flex-col gap-3 rounded-lg border border-divider p-3">
|
||||||
|
<div class="flex items-center justify-between gap-2">
|
||||||
|
<h3 class="text-[13px] font-medium text-foreground">动作(按顺序执行)</h3>
|
||||||
|
<div class="flex items-center gap-1">
|
||||||
|
<Button variant="ghost" size="sm" @click="addAction('service')">
|
||||||
|
<Plus class="size-3.5" />调服务
|
||||||
|
</Button>
|
||||||
|
<Button variant="ghost" size="sm" @click="addAction('delay')">
|
||||||
|
<Plus class="size-3.5" />延时
|
||||||
|
</Button>
|
||||||
|
<Button variant="ghost" size="sm" @click="addAction('notify')">
|
||||||
|
<Plus class="size-3.5" />通知
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p v-if="draft.actions.length === 0" class="text-[11.5px] text-muted-foreground">
|
||||||
|
还没有动作。至少需要一个动作才能保存。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div
|
||||||
|
v-for="(a, i) in draft.actions"
|
||||||
|
:key="`a${i}`"
|
||||||
|
class="flex flex-col gap-2 rounded-md bg-subtle px-2.5 py-2"
|
||||||
|
>
|
||||||
|
<div class="flex flex-wrap items-center gap-2">
|
||||||
|
<Select
|
||||||
|
:model-value="a.kind"
|
||||||
|
@update:model-value="(v) => (a.kind = String(v))"
|
||||||
|
>
|
||||||
|
<SelectTrigger class="h-8 w-24"><SelectValue /></SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="service">调服务</SelectItem>
|
||||||
|
<SelectItem value="delay">延时</SelectItem>
|
||||||
|
<SelectItem value="notify">通知</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
|
||||||
|
<!-- 调服务 -->
|
||||||
|
<template v-if="a.kind === 'service'">
|
||||||
|
<EntityPicker
|
||||||
|
:model-value="a.entityId"
|
||||||
|
placeholder="选择实体"
|
||||||
|
class="w-56"
|
||||||
|
controllable-only
|
||||||
|
@update:model-value="(v) => onActionEntity(a, v)"
|
||||||
|
/>
|
||||||
|
<Select
|
||||||
|
:model-value="a.service"
|
||||||
|
@update:model-value="(v) => onActionService(a, String(v))"
|
||||||
|
>
|
||||||
|
<SelectTrigger class="h-8 w-36"><SelectValue placeholder="选择服务" /></SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem v-for="p in actionPresets(a)" :key="p.value" :value="p.value">
|
||||||
|
{{ p.label }}
|
||||||
|
</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
<span v-for="key in actionParams(a)" :key="key" class="flex items-center gap-1.5">
|
||||||
|
<span class="text-[11px] text-muted-foreground">{{ PARAM_LABEL[key] }}</span>
|
||||||
|
<Select
|
||||||
|
v-if="key === 'option'"
|
||||||
|
:model-value="paramText(a, key)"
|
||||||
|
@update:model-value="(v) => setParam(a, key, String(v))"
|
||||||
|
>
|
||||||
|
<SelectTrigger class="h-8 w-32"><SelectValue placeholder="选择" /></SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem v-for="opt in optionChoices(a)" :key="opt" :value="opt">
|
||||||
|
{{ opt }}
|
||||||
|
</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
<Input
|
||||||
|
v-else
|
||||||
|
:model-value="paramText(a, key)"
|
||||||
|
type="number"
|
||||||
|
class="h-8 w-28"
|
||||||
|
@update:model-value="(v) => setParam(a, key, String(v))"
|
||||||
|
/>
|
||||||
|
</span>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<!-- 延时 -->
|
||||||
|
<template v-else-if="a.kind === 'delay'">
|
||||||
|
<span class="text-xs text-muted-foreground">等待</span>
|
||||||
|
<Input v-model.number="a.seconds" type="number" min="1" max="600" class="h-8 w-24" />
|
||||||
|
<span class="text-xs text-muted-foreground">秒(最长 600)</span>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<!-- 通知 -->
|
||||||
|
<template v-else>
|
||||||
|
<Input v-model="a.title" placeholder="标题" class="h-8 w-40" />
|
||||||
|
<Input v-model="a.message" placeholder="正文" class="h-8 min-w-40 flex-1" />
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<div class="ml-auto flex shrink-0 items-center gap-0.5">
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
class="size-8"
|
||||||
|
aria-label="上移"
|
||||||
|
:disabled="i === 0"
|
||||||
|
@click="moveAction(i, -1)"
|
||||||
|
>
|
||||||
|
<ArrowUp class="size-3.5" />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
class="size-8"
|
||||||
|
aria-label="下移"
|
||||||
|
:disabled="i === draft.actions.length - 1"
|
||||||
|
@click="moveAction(i, 1)"
|
||||||
|
>
|
||||||
|
<ArrowDown class="size-3.5" />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
class="size-8 text-destructive"
|
||||||
|
aria-label="删除动作"
|
||||||
|
@click="draft.actions.splice(i, 1)"
|
||||||
|
>
|
||||||
|
<Trash2 class="size-3.5" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- ===== 冷却 ===== -->
|
||||||
|
<section class="flex flex-wrap items-center gap-3 rounded-lg border border-divider p-3">
|
||||||
|
<Label class="text-[13px]">冷却时间</Label>
|
||||||
|
<Input v-model.number="draft.cooldownSec" type="number" min="0" class="h-9 w-24" />
|
||||||
|
<span class="text-xs text-muted-foreground">
|
||||||
|
秒内的重复触发会被丢弃(防止状态抖动反复触发;0 = 不限制)
|
||||||
|
</span>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- ===== 一句话预览(保存前的最后一道人眼检查) ===== -->
|
||||||
|
<div class="flex items-start gap-2 rounded-lg bg-subtle px-3 py-2.5">
|
||||||
|
<Info class="mt-0.5 size-3.5 shrink-0 text-fg-secondary" :stroke-width="1.75" />
|
||||||
|
<p class="text-[12.5px] text-fg-secondary">{{ preview }}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<DialogFooter class="gap-2">
|
||||||
|
<Button
|
||||||
|
v-if="draft.id"
|
||||||
|
variant="ghost"
|
||||||
|
class="mr-auto text-destructive"
|
||||||
|
@click="deleting = draft"
|
||||||
|
>
|
||||||
|
删除规则
|
||||||
|
</Button>
|
||||||
|
<Button variant="outline" @click="emit('update:open', false)">取消</Button>
|
||||||
|
<Button :disabled="saving" @click="save">保存</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogScrollContent>
|
||||||
|
</Dialog>
|
||||||
|
|
||||||
|
<ConfirmDialog
|
||||||
|
:open="!!deleting"
|
||||||
|
variant="danger"
|
||||||
|
title="删除这条规则?"
|
||||||
|
:description="deleting ? `「${deleting.name}」将被移除,且不可恢复。` : ''"
|
||||||
|
confirm-text="删除"
|
||||||
|
@update:open="(v) => !v && (deleting = null)"
|
||||||
|
@confirm="confirmDelete"
|
||||||
|
/>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,427 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, ref } from 'vue'
|
||||||
|
import { toast } from 'vue-sonner'
|
||||||
|
import { CircleCheck, ExternalLink, Loader2, Pencil, Plus, Trash2 } from '@lucide/vue'
|
||||||
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Card, CardContent } from '@/components/ui/card'
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue
|
||||||
|
} from '@/components/ui/select'
|
||||||
|
import { ConfirmDialog, SettingGroup, SettingRow, StatusDot } from '@/components/common'
|
||||||
|
import {
|
||||||
|
AUTO_REFRESH_OPTIONS,
|
||||||
|
useSmartHomeStore,
|
||||||
|
type EndpointMode,
|
||||||
|
type HaConnectionView
|
||||||
|
} from '@/stores/smartHomeStore'
|
||||||
|
import ConnectionDialog from './ConnectionDialog.vue'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 设置页(连接 + 链路与诊断 + 数据刷新 + 安全)。
|
||||||
|
*
|
||||||
|
* 「实时推送」开关落在这里而不是设备页:它是**全局行为**(会一直保持一条 WebSocket),
|
||||||
|
* 而且和"自动刷新"是同一组取舍(远端链路上自动刷新被停用,靠推送补上)。
|
||||||
|
*/
|
||||||
|
const store = useSmartHomeStore()
|
||||||
|
|
||||||
|
const dialogOpen = ref(false)
|
||||||
|
const editing = ref<HaConnectionView | null>(null)
|
||||||
|
const deleting = ref<HaConnectionView | null>(null)
|
||||||
|
const deleteBusy = ref(false)
|
||||||
|
|
||||||
|
const conn = computed(() => store.activeConnection)
|
||||||
|
|
||||||
|
const linkLabel = computed(() => {
|
||||||
|
const c = conn.value
|
||||||
|
if (c?.endpointUrl) {
|
||||||
|
const kind = c.endpointKind === 'local' ? '局域网' : '远程(反代)'
|
||||||
|
return `${kind} · ${c.endpointLatencyMs ?? 0}ms`
|
||||||
|
}
|
||||||
|
if (store.link && !store.link.ok) return '没有可用链路'
|
||||||
|
return '尚未探测'
|
||||||
|
})
|
||||||
|
|
||||||
|
const linkState = computed<'success' | 'warning' | 'neutral'>(() => {
|
||||||
|
if (conn.value?.endpointUrl) return 'success'
|
||||||
|
return store.link && !store.link.ok ? 'warning' : 'neutral'
|
||||||
|
})
|
||||||
|
|
||||||
|
function modeLabel(m: EndpointMode) {
|
||||||
|
return m === 'local' ? '仅局域网' : m === 'remote' ? '仅反代' : '自动'
|
||||||
|
}
|
||||||
|
|
||||||
|
function fmtTime(ts: number) {
|
||||||
|
if (!ts) return '从未'
|
||||||
|
return new Date(ts * 1000).toLocaleString('zh-CN', { hour12: false })
|
||||||
|
}
|
||||||
|
|
||||||
|
function openNew() {
|
||||||
|
editing.value = null
|
||||||
|
dialogOpen.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
function openEdit(c: HaConnectionView) {
|
||||||
|
editing.value = c
|
||||||
|
dialogOpen.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
async function activate(c: HaConnectionView) {
|
||||||
|
try {
|
||||||
|
await store.activate(c.id)
|
||||||
|
toast.success(`已切换为「${c.name}」`)
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(String(e))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function confirmDelete() {
|
||||||
|
const c = deleting.value
|
||||||
|
if (!c) return
|
||||||
|
deleteBusy.value = true
|
||||||
|
try {
|
||||||
|
await store.removeConnection(c.id)
|
||||||
|
deleting.value = null
|
||||||
|
toast.success(`已删除「${c.name}」`)
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(String(e))
|
||||||
|
} finally {
|
||||||
|
deleteBusy.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function setMode(mode: EndpointMode) {
|
||||||
|
if (!conn.value) return
|
||||||
|
try {
|
||||||
|
await store.setEndpointMode(conn.value.id, mode)
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(String(e))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function check() {
|
||||||
|
if (!conn.value) return
|
||||||
|
try {
|
||||||
|
const info = await store.checkLink(conn.value.id)
|
||||||
|
if (info.ok) toast.success(`链路正常:${linkLabel.value}`)
|
||||||
|
else toast.error(info.error ?? '链路检测失败')
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(String(e))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 在 HA 自己的前端里打开(排障时最有用的出口) */
|
||||||
|
function openInHa() {
|
||||||
|
void store.openHaPage()
|
||||||
|
}
|
||||||
|
|
||||||
|
async function setAutoRefresh(sec: number) {
|
||||||
|
try {
|
||||||
|
await store.setAutoRefreshSec(sec)
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(`保存失败:${(e as { message?: string }).message ?? String(e)}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 实时推送开关:Rust 侧会据此建立 / 断开 WebSocket */
|
||||||
|
async function setRealtime(on: boolean) {
|
||||||
|
try {
|
||||||
|
await store.setRealtimeEnabled(on)
|
||||||
|
toast.success(on ? '已开启实时推送' : '已关闭实时推送')
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(`切换失败:${(e as { message?: string }).message ?? String(e)}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function reconnectWs() {
|
||||||
|
try {
|
||||||
|
await store.startRealtime()
|
||||||
|
toast.success('已请求重新连接')
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(`连接失败:${(e as { message?: string }).message ?? String(e)}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 自动刷新的停用条件与原因。
|
||||||
|
*
|
||||||
|
* 两条都要置灰,而且**要让用户知道**为什么(否则会以为是 bug):
|
||||||
|
* - 实时推送已经连上:状态本来就实时更新,再每 5s 拉一次全量是纯浪费
|
||||||
|
* - 反代链路:每次刷新都是几百 KB,应该改用实时推送
|
||||||
|
*/
|
||||||
|
const autoRefreshDisabled = computed(() => store.isRemoteLink || store.wsConnected)
|
||||||
|
const autoRefreshDisabledReason = computed(() => {
|
||||||
|
if (store.wsConnected) return '实时推送已连接,状态会自动更新,因此自动刷新已停用'
|
||||||
|
if (store.isRemoteLink)
|
||||||
|
return '当前走反代链路,自动刷新已停用:反代上每次刷新都是几百 KB 的全量请求,请改用上面的「实时推送」'
|
||||||
|
return ''
|
||||||
|
})
|
||||||
|
|
||||||
|
const wsStateLabel = computed(() => {
|
||||||
|
switch (store.wsState) {
|
||||||
|
case 'connected':
|
||||||
|
return `已连接(${store.wsStatus?.entityCount ?? 0} 个实体实时同步)`
|
||||||
|
case 'connecting':
|
||||||
|
return '连接中…'
|
||||||
|
case 'authFailed':
|
||||||
|
return '鉴权失败'
|
||||||
|
case 'disconnected':
|
||||||
|
return '已断开(自动重连中)'
|
||||||
|
default:
|
||||||
|
return '未连接'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const wsDotState = computed<'success' | 'warning' | 'neutral'>(() => {
|
||||||
|
if (store.wsState === 'connected') return 'success'
|
||||||
|
if (store.wsState === 'authFailed' || store.wsState === 'disconnected') return 'warning'
|
||||||
|
return 'neutral'
|
||||||
|
})
|
||||||
|
|
||||||
|
async function setConfirmDangerous(v: boolean) {
|
||||||
|
const cur = store.ui
|
||||||
|
if (!cur) return
|
||||||
|
try {
|
||||||
|
await store.saveUi({ ...cur, confirmDangerous: v })
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(`保存失败:${(e as { message?: string }).message ?? String(e)}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="flex flex-col gap-6">
|
||||||
|
<!-- ===== 连接 ===== -->
|
||||||
|
<section class="flex flex-col gap-3">
|
||||||
|
<div class="flex items-start justify-between gap-4">
|
||||||
|
<div class="flex min-w-0 flex-col gap-1">
|
||||||
|
<h2 class="text-sm font-semibold text-foreground">Home Assistant 连接</h2>
|
||||||
|
<p class="text-xs text-muted-foreground">
|
||||||
|
一条连接可同时配「局域网地址」(在家,最快)与「反代地址」(在外面,如 Cloudflare Tunnel)
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Button variant="outline" size="sm" class="shrink-0" @click="openNew">
|
||||||
|
<Plus class="size-4" />新建
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Card class="!py-0 !gap-0">
|
||||||
|
<CardContent class="flex flex-col divide-y divide-divider !px-4">
|
||||||
|
<p v-if="!store.connections.length" class="py-4 text-xs text-muted-foreground">
|
||||||
|
还没有连接。新建一个并填写局域网地址(http://192.168.x.x:8123)和/或反代地址,
|
||||||
|
再粘贴 Home Assistant 的长期访问令牌。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div
|
||||||
|
v-for="c in store.connections"
|
||||||
|
:key="c.id"
|
||||||
|
class="flex items-center gap-3 py-3"
|
||||||
|
>
|
||||||
|
<div class="min-w-0 flex-1">
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<span class="truncate text-[13px] font-medium text-foreground">{{ c.name }}</span>
|
||||||
|
<Badge variant="secondary" class="text-[11px]">{{ modeLabel(c.endpointMode) }}</Badge>
|
||||||
|
<Badge v-if="store.activeId === c.id" class="text-[11px]">激活</Badge>
|
||||||
|
</div>
|
||||||
|
<div class="truncate text-xs text-muted-foreground">
|
||||||
|
{{ c.localUrl || '未配置局域网' }} · {{ c.remoteUrl || '未配置反代' }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<span
|
||||||
|
class="hidden shrink-0 font-mono text-xs sm:inline"
|
||||||
|
:class="c.hasToken ? 'text-success-text' : 'text-warning-text'"
|
||||||
|
>
|
||||||
|
{{ c.hasToken ? c.tokenMasked : '未配置令牌' }}
|
||||||
|
</span>
|
||||||
|
|
||||||
|
<div class="flex shrink-0 items-center gap-1">
|
||||||
|
<Button
|
||||||
|
v-if="store.activeId !== c.id"
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
class="size-8"
|
||||||
|
title="设为激活连接"
|
||||||
|
aria-label="设为激活连接"
|
||||||
|
@click="activate(c)"
|
||||||
|
>
|
||||||
|
<CircleCheck class="size-4" />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
class="size-8"
|
||||||
|
title="编辑连接"
|
||||||
|
aria-label="编辑连接"
|
||||||
|
@click="openEdit(c)"
|
||||||
|
>
|
||||||
|
<Pencil class="size-4" />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
class="size-8 text-destructive"
|
||||||
|
title="删除连接"
|
||||||
|
aria-label="删除连接"
|
||||||
|
@click="deleting = c"
|
||||||
|
>
|
||||||
|
<Trash2 class="size-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- ===== 数据刷新 ===== -->
|
||||||
|
<SettingGroup
|
||||||
|
title="数据刷新"
|
||||||
|
description="设备状态按需拉取;反代链路下不建议自动刷新(每次都是一次几百 KB 的全量请求)"
|
||||||
|
>
|
||||||
|
<SettingRow
|
||||||
|
label="实时推送"
|
||||||
|
description="开启后使用 WebSocket,设备状态实时反映(不需要手动刷新)。反代链路上尤其值得开:空闲时几乎无流量,比轮询便宜得多"
|
||||||
|
>
|
||||||
|
<Switch
|
||||||
|
:model-value="store.realtimeEnabled"
|
||||||
|
@update:model-value="(v: boolean | 'indeterminate') => setRealtime(v === true)"
|
||||||
|
/>
|
||||||
|
</SettingRow>
|
||||||
|
|
||||||
|
<SettingRow label="自动刷新间隔"
|
||||||
|
:description="
|
||||||
|
autoRefreshDisabledReason ||
|
||||||
|
'仅在设备页打开时生效;关闭后可用「刷新」按钮手动更新'
|
||||||
|
"
|
||||||
|
>
|
||||||
|
<Select
|
||||||
|
:model-value="String(store.autoRefreshSec)"
|
||||||
|
:disabled="autoRefreshDisabled"
|
||||||
|
@update:model-value="(v) => setAutoRefresh(Number(v))"
|
||||||
|
>
|
||||||
|
<SelectTrigger class="h-8 w-50">
|
||||||
|
<SelectValue />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem v-for="s in AUTO_REFRESH_OPTIONS" :key="s" :value="String(s)">
|
||||||
|
{{ s === 0 ? '关闭' : `每 ${s} 秒` }}
|
||||||
|
</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</SettingRow>
|
||||||
|
</SettingGroup>
|
||||||
|
|
||||||
|
<!-- ===== 链路与诊断 ===== -->
|
||||||
|
<SettingGroup
|
||||||
|
title="链路与诊断"
|
||||||
|
description="反代(Cloudflare Tunnel)的延迟通常比局域网高一到两个数量级,这里能看到实际走的是哪条"
|
||||||
|
>
|
||||||
|
<SettingRow label="当前链路" description="会话内命中的端点(未探测时显示占位)">
|
||||||
|
<StatusDot
|
||||||
|
:state="linkState"
|
||||||
|
:label="linkLabel"
|
||||||
|
:pulse="store.linkChecking"
|
||||||
|
/>
|
||||||
|
</SettingRow>
|
||||||
|
|
||||||
|
<SettingRow label="端点策略" description="自动 = 先试局域网(900ms 超时),失败再用反代">
|
||||||
|
<Select
|
||||||
|
:model-value="conn?.endpointMode ?? 'auto'"
|
||||||
|
:disabled="!conn"
|
||||||
|
@update:model-value="(v) => setMode(String(v) as EndpointMode)"
|
||||||
|
>
|
||||||
|
<SelectTrigger class="h-8 w-50">
|
||||||
|
<SelectValue />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="auto">自动</SelectItem>
|
||||||
|
<SelectItem value="local">仅局域网</SelectItem>
|
||||||
|
<SelectItem value="remote">仅反代</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</SettingRow>
|
||||||
|
|
||||||
|
<SettingRow label="检测链路" description="强制重新探测一次,并记录耗时">
|
||||||
|
<Button variant="outline" size="sm" :disabled="!conn || store.linkChecking" @click="check">
|
||||||
|
<Loader2 v-if="store.linkChecking" class="size-4 animate-spin" />检测
|
||||||
|
</Button>
|
||||||
|
</SettingRow>
|
||||||
|
|
||||||
|
<SettingRow
|
||||||
|
label="实时连接"
|
||||||
|
:description="store.wsStatus?.detail || '用于设备状态实时推送与本地规则触发'"
|
||||||
|
>
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<StatusDot :state="wsDotState" :label="wsStateLabel" :pulse="store.wsBusy" />
|
||||||
|
<Button
|
||||||
|
v-if="store.realtimeEnabled || store.rulesEnabled"
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
:disabled="store.wsBusy || store.wsState === 'connecting'"
|
||||||
|
@click="reconnectWs"
|
||||||
|
>
|
||||||
|
<Loader2 v-if="store.wsBusy" class="size-4 animate-spin" />重连
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</SettingRow>
|
||||||
|
|
||||||
|
<SettingRow label="Home Assistant 版本">
|
||||||
|
<span class="text-[13px] tabular-nums text-foreground">{{ conn?.haVersion || '—' }}</span>
|
||||||
|
</SettingRow>
|
||||||
|
|
||||||
|
<SettingRow label="实例名称">
|
||||||
|
<span class="text-[13px] text-foreground">{{ conn?.locationName || '—' }}</span>
|
||||||
|
</SettingRow>
|
||||||
|
|
||||||
|
<SettingRow label="上次成功" description="最近一次成功通信的时间">
|
||||||
|
<span class="text-[13px] tabular-nums text-foreground">{{ fmtTime(conn?.lastOkAt ?? 0) }}</span>
|
||||||
|
</SettingRow>
|
||||||
|
|
||||||
|
<SettingRow label="在 Home Assistant 中打开" description="用浏览器打开 HA 自己的前端,便于查看日志与设备详情">
|
||||||
|
<Button variant="outline" size="sm" :disabled="!conn" @click="openInHa">
|
||||||
|
<ExternalLink class="size-4" />打开
|
||||||
|
</Button>
|
||||||
|
</SettingRow>
|
||||||
|
</SettingGroup>
|
||||||
|
|
||||||
|
<!-- ===== 安全 ===== -->
|
||||||
|
<SettingGroup
|
||||||
|
title="安全"
|
||||||
|
description="有实际后果的操作(开锁 / 窗帘全开)默认需要二次确认"
|
||||||
|
>
|
||||||
|
<SettingRow
|
||||||
|
label="危险操作二次确认"
|
||||||
|
description="开锁、窗帘全开等操作会先弹确认框;关掉后单击即下发"
|
||||||
|
>
|
||||||
|
<Switch
|
||||||
|
:model-value="store.ui?.confirmDangerous ?? true"
|
||||||
|
@update:model-value="(v: boolean | 'indeterminate') => setConfirmDangerous(v === true)"
|
||||||
|
/>
|
||||||
|
</SettingRow>
|
||||||
|
</SettingGroup>
|
||||||
|
|
||||||
|
<!-- ===== 安全提示(不是免责声明:它决定用户该不该只用局域网) ===== -->
|
||||||
|
<p class="text-xs text-muted-foreground">
|
||||||
|
长期访问令牌保存在 Windows 凭据管理器(DPAPI 保护),不会写进配置文件,界面只显示掩码。
|
||||||
|
局域网地址通常是 <span class="font-mono">http://</span>,令牌会以明文过网 ——
|
||||||
|
建议仅在家庭内网使用,或改用带 HTTPS 的反代地址。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<ConnectionDialog v-model:open="dialogOpen" :connection="editing" />
|
||||||
|
|
||||||
|
<ConfirmDialog
|
||||||
|
:open="!!deleting"
|
||||||
|
variant="danger"
|
||||||
|
title="删除这条连接?"
|
||||||
|
:description="deleting ? `「${deleting.name}」的地址配置与保存的访问令牌都会一并删除。` : ''"
|
||||||
|
confirm-text="删除"
|
||||||
|
:loading="deleteBusy"
|
||||||
|
@update:open="(v) => !v && (deleting = null)"
|
||||||
|
@confirm="confirmDelete"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, ref } from 'vue'
|
||||||
|
import { toast } from 'vue-sonner'
|
||||||
|
import { Loader2, Play } from '@lucide/vue'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { useSmartHomeStore, type EntitySummary } from '@/stores/smartHomeStore'
|
||||||
|
import { controlFail } from './shared'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 「动作」类实体:场景 / 脚本 / 按钮。
|
||||||
|
*
|
||||||
|
* 它们的共同点是**没有乐观状态**(传空对象):执行场景、运行脚本、按下按钮
|
||||||
|
* 都不会让这条实体自身产生可预期的状态变化。因此 store 里既不会走"服务端结果快速通道",
|
||||||
|
* 也不会做"状态没变就回滚"的校正 —— 否则一次成功执行会被冤枉成失败(§5.3 的例外分支)。
|
||||||
|
* 按钮尤其明显:它的 `state` 是"上次按下时间"。
|
||||||
|
*/
|
||||||
|
const props = defineProps<{ entity: EntitySummary; disabled?: boolean }>()
|
||||||
|
const store = useSmartHomeStore()
|
||||||
|
|
||||||
|
const busy = ref(false)
|
||||||
|
|
||||||
|
/** 按钮是 `press`,场景/脚本是 `turn_on`(HA 的语义就这么定的) */
|
||||||
|
const action = computed(() =>
|
||||||
|
props.entity.domain === 'button'
|
||||||
|
? { service: 'press', label: '按下', done: '已按下' }
|
||||||
|
: { service: 'turn_on', label: '执行', done: '已执行' }
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 乐观状态。
|
||||||
|
*
|
||||||
|
* - 场景 / 脚本:空对象(它们没有可预期的状态变化)
|
||||||
|
* - 按钮:**它的 `state` 就是"上次按下时间"**,所以按下时乐观地把 state 与 lastChanged
|
||||||
|
* 一起改成当前时刻 —— 这样卡片底部的相对时间会立刻跳到"刚刚",页脚不再是按了没反应。
|
||||||
|
* 带上了乐观状态也就顺带走进了"服务端已确认就采用、否则分级校正"的常规流程。
|
||||||
|
*/
|
||||||
|
function optimistic(): Partial<EntitySummary> {
|
||||||
|
if (props.entity.domain !== 'button') return {}
|
||||||
|
const now = new Date().toISOString()
|
||||||
|
return { state: now, lastChanged: now }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function run() {
|
||||||
|
if (busy.value) return
|
||||||
|
busy.value = true
|
||||||
|
try {
|
||||||
|
await store.control(props.entity, action.value.service, {}, optimistic())
|
||||||
|
toast.success(`${action.value.done}「${props.entity.name}」`)
|
||||||
|
} catch (e) {
|
||||||
|
controlFail(e)
|
||||||
|
} finally {
|
||||||
|
busy.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<Button variant="outline" size="sm" class="w-full" :disabled="disabled || busy" @click="run">
|
||||||
|
<Loader2 v-if="busy" class="size-4 animate-spin" />
|
||||||
|
<Play v-else class="size-4" />{{ action.label }}
|
||||||
|
</Button>
|
||||||
|
</template>
|
||||||
|
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed } from 'vue'
|
||||||
|
import { Minus, Plus } from '@lucide/vue'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue
|
||||||
|
} from '@/components/ui/select'
|
||||||
|
import { useSmartHomeStore, type EntitySummary } from '@/stores/smartHomeStore'
|
||||||
|
import { hasFeature, hvacModeLabel } from '../../format'
|
||||||
|
import { controlFail } from './shared'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 空调:模式 + 目标温度步进。
|
||||||
|
*
|
||||||
|
* **单位与上下限都从实例读,绝不写死**:
|
||||||
|
* - `min_temp` / `max_temp` 由实体自带(HA 美制实例给的是 61–86,写死 5–35 会把 77 钳成 35 —— 真机踩到过)
|
||||||
|
* - 显示单位取 `/api/config` 的 `unit_system.temperature`(存在连接上,见 `temperatureUnit`)
|
||||||
|
*
|
||||||
|
* 温度步进只在"真的能设温度"时出现(`TARGET_TEMPERATURE` / `TARGET_TEMPERATURE_RANGE`
|
||||||
|
* 两位之一,且当前不是 off);步长取 HA 报的 `target_temp_step`,不自作主张 ——
|
||||||
|
* 有些设备只接受整度。
|
||||||
|
*/
|
||||||
|
const props = defineProps<{ entity: EntitySummary; disabled?: boolean }>()
|
||||||
|
const store = useSmartHomeStore()
|
||||||
|
|
||||||
|
/** HA climate 的 supported_features:1 = TARGET_TEMPERATURE,2 = TARGET_TEMPERATURE_RANGE */
|
||||||
|
const TEMP_FEATURE = 1 | 2
|
||||||
|
|
||||||
|
const modes = computed(() => props.entity.hvacModes)
|
||||||
|
const mode = computed(() => props.entity.state)
|
||||||
|
const step = computed(() => props.entity.targetTempStep ?? 0.5)
|
||||||
|
const target = computed(() => props.entity.targetTemp ?? 24)
|
||||||
|
const unit = computed(() => store.activeConnection?.temperatureUnit ?? '')
|
||||||
|
const minTemp = computed(() => props.entity.minTemp ?? 5)
|
||||||
|
const maxTemp = computed(() => props.entity.maxTemp ?? 35)
|
||||||
|
const tempEnabled = computed(
|
||||||
|
() =>
|
||||||
|
mode.value !== 'off' &&
|
||||||
|
mode.value !== 'unavailable' &&
|
||||||
|
hasFeature(props.entity, TEMP_FEATURE)
|
||||||
|
)
|
||||||
|
|
||||||
|
const targetLabel = computed(() => {
|
||||||
|
const n = Number(target.value.toFixed(1))
|
||||||
|
return `${Number.isInteger(n) ? n : n.toFixed(1)}${unit.value}`
|
||||||
|
})
|
||||||
|
|
||||||
|
async function setMode(next: string) {
|
||||||
|
try {
|
||||||
|
if (next === 'off') {
|
||||||
|
await store.control(props.entity, 'turn_off', {}, { state: 'off' })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
await store.control(props.entity, 'set_hvac_mode', { hvacMode: next }, { state: next })
|
||||||
|
} catch (e) {
|
||||||
|
controlFail(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 按步长取整 + 夹在实体自带的上下限内(浮点连加会出现 24.500000000000004) */
|
||||||
|
function roundToStep(v: number): number {
|
||||||
|
const s = step.value || 0.5
|
||||||
|
const clamped = Math.min(Math.max(v, minTemp.value), maxTemp.value)
|
||||||
|
return Number((Math.round(clamped / s) * s).toFixed(2))
|
||||||
|
}
|
||||||
|
|
||||||
|
async function nudge(delta: number) {
|
||||||
|
const next = roundToStep(target.value + delta)
|
||||||
|
if (next === target.value) return
|
||||||
|
try {
|
||||||
|
await store.control(props.entity, 'set_temperature', { temperature: next }, { targetTemp: next })
|
||||||
|
} catch (e) {
|
||||||
|
controlFail(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="flex flex-col gap-2">
|
||||||
|
<Select
|
||||||
|
v-if="modes.length"
|
||||||
|
:model-value="mode"
|
||||||
|
:disabled="disabled"
|
||||||
|
@update:model-value="(v) => setMode(String(v))"
|
||||||
|
>
|
||||||
|
<SelectTrigger class="h-8 w-full">
|
||||||
|
<SelectValue />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem v-for="m in modes" :key="m" :value="m">{{ hvacModeLabel(m) }}</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
|
||||||
|
<div v-if="tempEnabled" class="flex items-center justify-between gap-2">
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="icon"
|
||||||
|
class="size-7"
|
||||||
|
:disabled="disabled"
|
||||||
|
aria-label="降低温度"
|
||||||
|
@click="nudge(-step)"
|
||||||
|
>
|
||||||
|
<Minus class="size-3.5" />
|
||||||
|
</Button>
|
||||||
|
<span class="text-[15px] font-semibold tabular-nums text-foreground">{{ targetLabel }}</span>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="icon"
|
||||||
|
class="size-7"
|
||||||
|
:disabled="disabled"
|
||||||
|
aria-label="升高温度"
|
||||||
|
@click="nudge(step)"
|
||||||
|
>
|
||||||
|
<Plus class="size-3.5" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, ref, watch } from 'vue'
|
||||||
|
import { Slider } from '@/components/ui/slider'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 带标签的滑杆:**拖动时只改本地值,松手(`valueCommit`)才回调**。
|
||||||
|
*
|
||||||
|
* 这条是硬要求(§5.3):`update:modelValue` 在拖动过程中持续触发,
|
||||||
|
* 而每次回调都是一次 HTTP(远端链路约 300ms)—— 不松手就会刷出几十条命令。
|
||||||
|
*/
|
||||||
|
const props = defineProps<{
|
||||||
|
label: string
|
||||||
|
value: number
|
||||||
|
min: number
|
||||||
|
max: number
|
||||||
|
step?: number
|
||||||
|
/** 值后缀(`%` / `K`) */
|
||||||
|
suffix?: string
|
||||||
|
disabled?: boolean
|
||||||
|
}>()
|
||||||
|
const emit = defineEmits<{ commit: [value: number] }>()
|
||||||
|
|
||||||
|
const local = ref(props.value)
|
||||||
|
|
||||||
|
/** 外部值变化(刷新 / 校正 / 别处操作)时同步回来 */
|
||||||
|
watch(
|
||||||
|
() => props.value,
|
||||||
|
(v) => {
|
||||||
|
local.value = v
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
const display = computed(() => `${Math.round(local.value)}${props.suffix ?? ''}`)
|
||||||
|
|
||||||
|
function toNumber(v: number | number[] | undefined | null): number {
|
||||||
|
if (Array.isArray(v)) return v[0] ?? props.min
|
||||||
|
return typeof v === 'number' ? v : props.min
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<span class="w-8 shrink-0 text-[11px] text-muted-foreground">{{ label }}</span>
|
||||||
|
<Slider
|
||||||
|
class="min-w-0 flex-1"
|
||||||
|
:model-value="[local]"
|
||||||
|
:min="min"
|
||||||
|
:max="max"
|
||||||
|
:step="step ?? 1"
|
||||||
|
:disabled="disabled"
|
||||||
|
@update:model-value="(v) => (local = toNumber(v))"
|
||||||
|
@value-commit="(v) => emit('commit', toNumber(v))"
|
||||||
|
/>
|
||||||
|
<span class="w-9 shrink-0 text-right text-[11px] tabular-nums text-fg-secondary">{{
|
||||||
|
display
|
||||||
|
}}</span>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, ref } from 'vue'
|
||||||
|
import { ArrowDown, ArrowUp, Square } from '@lucide/vue'
|
||||||
|
import {
|
||||||
|
AlertDialog,
|
||||||
|
AlertDialogAction,
|
||||||
|
AlertDialogCancel,
|
||||||
|
AlertDialogContent,
|
||||||
|
AlertDialogDescription,
|
||||||
|
AlertDialogFooter,
|
||||||
|
AlertDialogHeader,
|
||||||
|
AlertDialogTitle
|
||||||
|
} from '@/components/ui/alert-dialog'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { useSmartHomeStore, type EntitySummary } from '@/stores/smartHomeStore'
|
||||||
|
import { COVER_FEATURE, hasFeature } from '../../format'
|
||||||
|
import ControlSlider from './ControlSlider.vue'
|
||||||
|
import { controlFail } from './shared'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 窗帘:升 / 停 / 降 + 位置滑杆。
|
||||||
|
*
|
||||||
|
* 三个按钮都按 `supported_features` 位决定是否出现 —— 只支持"开关"的窗帘
|
||||||
|
* 不该看到一个点了没反应的"停"。
|
||||||
|
* **全开**是计划里列的危险操作(§5.3),确认后才下发。
|
||||||
|
*/
|
||||||
|
const props = defineProps<{ entity: EntitySummary; disabled?: boolean }>()
|
||||||
|
const store = useSmartHomeStore()
|
||||||
|
|
||||||
|
const canOpen = computed(() => hasFeature(props.entity, COVER_FEATURE.OPEN))
|
||||||
|
const canClose = computed(() => hasFeature(props.entity, COVER_FEATURE.CLOSE))
|
||||||
|
const canStop = computed(() => hasFeature(props.entity, COVER_FEATURE.STOP))
|
||||||
|
const canPosition = computed(() => hasFeature(props.entity, COVER_FEATURE.SET_POSITION))
|
||||||
|
const position = computed(() => props.entity.position ?? 0)
|
||||||
|
const confirmOpen = ref(false)
|
||||||
|
|
||||||
|
async function run(service: string, params = {}, optimistic: Partial<EntitySummary> = {}) {
|
||||||
|
try {
|
||||||
|
await store.control(props.entity, service, params, optimistic)
|
||||||
|
} catch (e) {
|
||||||
|
controlFail(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function doOpen() {
|
||||||
|
void run('open_cover', {}, { state: 'open', position: 100 })
|
||||||
|
}
|
||||||
|
|
||||||
|
function requestOpen() {
|
||||||
|
if (store.ui?.confirmDangerous) {
|
||||||
|
confirmOpen.value = true
|
||||||
|
return
|
||||||
|
}
|
||||||
|
doOpen()
|
||||||
|
}
|
||||||
|
|
||||||
|
function setPosition(v: number) {
|
||||||
|
void run('set_cover_position', { position: v }, { position: v, state: v > 0 ? 'open' : 'closed' })
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="flex flex-col gap-2">
|
||||||
|
<div class="flex items-center gap-1.5">
|
||||||
|
<Button
|
||||||
|
v-if="canOpen"
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
class="min-w-0 flex-1"
|
||||||
|
:disabled="disabled"
|
||||||
|
@click="requestOpen"
|
||||||
|
>
|
||||||
|
<ArrowUp class="size-4" />开
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
v-if="canStop"
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
:disabled="disabled"
|
||||||
|
aria-label="停止"
|
||||||
|
@click="run('stop_cover')"
|
||||||
|
>
|
||||||
|
<Square class="size-3.5" />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
v-if="canClose"
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
class="min-w-0 flex-1"
|
||||||
|
:disabled="disabled"
|
||||||
|
@click="run('close_cover', {}, { state: 'closed', position: 0 })"
|
||||||
|
>
|
||||||
|
<ArrowDown class="size-4" />关
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ControlSlider
|
||||||
|
v-if="canPosition"
|
||||||
|
label="位置"
|
||||||
|
:value="position"
|
||||||
|
:min="0"
|
||||||
|
:max="100"
|
||||||
|
suffix="%"
|
||||||
|
:disabled="disabled"
|
||||||
|
@commit="setPosition"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<AlertDialog :open="confirmOpen" @update:open="(v) => (confirmOpen = v)">
|
||||||
|
<AlertDialogContent>
|
||||||
|
<AlertDialogHeader>
|
||||||
|
<AlertDialogTitle>确认全开?</AlertDialogTitle>
|
||||||
|
<AlertDialogDescription>{{ entity.name }} 将完全打开。</AlertDialogDescription>
|
||||||
|
</AlertDialogHeader>
|
||||||
|
<AlertDialogFooter>
|
||||||
|
<AlertDialogCancel>取消</AlertDialogCancel>
|
||||||
|
<AlertDialogAction @click="doOpen">确认全开</AlertDialogAction>
|
||||||
|
</AlertDialogFooter>
|
||||||
|
</AlertDialogContent>
|
||||||
|
</AlertDialog>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed } from 'vue'
|
||||||
|
import { useSmartHomeStore, type EntitySummary } from '@/stores/smartHomeStore'
|
||||||
|
import ControlSlider from './ControlSlider.vue'
|
||||||
|
import SwitchControl from './SwitchControl.vue'
|
||||||
|
import { controlFail } from './shared'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 风扇:开关 + 档位滑杆(仅在 HA 报出 `percentage` 时出现)。
|
||||||
|
*
|
||||||
|
* `set_percentage` 会附带把风扇打开(HA 的语义),所以乐观状态里同时置 `state: on`。
|
||||||
|
*/
|
||||||
|
const props = defineProps<{ entity: EntitySummary; disabled?: boolean }>()
|
||||||
|
const store = useSmartHomeStore()
|
||||||
|
|
||||||
|
const hasPercentage = computed(() => props.entity.percentage != null)
|
||||||
|
|
||||||
|
async function setPercentage(v: number) {
|
||||||
|
try {
|
||||||
|
await store.control(
|
||||||
|
props.entity,
|
||||||
|
'set_percentage',
|
||||||
|
{ percentage: v },
|
||||||
|
{ state: 'on', percentage: v }
|
||||||
|
)
|
||||||
|
} catch (e) {
|
||||||
|
controlFail(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="flex flex-col gap-2">
|
||||||
|
<SwitchControl :entity="entity" :disabled="disabled" />
|
||||||
|
<ControlSlider
|
||||||
|
v-if="hasPercentage"
|
||||||
|
label="档位"
|
||||||
|
:value="entity.percentage ?? 0"
|
||||||
|
:min="1"
|
||||||
|
:max="100"
|
||||||
|
suffix="%"
|
||||||
|
:disabled="disabled"
|
||||||
|
@commit="setPercentage"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed } from 'vue'
|
||||||
|
import { useSmartHomeStore, type EntitySummary } from '@/stores/smartHomeStore'
|
||||||
|
import {
|
||||||
|
brightnessToPct,
|
||||||
|
lightColorTempRange,
|
||||||
|
lightHasBrightness,
|
||||||
|
lightHasColorTemp,
|
||||||
|
pctToBrightness
|
||||||
|
} from '../../format'
|
||||||
|
import ControlSlider from './ControlSlider.vue'
|
||||||
|
import SwitchControl from './SwitchControl.vue'
|
||||||
|
import { controlFail } from './shared'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 灯:开关 + 亮度 + 色温。
|
||||||
|
*
|
||||||
|
* 两个滑杆都**按能力位决定是否出现**(`supported_color_modes`)—— 给一个
|
||||||
|
* 点了没反应的滑杆比不给控件更糟(§3.4)。
|
||||||
|
* 两个参数都走 `light.turn_on`:HA 的约定就是"设置亮度/色温顺便开灯",
|
||||||
|
* 因此灯关着时拖滑杆也会亮起来(与 HA 自己前端一致)。
|
||||||
|
*/
|
||||||
|
const props = defineProps<{ entity: EntitySummary; disabled?: boolean }>()
|
||||||
|
const store = useSmartHomeStore()
|
||||||
|
|
||||||
|
const hasBrightness = computed(() => lightHasBrightness(props.entity))
|
||||||
|
const hasColorTemp = computed(() => lightHasColorTemp(props.entity))
|
||||||
|
const tempRange = computed(() => lightColorTempRange(props.entity))
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 关灯时 HA 不给当前亮度 / 色温(真机上这两个属性都是 `null`)。
|
||||||
|
*
|
||||||
|
* 此时**不能用 0 或范围上界去假装知道** —— 那会让滑杆看起来"亮度最低 / 色温最冷",
|
||||||
|
* 是一句假话。取范围中点作为中性占位:拖动本身会带上明确的值并开灯,
|
||||||
|
* 所以这不影响正确性,只是不误导。
|
||||||
|
*/
|
||||||
|
const brightnessPct = computed(() =>
|
||||||
|
props.entity.brightness != null ? brightnessToPct(props.entity.brightness) : 50
|
||||||
|
)
|
||||||
|
|
||||||
|
const colorTemp = computed(() => {
|
||||||
|
const [min, max] = tempRange.value
|
||||||
|
const k = props.entity.colorTempKelvin
|
||||||
|
return k != null ? Math.min(Math.max(k, min), max) : Math.round((min + max) / 2)
|
||||||
|
})
|
||||||
|
|
||||||
|
async function commitBrightness(pct: number) {
|
||||||
|
try {
|
||||||
|
await store.control(
|
||||||
|
props.entity,
|
||||||
|
'turn_on',
|
||||||
|
{ brightnessPct: pct },
|
||||||
|
{ state: 'on', brightness: pctToBrightness(pct) }
|
||||||
|
)
|
||||||
|
} catch (e) {
|
||||||
|
controlFail(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function commitColorTemp(kelvin: number) {
|
||||||
|
try {
|
||||||
|
await store.control(
|
||||||
|
props.entity,
|
||||||
|
'turn_on',
|
||||||
|
{ colorTempKelvin: kelvin },
|
||||||
|
{ state: 'on', colorTempKelvin: kelvin }
|
||||||
|
)
|
||||||
|
} catch (e) {
|
||||||
|
controlFail(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="flex flex-col gap-2">
|
||||||
|
<SwitchControl :entity="entity" :disabled="disabled" />
|
||||||
|
<ControlSlider
|
||||||
|
v-if="hasBrightness"
|
||||||
|
label="亮度"
|
||||||
|
:value="brightnessPct"
|
||||||
|
:min="1"
|
||||||
|
:max="100"
|
||||||
|
suffix="%"
|
||||||
|
:disabled="disabled"
|
||||||
|
@commit="commitBrightness"
|
||||||
|
/>
|
||||||
|
<ControlSlider
|
||||||
|
v-if="hasColorTemp"
|
||||||
|
label="色温"
|
||||||
|
:value="colorTemp"
|
||||||
|
:min="tempRange[0]"
|
||||||
|
:max="tempRange[1]"
|
||||||
|
:step="50"
|
||||||
|
suffix="K"
|
||||||
|
:disabled="disabled"
|
||||||
|
@commit="commitColorTemp"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed } from 'vue'
|
||||||
|
import { Pause, Play } from '@lucide/vue'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { useSmartHomeStore, type EntitySummary } from '@/stores/smartHomeStore'
|
||||||
|
import ControlSlider from './ControlSlider.vue'
|
||||||
|
import SwitchControl from './SwitchControl.vue'
|
||||||
|
import { controlFail } from './shared'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 媒体播放器:播放/暂停 + 音量 + 开关。
|
||||||
|
*
|
||||||
|
* 这里只做"控制"这一层,不做播放器 UI(选歌、进度条是 HA 自己的前端的活)。
|
||||||
|
*/
|
||||||
|
const props = defineProps<{ entity: EntitySummary; disabled?: boolean }>()
|
||||||
|
const store = useSmartHomeStore()
|
||||||
|
|
||||||
|
const playing = computed(() => props.entity.state === 'playing')
|
||||||
|
const hasVolume = computed(() => props.entity.volumeLevel != null)
|
||||||
|
const volumePct = computed(() => Math.round((props.entity.volumeLevel ?? 0) * 100))
|
||||||
|
|
||||||
|
async function playPause() {
|
||||||
|
try {
|
||||||
|
await store.control(
|
||||||
|
props.entity,
|
||||||
|
'media_play_pause',
|
||||||
|
{},
|
||||||
|
{ state: playing.value ? 'paused' : 'playing' }
|
||||||
|
)
|
||||||
|
} catch (e) {
|
||||||
|
controlFail(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function setVolume(pct: number) {
|
||||||
|
const level = pct / 100
|
||||||
|
try {
|
||||||
|
await store.control(props.entity, 'volume_set', { volumeLevel: level }, { volumeLevel: level })
|
||||||
|
} catch (e) {
|
||||||
|
controlFail(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="flex flex-col gap-2">
|
||||||
|
<div class="flex items-center justify-between gap-2">
|
||||||
|
<Button variant="outline" size="sm" :disabled="disabled" @click="playPause">
|
||||||
|
<Pause v-if="playing" class="size-4" />
|
||||||
|
<Play v-else class="size-4" />{{ playing ? '暂停' : '播放' }}
|
||||||
|
</Button>
|
||||||
|
<SwitchControl :entity="entity" :disabled="disabled" />
|
||||||
|
</div>
|
||||||
|
<ControlSlider
|
||||||
|
v-if="hasVolume"
|
||||||
|
label="音量"
|
||||||
|
:value="volumePct"
|
||||||
|
:min="0"
|
||||||
|
:max="100"
|
||||||
|
suffix="%"
|
||||||
|
:disabled="disabled"
|
||||||
|
@commit="setVolume"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed } from 'vue'
|
||||||
|
import { useSmartHomeStore, type EntitySummary } from '@/stores/smartHomeStore'
|
||||||
|
import { numberUsable } from '../../format'
|
||||||
|
import ControlSlider from './ControlSlider.vue'
|
||||||
|
import { controlFail } from './shared'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 数值实体(`number.*`):滑杆 + 数值显示。
|
||||||
|
*
|
||||||
|
* 上下限与步长**全部用实体自带的**(`min` / `max` / `step`)—— 真机上这批实体差异极大:
|
||||||
|
* 0–100 的扬声器音量、10–90 的摄像机变焦倍数、步长 180 的图像翻转角。
|
||||||
|
* 写死任何一个都会让另一批实体没法用。
|
||||||
|
*
|
||||||
|
* 退化情形(没给 min/max,或 max ≤ min,或步长 ≤ 0)**不渲染控件** ——
|
||||||
|
* 给一个拖不动的滑杆比不给控件更糟。
|
||||||
|
*/
|
||||||
|
const props = defineProps<{ entity: EntitySummary; disabled?: boolean }>()
|
||||||
|
const store = useSmartHomeStore()
|
||||||
|
|
||||||
|
const usable = computed(() => numberUsable(props.entity))
|
||||||
|
|
||||||
|
/** 当前值:优先用 `numeric`(state 是数字字符串时解析出来的),并夹在上下限内 */
|
||||||
|
const value = computed(() => {
|
||||||
|
const min = props.entity.min ?? 0
|
||||||
|
const max = props.entity.max ?? 100
|
||||||
|
const v = props.entity.numeric ?? min
|
||||||
|
return Math.min(Math.max(v, min), max)
|
||||||
|
})
|
||||||
|
|
||||||
|
async function commit(next: number) {
|
||||||
|
try {
|
||||||
|
// state 也要一起改:校正逻辑比的是 state / 数值那几个字段,
|
||||||
|
// 只改 numeric 的话"服务端已确认变化"的快速通道会看不出来
|
||||||
|
await store.control(
|
||||||
|
props.entity,
|
||||||
|
'set_value',
|
||||||
|
{ value: next },
|
||||||
|
{ numeric: next, state: String(next) }
|
||||||
|
)
|
||||||
|
} catch (e) {
|
||||||
|
controlFail(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<ControlSlider
|
||||||
|
v-if="usable"
|
||||||
|
label="值"
|
||||||
|
:value="value"
|
||||||
|
:min="entity.min ?? 0"
|
||||||
|
:max="entity.max ?? 100"
|
||||||
|
:step="entity.step ?? 1"
|
||||||
|
:suffix="entity.unit"
|
||||||
|
:disabled="disabled"
|
||||||
|
@commit="commit"
|
||||||
|
/>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed } from 'vue'
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue
|
||||||
|
} from '@/components/ui/select'
|
||||||
|
import { useSmartHomeStore, type EntitySummary } from '@/stores/smartHomeStore'
|
||||||
|
import { selectUsable } from '../../format'
|
||||||
|
import { controlFail } from './shared'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 下拉实体(`select.*`):从实体自带的 `options` 里选一个。
|
||||||
|
*
|
||||||
|
* `select.select_option` 的参数是 `option`;乐观状态直接把 state 改成所选项 ——
|
||||||
|
* 这类实体的 state 就是当前选项(真机上如"HDMI 1"、"自动")。
|
||||||
|
*
|
||||||
|
* 没给选项时不渲染(有些集成只暴露实体却不给选项表,那样点了也不知道能填什么)。
|
||||||
|
*/
|
||||||
|
const props = defineProps<{ entity: EntitySummary; disabled?: boolean }>()
|
||||||
|
const store = useSmartHomeStore()
|
||||||
|
|
||||||
|
const usable = computed(() => selectUsable(props.entity))
|
||||||
|
|
||||||
|
/** 当前选项不在 options 里时(如 HA 的 `unknown`)仍原样传给 Select,让用户自己选 */
|
||||||
|
const current = computed(() => props.entity.state)
|
||||||
|
|
||||||
|
async function pick(next: string) {
|
||||||
|
try {
|
||||||
|
await store.control(props.entity, 'select_option', { option: next }, { state: next })
|
||||||
|
} catch (e) {
|
||||||
|
controlFail(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<Select
|
||||||
|
v-if="usable"
|
||||||
|
:model-value="current"
|
||||||
|
:disabled="disabled"
|
||||||
|
@update:model-value="(v) => pick(String(v))"
|
||||||
|
>
|
||||||
|
<SelectTrigger class="h-8 w-full">
|
||||||
|
<SelectValue placeholder="选择…" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem v-for="o in entity.options" :key="o" :value="o">{{ o }}</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, ref } from 'vue'
|
||||||
|
import {
|
||||||
|
AlertDialog,
|
||||||
|
AlertDialogAction,
|
||||||
|
AlertDialogCancel,
|
||||||
|
AlertDialogContent,
|
||||||
|
AlertDialogDescription,
|
||||||
|
AlertDialogFooter,
|
||||||
|
AlertDialogHeader,
|
||||||
|
AlertDialogTitle
|
||||||
|
} from '@/components/ui/alert-dialog'
|
||||||
|
import { Switch } from '@/components/ui/switch'
|
||||||
|
import { useSmartHomeStore, type EntitySummary } from '@/stores/smartHomeStore'
|
||||||
|
import { controlFail } from './shared'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 开 / 关控件。
|
||||||
|
*
|
||||||
|
* 覆盖 `switch` / `input_boolean` / `automation`(on/off)与 `lock`(locked/unlocked)。
|
||||||
|
* 门锁的**开锁**是危险操作(§5.3):二次确认后才下发。
|
||||||
|
*
|
||||||
|
* 这里不重复显示状态文字 —— 卡片上方那行已经是"开 / 关 / 已上锁",
|
||||||
|
* 再写一遍只是噪声。
|
||||||
|
*/
|
||||||
|
const props = defineProps<{ entity: EntitySummary; disabled?: boolean }>()
|
||||||
|
const store = useSmartHomeStore()
|
||||||
|
|
||||||
|
const isLock = computed(() => props.entity.domain === 'lock')
|
||||||
|
const isOn = computed(() =>
|
||||||
|
isLock.value ? props.entity.state === 'locked' : props.entity.state === 'on'
|
||||||
|
)
|
||||||
|
const confirmOpen = ref(false)
|
||||||
|
|
||||||
|
async function dispatch() {
|
||||||
|
const e = props.entity
|
||||||
|
try {
|
||||||
|
if (isLock.value) {
|
||||||
|
const unlocking = e.state === 'locked'
|
||||||
|
await store.control(
|
||||||
|
e,
|
||||||
|
unlocking ? 'unlock' : 'lock',
|
||||||
|
{},
|
||||||
|
{ state: unlocking ? 'unlocked' : 'locked' }
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const next = !isOn.value
|
||||||
|
await store.control(e, next ? 'turn_on' : 'turn_off', {}, { state: next ? 'on' : 'off' })
|
||||||
|
} catch (err) {
|
||||||
|
controlFail(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function request(next: boolean | 'indeterminate') {
|
||||||
|
if (next === 'indeterminate') return
|
||||||
|
// 开锁 = 危险操作,先确认(可在设置里关掉)
|
||||||
|
if (isLock.value && !next && store.ui?.confirmDangerous) {
|
||||||
|
confirmOpen.value = true
|
||||||
|
return
|
||||||
|
}
|
||||||
|
void dispatch()
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="flex items-center justify-end">
|
||||||
|
<Switch
|
||||||
|
:model-value="isOn"
|
||||||
|
:disabled="disabled"
|
||||||
|
:aria-label="isLock ? (isOn ? '解锁' : '上锁') : isOn ? '关闭' : '打开'"
|
||||||
|
@update:model-value="request"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<AlertDialog :open="confirmOpen" @update:open="(v) => (confirmOpen = v)">
|
||||||
|
<AlertDialogContent>
|
||||||
|
<AlertDialogHeader>
|
||||||
|
<AlertDialogTitle>确认开锁?</AlertDialogTitle>
|
||||||
|
<AlertDialogDescription>
|
||||||
|
{{ entity.name }} 将解除锁定,请先确认周围环境安全。
|
||||||
|
</AlertDialogDescription>
|
||||||
|
</AlertDialogHeader>
|
||||||
|
<AlertDialogFooter>
|
||||||
|
<AlertDialogCancel>取消</AlertDialogCancel>
|
||||||
|
<AlertDialogAction @click="dispatch">确认开锁</AlertDialogAction>
|
||||||
|
</AlertDialogFooter>
|
||||||
|
</AlertDialogContent>
|
||||||
|
</AlertDialog>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import type { Component } from 'vue'
|
||||||
|
import ActionControl from './ActionControl.vue'
|
||||||
|
import ClimateControl from './ClimateControl.vue'
|
||||||
|
import CoverControl from './CoverControl.vue'
|
||||||
|
import FanControl from './FanControl.vue'
|
||||||
|
import LightControl from './LightControl.vue'
|
||||||
|
import MediaControl from './MediaControl.vue'
|
||||||
|
import NumberControl from './NumberControl.vue'
|
||||||
|
import SelectControl from './SelectControl.vue'
|
||||||
|
import SwitchControl from './SwitchControl.vue'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* domain → 控件组件。
|
||||||
|
*
|
||||||
|
* 与 `format.ts` 的 `CONTROLLABLE_DOMAINS` **必须一致**:只有这里存在的 domain
|
||||||
|
* 才允许声明"可控",否则卡片会拿到一个点不了的控制位(§3.4 的取舍)。
|
||||||
|
* 新增 domain 时两边一起改。
|
||||||
|
*/
|
||||||
|
const CONTROL_MAP: Record<string, Component> = {
|
||||||
|
light: LightControl,
|
||||||
|
switch: SwitchControl,
|
||||||
|
input_boolean: SwitchControl,
|
||||||
|
automation: SwitchControl,
|
||||||
|
lock: SwitchControl,
|
||||||
|
cover: CoverControl,
|
||||||
|
climate: ClimateControl,
|
||||||
|
fan: FanControl,
|
||||||
|
media_player: MediaControl,
|
||||||
|
scene: ActionControl,
|
||||||
|
script: ActionControl,
|
||||||
|
// 通用域(真机上覆盖 206 个"能控但没控件"的实体)
|
||||||
|
number: NumberControl,
|
||||||
|
select: SelectControl,
|
||||||
|
button: ActionControl
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 取该实体的控件(无对应控件时返回 null,卡片就不渲染控制位) */
|
||||||
|
export function controlFor(domain: string): Component | null {
|
||||||
|
return CONTROL_MAP[domain] ?? null
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import { toast } from 'vue-sonner'
|
||||||
|
import { toApiError } from '@/stores/smartHomeStore'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 控制类命令的统一失败提示。
|
||||||
|
*
|
||||||
|
* 一律用 toast 就地反馈:顶部横幅只留给"链路 / 令牌"这类**全局**问题
|
||||||
|
* (否则每次点错一个参数都会挂一条常驻横幅)。
|
||||||
|
*/
|
||||||
|
export function controlFail(e: unknown) {
|
||||||
|
toast.error(toApiError(e).message)
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,50 @@
|
|||||||
|
import type { ModuleConfig } from '@/types/module'
|
||||||
|
import type { SearchIndexItem } from '@/stores/searchIndex'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 智能家居模块(Home Assistant 对接)。
|
||||||
|
*
|
||||||
|
* 规划见 doc/SMART_HOME_MODULE_PLAN.md:
|
||||||
|
* - P0 连接管理(双地址:局域网 / 反代)+ 令牌入系统凭据管理器 + 端点选择 + 链路诊断
|
||||||
|
* - P1 设备状态列表 P2 设备控制 P3 HA 已有自动化
|
||||||
|
* - P4 WebSocket 实时推送(含房间分组)+ 本地规则引擎(三段式,仅在 Thing 运行时生效)
|
||||||
|
*/
|
||||||
|
|
||||||
|
const searchItems: SearchIndexItem[] = [
|
||||||
|
{
|
||||||
|
title: '智能家居',
|
||||||
|
description: '查看与控制 Home Assistant 中的智能家居设备',
|
||||||
|
keywords: ['智能家居', 'home assistant', 'ha', '设备', '实体', '灯', '开关', 'smarthome'],
|
||||||
|
tab: 'devices'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '智能家居 · 自动化',
|
||||||
|
description: '查看与运行 Home Assistant 自动化,管理本地联动规则',
|
||||||
|
keywords: ['自动化', 'automation', '场景', 'scene', '脚本', 'script', '联动', '规则'],
|
||||||
|
tab: 'automations'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '智能家居连接设置',
|
||||||
|
description: '配置 Home Assistant 地址(局域网 / 反代)与长期访问令牌',
|
||||||
|
keywords: ['连接', '令牌', 'token', '地址', '反代', '局域网', 'home assistant', '设置'],
|
||||||
|
tab: 'settings'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '检测智能家居链路',
|
||||||
|
description: '探测当前使用的是局域网还是反代,并显示耗时',
|
||||||
|
keywords: ['链路', '延迟', '检测', '局域网', '反代', 'cloudflare', 'tunnel', '诊断'],
|
||||||
|
tab: 'settings'
|
||||||
|
}
|
||||||
|
]
|
||||||
|
|
||||||
|
export const moduleConfig: ModuleConfig = {
|
||||||
|
id: 'smarthome',
|
||||||
|
name: '智能家居',
|
||||||
|
icon: 'smarthome',
|
||||||
|
description: '对接 Home Assistant:设备状态、控制与简单自动化',
|
||||||
|
category: 'system',
|
||||||
|
defaultEnabled: false,
|
||||||
|
loader: () => import('./SmartHomeModule.vue'),
|
||||||
|
searchItems,
|
||||||
|
order: 85
|
||||||
|
}
|
||||||
@@ -72,6 +72,30 @@ function resetMenuState() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 被禁用的模块 ID 集合(模块启停状态的真相在 appSettings.modules) */
|
||||||
|
const disabledModules = ref<Set<string>>(new Set())
|
||||||
|
|
||||||
|
/** 读取模块启停状态:未记录的模块按默认启用处理 */
|
||||||
|
function readModuleStates() {
|
||||||
|
const disabled = new Set<string>()
|
||||||
|
try {
|
||||||
|
const raw = localStorage.getItem(STORAGE_KEYS.appSettings)
|
||||||
|
if (raw) {
|
||||||
|
const parsed = JSON.parse(raw)
|
||||||
|
if (Array.isArray(parsed.modules)) {
|
||||||
|
for (const m of parsed.modules) {
|
||||||
|
if (m && typeof m.id === 'string' && m.enabled === false) disabled.add(m.id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch { /* 忽略 */ }
|
||||||
|
disabledModules.value = disabled
|
||||||
|
}
|
||||||
|
|
||||||
|
function moduleEnabled(id: string): boolean {
|
||||||
|
return !disabledModules.value.has(id)
|
||||||
|
}
|
||||||
|
|
||||||
function readOsdVisible(): boolean {
|
function readOsdVisible(): boolean {
|
||||||
try {
|
try {
|
||||||
const raw = localStorage.getItem(STORAGE_KEYS.monitorOsdConfig)
|
const raw = localStorage.getItem(STORAGE_KEYS.monitorOsdConfig)
|
||||||
@@ -87,6 +111,19 @@ const proxyLoading = computed(() =>
|
|||||||
loadingAction.value !== null && loadingAction.value.startsWith('proxy')
|
loadingAction.value !== null && loadingAction.value.startsWith('proxy')
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// 各区块/快捷入口跟随模块启停状态显示;分隔线只在其上方确实有内容时出现
|
||||||
|
const showMusic = computed(() => moduleEnabled('music'))
|
||||||
|
const showProxy = computed(() => moduleEnabled('proxy'))
|
||||||
|
const showMonitor = computed(() => moduleEnabled('monitor'))
|
||||||
|
const showProxySeparator = computed(() => showProxy.value && showMusic.value)
|
||||||
|
const showMonitorSeparator = computed(() => showMonitor.value && (showMusic.value || showProxy.value))
|
||||||
|
const showQuickLaunch = computed(() =>
|
||||||
|
moduleEnabled('terminal') || moduleEnabled('dsh') || moduleEnabled('editor')
|
||||||
|
)
|
||||||
|
const showQuickSeparator = computed(() =>
|
||||||
|
showQuickLaunch.value && (showMusic.value || showProxy.value || showMonitor.value)
|
||||||
|
)
|
||||||
|
|
||||||
const REGION_MAP: Record<string, string> = {
|
const REGION_MAP: Record<string, string> = {
|
||||||
'日本': 'JP', '香港': 'HK', '美国': 'US', '新加坡': 'SG',
|
'日本': 'JP', '香港': 'HK', '美国': 'US', '新加坡': 'SG',
|
||||||
'台湾': 'TW', '韩国': 'KR', '印度': 'IN', '英国': 'UK',
|
'台湾': 'TW', '韩国': 'KR', '印度': 'IN', '英国': 'UK',
|
||||||
@@ -397,6 +434,11 @@ const modeTitle = computed(() =>
|
|||||||
let musicTimer: number | null = null
|
let musicTimer: number | null = null
|
||||||
|
|
||||||
function startMusicPolling() {
|
function startMusicPolling() {
|
||||||
|
// 音乐模块被禁用时不查询、不轮询音乐状态
|
||||||
|
if (!moduleEnabled('music')) {
|
||||||
|
stopMusicPolling()
|
||||||
|
return
|
||||||
|
}
|
||||||
void refreshMusic()
|
void refreshMusic()
|
||||||
if (musicTimer !== null) return
|
if (musicTimer !== null) return
|
||||||
musicTimer = window.setInterval(() => void refreshMusic(), 1000)
|
musicTimer = window.setInterval(() => void refreshMusic(), 1000)
|
||||||
@@ -534,6 +576,7 @@ async function applyTheme() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
onMounted(async () => {
|
onMounted(async () => {
|
||||||
|
readModuleStates()
|
||||||
await applyTheme()
|
await applyTheme()
|
||||||
|
|
||||||
const mq = window.matchMedia('(prefers-color-scheme: dark)')
|
const mq = window.matchMedia('(prefers-color-scheme: dark)')
|
||||||
@@ -541,9 +584,16 @@ onMounted(async () => {
|
|||||||
mq.addEventListener('change', onThemeChange)
|
mq.addEventListener('change', onThemeChange)
|
||||||
unlistenFns.push(() => mq.removeEventListener('change', onThemeChange))
|
unlistenFns.push(() => mq.removeEventListener('change', onThemeChange))
|
||||||
|
|
||||||
// 主窗口改主题/效果/主题色时同步(托盘菜单常驻,不监听就会一直用旧值)
|
// 主窗口改主题/效果/主题色或模块启停时同步(托盘菜单常驻,不监听就会一直用旧值)
|
||||||
const onStorage = (e: StorageEvent) => {
|
const onStorage = (e: StorageEvent) => {
|
||||||
if (e.key === STORAGE_KEYS.appSettings) void applyTheme()
|
if (e.key !== STORAGE_KEYS.appSettings) return
|
||||||
|
void applyTheme()
|
||||||
|
readModuleStates()
|
||||||
|
// 音乐模块关闭后立即停止轮询并收起音量面板,避免无效查询与残留 UI
|
||||||
|
if (!moduleEnabled('music')) {
|
||||||
|
stopMusicPolling()
|
||||||
|
volumeOpen.value = false
|
||||||
|
}
|
||||||
}
|
}
|
||||||
window.addEventListener('storage', onStorage)
|
window.addEventListener('storage', onStorage)
|
||||||
unlistenFns.push(() => window.removeEventListener('storage', onStorage))
|
unlistenFns.push(() => window.removeEventListener('storage', onStorage))
|
||||||
@@ -556,6 +606,8 @@ onMounted(async () => {
|
|||||||
|
|
||||||
unlistenFns.push(await listen<TrayMenuState>('tray-menu-show', async (event) => {
|
unlistenFns.push(await listen<TrayMenuState>('tray-menu-show', async (event) => {
|
||||||
await applyTheme()
|
await applyTheme()
|
||||||
|
// 每次弹出前重读模块启停状态,设置页刚改完立即生效
|
||||||
|
readModuleStates()
|
||||||
Object.assign(state, event.payload)
|
Object.assign(state, event.payload)
|
||||||
osdVisible.value = readOsdVisible()
|
osdVisible.value = readOsdVisible()
|
||||||
// 显示前重置上次残留的下拉/焦点状态(双保险)
|
// 显示前重置上次残留的下拉/焦点状态(双保险)
|
||||||
@@ -604,7 +656,7 @@ onUnmounted(() => {
|
|||||||
<div class="tray-menu-root flex flex-col" @keydown="onKeydown" tabindex="0">
|
<div class="tray-menu-root flex flex-col" @keydown="onKeydown" tabindex="0">
|
||||||
<div class="tray-menu-scroll flex-1 min-h-0 overflow-y-auto">
|
<div class="tray-menu-scroll flex-1 min-h-0 overflow-y-auto">
|
||||||
<!-- 音乐控制条(代理之上):第一行曲目信息,第二行播放控制(一行太挤) -->
|
<!-- 音乐控制条(代理之上):第一行曲目信息,第二行播放控制(一行太挤) -->
|
||||||
<div class="tray-music">
|
<div v-if="showMusic" class="tray-music">
|
||||||
<div class="tray-music-info">
|
<div class="tray-music-info">
|
||||||
<Music class="size-4 shrink-0 tray-music-icon" />
|
<Music class="size-4 shrink-0 tray-music-icon" />
|
||||||
<div class="tray-music-text">
|
<div class="tray-music-text">
|
||||||
@@ -674,9 +726,9 @@ onUnmounted(() => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="tray-separator"></div>
|
<div v-if="showProxySeparator" class="tray-separator"></div>
|
||||||
|
|
||||||
<div class="tray-section">
|
<div v-if="showProxy" class="tray-section">
|
||||||
<div class="tray-section-header">
|
<div class="tray-section-header">
|
||||||
<Globe class="size-4 text-primary" />
|
<Globe class="size-4 text-primary" />
|
||||||
<span class="tray-section-title">代理</span>
|
<span class="tray-section-title">代理</span>
|
||||||
@@ -740,9 +792,9 @@ onUnmounted(() => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="tray-separator"></div>
|
<div v-if="showMonitorSeparator" class="tray-separator"></div>
|
||||||
|
|
||||||
<div class="tray-section">
|
<div v-if="showMonitor" class="tray-section">
|
||||||
<div class="tray-section-header">
|
<div class="tray-section-header">
|
||||||
<Monitor class="size-4 text-primary" />
|
<Monitor class="size-4 text-primary" />
|
||||||
<span class="tray-section-title">监控</span>
|
<span class="tray-section-title">监控</span>
|
||||||
@@ -767,17 +819,17 @@ onUnmounted(() => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="tray-separator"></div>
|
<div v-if="showQuickSeparator" class="tray-separator"></div>
|
||||||
|
|
||||||
<button class="tray-item" @click="handleAction('terminal')">
|
<button v-if="moduleEnabled('terminal')" class="tray-item" @click="handleAction('terminal')">
|
||||||
<SquareTerminal class="size-4" />
|
<SquareTerminal class="size-4" />
|
||||||
<span>终端</span>
|
<span>终端</span>
|
||||||
</button>
|
</button>
|
||||||
<button class="tray-item" @click="handleAction('dsh')">
|
<button v-if="moduleEnabled('dsh')" class="tray-item" @click="handleAction('dsh')">
|
||||||
<Bot class="size-4" />
|
<Bot class="size-4" />
|
||||||
<span>dsh</span>
|
<span>dsh</span>
|
||||||
</button>
|
</button>
|
||||||
<button class="tray-item" @click="handleAction('editor')">
|
<button v-if="moduleEnabled('editor')" class="tray-item" @click="handleAction('editor')">
|
||||||
<FileCode2 class="size-4" />
|
<FileCode2 class="size-4" />
|
||||||
<span>编辑器</span>
|
<span>编辑器</span>
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { defineStore } from 'pinia'
|
import { defineStore } from 'pinia'
|
||||||
import { ref } from 'vue'
|
import { ref } from 'vue'
|
||||||
|
import { invoke } from '@tauri-apps/api/core'
|
||||||
import { WebviewWindow } from '@tauri-apps/api/webviewWindow'
|
import { WebviewWindow } from '@tauri-apps/api/webviewWindow'
|
||||||
import { PhysicalPosition, PhysicalSize } from '@tauri-apps/api/dpi'
|
|
||||||
import { availableMonitors } from '@tauri-apps/api/window'
|
import { availableMonitors } from '@tauri-apps/api/window'
|
||||||
import { emit, listen, type UnlistenFn } from '@tauri-apps/api/event'
|
import { emit, listen, type UnlistenFn } from '@tauri-apps/api/event'
|
||||||
import { toast } from 'vue-sonner'
|
import { toast } from 'vue-sonner'
|
||||||
@@ -70,6 +70,49 @@ const DEFAULT_SETTINGS: ScreenshotSettings = {
|
|||||||
shortcutDefaultsVersion: SHORTCUT_DEFAULTS_VERSION,
|
shortcutDefaultsVersion: SHORTCUT_DEFAULTS_VERSION,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ===== 历史持久化(键 / 结构 / 跨窗口只读访问) =====
|
||||||
|
const HISTORY_KEY = STORAGE_KEYS.screenshotHistory
|
||||||
|
const HISTORY_VERSION = 1
|
||||||
|
|
||||||
|
/** 历史在 localStorage 里的持久化形态 */
|
||||||
|
interface HistorySnapshot {
|
||||||
|
version?: number
|
||||||
|
items?: RecentCapture[]
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 截图文件名 —— 与截图**编辑栏**的「保存」(`ScreenshotOverlay.doSave`)、
|
||||||
|
* 本 store 的 `saveImage`(历史项保存)以及自动保存**同一条规则**:
|
||||||
|
* `screenshot_<ISO 到秒>.png`(如 `screenshot_2026-10-20T12-34-56.png`)。
|
||||||
|
*
|
||||||
|
* 抽成函数是为了让"快速面板 → 保存截图"落下的文件名**不可能**与那几个按钮漂移。
|
||||||
|
*/
|
||||||
|
export function screenshotFileName(now: Date = new Date()): string {
|
||||||
|
const ts = now.toISOString().replace(/[:.]/g, '-').slice(0, 19)
|
||||||
|
return `screenshot_${ts}.png`
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 最近一张截图的完整 PNG 缓存路径(**只读**,无任何副作用)。
|
||||||
|
*
|
||||||
|
* 为什么快速面板不用 store 而是直接读 localStorage:它是独立窗口,Pinia 是
|
||||||
|
* **窗口级**的(`main.ts` 里每个窗口装一份,store 实例互不可见),读 store 就得先
|
||||||
|
* `loadSettings` + `loadHistory` —— 而 `loadHistory` 会按"当前设置里的保留条数"
|
||||||
|
* 删除超限的缓存文件;设置没加载时限额取默认值,可能误删用户的历史缓存。
|
||||||
|
* 这里只取 `items[0].filePath`(历史里只有缩略图,完整 PNG 在缓存目录按需读取)。
|
||||||
|
*/
|
||||||
|
export function latestCaptureCachePath(): string | null {
|
||||||
|
try {
|
||||||
|
const raw = localStorage.getItem(HISTORY_KEY)
|
||||||
|
if (!raw) return null
|
||||||
|
const parsed = JSON.parse(raw) as HistorySnapshot
|
||||||
|
if (parsed.version !== HISTORY_VERSION || !Array.isArray(parsed.items)) return null
|
||||||
|
return parsed.items[0]?.filePath ?? null
|
||||||
|
} catch {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export const useScreenshotStore = defineStore('screenshot', () => {
|
export const useScreenshotStore = defineStore('screenshot', () => {
|
||||||
const capturing = ref(false)
|
const capturing = ref(false)
|
||||||
const recent = ref<RecentCapture[]>([])
|
const recent = ref<RecentCapture[]>([])
|
||||||
@@ -98,10 +141,6 @@ export const useScreenshotStore = defineStore('screenshot', () => {
|
|||||||
/** 贴图全局快捷键事件监听 */
|
/** 贴图全局快捷键事件监听 */
|
||||||
let pinShortcutUnlisten: UnlistenFn | null = null
|
let pinShortcutUnlisten: UnlistenFn | null = null
|
||||||
|
|
||||||
// ===== 历史持久化 =====
|
|
||||||
const HISTORY_KEY = STORAGE_KEYS.screenshotHistory
|
|
||||||
const HISTORY_VERSION = 1
|
|
||||||
|
|
||||||
// ===== 设置持久化 =====
|
// ===== 设置持久化 =====
|
||||||
function loadSettings() {
|
function loadSettings() {
|
||||||
try {
|
try {
|
||||||
@@ -205,8 +244,16 @@ export const useScreenshotStore = defineStore('screenshot', () => {
|
|||||||
// 矩形未变化时跳过(覆盖层仅由本流程定位,跳过安全),省 2 次 IPC 往返
|
// 矩形未变化时跳过(覆盖层仅由本流程定位,跳过安全),省 2 次 IPC 往返
|
||||||
const rectKey = `${rect.x},${rect.y},${rect.width},${rect.height}`
|
const rectKey = `${rect.x},${rect.y},${rect.width},${rect.height}`
|
||||||
if (rectKey !== lastOverlayRectKey) {
|
if (rectKey !== lastOverlayRectKey) {
|
||||||
await overlayWin?.setPosition(new PhysicalPosition(rect.x, rect.y))
|
// 原生 SetWindowPos 一次设置位置 + 尺寸(物理像素,同步生效,窗口隐藏态也立即落位)。
|
||||||
await overlayWin?.setSize(new PhysicalSize(rect.width, rect.height))
|
// 覆盖层创建时即为不可缩放(见 ensureOverlay),Tauri 的 setSize 在非 resizable 窗口上
|
||||||
|
// 不生效,所以这里统一走原生命令。
|
||||||
|
await invoke('osd_set_bounds', {
|
||||||
|
label: OVERLAY_LABEL,
|
||||||
|
x: rect.x,
|
||||||
|
y: rect.y,
|
||||||
|
w: rect.width,
|
||||||
|
h: rect.height,
|
||||||
|
}).catch((e) => logger.warn(`覆盖层定位失败: ${e}`))
|
||||||
lastOverlayRectKey = rectKey
|
lastOverlayRectKey = rectKey
|
||||||
}
|
}
|
||||||
await ensureOverlayReady()
|
await ensureOverlayReady()
|
||||||
@@ -269,6 +316,8 @@ export const useScreenshotStore = defineStore('screenshot', () => {
|
|||||||
overlayWin = null
|
overlayWin = null
|
||||||
}
|
}
|
||||||
resetOverlayReady()
|
resetOverlayReady()
|
||||||
|
// 新窗口必须重新定位:清空上次矩形记录,否则会跳过定位,新窗口停留在初始 800×600
|
||||||
|
lastOverlayRectKey = ''
|
||||||
overlayWin = new WebviewWindow(OVERLAY_LABEL, {
|
overlayWin = new WebviewWindow(OVERLAY_LABEL, {
|
||||||
url: 'index.html#screenshot-overlay',
|
url: 'index.html#screenshot-overlay',
|
||||||
title: '截图',
|
title: '截图',
|
||||||
@@ -276,9 +325,12 @@ export const useScreenshotStore = defineStore('screenshot', () => {
|
|||||||
y: 0,
|
y: 0,
|
||||||
width: 800,
|
width: 800,
|
||||||
height: 600,
|
height: 600,
|
||||||
// 必须 true:resizable:false 在 Windows 上会导致 setSize 失效,
|
// 直接创建为不可缩放:可缩放的无边框窗口在屏幕原点会暴露系统缩放手柄
|
||||||
// 覆盖层无法铺满虚拟屏,选区被 clamp 到初始 800x600 区域(表现为工具栏始终停在左上角)
|
// (tao 在 WM_NCHITTEST 中按 RESIZABLE 标志返回 HTTOPLEFT 等),
|
||||||
resizable: true,
|
// 于是「从屏幕左上角 (0,0) 起笔框选」会被判定为拖动窗口缩放边框,把整个覆盖层拉小。
|
||||||
|
// 覆盖层始终铺满虚拟屏,无需用户调整大小;尺寸改由原生 SetWindowPos
|
||||||
|
// (osd_set_bounds)设置,不受 resizable 限制(Tauri setSize 在非 resizable 窗口上不生效)。
|
||||||
|
resizable: false,
|
||||||
decorations: false,
|
decorations: false,
|
||||||
alwaysOnTop: true,
|
alwaysOnTop: true,
|
||||||
skipTaskbar: true,
|
skipTaskbar: true,
|
||||||
@@ -434,7 +486,7 @@ export const useScreenshotStore = defineStore('screenshot', () => {
|
|||||||
try {
|
try {
|
||||||
const raw = localStorage.getItem(HISTORY_KEY)
|
const raw = localStorage.getItem(HISTORY_KEY)
|
||||||
if (!raw) return
|
if (!raw) return
|
||||||
const parsed = JSON.parse(raw) as { version?: number; items?: RecentCapture[] }
|
const parsed = JSON.parse(raw) as HistorySnapshot
|
||||||
if (parsed.version !== HISTORY_VERSION || !Array.isArray(parsed.items)) {
|
if (parsed.version !== HISTORY_VERSION || !Array.isArray(parsed.items)) {
|
||||||
localStorage.removeItem(HISTORY_KEY)
|
localStorage.removeItem(HISTORY_KEY)
|
||||||
return
|
return
|
||||||
@@ -506,12 +558,8 @@ export const useScreenshotStore = defineStore('screenshot', () => {
|
|||||||
|
|
||||||
async function saveImage(pngBase64: string) {
|
async function saveImage(pngBase64: string) {
|
||||||
const { save } = await import('@tauri-apps/plugin-dialog')
|
const { save } = await import('@tauri-apps/plugin-dialog')
|
||||||
const ts = new Date()
|
|
||||||
.toISOString()
|
|
||||||
.replace(/[:.]/g, '-')
|
|
||||||
.slice(0, 19)
|
|
||||||
const path = await save({
|
const path = await save({
|
||||||
defaultPath: `screenshot_${ts}.png`,
|
defaultPath: screenshotFileName(),
|
||||||
filters: [{ name: 'PNG', extensions: ['png'] }],
|
filters: [{ name: 'PNG', extensions: ['png'] }],
|
||||||
})
|
})
|
||||||
if (!path) return
|
if (!path) return
|
||||||
@@ -546,11 +594,7 @@ export const useScreenshotStore = defineStore('screenshot', () => {
|
|||||||
}
|
}
|
||||||
// 自动保存到指定目录
|
// 自动保存到指定目录
|
||||||
if (settings.value.autoSave && settings.value.saveDir) {
|
if (settings.value.autoSave && settings.value.saveDir) {
|
||||||
const ts = new Date()
|
const path = `${settings.value.saveDir.replace(/\\$/, '')}\\${screenshotFileName()}`
|
||||||
.toISOString()
|
|
||||||
.replace(/[:.]/g, '-')
|
|
||||||
.slice(0, 19)
|
|
||||||
const path = `${settings.value.saveDir.replace(/\\$/, '')}\\screenshot_${ts}.png`
|
|
||||||
try {
|
try {
|
||||||
await commands.screenshotSavePng(pngBase64, path)
|
await commands.screenshotSavePng(pngBase64, path)
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user