bug改修,智家模块

This commit is contained in:
zhongluofeng committed 2026-10-23 17:25:17 +08:00
1 parent 063718f86d
commit fcbcf07b87
52 files changed
+12602 -142

No files matched your search

+29
View File
@@ -7895,8 +7895,12 @@ checksum = "edc5f74e248dc973e0dbb7b74c7e0d6fcc301c694ff50049504004ef4d0cdcd9"
dependencies = [
"futures-util",
"log",
"rustls",
"rustls-pki-types",
"tokio",
"tokio-rustls",
"tungstenite",
"webpki-roots 0.26.11",
]
[[package]]
@@ -8032,12 +8036,17 @@ version = "0.6.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"
dependencies = [
"async-compression",
"bitflags 2.13.2",
"bytes",
"futures-core",
"futures-util",
"http",
"http-body",
"http-body-util",
"pin-project-lite",
"tokio",
"tokio-util",
"tower",
"tower-layer",
"tower-service",
@@ -8139,6 +8148,8 @@ dependencies = [
"httparse",
"log",
"rand 0.8.8",
"rustls",
"rustls-pki-types",
"sha1 0.10.7",
"thiserror 1.0.69",
"utf-8",
@@ -8512,6 +8523,24 @@ dependencies = [
"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]]
name = "webview2-com"
version = "0.39.1"
+19 -3
View File
@@ -42,8 +42,14 @@ chrono = "0.4"
# blocking:音乐播放引擎在**独立 std 线程**上解码(symphonia 的 MediaSource 是同步
# Read+Seek),需要同步 HTTP 客户端去按 Range 拉 NAS 音频流。放在 std 线程上用
# blocking 是安全的(在 tokio 运行时线程里用才会 panic)。
reqwest = { version = "0.12", features = ["json", "stream", "multipart", "blocking"] }
futures-util = "0.3"
# gzip:智能家居模块走反代(Cloudflare Tunnel)链路时,`/api/states` 是几百 KB JSON。
# **默认不开压缩就不会发 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"] }
axum = { version = "0.7", features = ["ws"] }
url = "2"
@@ -104,7 +110,14 @@ aes = "0.8"
cbc = "0.1"
rsa = { version = "0.9", features = ["pem"] }
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"] }
walkdir = "2"
notify = { version = "6", features = [] }
@@ -178,6 +191,9 @@ windows = { version = "0.52", features = [
"Win32_System_Ole",
"Win32_System_Variant",
"Win32_UI_Shell",
# 快速面板「保存截图后定位并进入重命名」:SHParseDisplayName / SHOpenFolderAndSelectItems
# 与 ITEMIDLIST 都被 Win32_UI_Shell_Common 门控(windows 0.52 源码 cfg)
"Win32_UI_Shell_Common",
"Win32_UI_WindowsAndMessaging",
# 翻译模块:Windows.Media.Ocr 本地识别(WinRT)
# Foundation_Collections:OcrResult.Lines / OcrEngine.AvailableRecognizerLanguages 返回 IVectorView
+8
View File
@@ -178,4 +178,12 @@ pub mod events {
// 进度在**发送端**按时间节流(见 diff::commands::diff_compare_dirs):整棵树可能有
// 上万个条目、上千次读盘,逐条 emit 会把 IPC 打满;前端只负责显示。
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
View File
@@ -20,6 +20,7 @@ mod screenshot;
mod secrets;
mod setup;
mod shortcut;
mod smarthome;
mod snap_fix;
mod taskbar_identity;
mod terminal;
@@ -145,7 +146,8 @@ use quickpanel::{
quickpanel_get_special_locations, quickpanel_hide_popup, quickpanel_init_file_index,
quickpanel_list_archives, quickpanel_list_dir, quickpanel_lock_screen, quickpanel_open_file,
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_show_window, quickpanel_unregister_shortcut, quickpanel_focus_main_window,
};
@@ -194,6 +196,15 @@ use terminal::commands::{
};
use terminal::TerminalManager;
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 translate::{
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_build_file_index, quickpanel_search_files, quickpanel_file_index_stats,
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_run_system_command, quickpanel_list_archives, quickpanel_list_dir,
quickpanel_batch_extract, quickpanel_preview_rename, quickpanel_apply_rename,
@@ -381,6 +393,30 @@ fn export_bindings() {
diff_compare_dirs,
diff_get_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 + 组合图标)
window_set_taskbar_identity,
// 通用「显示 + 取消最小化 + 强制置前」(绕过 Windows 前台锁定)
@@ -639,6 +675,7 @@ pub fn run() {
quickpanel_get_app_icon,
quickpanel_clear_app_icon_cache,
quickpanel_reveal_in_explorer,
quickpanel_reveal_in_explorer_rename,
quickpanel_open_file,
quickpanel_delete_file,
quickpanel_delete_files,
@@ -916,6 +953,30 @@ pub fn run() {
diff_compare_dirs,
diff_get_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 + 组合图标)
window_set_taskbar_identity,
// 通用「显示 + 取消最小化 + 强制置前」
+141
View File
@@ -337,6 +337,147 @@ pub fn quickpanel_reveal_in_explorer(path: String) -> Result<(), String> {
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 直接打开(修复索引目录点击后未打开的问题)
/// - 文件:ShellExecuteW open,无关联应用时自动 fallback 到「打开方式」对话框(verb: openas)
+2 -1
View File
@@ -23,7 +23,8 @@ pub use commands::{
quickpanel_get_app_icon, quickpanel_get_settings, quickpanel_get_special_locations,
quickpanel_hide_popup, quickpanel_init_file_index, quickpanel_lock_screen,
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_show_window, quickpanel_unregister_shortcut,
};
+16
View File
@@ -22,6 +22,7 @@ use crate::monitor_kernel::MonitorKernel;
use crate::music::MusicManager;
use crate::network_monitor::NetworkMonitor;
use crate::editor::EditorManager;
use crate::smarthome::HaManager;
use crate::process_manager::{ProcessManager, start_monitoring_thread};
use crate::terminal::TerminalManager;
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());
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 =====
// 仅注册状态:设置与密钥都在命令调用时按需读取,启动阶段不发任何网络请求
// (模型可用性校验因此改为懒校验:首次翻译失败时解释原因 + 设置页手动拉取模型列表)。
+549
View File
@@ -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, &current) {
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,
},
);
}
+735
View File
@@ -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) = &params.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) = &params.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
}
}
}
}
+734
View File
@@ -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, &params,
)
.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())
}
+582
View File
@@ -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}"))
}
+109
View File
@@ -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()
}
+699
View File
@@ -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)
}
}
+768
View File
@@ -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)
}