Răsfoiți Sursa

添加UDP键值服务器

soease 2 săptămâni în urmă
părinte
comite
56b2e0b3f6

+ 5 - 1
README.md

@@ -24,6 +24,7 @@ wails3 build
 | 记录 | 每行一条「姓名\|名称\|值」记录,保存到 SQLite 数据库;姓名/名称输入自动补全历史值,选择姓名与名称后按值绘制柱状图,支持日期范围过滤,路径可在设置中修改 |
 | 工具 | 开发/运维辅助工具:Web 服务(选目录开启浏览服务)、翻译(中英互译)、二维码生成、发送 ntfy 消息、ntfy 聊天室、古诗词、屏幕截图、延时关机、MD5 加密、SHA256 编码、LED 滚动文字、定时提醒、LocalSend 互传、Croc 传送(自动检测系统 PATH 中的 `croc`,存在才显示)、视频下载(自动检测 `yt-dlp`,监视剪贴板中的 B 站链接)、Memos 速记(调用 Memos REST API 新建备忘)、显示器设置(DDC/CI 硬件调光、Gamma 兜底、一键息屏);各功能区默认折叠,点击标题展开 |
 | 本地 | 快捷启动在设置中配置的本机资源/工具:每行一条「标题|启动程序|说明(可空)」,与工具页相同的卡片样式;支持可执行文件、脚本(.bat/.cmd/.ps1/.vbs,.ps1 自动用 PowerShell 执行)、PATH 中的命令(如 notepad),可带参数与 %VAR% 环境变量,ShellExecute 分离启动、无黑框闪烁;启动地址为 .html 页面时自动在本机随机端口起 web 服务(页面所在目录即站点根,相对引用的本地资源可正常加载,仅监听 127.0.0.1,同一页面复用已有服务)并用浏览器打开 |
+| 控制 | 遥控小车:方向盘式的「上 / 下 / 左 / 右 / 休眠」按钮,点击后通过 `POST /api/xz/cmd` 下发指令(`^`、`v`、`<`、`>`、`sleep`),小车端用 `GET /api/xz/cmd` 取走并执行(读取即清除)。优先发往服务模式地址(小车从服务取指令,未登录也可用),服务不可用时自动改用界面 API;面板上显示当前目标地址与发送结果。四个方向键支持**长按连发**:按住某方向键超过 3 秒不释放即进入长按状态,按键变为渐变高亮(带呼吸光圈)并每 1 秒下发一次同一指令;松开鼠标/手指(任意位置)即停止连发,长按中点其他按键也只用于停止(不再下发指令),窗口失焦也会自动停止。未满 3 秒就松手则按单击处理(只下发一次) |
 | 服务 | 内置 API 服务状态、服务模式(启动/停止 Windows 服务、运行状态)与 Gin 日志(每 3 秒轮询 `/api/logs`,标题右侧可「清空日志」;经服务转发的请求带 `[via service]` 标记);原截屏功能已迁移至工具页 |
 | 设置 | 入口在标签栏末尾 ☰ 汉堡菜单的最后一项;按「系统 + 各 Tab」分组展示配置项,保存后立即生效 |
 | 自定义 | 在设置中可添加任意多个自定义 Tab(名字 + 网址,支持 http/https 网页或本地 Markdown 文件);网页类型内嵌 iframe,文件类型提供编辑 / 预览 / 保存 / 刷新 / 备份 |
@@ -114,9 +115,12 @@ Windows Vista 起服务运行在 Session 0,与用户桌面隔离,**无法显
 - `GET /api/power/cancel` 取消待执行命令
 - `GET /api/power/status` 查询命令状态
 - `POST /api/xz/cmd` 下发指令,body `{"cmd":"left"}`(也兼容 `?cmd=left`);除 `left/right/up/down` 外可传任意非空文本(≤200 字符,保留大小写),返回 `{"ok":true,"cmd":"left","seq":1}`
+- `GET /api/xz/cmd/<命令>` 路径参数下发(URL 编码,如 `/api/xz/cmd/left`、`/api/xz/cmd/%E5%97%A1%E5%8F%AD`),等效于 POST,返回 `{"ok":true,"cmd":"left","seq":1}`;适合浏览器地址栏 / 网页按钮直接下发
 - `GET /api/xz/cmd` 取走最近一条指令,**直接返回纯文本**(如 `left`,无 JSON、无其他信息);**读取后立即清除**,再次读取返回空字符串(无待取指令)
 
-指令信箱(`/api/xz/cmd`)保存在进程内存中,服务模式与界面兜底共用同一份状态,因此仅服务模式运行(未登录)时也能用;重启后指令清空。
+指令信箱(`/api/xz/cmd`)保存在进程内存中。服务模式运行(未登录)时:若界面已登记在线,`/api/xz/cmd` 的三个接口(POST/GET/路径参数)**转发给界面进程**,与界面共用同一份指令状态(控制页经界面下发、小车经服务读取,二者互通);界面离线时由服务进程本地兜底,仍可用。重启后指令清空。
+
+界面「控制」页的 5 个方向盘按键(上/下/左/右/休眠)可在 `设置 → 控制` 配置,每行格式 `图标|命令URL`(前 5 行顺序固定 上/下/左/右/休眠;第 6 行起为额外按键,显示在方向键下方从左至右排列)。命令非空时,点击按键直接以 `GET` 方式请求该 URL(fire-and-forget,不解析响应,失败仅在状态区提示);固定 5 键命令为空时回退到上述 `POST /api/xz/cmd` 指令信箱(指令值为 `up/down/left/right/sleep`),额外按键命令为空时仅提示未配置。
 
 界面 API 常用接口(服务模式下除电源类外均转发到界面):
 

+ 1 - 0
apiserver.go

@@ -227,6 +227,7 @@ func runAPIServer(addr string) {
 	api.GET("/download/:filename", handleDownload)   // 下载已上传文件(需密码)
 	api.POST("/xz/cmd", handleXZCmdPost)             // 下发指令(left/right/up/down),与服务模式共用实现
 	api.GET("/xz/cmd", handleXZCmdGet)               // 读取最新指令
+	api.GET("/xz/cmd/:cmd", handleXZCmdPathPost)     // 路径参数下发(URL 编码),如 /xz/cmd/left
 
 	pc := api.Group("/pc")              // 主机控制接口(移植自主机服务)
 	pc.GET("/poweroff", handlePoweroff) // 30 秒后关机

+ 4 - 0
frontend/bindings/TengTuToolbox/index.js

@@ -9,6 +9,7 @@ import * as LocalSendService from "./localsendservice.js";
 import * as LocalService from "./localservice.js";
 import * as MemosService from "./memosservice.js";
 import * as SettingsService from "./settingsservice.js";
+import * as UDPService from "./udpservice.js";
 import * as YTDLPService from "./ytdlpservice.js";
 export {
     BrightnessService,
@@ -18,6 +19,7 @@ export {
     LocalService,
     MemosService,
     SettingsService,
+    UDPService,
     YTDLPService
 };
 
@@ -28,6 +30,7 @@ export {
     BiliFeedResult,
     BrightnessConfig,
     CommitItem,
+    ControlKeyConfig,
     CrocConfig,
     CrocInfo,
     CustomTab,
@@ -53,6 +56,7 @@ export {
     TickerConfig,
     TranslateResult,
     TrendingRepo,
+    UDPInfo,
     WebServiceInfo,
     YTDLPConfig,
     YTDLPInfo

+ 178 - 36
frontend/bindings/TengTuToolbox/models.js

@@ -191,6 +191,22 @@ export class AppSettings {
              */
             this["localTools"] = [];
         }
+        if (!("controlKeys" in $$source)) {
+            /**
+             * 控制页按键配置(前 5 键固定 上/下/左/右/休眠,第 6 键起为额外按键)
+             * @member
+             * @type {ControlKeyConfig[]}
+             */
+            this["controlKeys"] = [];
+        }
+        if (!("controlRepeatSecs" in $$source)) {
+            /**
+             * 控制页长按连发频率(秒,0.0-10.0,默认 1.0)
+             * @member
+             * @type {number}
+             */
+            this["controlRepeatSecs"] = 0;
+        }
         if (!("apiAddr" in $$source)) {
             /**
              * 内置 API 服务监听地址
@@ -447,16 +463,17 @@ export class AppSettings {
         const $$createField12_0 = $$createType4;
         const $$createField13_0 = $$createType6;
         const $$createField14_0 = $$createType8;
-        const $$createField25_0 = $$createType9;
-        const $$createField26_0 = $$createType9;
-        const $$createField27_0 = $$createType10;
+        const $$createField15_0 = $$createType10;
+        const $$createField27_0 = $$createType11;
         const $$createField28_0 = $$createType11;
-        const $$createField39_0 = $$createType12;
-        const $$createField40_0 = $$createType13;
+        const $$createField29_0 = $$createType12;
+        const $$createField30_0 = $$createType13;
         const $$createField41_0 = $$createType14;
         const $$createField42_0 = $$createType15;
         const $$createField43_0 = $$createType16;
-        const $$createField44_0 = $$createType0;
+        const $$createField44_0 = $$createType17;
+        const $$createField45_0 = $$createType18;
+        const $$createField46_0 = $$createType0;
         let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
         if ("tabOrder" in $$parsedSource) {
             $$parsedSource["tabOrder"] = $$createField7_0($$parsedSource["tabOrder"]);
@@ -476,35 +493,38 @@ export class AppSettings {
         if ("localTools" in $$parsedSource) {
             $$parsedSource["localTools"] = $$createField14_0($$parsedSource["localTools"]);
         }
+        if ("controlKeys" in $$parsedSource) {
+            $$parsedSource["controlKeys"] = $$createField15_0($$parsedSource["controlKeys"]);
+        }
         if ("stockTicker" in $$parsedSource) {
-            $$parsedSource["stockTicker"] = $$createField25_0($$parsedSource["stockTicker"]);
+            $$parsedSource["stockTicker"] = $$createField27_0($$parsedSource["stockTicker"]);
         }
         if ("newsTicker" in $$parsedSource) {
-            $$parsedSource["newsTicker"] = $$createField26_0($$parsedSource["newsTicker"]);
+            $$parsedSource["newsTicker"] = $$createField28_0($$parsedSource["newsTicker"]);
         }
         if ("poem" in $$parsedSource) {
-            $$parsedSource["poem"] = $$createField27_0($$parsedSource["poem"]);
+            $$parsedSource["poem"] = $$createField29_0($$parsedSource["poem"]);
         }
         if ("mouseAlert" in $$parsedSource) {
-            $$parsedSource["mouseAlert"] = $$createField28_0($$parsedSource["mouseAlert"]);
+            $$parsedSource["mouseAlert"] = $$createField30_0($$parsedSource["mouseAlert"]);
         }
         if ("localSend" in $$parsedSource) {
-            $$parsedSource["localSend"] = $$createField39_0($$parsedSource["localSend"]);
+            $$parsedSource["localSend"] = $$createField41_0($$parsedSource["localSend"]);
         }
         if ("croc" in $$parsedSource) {
-            $$parsedSource["croc"] = $$createField40_0($$parsedSource["croc"]);
+            $$parsedSource["croc"] = $$createField42_0($$parsedSource["croc"]);
         }
         if ("ytdlp" in $$parsedSource) {
-            $$parsedSource["ytdlp"] = $$createField41_0($$parsedSource["ytdlp"]);
+            $$parsedSource["ytdlp"] = $$createField43_0($$parsedSource["ytdlp"]);
         }
         if ("memos" in $$parsedSource) {
-            $$parsedSource["memos"] = $$createField42_0($$parsedSource["memos"]);
+            $$parsedSource["memos"] = $$createField44_0($$parsedSource["memos"]);
         }
         if ("brightness" in $$parsedSource) {
-            $$parsedSource["brightness"] = $$createField43_0($$parsedSource["brightness"]);
+            $$parsedSource["brightness"] = $$createField45_0($$parsedSource["brightness"]);
         }
         if ("toolOrder" in $$parsedSource) {
-            $$parsedSource["toolOrder"] = $$createField44_0($$parsedSource["toolOrder"]);
+            $$parsedSource["toolOrder"] = $$createField46_0($$parsedSource["toolOrder"]);
         }
         return new AppSettings(/** @type {Partial<AppSettings>} */($$parsedSource));
     }
@@ -599,7 +619,7 @@ export class BiliFeedResult {
      * @returns {BiliFeedResult}
      */
     static createFrom($$source = {}) {
-        const $$createField0_0 = $$createType18;
+        const $$createField0_0 = $$createType20;
         let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
         if ("items" in $$parsedSource) {
             $$parsedSource["items"] = $$createField0_0($$parsedSource["items"]);
@@ -643,7 +663,7 @@ export class BrightnessConfig {
      * @returns {BrightnessConfig}
      */
     static createFrom($$source = {}) {
-        const $$createField1_0 = $$createType19;
+        const $$createField1_0 = $$createType21;
         let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
         if ("levels" in $$parsedSource) {
             $$parsedSource["levels"] = $$createField1_0($$parsedSource["levels"]);
@@ -700,6 +720,46 @@ export class CommitItem {
     }
 }
 
+/**
+ * ControlKeyConfig 控制页方向盘单个按键配置(图标 + 命令 URL)
+ */
+export class ControlKeyConfig {
+    /**
+     * Creates a new ControlKeyConfig instance.
+     * @param {Partial<ControlKeyConfig>} [$$source = {}] - The source object to create the ControlKeyConfig.
+     */
+    constructor($$source = {}) {
+        if (!("icon" in $$source)) {
+            /**
+             * 按钮显示字符,如 ↑、↓、←、→、休眠
+             * @member
+             * @type {string}
+             */
+            this["icon"] = "";
+        }
+        if (!("cmd" in $$source)) {
+            /**
+             * 点击时 GET 请求的完整 URL;空则回退旧指令信箱模式
+             * @member
+             * @type {string}
+             */
+            this["cmd"] = "";
+        }
+
+        Object.assign(this, $$source);
+    }
+
+    /**
+     * Creates a new ControlKeyConfig instance from a string or object.
+     * @param {any} [$$source = {}]
+     * @returns {ControlKeyConfig}
+     */
+    static createFrom($$source = {}) {
+        let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
+        return new ControlKeyConfig(/** @type {Partial<ControlKeyConfig>} */($$parsedSource));
+    }
+}
+
 /**
  * CrocConfig 是 Croc 传送的配置(发送/接收共用密码)。
  */
@@ -1151,7 +1211,7 @@ export class MinuteChart {
      * @returns {MinuteChart}
      */
     static createFrom($$source = {}) {
-        const $$createField2_0 = $$createType21;
+        const $$createField2_0 = $$createType23;
         let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
         if ("points" in $$parsedSource) {
             $$parsedSource["points"] = $$createField2_0($$parsedSource["points"]);
@@ -1887,8 +1947,8 @@ export class RepoFeed {
      * @returns {RepoFeed}
      */
     static createFrom($$source = {}) {
-        const $$createField9_0 = $$createType23;
-        const $$createField10_0 = $$createType25;
+        const $$createField9_0 = $$createType25;
+        const $$createField10_0 = $$createType27;
         let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
         if ("newer" in $$parsedSource) {
             $$parsedSource["newer"] = $$createField9_0($$parsedSource["newer"]);
@@ -2324,6 +2384,86 @@ export class TrendingRepo {
     }
 }
 
+/**
+ * UDPInfo 描述一次 UDP 键值服务的运行状态,供前端展示。
+ */
+export class UDPInfo {
+    /**
+     * Creates a new UDPInfo instance.
+     * @param {Partial<UDPInfo>} [$$source = {}] - The source object to create the UDPInfo.
+     */
+    constructor($$source = {}) {
+        if (!("running" in $$source)) {
+            /**
+             * 是否运行中
+             * @member
+             * @type {boolean}
+             */
+            this["running"] = false;
+        }
+        if (!("port" in $$source)) {
+            /**
+             * 监听端口
+             * @member
+             * @type {number}
+             */
+            this["port"] = 0;
+        }
+        if (!("addr" in $$source)) {
+            /**
+             * 监听地址 udp://0.0.0.0:port
+             * @member
+             * @type {string}
+             */
+            this["addr"] = "";
+        }
+        if (!("startedAt" in $$source)) {
+            /**
+             * 启动时间
+             * @member
+             * @type {string}
+             */
+            this["startedAt"] = "";
+        }
+        if (!("error" in $$source)) {
+            /**
+             * 最近一次错误
+             * @member
+             * @type {string}
+             */
+            this["error"] = "";
+        }
+        if (!("rxCount" in $$source)) {
+            /**
+             * 累计接收数据包数
+             * @member
+             * @type {number}
+             */
+            this["rxCount"] = 0;
+        }
+        if (!("txCount" in $$source)) {
+            /**
+             * 累计发送(回发/手动)数据包数
+             * @member
+             * @type {number}
+             */
+            this["txCount"] = 0;
+        }
+
+        Object.assign(this, $$source);
+    }
+
+    /**
+     * Creates a new UDPInfo instance from a string or object.
+     * @param {any} [$$source = {}]
+     * @returns {UDPInfo}
+     */
+    static createFrom($$source = {}) {
+        let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
+        return new UDPInfo(/** @type {Partial<UDPInfo>} */($$parsedSource));
+    }
+}
+
 /**
  * WebServiceInfo 描述一次 Web 服务运行实例的状态,供前端展示。
  */
@@ -2510,20 +2650,22 @@ const $$createType5 = CustomTab.createFrom;
 const $$createType6 = $Create.Array($$createType5);
 const $$createType7 = LocalTool.createFrom;
 const $$createType8 = $Create.Array($$createType7);
-const $$createType9 = TickerConfig.createFrom;
-const $$createType10 = PoemConfig.createFrom;
-const $$createType11 = MouseAlertConfig.createFrom;
-const $$createType12 = LocalSendConfig.createFrom;
-const $$createType13 = CrocConfig.createFrom;
-const $$createType14 = YTDLPConfig.createFrom;
-const $$createType15 = MemosConfig.createFrom;
-const $$createType16 = BrightnessConfig.createFrom;
-const $$createType17 = BiliDynamicItem.createFrom;
-const $$createType18 = $Create.Array($$createType17);
-const $$createType19 = $Create.Map($Create.Any, $Create.Any);
-const $$createType20 = MinutePoint.createFrom;
-const $$createType21 = $Create.Array($$createType20);
-const $$createType22 = ReleaseItem.createFrom;
+const $$createType9 = ControlKeyConfig.createFrom;
+const $$createType10 = $Create.Array($$createType9);
+const $$createType11 = TickerConfig.createFrom;
+const $$createType12 = PoemConfig.createFrom;
+const $$createType13 = MouseAlertConfig.createFrom;
+const $$createType14 = LocalSendConfig.createFrom;
+const $$createType15 = CrocConfig.createFrom;
+const $$createType16 = YTDLPConfig.createFrom;
+const $$createType17 = MemosConfig.createFrom;
+const $$createType18 = BrightnessConfig.createFrom;
+const $$createType19 = BiliDynamicItem.createFrom;
+const $$createType20 = $Create.Array($$createType19);
+const $$createType21 = $Create.Map($Create.Any, $Create.Any);
+const $$createType22 = MinutePoint.createFrom;
 const $$createType23 = $Create.Array($$createType22);
-const $$createType24 = CommitItem.createFrom;
+const $$createType24 = ReleaseItem.createFrom;
 const $$createType25 = $Create.Array($$createType24);
+const $$createType26 = CommitItem.createFrom;
+const $$createType27 = $Create.Array($$createType26);

+ 71 - 0
frontend/bindings/TengTuToolbox/udpservice.js

@@ -0,0 +1,71 @@
+// @ts-check
+// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
+// This file is automatically generated. DO NOT EDIT
+
+/**
+ * UDPService 是 UDP 键值服务的 Wails 服务。
+ * @module
+ */
+
+// eslint-disable-next-line @typescript-eslint/ban-ts-comment
+// @ts-ignore: Unused imports
+import { Call as $Call, CancellablePromise as $CancellablePromise, Create as $Create } from "@wailsio/runtime";
+
+// eslint-disable-next-line @typescript-eslint/ban-ts-comment
+// @ts-ignore: Unused imports
+import * as $models from "./models.js";
+
+/**
+ * SendUDP 手动发送文本到指定远端(addr 形如 ip:port)。
+ * @param {string} addr
+ * @param {string} text
+ * @returns {$CancellablePromise<$models.UDPInfo>}
+ */
+export function SendUDP(addr, text) {
+    return $Call.ByID(1977683411, addr, text).then(/** @type {($result: any) => any} */(($result) => {
+        return $$createType0($result);
+    }));
+}
+
+/**
+ * StartUDPServer 启动 UDP 键值服务器,监听 0.0.0.0:port。
+ * 若已运行则先停止旧实例,并清空键值存储。端口占用时返回错误。
+ * @param {number} port
+ * @returns {$CancellablePromise<$models.UDPInfo>}
+ */
+export function StartUDPServer(port) {
+    return $Call.ByID(1291615814, port).then(/** @type {($result: any) => any} */(($result) => {
+        return $$createType0($result);
+    }));
+}
+
+/**
+ * StopUDPServer 停止当前 UDP 键值服务(未运行则无副作用),并清空键值存储。
+ * @returns {$CancellablePromise<$models.UDPInfo>}
+ */
+export function StopUDPServer() {
+    return $Call.ByID(2179332070).then(/** @type {($result: any) => any} */(($result) => {
+        return $$createType0($result);
+    }));
+}
+
+/**
+ * UDPServerJSON 为前端提供一次调用获取完整状态的辅助(避免多次 IPC)。
+ * @returns {$CancellablePromise<string>}
+ */
+export function UDPServerJSON() {
+    return $Call.ByID(839381736);
+}
+
+/**
+ * UDPServerStatus 返回当前 UDP 键值服务状态。
+ * @returns {$CancellablePromise<$models.UDPInfo>}
+ */
+export function UDPServerStatus() {
+    return $Call.ByID(830505824).then(/** @type {($result: any) => any} */(($result) => {
+        return $$createType0($result);
+    }));
+}
+
+// Private type creation functions
+const $$createType0 = $models.UDPInfo.createFrom;

+ 67 - 1
frontend/index.html

@@ -27,6 +27,7 @@
             <button class="tab-btn" data-tab="record">记录</button>
             <button class="tab-btn" data-tab="tools">工具</button>
             <button class="tab-btn" data-tab="locals">本地</button>
+            <button class="tab-btn" data-tab="control">控制</button>
             <button class="tab-btn" data-tab="host">服务</button>
             <button class="tab-btn" data-tab="settings">设置</button>
             <!-- 更多 Tab:顺序设置中用 [] 包裹的项折叠到这里,悬停展开下拉菜单 -->
@@ -190,7 +191,33 @@
                     </div>
                 </div>
 
-                <!-- 工具 2:翻译——中文→英文 / 英文→中文,自动检测 -->
+                <!-- 工具 2:UDP 键值服务——启动 UDP 服务器,存储/查询键值 -->
+                <div class="tool-card is-collapsed" data-tool="udp">
+                    <div class="tool-card-head" role="button" tabindex="0" aria-expanded="false">
+                        <span class="tool-card-title"><span class="tool-arrow">▸</span><span class="dot"></span>UDP 键值服务</span>
+                        <span class="tool-status" id="udp-status"></span>
+                        <span class="tool-order-btns"><button class="tool-order-btn tool-up" type="button" title="上移">↑</button><button class="tool-order-btn tool-down" type="button" title="下移">↓</button></span>
+                    </div>
+                    <div class="tool-card-body">
+                        <p class="tool-desc">启动 UDP 服务器,任意客户机可连。发送 <code>键=值</code> 存储;发送键名查询,服务端回发已存值(不存在则空)。</p>
+                        <div class="tool-row">
+                            <input class="input" id="udp-port" type="number" min="1" max="65535" placeholder="9000" title="监听端口">
+                            <button class="btn-ghost" id="udp-toggle">启动</button>
+                        </div>
+                        <div class="tool-row">
+                            <input class="input" id="udp-target" type="text" placeholder="目标地址 IP:端口">
+                            <input class="input" id="udp-msg" type="text" placeholder="键=值 或 键名">
+                            <button class="btn-primary" id="udp-send">发送</button>
+                        </div>
+                        <div class="tool-row tool-actions">
+                            <button class="btn-ghost" id="udp-clear">清空信息</button>
+                            <span class="tool-hint" id="udp-hint"></span>
+                        </div>
+                        <pre class="croc-log" id="udp-log" hidden></pre>
+                    </div>
+                </div>
+
+                <!-- 工具 3:翻译——中文→英文 / 英文→中文,自动检测 -->
                 <div class="tool-card is-collapsed" data-tool="translate">
                     <div class="tool-card-head" role="button" tabindex="0" aria-expanded="false">
                         <span class="tool-card-title"><span class="tool-arrow">▸</span><span class="dot"></span>翻译</span>
@@ -516,6 +543,27 @@
                 <div id="locals-list"></div>
             </div>
 
+            <!-- 控制:遥控小车,按键图标与命令可在 设置→控制 配置(命令非空时以 GET 请求,空则回退指令信箱) -->
+            <div class="tab-panel" id="tab-control">
+                <div class="control-wrap">
+                    <div class="control-pad">
+                        <div class="control-pad-grid">
+                            <button class="control-key" type="button" data-key="up" title="前进">↑</button>
+                            <button class="control-key" type="button" data-key="left" title="左转">←</button>
+                            <button class="control-key control-key-sleep" type="button" data-key="sleep" title="休眠">休眠</button>
+                            <button class="control-key" type="button" data-key="right" title="右转">→</button>
+                            <button class="control-key" type="button" data-key="down" title="后退">↓</button>
+                        </div>
+                        <!-- 设置中配置的额外按键(第 6 键起),方向键下方从左至右排列 -->
+                        <div class="control-extra" id="control-extra"></div>
+                    </div>
+                    <div class="control-info">
+                        <p class="control-hint" id="control-target">目标:检测中…</p>
+                        <p class="control-status" id="control-status">就绪</p>
+                    </div>
+                </div>
+            </div>
+
             <div class="tab-panel" id="tab-host">
                 <div class="host-cards">
                     <div class="card">
@@ -712,6 +760,24 @@
                         <textarea class="input textarea" id="local-tools" rows="4" placeholder="记事本|notepad|系统自带&#10;清理|D:\scripts\clean.bat|每日清理临时文件&#10;脚本|powershell D:\scripts\hello.ps1|PowerShell 示例&#10;帮助页|D:\docs\help.html|本地文档,自动起服务打开"></textarea>
                     </div>
 
+                    <!-- 控制页按键 -->
+                    <div class="setting-row setting-row-col" data-tab-group="control">
+                        <div class="setting-info">
+                            <div class="setting-title">控制页按键</div>
+                            <div class="setting-hint">每行一条,格式:图标|命令URL(命令可空,为空时回退到本机指令信箱模式)。前 5 行固定为 上/下/左/右/休眠;第 6 行起为额外按键,显示在方向键下方从左至右排列。点击按键将以 GET 请求命令 URL</div>
+                        </div>
+                        <textarea class="input textarea" id="control-keys" rows="5" placeholder="↑|http://192.168.1.5/api/xz/cmd/up&#10;↓|http://192.168.1.5/api/xz/cmd/down&#10;←|http://192.168.1.5/api/xz/cmd/left&#10;→|http://192.168.1.5/api/xz/cmd/right&#10;休眠|&#10;喇叭|http://192.168.1.5/api/xz/cmd/horn&#10;灯|http://192.168.1.5/api/xz/cmd/light"></textarea>
+                    </div>
+
+                    <!-- 控制页长按连发频率 -->
+                    <div class="setting-row" data-tab-group="control">
+                        <div class="setting-info">
+                            <div class="setting-title">长按连发频率</div>
+                            <div class="setting-hint">按键超过 3 秒后,按此频率每x秒连发一次;范围 0.0 - 10.0 秒,默认 1.0 秒</div>
+                        </div>
+                        <input class="input" id="control-repeat" type="number" step="0.1" min="0" max="10" placeholder="1.0">
+                    </div>
+
                     <!-- 股市代码 -->
                     <div class="setting-row" data-tab-group="stock">
                         <div class="setting-info">

+ 96 - 0
frontend/public/style.css

@@ -2391,6 +2391,102 @@ a.ver-muted:hover {
     opacity: 1;
 }
 
+/* ---------- 控制页:小车方向盘 ---------- */
+.control-wrap {
+    display: flex;
+    align-items: center;
+    gap: 28px;
+    flex-wrap: wrap;
+    padding: 18px;
+    border: 1px solid var(--glass-border);
+    border-radius: var(--radius);
+    background: var(--glass);
+}
+.control-pad {
+    display: flex;
+    flex-direction: column;
+    gap: 10px;
+    flex-shrink: 0;
+}
+/* 方向盘 3x3 网格:上 / 左 / 休眠 / 右 / 下 */
+.control-pad-grid {
+    display: grid;
+    grid-template-columns: repeat(3, 64px);
+    grid-template-rows: repeat(3, 64px);
+    gap: 8px;
+}
+/* 额外按键行:设置中第 6 键起,方向键下方从左至右排列 */
+.control-extra {
+    display: flex;
+    flex-wrap: wrap;
+    gap: 8px;
+    justify-content: center;
+    max-width: 208px; /* 3 列 64px + 2*8px 间隙 = 208px,与方向盘等宽 */
+}
+.control-key-extra {
+    width: 64px;
+    height: 48px;
+    font-size: calc(15px + var(--font-delta));
+}
+.control-key {
+    display: flex;
+    align-items: center;
+    justify-content: center;
+    border: 1px solid var(--glass-border);
+    border-radius: 12px;
+    background: var(--glass-strong);
+    color: var(--ink);
+    font-size: 22px;
+    font-weight: 600;
+    cursor: pointer;
+    user-select: none;
+    transition: color 0.15s ease, border-color 0.15s ease, transform 0.15s ease, background 0.15s ease;
+}
+.control-key:hover {
+    color: var(--accent);
+    border-color: var(--accent);
+    transform: translateY(-1px);
+}
+.control-key:active,
+.control-key.is-holding {
+    color: #fff;
+    background: var(--grad);
+    border-color: transparent;
+    transform: translateY(0);
+}
+/* 长按状态:渐变底 + 呼吸光圈,明确提示正处于连发 */
+.control-key.is-holding {
+    animation: control-hold-pulse 1s ease-in-out infinite;
+}
+@keyframes control-hold-pulse {
+    0%, 100% { box-shadow: 0 0 0 0 rgba(255, 61, 90, 0.45); }
+    50%      { box-shadow: 0 0 0 8px rgba(255, 61, 90, 0); }
+}
+/* 方向盘布局:上 / 左 / 休眠 / 右 / 下 */
+.control-key[data-key="up"] { grid-area: 1 / 2; }
+.control-key[data-key="left"] { grid-area: 2 / 1; }
+.control-key-sleep { grid-area: 2 / 2; font-size: calc(13px + var(--font-delta)); }
+.control-key[data-key="right"] { grid-area: 2 / 3; }
+.control-key[data-key="down"] { grid-area: 3 / 2; }
+.control-info {
+    flex: 1;
+    min-width: 240px;
+}
+.control-title {
+    font-weight: 600;
+    margin-bottom: 6px;
+}
+.control-hint {
+    color: var(--muted);
+    font-size: calc(13px + var(--font-delta));
+    line-height: 1.7;
+}
+.control-status {
+    margin-top: 10px;
+    font-size: calc(13px + var(--font-delta));
+    color: var(--accent);
+}
+
 /* 卡片标题行内嵌操作按钮(如 API 服务右上角的「停止/启动」) */
 .card-title-row {
     display: flex;

+ 409 - 7
frontend/src/main.js

@@ -6,6 +6,7 @@ import {MemosService} from "../bindings/TengTuToolbox/index.js"; // Memos 服务
 import {BrightnessService} from "../bindings/TengTuToolbox/index.js"; // 显示器亮度服务(DDC/CI + Gamma 兜底)
 import {YTDLPService} from "../bindings/TengTuToolbox/index.js"; // yt-dlp 服务(视频下载)
 import {LocalService} from "../bindings/TengTuToolbox/index.js"; // 本地资源启动服务(「本地」页)
+import {UDPService} from "../bindings/TengTuToolbox/index.js"; // UDP 键值服务(工具页 UDP 服务器)
 import {getCalendarInfo} from "./lunar.js"; // 农历与节日计算
 
 WML.Enable(); // 为带 data-wml-openURL 属性的链接绑定打开行为(动态内容渲染后需调 WML.Reload())
@@ -36,7 +37,7 @@ const FALLBACK_SETTINGS = {
     alwaysOnTop: false,
     startCompact: false, // 启动时自动收拢为圆点
     hotkey: 'CmdOrCtrl+Shift+G',
-    tabOrder: ['links', 'news', 'github', 'stock', 'todo', 'record', 'tools', 'locals', 'host', 'settings'],
+    tabOrder: ['links', 'news', 'github', 'stock', 'todo', 'record', 'tools', 'locals', 'control', 'host', 'settings'],
     stockCodes: ['sh000001', 'sh600519', 'sz000001'],
     links: [{name: '煎蛋', url: 'https://jandan.net/'}],
     newsKeywords: '',
@@ -59,7 +60,7 @@ const FALLBACK_SETTINGS = {
     newsCount: 30,                // 新闻页显示条数
     githubRefreshMinutes: 120,    // Github 自动刷新间隔(分钟)
     fontDelta: 0,                 // 全局字号偏移(px),+-3,默认 0(基准字号已含 +2)
-    toolOrder: ['websvc', 'translate', 'qrcode', 'ntfy', 'chat', 'poem', 'screenshot', 'shutdown', 'md5', 'sha256', 'led', 'reminder', 'localsend', 'croc', 'ytdlp', 'memos', 'brightness'], // 工具页卡片默认顺序
+    toolOrder: ['websvc', 'udp', 'translate', 'qrcode', 'ntfy', 'chat', 'poem', 'screenshot', 'shutdown', 'md5', 'sha256', 'led', 'reminder', 'localsend', 'croc', 'ytdlp', 'memos', 'brightness'], // 工具页卡片默认顺序
     croc: {password: '', dir: ''}, // Croc 传送:发送/接收共用密码、接收保存目录
     ytdlp: {dir: '', mp3Quality: '0'}, // 视频下载:yt-dlp 下载保存目录 + mp3 转换质量
     memos: {url: 'https://m.scwy.net', token: ''}, // Memos 速记:实例地址/访问令牌
@@ -68,6 +69,15 @@ const FALLBACK_SETTINGS = {
     newsTicker: {enabled: false, width: 1400, fontSize: 14, color: '#3ddc84', speed: 60, transparent: true, x: -1, y: -1},
     poem: {enabled: false, color: '#c98a3a', fontSize: 16, tts: false, speed: 18},
     mouseAlert: {fontSize: 20, width: 200, speed: 33, color: '#ffffff', outlineColor: '#000000', outlineWidth: 2, duration: 8},
+    // 控制页方向盘 5 键(顺序 上/下/左/右/休眠):图标 + 命令URL;命令空 = 回退旧指令信箱模式
+    controlKeys: [
+        {icon: '↑', cmd: ''},
+        {icon: '↓', cmd: ''},
+        {icon: '←', cmd: ''},
+        {icon: '→', cmd: ''},
+        {icon: '休眠', cmd: ''},
+    ],
+    controlRepeatSecs: 1.0, // 长按连发频率(秒),默认 1 秒
 };
 
 // HTML 转义:外部来源的新闻 / 提交标题插入页面前先转义,防止注入
@@ -94,7 +104,7 @@ const poemReadBtn = document.getElementById('poem-read');          // 朗读按
 // Tab 名称映射:id -> 显示名(用于顺序编辑与 footer 注释)
 const TAB_NAMES = {
     links: '网址', news: '新闻', github: 'Github', stock: '股市',
-    todo: '待办', record: '记录', tools: '工具', locals: '本地', host: '服务', settings: '设置',
+    todo: '待办', record: '记录', tools: '工具', locals: '本地', control: '控制', host: '服务', settings: '设置',
 };
 
 // Tab 注释映射:id -> 在 footer 显示的说明文字(切换时显示,不占页面空间)
@@ -107,6 +117,7 @@ const TAB_DESCS = {
     record: '每行一条「姓名|名称|值」,保存到 SQLite 数据库;姓名/名称输入自动补全历史值,选择姓名与名称后按值绘柱状图。',
     tools: '开发/运维辅助工具:Web 服务(选目录开启浏览)、翻译(中英互译)、二维码生成。',
     locals: '本机快捷启动:设置中配置的本地程序/脚本,点击卡片「启动」运行。',
+    control: '遥控小车:上 / 下 / 左 / 右 / 休眠,指令通过 POST /api/xz/cmd 下发。',
     host: '内置 API 服务状态、电源命令与 Gin 日志。',
     settings: '修改后点击保存立即生效,焦点离开时自动保存。',
 };
@@ -519,7 +530,7 @@ function applyTabOrder(order) {
 // 工具页卡片排序:按设置中的 toolOrder 重排 DOM 顺序,并刷新上移/下移按钮禁用状态。
 // 未在 toolOrder 中的工具(如新增工具)追加到末尾,保证全部工具都能显示。
 const DEFAULT_TOOL_ORDER = [
-    'websvc', 'translate', 'qrcode', 'ntfy', 'chat', 'poem',
+    'websvc', 'udp', 'translate', 'qrcode', 'ntfy', 'chat', 'poem',
     'screenshot', 'shutdown', 'md5', 'sha256', 'led', 'reminder', 'localsend', 'croc', 'ytdlp',
 ];
 
@@ -627,6 +638,7 @@ function switchTab(tabId) {
         if (tabId === 'record') loadRecords();
         if (tabId === 'host') loadHostPanel();
         if (tabId === 'tools') loadToolsPanel();
+        if (tabId === 'control') refreshControlTarget();
     } else if (tabId === 'record') {
         // 记录依赖「记录数据库路径」设置:路径可能后配置或修改,切回时必须刷新状态。
         // 有未保存修改时保留列表,仅更新路径说明,避免覆盖用户正在编辑的内容。
@@ -702,6 +714,8 @@ const browserPickBtn = document.getElementById('browser-pick');     // 选择浏
 const browserClearBtn = document.getElementById('browser-clear');   // 清除浏览器按钮
 const customTabsText = document.getElementById('custom-tabs');      // 自定义 Tab(每行 名称|地址|备注)
 const localToolsText = document.getElementById('local-tools');      // 本地资源/工具(每行 标题|命令|说明)
+const controlKeysText = document.getElementById('control-keys');    // 控制页按键(每行 图标|命令URL)
+const controlRepeatInput = document.getElementById('control-repeat'); // 控制页长按连发频率(秒)
 const saveButton = document.getElementById('save-settings');        // 保存按钮
 const saveStatus = document.getElementById('save-status');          // 保存状态提示
 const stockList = document.getElementById('stock-list');            // 股市列表容器
@@ -830,6 +844,15 @@ async function syncForm(settings) {
     customTabsText.value = (settings.customTabs || []).map(t => `${t.name}|${t.url}${t.desc ? '|' + t.desc : ''}`).join('\n');
     localToolsText.value = (settings.localTools || []).map(t => `${t.title}|${t.cmd}${t.desc ? '|' + t.desc : ''}`).join('\n');
     renderLocals(settings.localTools || []); // 「本地」页卡片按最新配置重建
+    // 控制页按键:回填设置表单并刷新方向盘按钮
+    const cKeys = settings.controlKeys || FALLBACK_SETTINGS.controlKeys;
+    controlKeysText.value = cKeys.map(k => `${k.icon || ''}|${k.cmd || ''}`).join('\n');
+    applyControlKeys(cKeys);
+    // 长按连发频率:回填(0.0-10.0 秒)
+    if (controlRepeatInput) {
+        const v = settings.controlRepeatSecs;
+        controlRepeatInput.value = (typeof v === 'number' && !isNaN(v) && v >= 0 && v <= 10) ? v : 1.0;
+    }
     apiAddrInput.value = settings.apiAddr;
     if (serviceAddrInput) serviceAddrInput.value = settings.serviceAddr || FALLBACK_SETTINGS.serviceAddr;
     apiAutoStartToggle.checked = settings.apiAutoStart !== false; // 默认开启(兼容旧配置无该字段)
@@ -1087,6 +1110,7 @@ function collectForm() {
             if (key === 'githubRepos') return `${item.url}|${item.desc}|${item.version || ''}`;
             if (key === 'customTabs') return `${item.name}|${item.url}${item.desc ? '|' + item.desc : ''}`;
             if (key === 'localTools') return `${item.title}|${item.cmd}${item.desc ? '|' + item.desc : ''}`;
+            if (key === 'controlKeys') return `${item.icon || ''}|${item.cmd || ''}`;
             return '';
         }).join('\n');
         return '';
@@ -1119,6 +1143,26 @@ function collectForm() {
         githubRepos: parsePipeLines3(fallbackArr(githubReposText, 'githubRepos'), 'url', 'desc', 'version').filter(r => r.url),
         customTabs: parsePipeLines3(fallbackArr(customTabsText, 'customTabs'), 'name', 'url', 'desc').filter(t => t.name && t.url),
         localTools: parsePipeLines3(fallbackArr(localToolsText, 'localTools'), 'title', 'cmd', 'desc').filter(t => t.title && t.cmd),
+        // 控制页按键:前 5 键固定(顺序 上/下/左/右/休眠),第 6 键起为额外按键;
+        // 固定键图标空回填默认、命令可空;额外键图标空 = 跳过该行,命令可空
+        controlKeys: (() => {
+            const def = FALLBACK_SETTINGS.controlKeys;
+            const parsed = parsePipeLines(fallbackArr(controlKeysText, 'controlKeys'), 'icon', 'cmd');
+            const fixed = def.map((d, i) => ({
+                icon: (parsed[i]?.icon || d.icon).trim(),
+                cmd: (parsed[i]?.cmd || '').trim(),
+            }));
+            const extras = parsed.slice(def.length).map(p => ({
+                icon: (p.icon || '').trim(),
+                cmd: (p.cmd || '').trim(),
+            }));
+            return [...fixed, ...extras];
+        })(),
+        // 长按连发频率:0.0-10.0 秒,非法/越界回退默认 1.0
+        controlRepeatSecs: (() => {
+            const v = parseFloat(controlRepeatInput?.value);
+            return (isNaN(v) || v < 0 || v > 10) ? 1.0 : v;
+        })(),
         apiAddr: apiAddrInput.value.trim(),
         serviceAddr: serviceAddrInput?.value.trim() || FALLBACK_SETTINGS.serviceAddr, // 服务模式 API 地址
         apiAutoStart: apiAutoStartToggle.checked,
@@ -4108,6 +4152,231 @@ async function toggleAPIService() {
 
 apiToggleBtn.addEventListener('click', toggleAPIService);
 
+// ------------------------------------------------------------------------
+// 控制页:遥控小车(上 / 下 / 左 / 右 / 休眠 → POST /api/xz/cmd)
+// ------------------------------------------------------------------------
+const controlStatusEl = document.getElementById('control-status'); // 发送结果
+const controlTargetEl = document.getElementById('control-target'); // 当前指令目标地址
+
+// 控制页方向盘固定 5 键顺序(对应设置里的 controlKeys 数组索引)
+const CONTROL_KEY_ORDER = ['up', 'down', 'left', 'right', 'sleep'];
+
+// 按 data-key 取该键配置 {icon, cmd};前 5 键按索引,额外键(extra-N,第 6 键起)按数组顺序
+function controlKeyFor(key) {
+    const def = FALLBACK_SETTINGS.controlKeys;
+    const list = currentSettings?.controlKeys || def;
+    let idx = CONTROL_KEY_ORDER.indexOf(key);
+    if (idx < 0 && /^extra-\d+$/.test(key)) {
+        idx = CONTROL_KEY_ORDER.length + parseInt(key.slice(6), 10); // 额外键:数组第 6 键起
+    }
+    const cfg = list[idx] || def[idx] || {};
+    return { icon: cfg.icon || def[idx]?.icon || key, cmd: (cfg.cmd || '').trim() };
+}
+
+// 用配置刷新方向盘按钮的文字与标题,并重建额外按键行(第 6 键起,方向键下方从左至右)
+function applyControlKeys(keys) {
+    const list = keys || currentSettings?.controlKeys || FALLBACK_SETTINGS.controlKeys;
+    // 固定 5 键:更新文字与标题
+    document.querySelectorAll('#tab-control .control-pad-grid .control-key').forEach(btn => {
+        const idx = CONTROL_KEY_ORDER.indexOf(btn.dataset.key);
+        const cfg = list[idx] || {};
+        if (cfg.icon) btn.textContent = cfg.icon;
+        btn.title = `${cfg.icon || btn.dataset.key}${cfg.cmd ? '(' + cfg.cmd + ')' : ''}`;
+    });
+    // 额外按键:重建 #control-extra 子元素(第 6 键起,图标空的行跳过)
+    const extraEl = document.getElementById('control-extra');
+    if (!extraEl) return;
+    extraEl.innerHTML = '';
+    const extraKeys = list.slice(CONTROL_KEY_ORDER.length); // 第 6 键起
+    extraKeys.forEach((cfg, i) => {
+        const icon = (cfg.icon || '').trim();
+        if (!icon) return; // 图标空的行不生成按钮
+        const btn = document.createElement('button');
+        btn.type = 'button';
+        btn.className = 'control-key control-key-extra';
+        btn.dataset.key = `extra-${i}`;
+        btn.dataset.cmd = cfg.cmd || '';
+        btn.textContent = icon;
+        btn.title = `${icon}${cfg.cmd ? '(' + cfg.cmd + ')' : ''}`;
+        bindControlKeyEvents(btn);
+        extraEl.appendChild(btn);
+    });
+}
+
+// 把监听地址转成可访问地址:0.0.0.0 不能直连,统一换成本机回环
+function normalizeHttpAddr(addr) {
+    return String(addr || '').trim().replace(/^0\.0\.0\.0(?=:)/, '127.0.0.1');
+}
+
+// 候选目标:优先服务模式(小车从服务读取指令),其后界面 API(直连也可用)
+async function controlCandidates() {
+    const list = [];
+    try {
+        const st = await SettingsService.GetServiceModeStatus();
+        if (st?.addr) list.push(st.addr);
+    } catch (err) { /* 浏览器预览模式无后端,忽略 */ }
+    list.push(currentSettings?.apiAddr || FALLBACK_SETTINGS.apiAddr);
+    return [...new Set(list.map(normalizeHttpAddr).filter(Boolean))];
+}
+
+async function refreshControlTarget() {
+    if (!controlTargetEl) return;
+    const list = await controlCandidates();
+    controlTargetEl.textContent = list.length
+        ? `目标:http://${list[0]}/api/xz/cmd${list.length > 1 ? '(失败时自动改用界面 API)' : ''}`
+        : '目标:未配置 API 地址';
+}
+
+let controlSending = false; // 上一次指令还在发送中(长按连发时避免堆积)
+
+// 旧指令信箱模式:POST /api/xz/cmd(指令值为 key:up/down/left/right/sleep)
+async function legacySendCmd(key) {
+    const candidates = await controlCandidates();
+    let lastErr = null;
+    for (const addr of candidates) {
+        try {
+            const resp = await fetch(`http://${addr}/api/xz/cmd`, {
+                method: 'POST',
+                headers: { 'Content-Type': 'application/json' },
+                body: JSON.stringify({ cmd: key }),
+            });
+            if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
+            if (controlTargetEl) controlTargetEl.textContent = `目标:http://${addr}/api/xz/cmd`;
+            return { ok: true, msg: `已下发 ${key}` };
+        } catch (err) {
+            lastErr = err; // 当前地址不可用,尝试下一个
+        }
+    }
+    return { ok: false, msg: `发送失败:${lastErr?.message || lastErr}` };
+}
+
+// 下发控制指令:key = up/down/left/right/sleep。命令非空 → 直接 GET 该 URL(fire-and-forget);空 → 回退指令信箱
+async function sendControlCommand(key) {
+    if (controlSending) return; // 本机请求很快,上一发未完成时直接跳过这次
+    controlSending = true;
+    try {
+        const cfg = controlKeyFor(key);
+        if (cfg.cmd) {
+            // 命令非空:直接以 GET 请求配置的完整 URL,不解析响应体(避免 CORS 拦截报错)
+            try {
+                await fetch(cfg.cmd, { method: 'GET', mode: 'no-cors' });
+                if (controlStatusEl) controlStatusEl.textContent = `已发送 ${cfg.icon}(${new Date().toLocaleTimeString('zh-CN')})`;
+            } catch (err) {
+                if (controlStatusEl) controlStatusEl.textContent = `发送失败:${err?.message || err}`;
+            }
+            return;
+        }
+        // 命令为空:固定 5 键回退旧指令信箱模式;额外键无指令信箱语义,提示未配置
+        if (/^extra-/.test(key)) {
+            if (controlStatusEl) controlStatusEl.textContent = `${cfg.icon}:未配置命令(设置 → 控制)`;
+            return;
+        }
+        const r = await legacySendCmd(key);
+        if (controlStatusEl) controlStatusEl.textContent = r.ok
+            ? `${r.msg}(${new Date().toLocaleTimeString('zh-CN')})`
+            : r.msg;
+    } finally {
+        controlSending = false;
+    }
+}
+
+// 长按进入连发:按住某方向键超过 3 秒不释放 → 按键变色并每 1 秒连发一次;
+// 松手不停止;点击本界面任意按键退出长按,或其它按键长按超 3 秒接管为新的长按
+const CONTROL_HOLD_DELAY = 3000; // 判定长按的时长(毫秒,固定)
+let controlHoldTimer = null;      // 连发定时器
+let controlHoldBtn = null;        // 当前处于长按状态的按键
+let controlPressTimer = null;     // 3 秒判定定时器
+let controlPressBtn = null;       // 正在按住的按键
+
+// 长按连发间隔(毫秒):取当前设置的 controlRepeatSecs(0.0-10.0 秒,默认 1.0)
+function controlRepeatMs() {
+    const s = currentSettings?.controlRepeatSecs;
+    const v = (typeof s === 'number' && !isNaN(s) && s >= 0 && s <= 10) ? s : 1.0;
+    return Math.round(v * 1000);
+}
+
+function isControlHolding() {
+    return !!controlHoldBtn;
+}
+
+// 进入长按状态:按键变色 + 按设定频率连发;松手不停止,需点击任意按键退出(或其它键长按接管)
+function startControlHold(btn) {
+    controlHoldBtn = btn;
+    btn.classList.add('is-holding');
+    const key = btn.dataset.key;
+    const cfg = controlKeyFor(key);
+    if (controlStatusEl) controlStatusEl.textContent = `长按中:${cfg.icon}(点击任意按键停止)`;
+    controlHoldTimer = setInterval(() => sendControlCommand(key), controlRepeatMs());
+}
+
+// 退出长按状态并恢复按键颜色
+function stopControlHold() {
+    if (controlHoldTimer) {
+        clearInterval(controlHoldTimer);
+        controlHoldTimer = null;
+    }
+    if (controlHoldBtn) {
+        controlHoldBtn.classList.remove('is-holding');
+        controlHoldBtn = null;
+        if (controlStatusEl) controlStatusEl.textContent = '已停止长按';
+    }
+}
+
+// 取消「按住计时」(还未满 3 秒就松手,或移出按键)
+function cancelControlPressTimer() {
+    if (controlPressTimer) {
+        clearTimeout(controlPressTimer);
+        controlPressTimer = null;
+    }
+    controlPressBtn = null;
+}
+
+// 给单个方向/额外按键绑定 pointer 事件:单击下发一次;按住超 3 秒进入长按连发
+// 休眠键走 click(单次指令);长按状态下点击任意按键先退出长按
+function bindControlKeyEvents(btn) {
+    if (btn.dataset.key === 'sleep') {
+        // 休眠为单次指令;长按状态下点击则只取消长按
+        btn.addEventListener('click', () => {
+            if (isControlHolding()) {
+                stopControlHold();
+                return;
+            }
+            sendControlCommand('sleep');
+        });
+        return;
+    }
+    // 方向/额外键:pointer 事件覆盖鼠标与触屏
+    btn.addEventListener('pointerdown', (e) => {
+        e.preventDefault();
+        // 长按状态下按下其它键:先退出旧键长按;若继续按住满 3 秒则接管为新长按
+        if (isControlHolding()) {
+            stopControlHold();
+        }
+        cancelControlPressTimer();
+        sendControlCommand(btn.dataset.key); // 单击立即下发一次
+        controlPressBtn = btn;
+        controlPressTimer = setTimeout(() => {
+            controlPressTimer = null;
+            if (controlPressBtn === btn) {
+                controlPressBtn = null;
+                startControlHold(btn); // 超时未松开 → 进入长按连发
+            }
+        }, CONTROL_HOLD_DELAY);
+    });
+    // 未满 3 秒就松开/移出:取消判定(长按状态不受影响,需点击按键停止)
+    btn.addEventListener('pointerup', cancelControlPressTimer);
+    btn.addEventListener('pointercancel', cancelControlPressTimer);
+    btn.addEventListener('lostpointercapture', cancelControlPressTimer);
+    btn.addEventListener('contextmenu', (e) => e.preventDefault()); // 长按不弹出右键菜单
+}
+
+// 绑定方向盘固定 5 键 + 额外按键事件
+document.querySelectorAll('#tab-control .control-pad-grid .control-key').forEach(bindControlKeyEvents);
+window.addEventListener('blur', () => {
+    cancelControlPressTimer(); // 窗口失焦:取消未完成的 3 秒判定
+    stopControlHold();         // 并停止连发,避免小车失控
+});
+
 // 刷新服务模式状态:Windows 服务 / 界面进程兜底 / 端口被占用 / 未运行
 let serviceModeManaged = false; // 当前是否由 Windows 服务托管(决定乒乓按钮是「启动」还是「停止」)
 
@@ -4390,10 +4659,11 @@ async function loadToolsPanel() {
             websvcDir = info.dir;
             websvcDirInput.value = info.dir;
             renderWebSvc(info);
-            return;
+        } else {
+            renderWebSvc(null);
         }
-    } catch (err) { /* 预览模式忽略 */ }
-    renderWebSvc(null);
+    } catch (err) { /* 预览模式忽略 */ renderWebSvc(null); }
+    await loadUDPPanel(); // 恢复 UDP 键值服务状态(无论 websvc 是否运行都执行)
 }
 
 // 选择目录
@@ -4450,6 +4720,138 @@ websvcToggleBtn.addEventListener('click', async () => {
     }
 });
 
+// ------------------------------------------------------------------------
+// 工具页:UDP 键值服务——启动 UDP 服务器,存储/查询键值,来往数据显示在信息框
+// ------------------------------------------------------------------------
+const udpStatusEl = document.getElementById('udp-status');    // 运行状态徽标
+const udpPortInput = document.getElementById('udp-port');     // 监听端口输入
+const udpToggleBtn = document.getElementById('udp-toggle');   // 启动/停止乒乓按钮
+const udpTargetInput = document.getElementById('udp-target'); // 目标地址 IP:端口
+const udpMsgInput = document.getElementById('udp-msg');       // 要发送的内容
+const udpSendBtn = document.getElementById('udp-send');       // 发送按钮
+const udpClearBtn = document.getElementById('udp-clear');     // 清空信息按钮
+const udpHintEl = document.getElementById('udp-hint');        // 提示文字
+const udpLogEl = document.getElementById('udp-log');          // 信息框
+let udpRunning = false; // 当前 UDP 服务是否运行(乒乓按钮状态)
+
+// 追加一行到 UDP 信息框
+function udpAppendLog(kind, line) {
+    if (!udpLogEl) return;
+    udpLogEl.hidden = false;
+    const prefix = kind === 'send' ? '[发送] ' : kind === 'recv' ? '[接收] ' : '[信息] ';
+    udpLogEl.textContent += prefix + line + '\n';
+    udpLogEl.scrollTop = udpLogEl.scrollHeight; // 滚动到最新一行
+}
+
+// 订阅 UDP 日志事件(后端 udpservice.go 通过 app.Event.Emit 推送)
+if (typeof Events?.On === 'function') {
+    Events.On('udp:log', (e) => {
+        const d = e?.data || {};
+        udpAppendLog(d.kind, d.line || '');
+    });
+}
+
+// 渲染 UDP 服务状态(运行中 / 未运行)
+function renderUDP(info) {
+    if (info && info.running) {
+        udpRunning = true;
+        udpStatusEl.textContent = `● 运行中 ${info.addr || ''}`;
+        udpStatusEl.className = 'tool-status is-on';
+        udpHintEl.textContent = `接收 ${info.rxCount || 0} 包|发送 ${info.txCount || 0} 包`;
+        udpPortInput.disabled = true; // 运行中禁用端口输入
+    } else {
+        udpRunning = false;
+        udpStatusEl.textContent = '未运行';
+        udpStatusEl.className = 'tool-status';
+        udpHintEl.textContent = '';
+        udpPortInput.disabled = false;
+    }
+    // 乒乓按钮:运行中显示「停止」(红),未运行显示「启动」(主色)
+    udpToggleBtn.textContent = udpRunning ? '停止' : '启动';
+    udpToggleBtn.classList.toggle('btn-danger', udpRunning);
+    udpToggleBtn.classList.toggle('btn-primary', !udpRunning);
+    udpToggleBtn.disabled = false;
+}
+
+// 进入工具页:恢复上次端口与运行状态
+async function loadUDPPanel() {
+    const saved = localStorage.getItem('tengtu-udp-port');
+    if (saved && udpPortInput && !udpPortInput.value) udpPortInput.value = saved;
+    if (!udpPortInput?.value) udpPortInput.value = '9000'; // 默认端口
+    try {
+        const info = await UDPService.UDPServerStatus();
+        renderUDP(info);
+    } catch (err) { /* 预览模式忽略 */ renderUDP(null); }
+}
+
+// 启动/停止乒乓按钮
+if (udpToggleBtn) udpToggleBtn.addEventListener('click', async () => {
+    if (udpRunning) {
+        // 运行中 → 停止
+        udpToggleBtn.classList.add('loading');
+        udpToggleBtn.disabled = true;
+        try {
+            const info = await UDPService.StopUDPServer();
+            renderUDP(info);
+        } catch (err) {
+            console.warn('停止 UDP 服务失败:', err);
+            udpHintEl.textContent = '停止失败:' + (err?.message || String(err));
+            udpToggleBtn.disabled = false;
+        } finally {
+            udpToggleBtn.classList.remove('loading');
+        }
+    } else {
+        // 未运行 → 启动
+        const port = parseInt(udpPortInput.value, 10);
+        if (isNaN(port) || port < 1 || port > 65535) {
+            udpHintEl.textContent = '端口无效:请输入 1-65535';
+            return;
+        }
+        udpToggleBtn.classList.add('loading');
+        udpToggleBtn.disabled = true;
+        try {
+            const info = await UDPService.StartUDPServer(port);
+            localStorage.setItem('tengtu-udp-port', String(port));
+            renderUDP(info);
+        } catch (err) {
+            console.warn('启动 UDP 服务失败:', err);
+            udpHintEl.textContent = '启动失败:' + (err?.message || String(err));
+            udpToggleBtn.disabled = false;
+        } finally {
+            udpToggleBtn.classList.remove('loading');
+        }
+    }
+});
+
+// 手动发送键值/查询到指定远端
+if (udpSendBtn) udpSendBtn.addEventListener('click', async () => {
+    const target = udpTargetInput.value.trim();
+    const msg = udpMsgInput.value;
+    if (!target) {
+        udpHintEl.textContent = '请先填写目标地址 IP:端口';
+        return;
+    }
+    udpSendBtn.disabled = true;
+    try {
+        const info = await UDPService.SendUDP(target, msg);
+        udpHintEl.textContent = `已发送|接收 ${info.rxCount || 0} 包|发送 ${info.txCount || 0} 包`;
+        udpMsgInput.value = ''; // 发送后清空内容
+    } catch (err) {
+        console.warn('发送失败:', err);
+        udpHintEl.textContent = '发送失败:' + (err?.message || String(err));
+    } finally {
+        udpSendBtn.disabled = false;
+    }
+});
+
+// 清空信息框
+if (udpClearBtn) udpClearBtn.addEventListener('click', () => {
+    if (udpLogEl) {
+        udpLogEl.textContent = '';
+        udpLogEl.hidden = true;
+    }
+});
+
 // ------------------------------------------------------------------------
 // 翻译工具:中文→英文 / 英文→中文,自动检测方向(MyMemory 免费接口)
 // ------------------------------------------------------------------------

+ 1 - 0
main.go

@@ -150,6 +150,7 @@ func main() {
 			application.NewService(NewMemosService()),      // 注册 MemosService,供 Memos 速记工具调用 REST API
 			application.NewService(NewBrightnessService()), // 注册 BrightnessService,供显示器亮度工具调光
 			application.NewService(&LocalService{}),        // 注册 LocalService,供「本地」页启动配置的程序/脚本
+			application.NewService(NewUDPService()),        // 注册 UDPService,供工具页 UDP 键值服务器启停/发送
 			application.NewService(dockService),            // 注册 dockService,前端可通过 bindings 直接调用其 SetBadge 方法
 		},
 		Assets: application.AssetOptions{

+ 46 - 3
service_mode.go

@@ -165,6 +165,16 @@ func proxyToUI(c *gin.Context) {
 	_, _ = io.Copy(c.Writer, resp.Body)
 }
 
+// forwardToUI 服务模式下若界面已登记在线,把当前请求转发给界面并返回 true;
+// 界面离线返回 false,调用方继续本地兜底处理(电源/指令接口在无界面时仍可用)。
+func forwardToUI(c *gin.Context) bool {
+	if !uiPeerOnline() {
+		return false
+	}
+	proxyToUI(c)
+	return true
+}
+
 // ----------------------------------------------------------------------------
 // 指令信箱:POST /api/xz/cmd 下发指令(left / right / up / down,支持任意文本),
 // GET /api/xz/cmd 取走最近一条指令(读取后清除)。服务模式与界面兜底共用同一份
@@ -183,6 +193,9 @@ const xzCmdMaxLen = 200
 // handleXZCmdPost 下发指令:body {"cmd":"left"},也兼容 ?cmd=left 形式;除
 // left/right/up/down 外也接受其他自定义指令,仅要求非空。
 func handleXZCmdPost(c *gin.Context) {
+	if forwardToUI(c) {
+		return // 服务模式 + 界面在线 → 转发给界面(指令信箱与界面共享)
+	}
 	var req struct {
 		Cmd string `json:"cmd"`
 	}
@@ -211,6 +224,9 @@ func handleXZCmdPost(c *gin.Context) {
 // handleXZCmdGet 以纯文本返回最新一条指令并将其清除(消费式读取);
 // 没有待取指令时返回空字符串。
 func handleXZCmdGet(c *gin.Context) {
+	if forwardToUI(c) {
+		return // 服务模式 + 界面在线 → 转发给界面(指令信箱与界面共享)
+	}
 	xzCmdMu.Lock()
 	cmd := xzCmdLast
 	xzCmdLast = "" // 取走即清除,避免重复执行同一条指令
@@ -219,6 +235,32 @@ func handleXZCmdGet(c *gin.Context) {
 	c.String(http.StatusOK, cmd)
 }
 
+// handleXZCmdPathPost 通过路径参数下发指令:GET /api/xz/cmd/<命令>(URL 编码,
+// 如 /api/xz/cmd/left 或 /api/xz/cmd/%E5%97%A1%E5%8F%AD)。与 POST /api/xz/cmd
+// 等效,方便无法发送 POST body 的客户端(如浏览器地址栏 / 网页按钮)直接下发。
+func handleXZCmdPathPost(c *gin.Context) {
+	if forwardToUI(c) {
+		return // 服务模式 + 界面在线 → 转发给界面(指令信箱与界面共享)
+	}
+	cmd := strings.TrimSpace(c.Param("cmd")) // 保留原始大小写
+	if cmd == "" {
+		c.JSON(http.StatusBadRequest, gin.H{"error": "cmd 不能为空"})
+		return
+	}
+	if utf8.RuneCountInString(cmd) > xzCmdMaxLen {
+		c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("cmd 长度不能超过 %d 个字符", xzCmdMaxLen)})
+		return
+	}
+
+	xzCmdMu.Lock()
+	xzCmdLast = cmd
+	xzCmdSeq++
+	seq := xzCmdSeq
+	xzCmdMu.Unlock()
+
+	c.JSON(http.StatusOK, gin.H{"ok": true, "cmd": cmd, "seq": seq})
+}
+
 // startServicePowerAPI 启动仅含电源接口的 HTTP 服务,返回句柄用于停止
 func startServicePowerAPI(addr string) *http.Server {
 	gin.SetMode(gin.ReleaseMode) // 服务模式无控制台,关闭调试输出
@@ -240,9 +282,10 @@ func startServicePowerAPI(addr string) *http.Server {
 		pc.GET("/cancel", handleCancel)     // 取消待执行命令
 		pc.GET("/status", handlePCStatus)   // 查询命令状态
 	}
-	xz := router.Group("/api/xz")    // 指令信箱:POST 下发,GET 读取
-	xz.POST("/cmd", handleXZCmdPost) // body {"cmd":"left"};也接受其他自定义指令
-	xz.GET("/cmd", handleXZCmdGet)   // 返回最新指令
+	xz := router.Group("/api/xz")             // 指令信箱:POST 下发,GET 读取,GET /cmd/<命令> 路径下发
+	xz.POST("/cmd", handleXZCmdPost)         // body {"cmd":"left"};也接受其他自定义指令
+	xz.GET("/cmd", handleXZCmdGet)           // 返回最新指令
+	xz.GET("/cmd/:cmd", handleXZCmdPathPost) // 路径参数下发(URL 编码),如 /cmd/left
 
 	router.NoRoute(proxyToUI) // 其余接口交给界面 API 处理
 

+ 57 - 3
settings.go

@@ -65,6 +65,12 @@ type RepoItem struct {
 	Version string `json:"version"` // 本地已安装版本(用于与最新 release 比较),可为空
 }
 
+// ControlKeyConfig 控制页方向盘单个按键配置(图标 + 命令 URL)
+type ControlKeyConfig struct {
+	Icon string `json:"icon"` // 按钮显示字符,如 ↑、↓、←、→、休眠
+	Cmd  string `json:"cmd"`  // 点击时 GET 请求的完整 URL;空则回退旧指令信箱模式
+}
+
 // TickerConfig 置顶滚动条(股票 / 新闻)的显示配置
 type TickerConfig struct {
 	Enabled     bool   `json:"enabled"`     // 是否显示滚动条窗口
@@ -106,6 +112,8 @@ type AppSettings struct {
 	GithubRepos    []RepoItem       `json:"githubRepos"`    // 关注的 GitHub 仓库列表
 	CustomTabs     []CustomTab      `json:"customTabs"`     // 用户自定义 Tab 页面(名字 + 网址)
 	LocalTools     []LocalTool      `json:"localTools"`     // 「本地」页资源(标题|启动命令|说明,在设置中维护)
+	ControlKeys    []ControlKeyConfig `json:"controlKeys"`  // 控制页按键配置(前 5 键固定 上/下/左/右/休眠,第 6 键起为额外按键)
+	ControlRepeatSecs float64         `json:"controlRepeatSecs"` // 控制页长按连发频率(秒,0.0-10.0,默认 1.0)
 	APIAddr        string           `json:"apiAddr"`        // 内置 API 服务监听地址
 	ServiceAddr    string           `json:"serviceAddr"`    // Windows 服务模式(--service)监听地址,仅电源类接口
 	APIAutoStart   bool             `json:"apiAutoStart"`   // 应用启动时自动启动内置 API 服务(默认开启)
@@ -155,7 +163,7 @@ func defaultSettings() AppSettings {
 		WindowWidth:  DefaultWindowWidth,
 		WindowHeight: DefaultWindowHeight,
 		Hotkey:       DefaultHotkey,
-		TabOrder:     []string{"links", "news", "github", "stock", "todo", "record", "tools", "locals", "host", "settings"}, // 默认 Tab 顺序(控制/硬件等固定网页已改为自定义 Tab)
+		TabOrder:     []string{"links", "news", "github", "stock", "todo", "record", "tools", "locals", "control", "host", "settings"}, // 默认 Tab 顺序(「控制」为遥控小车页)
 		ToolOrder:    DefaultToolOrder(),                                                                                    // 工具页卡片默认显示顺序
 		StockCodes:   []string{"sh000001", "sh600519", "sz000001"},
 		Links: []LinkItem{
@@ -173,6 +181,8 @@ func defaultSettings() AppSettings {
 		UploadPassword: "",   // 上传密码:默认空(不启用上传/下载)
 		UploadDir:      "",   // 上传保存目录:默认空(回退到用户配置目录/uploads)
 		UploadMaxSize:  512,  // 上传大小上限:默认 512MB
+		ControlKeys:    DefaultControlKeys(), // 控制页 5 键默认配置(图标↑↓←→休眠,命令空回退指令信箱)
+		ControlRepeatSecs: 1.0,               // 长按连发频率默认 1 秒
 		TodoPath:       "",   // 待办路径:无默认值,用户须在设置中配置(空值时强制进入设置)
 		RecordPath:     "",   // 记录路径:无默认值,用户须在设置中配置(空值时强制进入设置)
 		RecordDBPath:   "",   // 记录数据库路径:无默认值,用户须在设置中配置(空值时强制进入设置)
@@ -226,6 +236,17 @@ func DefaultToolOrder() []string {
 	}
 }
 
+// DefaultControlKeys 返回控制页方向盘 5 键默认配置(顺序固定:上/下/左/右/休眠)。
+// 命令默认为空:空 = 未配置,前端回退到旧 POST /api/xz/cmd 指令信箱模式(指令值为 up/down/left/right/sleep)。
+func DefaultControlKeys() []ControlKeyConfig {
+	icons := []string{"↑", "↓", "←", "→", "休眠"}
+	keys := make([]ControlKeyConfig, len(icons))
+	for i, ic := range icons {
+		keys[i] = ControlKeyConfig{Icon: ic, Cmd: ""}
+	}
+	return keys
+}
+
 // settingsFilePath 返回配置文件路径:<用户配置目录>/TengTuToolbox/settings.json
 func settingsFilePath() (string, error) {
 	dir, err := os.UserConfigDir() // 例如 C:\Users\<用户名>\AppData\Roaming
@@ -333,9 +354,17 @@ func normalizeSettings(settings AppSettings) AppSettings {
 	}
 	settings.LocalTools = tools
 
+	// 清洗控制页按键:恒为 5 个(上/下/左/右/休眠),图标空回填默认,命令仅 trim(允许空=回退指令信箱)
+	settings.ControlKeys = normalizeControlKeys(settings.ControlKeys)
+
+	// 长按连发频率:0.0-10.0 秒,越界/非法回退默认 1.0
+	if settings.ControlRepeatSecs < 0.0 || settings.ControlRepeatSecs > 10.0 || settings.ControlRepeatSecs != settings.ControlRepeatSecs { // NaN 检查
+		settings.ControlRepeatSecs = 1.0
+	}
+
 	// Tab 顺序:只保留已存在的 tabId(内置 + 自定义 custom-N),去重;未列出的追加到末尾,保证全部 Tab 都能显示
 	validTabs := map[string]bool{"links": true,
-		"news": true, "github": true, "stock": true, "todo": true, "record": true, "tools": true, "locals": true, "host": true, "settings": true}
+		"news": true, "github": true, "stock": true, "todo": true, "record": true, "tools": true, "locals": true, "control": true, "host": true, "settings": true}
 	for i := range settings.CustomTabs {
 		validTabs[fmt.Sprintf("custom-%d", i)] = true // 自定义 Tab id:custom-0, custom-1...
 	}
@@ -357,7 +386,7 @@ func normalizeSettings(settings AppSettings) AppSettings {
 			}
 		}
 	}
-	for _, tab := range []string{"links", "news", "github", "stock", "todo", "record", "tools", "locals", "host", "settings"} {
+	for _, tab := range []string{"links", "news", "github", "stock", "todo", "record", "tools", "locals", "control", "host", "settings"} {
 		if !seen[tab] {
 			ordered = append(ordered, tab) // 设置中未列出的内置 Tab 追加到末尾
 		}
@@ -530,6 +559,31 @@ func normalizeTicker(cfg TickerConfig, defaultColor string, defaultSpeed int) Ti
 	return cfg
 }
 
+// normalizeControlKeys 校正控制页按键配置:
+// 前 5 键固定(顺序 上/下/左/右/休眠),图标空回填默认;第 6 键起为用户额外按键,
+// 图标与命令仅 trim(图标空 = 前端跳过该行),命令空 = 前端回退旧指令信箱模式
+func normalizeControlKeys(keys []ControlKeyConfig) []ControlKeyConfig {
+	def := DefaultControlKeys()
+	out := make([]ControlKeyConfig, len(def))
+	for i := range def {
+		if i < len(keys) {
+			out[i].Icon = strings.TrimSpace(keys[i].Icon)
+			out[i].Cmd = strings.TrimSpace(keys[i].Cmd)
+		}
+		if out[i].Icon == "" {
+			out[i].Icon = def[i].Icon // 图标空回填默认
+		}
+	}
+	// 额外按键(第 6 键起):保留用户输入,图标空由前端过滤
+	for i := len(def); i < len(keys); i++ {
+		out = append(out, ControlKeyConfig{
+			Icon: strings.TrimSpace(keys[i].Icon),
+			Cmd:  strings.TrimSpace(keys[i].Cmd),
+		})
+	}
+	return out
+}
+
 // normalizeMouseAlert 校正鼠标提醒配置:字号、宽度、速度、显示时长下限,颜色默认值
 func normalizeMouseAlert(cfg MouseAlertConfig) MouseAlertConfig {
 	if cfg.FontSize < 10 || cfg.FontSize > 48 {

+ 239 - 0
udpservice.go

@@ -0,0 +1,239 @@
+// ============================================================================
+// udpservice.go — 工具页 UDP 键值服务
+//
+// 启动一个 UDP 服务器(端口可设置),任何客户机都可连接。协议语义:
+//   - 客户端发送「键=值」→ 服务端存储该键值到内存;
+//   - 客户端发送纯字符串(键名)→ 服务端回发已存值给请求方,键不存在则回发空;
+//   - 键值存内存,服务停止即清空(不持久化);
+//   - 工具页也可手动发送文本到指定远端。
+// 来往数据通过 udp:log 事件推送给前端信息框展示。
+// ============================================================================
+package main
+
+import (
+	"context"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"net"
+	"strings"
+	"sync"
+	"time"
+)
+
+// UDPInfo 描述一次 UDP 键值服务的运行状态,供前端展示。
+type UDPInfo struct {
+	Running   bool   `json:"running"`   // 是否运行中
+	Port      int    `json:"port"`      // 监听端口
+	Addr      string `json:"addr"`      // 监听地址 udp://0.0.0.0:port
+	StartedAt string `json:"startedAt"` // 启动时间
+	Error     string `json:"error"`     // 最近一次错误
+	RxCount   int64  `json:"rxCount"`   // 累计接收数据包数
+	TxCount   int64  `json:"txCount"`   // 累计发送(回发/手动)数据包数
+}
+
+// udpService 持有 UDP 键值服务的运行状态(全局单例,工具页调用)。
+type udpService struct {
+	mu      sync.Mutex
+	conn    *net.UDPConn
+	port    int
+	started time.Time
+	cancel  context.CancelFunc
+	rx      int64
+	tx      int64
+	store   map[string]string // 键值存储:key -> value
+}
+
+var udpSrv = &udpService{store: map[string]string{}}
+
+// udpEmit 推送一条日志给前端信息框。kind: recv / send / info。
+func udpEmit(kind, line string) {
+	if app == nil {
+		return
+	}
+	app.Event.Emit("udp:log", map[string]string{"kind": kind, "line": line})
+}
+
+// udpInfoLocked 生成当前状态快照(调用方须持有 mu)。
+func udpInfoLocked() UDPInfo {
+	info := UDPInfo{
+		Running: udpSrv.conn != nil,
+		Port:    udpSrv.port,
+		RxCount: udpSrv.rx,
+		TxCount: udpSrv.tx,
+	}
+	if udpSrv.conn != nil {
+		info.Addr = fmt.Sprintf("udp://0.0.0.0:%d", udpSrv.port)
+		info.StartedAt = udpSrv.started.Format("2006-01-02 15:04:05")
+	}
+	return info
+}
+
+// stopUDPServerLocked 停止当前服务并清空键值存储(调用方须持有 mu)。
+// 关闭连接会使阻塞的 ReadFromUDP 立即返回,读循环检测 ctx 取消后退出。
+func stopUDPServerLocked() {
+	if udpSrv.cancel != nil {
+		udpSrv.cancel()
+		udpSrv.cancel = nil
+	}
+	if udpSrv.conn != nil {
+		_ = udpSrv.conn.Close()
+		udpSrv.conn = nil
+	}
+	udpSrv.port = 0
+	udpSrv.started = time.Time{}
+	udpSrv.store = map[string]string{} // 停止即清空
+}
+
+// udpReadLoop 阻塞读 UDP 数据包并处理键值协议,直到连接关闭。
+func udpReadLoop(ctx context.Context, conn *net.UDPConn) {
+	buf := make([]byte, 64*1024)
+	for {
+		n, remote, err := conn.ReadFromUDP(buf)
+		if err != nil {
+			if ctx.Err() != nil {
+				return // 正常停止
+			}
+			udpEmit("info", fmt.Sprintf("读取错误: %v", err))
+			continue
+		}
+		raw := string(buf[:n])
+		line := strings.TrimSpace(raw)
+		if line == "" {
+			continue // 空数据包忽略
+		}
+
+		// 含「=」→ 存储键值;否则 → 查询并回发
+		if i := strings.IndexByte(line, '='); i >= 0 {
+			key := line[:i]
+			val := line[i+1:]
+			udpSrv.mu.Lock()
+			udpSrv.store[key] = val
+			udpSrv.rx++
+			udpSrv.mu.Unlock()
+			udpEmit("recv", fmt.Sprintf("%s 存储 %s=%s <- %s", time.Now().Format("15:04:05"), key, val, remote))
+		} else {
+			key := line
+			udpSrv.mu.Lock()
+			val := udpSrv.store[key] // 不存在返回空串
+			udpSrv.rx++
+			udpSrv.mu.Unlock()
+			// 回发结果给请求方
+			if _, err := conn.WriteToUDP([]byte(val), remote); err != nil {
+				udpEmit("info", fmt.Sprintf("回发 %s 失败: %v", key, err))
+				continue
+			}
+			udpSrv.mu.Lock()
+			udpSrv.tx++
+			udpSrv.mu.Unlock()
+			disp := val
+			if disp == "" {
+				disp = "(空)"
+			}
+			udpEmit("send", fmt.Sprintf("%s 查询 %s -> %s -> %s", time.Now().Format("15:04:05"), key, disp, remote))
+		}
+	}
+}
+
+// UDPService 是 UDP 键值服务的 Wails 服务。
+type UDPService struct{}
+
+// NewUDPService 创建 UDP 服务实例。
+func NewUDPService() *UDPService {
+	return &UDPService{}
+}
+
+// StartUDPServer 启动 UDP 键值服务器,监听 0.0.0.0:port。
+// 若已运行则先停止旧实例,并清空键值存储。端口占用时返回错误。
+func (s *UDPService) StartUDPServer(port int) (UDPInfo, error) {
+	if port < 1 || port > 65535 {
+		return UDPInfo{}, fmt.Errorf("端口无效: %d(范围 1-65535)", port)
+	}
+
+	udpSrv.mu.Lock()
+	stopUDPServerLocked() // 幂等先停旧实例(含清空 store)
+	udpSrv.mu.Unlock()
+
+	udpAddr, err := net.ResolveUDPAddr("udp", fmt.Sprintf("0.0.0.0:%d", port))
+	if err != nil {
+		return UDPInfo{}, fmt.Errorf("解析地址失败: %w", err)
+	}
+	conn, err := net.ListenUDP("udp", udpAddr)
+	if err != nil {
+		return UDPInfo{}, fmt.Errorf("端口 %d 监听失败(可能被占用): %w", port, err)
+	}
+
+	ctx, cancel := context.WithCancel(context.Background())
+
+	udpSrv.mu.Lock()
+	udpSrv.conn = conn
+	udpSrv.port = port
+	udpSrv.started = time.Now()
+	udpSrv.cancel = cancel
+	udpSrv.rx = 0
+	udpSrv.tx = 0
+	udpSrv.store = map[string]string{} // 重新启动清空
+	info := udpInfoLocked()
+	udpSrv.mu.Unlock()
+
+	go udpReadLoop(ctx, conn)
+
+	udpEmit("info", fmt.Sprintf("%s UDP 键值服务已启动: %s", time.Now().Format("15:04:05"), info.Addr))
+	return info, nil
+}
+
+// StopUDPServer 停止当前 UDP 键值服务(未运行则无副作用),并清空键值存储。
+func (s *UDPService) StopUDPServer() (UDPInfo, error) {
+	udpSrv.mu.Lock()
+	wasRunning := udpSrv.conn != nil
+	stopUDPServerLocked()
+	udpSrv.mu.Unlock()
+	if wasRunning {
+		udpEmit("info", fmt.Sprintf("%s UDP 键值服务已停止(键值存储已清空)", time.Now().Format("15:04:05")))
+	}
+	return udpInfoLocked(), nil
+}
+
+// UDPServerStatus 返回当前 UDP 键值服务状态。
+func (s *UDPService) UDPServerStatus() UDPInfo {
+	udpSrv.mu.Lock()
+	defer udpSrv.mu.Unlock()
+	return udpInfoLocked()
+}
+
+// SendUDP 手动发送文本到指定远端(addr 形如 ip:port)。
+func (s *UDPService) SendUDP(addr, text string) (UDPInfo, error) {
+	if strings.TrimSpace(addr) == "" {
+		return UDPInfo{}, errors.New("目标地址不能为空")
+	}
+	udpAddr, err := net.ResolveUDPAddr("udp", strings.TrimSpace(addr))
+	if err != nil {
+		return UDPInfo{}, fmt.Errorf("目标地址无效: %w", err)
+	}
+	conn, err := net.DialUDP("udp", nil, udpAddr)
+	if err != nil {
+		return UDPInfo{}, fmt.Errorf("连接目标失败: %w", err)
+	}
+	defer conn.Close()
+	if _, err := conn.Write([]byte(text)); err != nil {
+		return UDPInfo{}, fmt.Errorf("发送失败: %w", err)
+	}
+	udpSrv.mu.Lock()
+	udpSrv.tx++
+	info := udpInfoLocked()
+	udpSrv.mu.Unlock()
+	disp := text
+	if disp == "" {
+		disp = "(空)"
+	}
+	udpEmit("send", fmt.Sprintf("%s 发送 %s -> %s", time.Now().Format("15:04:05"), disp, addr))
+	return info, nil
+}
+
+// UDPServerJSON 为前端提供一次调用获取完整状态的辅助(避免多次 IPC)。
+func (s *UDPService) UDPServerJSON() string {
+	udpSrv.mu.Lock()
+	defer udpSrv.mu.Unlock()
+	b, _ := json.Marshal(udpInfoLocked())
+	return string(b)
+}