From b7c0201ca318b532b57a77f3c881cbe855b58172 Mon Sep 17 00:00:00 2001
From: marlonz <235833017@qq.com>
Date: Tue, 17 Jun 2025 16:40:17 +0930
Subject: [PATCH 001/366] =?UTF-8?q?=E6=8F=90=E4=BA=A4mqtt=E5=90=8E?=
=?UTF-8?q?=E7=AB=AF=E4=BF=AE=E6=94=B9?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../xiaozhi/common/constant/Constant.java | 9 +++++++
.../java/xiaozhi/common/utils/JsonUtils.java | 2 +-
.../device/controller/OTAController.java | 4 ++++
.../device/dto/DeviceReportRespDTO.java | 20 ++++++++++++++++
.../service/impl/DeviceServiceImpl.java | 18 ++++++++++++++
.../resources/db/changelog/202506152342.sql | 3 +++
.../resources/db/changelog/202506152350.sql | 5 ++++
.../db/changelog/db.changelog-master.yaml | 16 ++++++++++++-
main/manager-web/package-lock.json | 24 +++++++++++++++----
9 files changed, 94 insertions(+), 7 deletions(-)
create mode 100644 main/manager-api/src/main/resources/db/changelog/202506152342.sql
create mode 100644 main/manager-api/src/main/resources/db/changelog/202506152350.sql
diff --git a/main/manager-api/src/main/java/xiaozhi/common/constant/Constant.java b/main/manager-api/src/main/java/xiaozhi/common/constant/Constant.java
index 44294756d..d6f1867d3 100644
--- a/main/manager-api/src/main/java/xiaozhi/common/constant/Constant.java
+++ b/main/manager-api/src/main/java/xiaozhi/common/constant/Constant.java
@@ -91,6 +91,15 @@ public interface Constant {
*/
String SERVER_WEBSOCKET = "server.websocket";
+ /**
+ * mqtt gateway 配置
+ */
+ String SERVER_MQTT_GATEWAY = "server.mqtt_gateway";
+
+ /**
+ * websocket地址
+ */
+
/**
* ota地址
*/
diff --git a/main/manager-api/src/main/java/xiaozhi/common/utils/JsonUtils.java b/main/manager-api/src/main/java/xiaozhi/common/utils/JsonUtils.java
index 288dae9ab..093f2acf1 100644
--- a/main/manager-api/src/main/java/xiaozhi/common/utils/JsonUtils.java
+++ b/main/manager-api/src/main/java/xiaozhi/common/utils/JsonUtils.java
@@ -66,5 +66,5 @@ public class JsonUtils {
throw new RuntimeException(e);
}
}
-
+
}
diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/controller/OTAController.java b/main/manager-api/src/main/java/xiaozhi/modules/device/controller/OTAController.java
index 05d36e9ac..7a826a336 100644
--- a/main/manager-api/src/main/java/xiaozhi/modules/device/controller/OTAController.java
+++ b/main/manager-api/src/main/java/xiaozhi/modules/device/controller/OTAController.java
@@ -78,6 +78,10 @@ public class OTAController {
@GetMapping
@Hidden
public ResponseEntity getOTA() {
+ String mqttUdpConfig = sysParamsService.getValue(Constant.SERVER_MQTT_GATEWAY, false);
+ if(StringUtils.isBlank(mqttUdpConfig)) {
+ return ResponseEntity.ok("OTA接口不正常,缺少websocket地址,请登录智控台,在参数管理找到【server.mqtt_udp】配置");
+ }
String wsUrl = sysParamsService.getValue(Constant.SERVER_WEBSOCKET, true);
if (StringUtils.isBlank(wsUrl) || wsUrl.equals("null")) {
return ResponseEntity.ok("OTA接口不正常,缺少websocket地址,请登录智控台,在参数管理找到【server.websocket】配置");
diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceReportRespDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceReportRespDTO.java
index f938001e0..5c53b7880 100644
--- a/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceReportRespDTO.java
+++ b/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceReportRespDTO.java
@@ -22,6 +22,9 @@ public class DeviceReportRespDTO {
@Schema(description = "WebSocket配置")
private Websocket websocket;
+
+ @Schema(description = "MQTT Gateway配置")
+ private MQTT mqtt;
@Getter
@Setter
@@ -70,4 +73,21 @@ public class DeviceReportRespDTO {
@Schema(description = "WebSocket服务器地址")
private String url;
}
+
+ @Getter
+ @Setter
+ public static class MQTT {
+ @Schema(description = "MQTT 配置网址")
+ private String endpoint;
+ @Schema(description = "MQTT 客户端唯一标识符")
+ private String client_id;
+ @Schema(description = "MQTT 认证用户名")
+ private String username;
+ @Schema(description = "MQTT 认证密码")
+ private String password;
+ @Schema(description = "ESP32 发布消息的主题")
+ private String publish_topic;
+ @Schema(description = "ESP32 订阅的主题")
+ private String subscribe_topic;
+ }
}
diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java
index ee31c41f0..26a370f41 100644
--- a/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java
+++ b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java
@@ -174,6 +174,24 @@ public class DeviceServiceImpl extends BaseServiceImpl
}
response.setWebsocket(websocket);
+
+ // 添加MQTT UDP配置
+ // 从系统参数获取WebSocket URL,如果未配置不使用默认值
+ String mqttUdpConfig = sysParamsService.getValue(Constant.SERVER_MQTT_GATEWAY, false);
+ if(!StringUtils.isBlank(mqttUdpConfig)) {
+ DeviceReportRespDTO.MQTT mqtt= new DeviceReportRespDTO.MQTT();
+ mqtt.setEndpoint(mqttUdpConfig);
+ mqtt.setClient_id(clientId);
+ String userNameString = deviceById.getId().replace(":", "_");
+ mqtt.setUsername(userNameString);
+ mqtt.setPassword(deviceById.getBoard());
+ String topicString = deviceById.getBoard() + '/' + deviceById.getAgentId();
+ mqtt.setPublish_topic(topicString);
+ String subscribeString = "devices/p2p/"+userNameString;
+ mqtt.setSubscribe_topic(subscribeString);
+ response.setMqtt(mqtt);
+ }
+
if (deviceById != null) {
// 如果设备存在,则异步更新上次连接时间和版本信息
diff --git a/main/manager-api/src/main/resources/db/changelog/202506152342.sql b/main/manager-api/src/main/resources/db/changelog/202506152342.sql
new file mode 100644
index 000000000..a18dd8efb
--- /dev/null
+++ b/main/manager-api/src/main/resources/db/changelog/202506152342.sql
@@ -0,0 +1,3 @@
+delete from `sys_params` where id = 108;
+INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (108, 'server.mqtt_udp', 'null', 'string', 1, 'mqtt udp 配置');
+
diff --git a/main/manager-api/src/main/resources/db/changelog/202506152350.sql b/main/manager-api/src/main/resources/db/changelog/202506152350.sql
new file mode 100644
index 000000000..917d04251
--- /dev/null
+++ b/main/manager-api/src/main/resources/db/changelog/202506152350.sql
@@ -0,0 +1,5 @@
+delete from `sys_params` where id = 108;
+INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (108, 'server.mqtt_gateway', 'null', 'string', 1, 'mqtt gateway 配置');
+
+delete from `sys_params` where id = 109;
+INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (109, 'server.udp_gateway', 'null', 'string', 1, 'udp gateway 配置');
diff --git a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml
index f33d28a29..392349688 100755
--- a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml
+++ b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml
@@ -204,4 +204,18 @@ databaseChangeLog:
changes:
- sqlFile:
encoding: utf8
- path: classpath:db/changelog/202506080955.sql
\ No newline at end of file
+ path: classpath:db/changelog/202506080955.sql
+ - changeSet:
+ id: 202506152342
+ author: marlonz
+ changes:
+ - sqlFile:
+ encoding: utf8
+ path: classpath:db/changelog/202506152342.sql
+ - changeSet:
+ id: 202506152350
+ author: marlonz
+ changes:
+ - sqlFile:
+ encoding: utf8
+ path: classpath:db/changelog/202506152350.sql
diff --git a/main/manager-web/package-lock.json b/main/manager-web/package-lock.json
index c104b60c2..6d1f51283 100644
--- a/main/manager-web/package-lock.json
+++ b/main/manager-web/package-lock.json
@@ -10,6 +10,7 @@
"dependencies": {
"core-js": "^3.41.0",
"cross-env": "^7.0.3",
+ "dotenv": "^16.5.0",
"element-ui": "^2.15.14",
"flyio": "^0.6.14",
"normalize.css": "^8.0.1",
@@ -2540,6 +2541,16 @@
}
}
},
+ "node_modules/@vue/cli-service/node_modules/dotenv": {
+ "version": "10.0.0",
+ "resolved": "https://registry.npmmirror.com/dotenv/-/dotenv-10.0.0.tgz",
+ "integrity": "sha512-rlBi9d8jpv9Sf1klPjNfFAuWDjKLwTIJJ/VxtoTwIR6hnZxcEOQCZg2oIL3MWBYw5GpUDKOEnND7LXTbIpQ03Q==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">=10"
+ }
+ },
"node_modules/@vue/cli-shared-utils": {
"version": "5.0.8",
"resolved": "https://registry.npmmirror.com/@vue/cli-shared-utils/-/cli-shared-utils-5.0.8.tgz",
@@ -4776,12 +4787,15 @@
}
},
"node_modules/dotenv": {
- "version": "10.0.0",
- "resolved": "https://registry.npmmirror.com/dotenv/-/dotenv-10.0.0.tgz",
- "integrity": "sha512-rlBi9d8jpv9Sf1klPjNfFAuWDjKLwTIJJ/VxtoTwIR6hnZxcEOQCZg2oIL3MWBYw5GpUDKOEnND7LXTbIpQ03Q==",
- "dev": true,
+ "version": "16.5.0",
+ "resolved": "https://registry.npmmirror.com/dotenv/-/dotenv-16.5.0.tgz",
+ "integrity": "sha512-m/C+AwOAr9/W1UOIZUo232ejMNnJAJtYQjUbHoNTBNTJSvqzzDh7vnrei3o3r3m9blf6ZoDkvcw0VmozNRFJxg==",
+ "license": "BSD-2-Clause",
"engines": {
- "node": ">=10"
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://dotenvx.com"
}
},
"node_modules/dotenv-expand": {
From 3d3875f14fe3cb862391e9995c4b98f5b76857ce Mon Sep 17 00:00:00 2001
From: marlonz <235833017@qq.com>
Date: Sat, 5 Jul 2025 12:34:57 +0930
Subject: [PATCH 002/366] update lq base sql
---
.../src/main/resources/db/changelog/202506152342.sql | 3 ---
.../db/changelog/{202506152350.sql => 202507051233.sql} | 2 +-
2 files changed, 1 insertion(+), 4 deletions(-)
delete mode 100644 main/manager-api/src/main/resources/db/changelog/202506152342.sql
rename main/manager-api/src/main/resources/db/changelog/{202506152350.sql => 202507051233.sql} (90%)
diff --git a/main/manager-api/src/main/resources/db/changelog/202506152342.sql b/main/manager-api/src/main/resources/db/changelog/202506152342.sql
deleted file mode 100644
index a18dd8efb..000000000
--- a/main/manager-api/src/main/resources/db/changelog/202506152342.sql
+++ /dev/null
@@ -1,3 +0,0 @@
-delete from `sys_params` where id = 108;
-INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (108, 'server.mqtt_udp', 'null', 'string', 1, 'mqtt udp 配置');
-
diff --git a/main/manager-api/src/main/resources/db/changelog/202506152350.sql b/main/manager-api/src/main/resources/db/changelog/202507051233.sql
similarity index 90%
rename from main/manager-api/src/main/resources/db/changelog/202506152350.sql
rename to main/manager-api/src/main/resources/db/changelog/202507051233.sql
index 917d04251..a85688772 100644
--- a/main/manager-api/src/main/resources/db/changelog/202506152350.sql
+++ b/main/manager-api/src/main/resources/db/changelog/202507051233.sql
@@ -2,4 +2,4 @@ delete from `sys_params` where id = 108;
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (108, 'server.mqtt_gateway', 'null', 'string', 1, 'mqtt gateway 配置');
delete from `sys_params` where id = 109;
-INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (109, 'server.udp_gateway', 'null', 'string', 1, 'udp gateway 配置');
+INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (109, 'server.udp_gateway', 'null', 'string', 1, 'udp gateway 配置');
\ No newline at end of file
From 7c0367729575e4edf8a7a8265f3f207da906ea90 Mon Sep 17 00:00:00 2001
From: marlonz <235833017@qq.com>
Date: Sat, 5 Jul 2025 13:25:42 +0930
Subject: [PATCH 003/366] update change log
---
.../main/resources/db/changelog/db.changelog-master.yaml | 9 +--------
1 file changed, 1 insertion(+), 8 deletions(-)
diff --git a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml
index 4d1d3798a..ffc60bdbb 100755
--- a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml
+++ b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml
@@ -245,11 +245,4 @@ databaseChangeLog:
changes:
- sqlFile:
encoding: utf8
- path: classpath:db/changelog/202506152342.sql
- - changeSet:
- id: 202506152350
- author: marlonz
- changes:
- - sqlFile:
- encoding: utf8
- path: classpath:db/changelog/202506152350.sql
+ path: classpath:db/changelog/202507051233.sql
From aed54bb3a683095ca1f81a06cbaa3eda90c5108d Mon Sep 17 00:00:00 2001
From: marlonz <235833017@qq.com>
Date: Sat, 5 Jul 2025 13:30:14 +0930
Subject: [PATCH 004/366] tech review change
---
.../src/main/java/xiaozhi/common/constant/Constant.java | 4 ----
.../src/main/java/xiaozhi/common/utils/JsonUtils.java | 1 -
2 files changed, 5 deletions(-)
diff --git a/main/manager-api/src/main/java/xiaozhi/common/constant/Constant.java b/main/manager-api/src/main/java/xiaozhi/common/constant/Constant.java
index d9fced7cd..518ebc70c 100644
--- a/main/manager-api/src/main/java/xiaozhi/common/constant/Constant.java
+++ b/main/manager-api/src/main/java/xiaozhi/common/constant/Constant.java
@@ -96,10 +96,6 @@ public interface Constant {
*/
String SERVER_MQTT_GATEWAY = "server.mqtt_gateway";
- /**
- * websocket地址
- */
-
/**
* ota地址
*/
diff --git a/main/manager-api/src/main/java/xiaozhi/common/utils/JsonUtils.java b/main/manager-api/src/main/java/xiaozhi/common/utils/JsonUtils.java
index 093f2acf1..6d628d381 100644
--- a/main/manager-api/src/main/java/xiaozhi/common/utils/JsonUtils.java
+++ b/main/manager-api/src/main/java/xiaozhi/common/utils/JsonUtils.java
@@ -66,5 +66,4 @@ public class JsonUtils {
throw new RuntimeException(e);
}
}
-
}
From 076aaae944555db4e9c414ae15969cb2c07a16c4 Mon Sep 17 00:00:00 2001
From: marlonz <235833017@qq.com>
Date: Sat, 5 Jul 2025 13:47:49 +0930
Subject: [PATCH 005/366] mqtt gateway project
---
main/mqtt-gateway/.gitignore | 4 +
main/mqtt-gateway/LICENSE | 21 +
main/mqtt-gateway/README.md | 215 +++++++
main/mqtt-gateway/app.js | 623 ++++++++++++++++++++
main/mqtt-gateway/config/mqtt.json.example | 15 +
main/mqtt-gateway/config/mqtt.json.test | 12 +
main/mqtt-gateway/ecosystem.config.js | 9 +
main/mqtt-gateway/generate_signature_key.js | 81 +++
main/mqtt-gateway/mqtt-protocol.js | 499 ++++++++++++++++
main/mqtt-gateway/utils/config-manager.js | 78 +++
main/mqtt-gateway/utils/mqtt_config_v2.js | 103 ++++
main/mqtt-gateway/测试说明.md | 239 ++++++++
12 files changed, 1899 insertions(+)
create mode 100644 main/mqtt-gateway/.gitignore
create mode 100644 main/mqtt-gateway/LICENSE
create mode 100644 main/mqtt-gateway/README.md
create mode 100644 main/mqtt-gateway/app.js
create mode 100644 main/mqtt-gateway/config/mqtt.json.example
create mode 100644 main/mqtt-gateway/config/mqtt.json.test
create mode 100644 main/mqtt-gateway/ecosystem.config.js
create mode 100644 main/mqtt-gateway/generate_signature_key.js
create mode 100644 main/mqtt-gateway/mqtt-protocol.js
create mode 100644 main/mqtt-gateway/utils/config-manager.js
create mode 100644 main/mqtt-gateway/utils/mqtt_config_v2.js
create mode 100644 main/mqtt-gateway/测试说明.md
diff --git a/main/mqtt-gateway/.gitignore b/main/mqtt-gateway/.gitignore
new file mode 100644
index 000000000..71b7ebc22
--- /dev/null
+++ b/main/mqtt-gateway/.gitignore
@@ -0,0 +1,4 @@
+node_modules/
+build/
+dist/
+package-lock.json
diff --git a/main/mqtt-gateway/LICENSE b/main/mqtt-gateway/LICENSE
new file mode 100644
index 000000000..b75f43388
--- /dev/null
+++ b/main/mqtt-gateway/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2025 Xiaoxia
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
\ No newline at end of file
diff --git a/main/mqtt-gateway/README.md b/main/mqtt-gateway/README.md
new file mode 100644
index 000000000..bb591758c
--- /dev/null
+++ b/main/mqtt-gateway/README.md
@@ -0,0 +1,215 @@
+# MQTT+UDP 到 WebSocket 桥接服务
+
+## 项目概述
+
+这是一个用于物联网设备通信的桥接服务,实现了MQTT和UDP协议到WebSocket的转换。该服务允许设备通过MQTT协议进行控制消息传输,同时通过UDP协议高效传输音频数据,并将这些数据桥接到WebSocket服务。
+
+## 功能特点
+
+- **多协议支持**: 同时支持MQTT、UDP和WebSocket协议
+- **音频数据传输**: 专为音频数据流优化的传输机制
+- **加密通信**: 使用AES-128-CTR加密UDP数据传输
+- **会话管理**: 完整的设备会话生命周期管理
+- **自动重连**: 连接断开时自动重连机制
+- **心跳检测**: 定期检查连接活跃状态
+- **开发/生产环境配置**: 支持不同环境的配置切换
+
+## 技术架构
+
+- **MQTT服务器**: 处理设备控制消息
+- **UDP服务器**: 处理高效的音频数据传输
+- **WebSocket客户端**: 连接到聊天服务器
+- **桥接层**: 在不同协议间转换和路由消息
+
+## 项目结构
+
+```
+├── app.js # 主应用入口
+├── mqtt-protocol.js # MQTT协议实现
+├── ecosystem.config.js # PM2配置文件
+├── package.json # 项目依赖
+├── .env # 环境变量配置
+├── utils/
+│ ├── config-manager.js # 配置管理工具
+│ ├── mqtt_config_v2.js # MQTT配置验证工具
+│ └── weixinAlert.js # 微信告警工具
+└── config/ # 配置文件目录
+```
+
+## 依赖项
+
+- **debug**: 调试日志输出
+- **dotenv**: 环境变量管理
+- **ws**: WebSocket客户端
+- **events**: Node.js 事件模块
+
+## 安装要求
+
+- Node.js 14.x 或更高版本
+- npm 或 yarn 包管理器
+- PM2 (用于生产环境部署)
+
+## 安装步骤
+
+1. 克隆仓库
+```bash
+git clone <仓库地址>
+cd mqtt-websocket-bridge
+```
+
+2. 安装依赖
+```bash
+npm install
+```
+
+3. 创建配置文件
+```bash
+mkdir -p config
+cp config/mqtt.json.example config/mqtt.json
+```
+
+4. 编辑配置文件 `config/mqtt.json`,设置适当的参数
+
+## 配置说明
+
+配置文件 `config/mqtt.json` 需要包含以下内容:
+
+```json
+{
+ "debug": false,
+ "development": {
+ "mac_addresss": ["aa:bb:cc:dd:ee:ff"],
+ "chat_servers": ["wss://dev-chat-server.example.com/ws"]
+ },
+ "production": {
+ "chat_servers": ["wss://chat-server.example.com/ws"]
+ }
+}
+```
+
+## 环境变量
+
+创建 `.env` 文件并设置以下环境变量:
+
+```
+MQTT_PORT=1883 # MQTT服务器端口
+UDP_PORT=8884 # UDP服务器端口
+PUBLIC_IP=your-ip # 服务器公网IP
+```
+
+## 运行服务
+
+### 开发环境
+
+```bash
+# 直接运行
+node app.js
+
+# 调试模式运行
+DEBUG=mqtt-server node app.js
+```
+
+### 生产环境 (使用PM2)
+
+```bash
+# 安装PM2
+npm install -g pm2
+
+# 启动服务
+pm2 start ecosystem.config.js
+
+# 查看日志
+pm2 logs xz-mqtt
+
+# 监控服务
+pm2 monit
+```
+
+服务将在以下端口启动:
+- MQTT 服务器: 端口 1883 (可通过环境变量修改)
+- UDP 服务器: 端口 8884 (可通过环境变量修改)
+
+## 协议说明
+
+### 设备连接流程
+
+1. 设备通过MQTT协议连接到服务器
+2. 设备发送 `hello` 消息,包含音频参数和特性
+3. 服务器创建WebSocket连接到聊天服务器
+4. 服务器返回UDP连接参数给设备
+5. 设备通过UDP发送音频数据
+6. 服务器将音频数据转发到WebSocket
+7. WebSocket返回的控制消息通过MQTT发送给设备
+
+### 消息格式
+
+#### Hello 消息 (设备 -> 服务器)
+```json
+{
+ "type": "hello",
+ "version": 3,
+ "audio_params": { ... },
+ "features": { ... }
+}
+```
+
+#### Hello 响应 (服务器 -> 设备)
+```json
+{
+ "type": "hello",
+ "version": 3,
+ "session_id": "uuid",
+ "transport": "udp",
+ "udp": {
+ "server": "server-ip",
+ "port": 8884,
+ "encryption": "aes-128-ctr",
+ "key": "hex-encoded-key",
+ "nonce": "hex-encoded-nonce"
+ },
+ "audio_params": { ... }
+}
+```
+
+## 安全说明
+
+- UDP通信使用AES-128-CTR加密
+- 每个会话使用唯一的加密密钥
+- 使用序列号防止重放攻击
+- 设备通过MAC地址进行身份验证
+- 支持设备分组和UUID验证
+
+## 性能优化
+
+- 使用预分配的缓冲区减少内存分配
+- UDP协议用于高效传输音频数据
+- 定期清理不活跃的连接
+- 连接数和活跃连接数监控
+- 支持多聊天服务器负载均衡
+
+## 故障排除
+
+- 检查设备MAC地址格式是否正确
+- 确保UDP端口在防火墙中开放
+- 启用调试模式查看详细日志
+- 检查配置文件中的聊天服务器地址是否正确
+- 验证设备认证信息是否正确
+
+## 开发指南
+
+### 添加新功能
+
+1. 修改 `mqtt-protocol.js` 以支持新的MQTT功能
+2. 在 `MQTTConnection` 类中添加新的消息处理方法
+3. 更新配置管理器以支持新的配置选项
+4. 在 `WebSocketBridge` 类中添加新的WebSocket处理逻辑
+
+### 调试技巧
+
+```bash
+# 启用所有调试输出
+DEBUG=* node app.js
+
+# 只启用MQTT服务器调试
+DEBUG=mqtt-server node app.js
+```
diff --git a/main/mqtt-gateway/app.js b/main/mqtt-gateway/app.js
new file mode 100644
index 000000000..aad3bc905
--- /dev/null
+++ b/main/mqtt-gateway/app.js
@@ -0,0 +1,623 @@
+// Description: MQTT+UDP 到 WebSocket 的桥接
+// Author: terrence@tenclass.com
+// Date: 2025-03-12
+
+require('dotenv').config();
+const net = require('net');
+const debugModule = require('debug');
+const debug = debugModule('mqtt-server');
+const crypto = require('crypto');
+const dgram = require('dgram');
+const Emitter = require('events');
+const WebSocket = require('ws');
+const { MQTTProtocol } = require('./mqtt-protocol');
+const { ConfigManager } = require('./utils/config-manager');
+const { validateMqttCredentials } = require('./utils/mqtt_config_v2');
+
+
+function setDebugEnabled(enabled) {
+ if (enabled) {
+ debugModule.enable('mqtt-server');
+ } else {
+ debugModule.disable();
+ }
+}
+
+const configManager = new ConfigManager('mqtt.json');
+configManager.on('configChanged', (config) => {
+ setDebugEnabled(config.debug);
+});
+
+setDebugEnabled(configManager.get('debug'));
+
+class WebSocketBridge extends Emitter {
+ constructor(connection, protocolVersion, macAddress, uuid, userData) {
+ super();
+ this.connection = connection;
+ this.macAddress = macAddress;
+ this.uuid = uuid;
+ this.userData = userData;
+ this.wsClient = null;
+ this.protocolVersion = protocolVersion;
+ this.deviceSaidGoodbye = false;
+ this.initializeChatServer();
+ }
+
+ initializeChatServer() {
+ const devMacAddresss = configManager.get('development')?.mac_addresss || [];
+ let chatServers;
+ if (devMacAddresss.includes(this.macAddress)) {
+ chatServers = configManager.get('development')?.chat_servers;
+ } else {
+ chatServers = configManager.get('production')?.chat_servers;
+ }
+ if (!chatServers) {
+ throw new Error(`未找到 ${this.macAddress} 的聊天服务器`);
+ }
+ this.chatServer = chatServers[Math.floor(Math.random() * chatServers.length)];
+ }
+
+ async connect(audio_params, features) {
+ return new Promise((resolve, reject) => {
+ const headers = {
+ 'device-id': this.macAddress,
+ 'protocol-version': '2',
+ 'authorization': `Bearer test-token`
+ };
+ if (this.uuid) {
+ headers['client-id'] = this.uuid;
+ }
+ if (this.userData && this.userData.ip) {
+ headers['x-forwarded-for'] = this.userData.ip;
+ }
+ this.wsClient = new WebSocket(this.chatServer, { headers });
+
+ this.wsClient.on('open', () => {
+ this.sendJson({
+ type: 'hello',
+ version: 2,
+ transport: 'websocket',
+ audio_params,
+ features
+ });
+ });
+
+ this.wsClient.on('message', (data, isBinary) => {
+ if (isBinary) {
+ const timestamp = data.readUInt32BE(8);
+ const opusLength = data.readUInt32BE(12);
+ const opus = data.subarray(16, 16 + opusLength);
+ // 二进制数据通过UDP发送
+ this.connection.sendUdpMessage(opus, timestamp);
+ } else {
+ // JSON数据通过MQTT发送
+ const message = JSON.parse(data.toString());
+ if (message.type === 'hello') {
+ resolve(message);
+ } else {
+ this.connection.sendMqttMessage(JSON.stringify(message));
+ }
+ }
+ });
+
+ this.wsClient.on('error', (error) => {
+ console.error(`WebSocket error for device ${this.macAddress}:`, error);
+ this.emit('close');
+ reject(error);
+ });
+
+ this.wsClient.on('close', () => {
+ this.emit('close');
+ });
+ });
+ }
+
+ sendJson(message) {
+ if (this.wsClient && this.wsClient.readyState === WebSocket.OPEN) {
+ this.wsClient.send(JSON.stringify(message));
+ }
+ }
+
+ sendAudio(opus, timestamp) {
+ if (this.wsClient && this.wsClient.readyState === WebSocket.OPEN) {
+ const buffer = Buffer.alloc(16 + opus.length);
+ buffer.writeUInt32BE(timestamp, 8);
+ buffer.writeUInt32BE(opus.length, 12);
+ buffer.set(opus, 16);
+ this.wsClient.send(buffer, { binary: true });
+ }
+ }
+
+ isAlive() {
+ return this.wsClient && this.wsClient.readyState === WebSocket.OPEN;
+ }
+
+ close() {
+ if (this.wsClient) {
+ this.wsClient.close();
+ this.wsClient = null;
+ }
+ }
+}
+
+const MacAddressRegex = /^[0-9a-f]{2}(:[0-9a-f]{2}){5}$/;
+
+/**
+ * MQTT连接类
+ * 负责应用层逻辑处理
+ */
+class MQTTConnection {
+ constructor(socket, connectionId, server) {
+ this.server = server;
+ this.connectionId = connectionId;
+ this.clientId = null;
+ this.username = null;
+ this.password = null;
+ this.bridge = null;
+ this.udp = {
+ remoteAddress: null,
+ cookie: null,
+ localSequence: 0,
+ remoteSequence: 0
+ };
+ this.headerBuffer = Buffer.alloc(16);
+
+ // 创建协议处理器,并传入socket
+ this.protocol = new MQTTProtocol(socket);
+
+ this.setupProtocolHandlers();
+ }
+
+ setupProtocolHandlers() {
+ // 设置协议事件处理
+ this.protocol.on('connect', (connectData) => {
+ this.handleConnect(connectData);
+ });
+
+ this.protocol.on('publish', (publishData) => {
+ this.handlePublish(publishData);
+ });
+
+ this.protocol.on('subscribe', (subscribeData) => {
+ this.handleSubscribe(subscribeData);
+ });
+
+ this.protocol.on('disconnect', () => {
+ this.handleDisconnect();
+ });
+
+ this.protocol.on('close', () => {
+ debug(`${this.clientId} 客户端断开连接`);
+ this.server.removeConnection(this);
+ });
+
+ this.protocol.on('error', (err) => {
+ debug(`${this.clientId} 连接错误:`, err);
+ this.close();
+ });
+
+ this.protocol.on('protocolError', (err) => {
+ debug(`${this.clientId} 协议错误:`, err);
+ this.close();
+ });
+ }
+
+ handleConnect(connectData) {
+ this.clientId = connectData.clientId;
+ this.username = connectData.username;
+ this.password = connectData.password;
+
+ debug('客户端连接:', {
+ clientId: this.clientId,
+ username: this.username,
+ password: this.password,
+ protocol: connectData.protocol,
+ protocolLevel: connectData.protocolLevel,
+ keepAlive: connectData.keepAlive
+ });
+
+ const parts = this.clientId.split('@@@');
+ if (parts.length === 3) { // GID_test@@@mac_address@@@uuid
+ try {
+ const validated = validateMqttCredentials(this.clientId, this.username, this.password);
+ this.groupId = validated.groupId;
+ this.macAddress = validated.macAddress;
+ this.uuid = validated.uuid;
+ this.userData = validated.userData;
+ } catch (error) {
+ debug('MQTT凭据验证失败:', error.message);
+ this.close();
+ return;
+ }
+ } else if (parts.length === 2) { // GID_test@@@mac_address
+ this.groupId = parts[0];
+ this.macAddress = parts[1].replace(/_/g, ':');
+ if (!MacAddressRegex.test(this.macAddress)) {
+ debug('无效的 macAddress:', this.macAddress);
+ this.close();
+ return;
+ }
+ } else {
+ debug('无效的 clientId:', this.clientId);
+ this.close();
+ return;
+ }
+ this.replyTo = `devices/p2p/${parts[1]}`;
+
+ this.server.addConnection(this);
+ }
+
+ handleSubscribe(subscribeData) {
+ debug('客户端订阅主题:', {
+ clientId: this.clientId,
+ topic: subscribeData.topic,
+ packetId: subscribeData.packetId
+ });
+
+ // 发送 SUBACK
+ this.protocol.sendSuback(subscribeData.packetId, 0);
+ }
+
+ handleDisconnect() {
+ debug('收到断开连接请求:', { clientId: this.clientId });
+ // 清理连接
+ this.server.removeConnection(this);
+ }
+
+ close() {
+ this.closing = true;
+ if (this.bridge) {
+ this.bridge.close();
+ this.bridge = null;
+ } else {
+ this.protocol.close();
+ }
+ }
+
+ checkKeepAlive() {
+ const now = Date.now();
+ const keepAliveInterval = this.protocol.getKeepAliveInterval();
+
+ // 如果keepAliveInterval为0,表示不需要心跳检查
+ if (keepAliveInterval === 0 || !this.protocol.isConnected) return;
+
+ const lastActivity = this.protocol.getLastActivity();
+ const timeSinceLastActivity = now - lastActivity;
+
+ // 如果超过心跳间隔,关闭连接
+ if (timeSinceLastActivity > keepAliveInterval) {
+ debug('心跳超时,关闭连接:', this.clientId);
+ this.close();
+ }
+ }
+
+ handlePublish(publishData) {
+ debug('收到发布消息:', {
+ clientId: this.clientId,
+ topic: publishData.topic,
+ payload: publishData.payload,
+ qos: publishData.qos
+ });
+
+ if (publishData.qos !== 0) {
+ debug('不支持的 QoS 级别:', publishData.qos, '关闭连接');
+ this.close();
+ return;
+ }
+
+ const json = JSON.parse(publishData.payload);
+ if (json.type === 'hello') {
+ if (json.version !== 3) {
+ debug('不支持的协议版本:', json.version, '关闭连接');
+ this.close();
+ return;
+ }
+ this.parseHelloMessage(json).catch(error => {
+ debug('处理 hello 消息失败:', error);
+ this.close();
+ });
+ } else {
+ this.parseOtherMessage(json).catch(error => {
+ debug('处理其他消息失败:', error);
+ this.close();
+ });
+ }
+ }
+
+ sendMqttMessage(payload) {
+ debug(`发送消息到 ${this.replyTo}: ${payload}`);
+ this.protocol.sendPublish(this.replyTo, payload, 0, false, false);
+ }
+
+ sendUdpMessage(payload, timestamp) {
+ if (!this.udp.remoteAddress) {
+ debug(`设备 ${this.clientId} 未连接,无法发送 UDP 消息`);
+ return;
+ }
+ this.udp.localSequence++;
+ const header = this.generateUdpHeader(payload.length, timestamp, this.udp.localSequence);
+ const cipher = crypto.createCipheriv(this.udp.encryption, this.udp.key, header);
+ const message = Buffer.concat([header, cipher.update(payload), cipher.final()]);
+ this.server.sendUdpMessage(message, this.udp.remoteAddress);
+ }
+
+ generateUdpHeader(length, timestamp, sequence) {
+ // 重用预分配的缓冲区
+ this.headerBuffer.writeUInt8(1, 0);
+ this.headerBuffer.writeUInt16BE(length, 2);
+ this.headerBuffer.writeUInt32BE(this.connectionId, 4);
+ this.headerBuffer.writeUInt32BE(timestamp, 8);
+ this.headerBuffer.writeUInt32BE(sequence, 12);
+ return Buffer.from(this.headerBuffer); // 返回副本以避免并发问题
+ }
+
+ async parseHelloMessage(json) {
+ this.udp = {
+ ...this.udp,
+ key: crypto.randomBytes(16),
+ nonce: this.generateUdpHeader(0, 0, 0),
+ encryption: 'aes-128-ctr',
+ remoteSequence: 0,
+ localSequence: 0,
+ startTime: Date.now()
+ }
+
+ if (this.bridge) {
+ debug(`${this.clientId} 收到重复 hello 消息,关闭之前的 bridge`);
+ this.bridge.close();
+ await new Promise(resolve => setTimeout(resolve, 100));
+ }
+ this.bridge = new WebSocketBridge(this, json.version, this.macAddress, this.uuid, this.userData);
+ this.bridge.on('close', () => {
+ const seconds = (Date.now() - this.udp.startTime) / 1000;
+ console.log(`通话结束: ${this.clientId} Session: ${this.udp.session_id} Duration: ${seconds}s`);
+ this.sendMqttMessage(JSON.stringify({ type: 'goodbye', session_id: this.udp.session_id }));
+ this.bridge = null;
+ if (this.closing) {
+ this.protocol.close();
+ }
+ });
+
+ try {
+ console.log(`通话开始: ${this.clientId} Protocol: ${json.version} ${this.bridge.chatServer}`);
+ const helloReply = await this.bridge.connect(json.audio_params, json.features);
+ this.udp.session_id = helloReply.session_id;
+ this.sendMqttMessage(JSON.stringify({
+ type: 'hello',
+ version: json.version,
+ session_id: this.udp.session_id,
+ transport: 'udp',
+ udp: {
+ server: this.server.publicIp,
+ port: this.server.udpPort,
+ encryption: this.udp.encryption,
+ key: this.udp.key.toString('hex'),
+ nonce: this.udp.nonce.toString('hex'),
+ },
+ audio_params: helloReply.audio_params
+ }));
+ } catch (error) {
+ this.sendMqttMessage(JSON.stringify({ type: 'error', message: '处理 hello 消息失败' }));
+ console.error(`${this.clientId} 处理 hello 消息失败: ${error}`);
+ }
+ }
+
+ async parseOtherMessage(json) {
+ if (!this.bridge) {
+ if (json.type !== 'goodbye') {
+ this.sendMqttMessage(JSON.stringify({ type: 'goodbye', session_id: json.session_id }));
+ }
+ return;
+ }
+
+ if (json.type === 'goodbye') {
+ this.bridge.close();
+ this.bridge = null;
+ return;
+ }
+
+ this.bridge.sendJson(json);
+ }
+
+ onUdpMessage(rinfo, message, payloadLength, timestamp, sequence) {
+ if (!this.bridge) {
+ return;
+ }
+ if (this.udp.remoteAddress !== rinfo) {
+ this.udp.remoteAddress = rinfo;
+ }
+ if (sequence < this.udp.remoteSequence) {
+ return;
+ }
+
+ // 处理加密数据
+ const header = message.slice(0, 16);
+ const encryptedPayload = message.slice(16, 16 + payloadLength);
+ const cipher = crypto.createDecipheriv(this.udp.encryption, this.udp.key, header);
+ const payload = Buffer.concat([cipher.update(encryptedPayload), cipher.final()]);
+
+ this.bridge.sendAudio(payload, timestamp);
+ this.udp.remoteSequence = sequence;
+ }
+
+ isAlive() {
+ return this.bridge && this.bridge.isAlive();
+ }
+}
+
+class MQTTServer {
+ constructor() {
+ this.mqttPort = parseInt(process.env.MQTT_PORT) || 1883;
+ this.udpPort = parseInt(process.env.UDP_PORT) || this.mqttPort;
+ this.publicIp = process.env.PUBLIC_IP || 'mqtt.xiaozhi.me';
+ this.connections = new Map(); // clientId -> MQTTConnection
+ this.keepAliveTimer = null;
+ this.keepAliveCheckInterval = 1000; // 默认每1秒检查一次
+
+ this.headerBuffer = Buffer.alloc(16);
+ }
+
+ generateNewConnectionId() {
+ // 生成一个32位不重复的整数
+ let id;
+ do {
+ id = Math.floor(Math.random() * 0xFFFFFFFF);
+ } while (this.connections.has(id));
+ return id;
+ }
+
+ start() {
+ this.mqttServer = net.createServer((socket) => {
+ const connectionId = this.generateNewConnectionId();
+ debug(`新客户端连接: ${connectionId}`);
+ new MQTTConnection(socket, connectionId, this);
+ });
+
+ this.mqttServer.listen(this.mqttPort, () => {
+ console.warn(`MQTT 服务器正在监听端口 ${this.mqttPort}`);
+ });
+
+
+ this.udpServer = dgram.createSocket('udp4');
+ this.udpServer.on('message', this.onUdpMessage.bind(this));
+ this.udpServer.on('error', err => {
+ console.error('UDP 错误', err);
+ setTimeout(() => { process.exit(1); }, 1000);
+ });
+ this.udpServer.bind(this.udpPort, () => {
+ console.warn(`UDP 服务器正在监听 ${this.publicIp}:${this.udpPort}`);
+ });
+
+ // 启动全局心跳检查定时器
+ this.setupKeepAliveTimer();
+ }
+
+ /**
+ * 设置全局心跳检查定时器
+ */
+ setupKeepAliveTimer() {
+ // 清除现有定时器
+ this.clearKeepAliveTimer();
+ this.lastConnectionCount = 0;
+ this.lastActiveConnectionCount = 0;
+
+ // 设置新的定时器
+ this.keepAliveTimer = setInterval(() => {
+ // 检查所有连接的心跳状态
+ for (const connection of this.connections.values()) {
+ connection.checkKeepAlive();
+ }
+
+ const activeCount = Array.from(this.connections.values()).filter(connection => connection.isAlive()).length;
+ if (activeCount !== this.lastActiveConnectionCount || this.connections.size !== this.lastConnectionCount) {
+ console.log(`连接数: ${this.connections.size}, 活跃数: ${activeCount}`);
+ this.lastActiveConnectionCount = activeCount;
+ this.lastConnectionCount = this.connections.size;
+ }
+ }, this.keepAliveCheckInterval);
+ }
+
+ /**
+ * 清除心跳检查定时器
+ */
+ clearKeepAliveTimer() {
+ if (this.keepAliveTimer) {
+ clearInterval(this.keepAliveTimer);
+ this.keepAliveTimer = null;
+ }
+ }
+
+ addConnection(connection) {
+ // 检查是否已存在相同 clientId 的连接
+ for (const [key, value] of this.connections.entries()) {
+ if (value.clientId === connection.clientId) {
+ debug(`${connection.clientId} 已存在连接,关闭旧连接`);
+ value.close();
+ }
+ }
+ this.connections.set(connection.connectionId, connection);
+ }
+
+ removeConnection(connection) {
+ debug(`关闭连接: ${connection.connectionId}`);
+ if (this.connections.has(connection.connectionId)) {
+ this.connections.delete(connection.connectionId);
+ }
+ }
+
+ sendUdpMessage(message, remoteAddress) {
+ this.udpServer.send(message, remoteAddress.port, remoteAddress.address);
+ }
+
+ onUdpMessage(message, rinfo) {
+ // message format: [type: 1u, flag: 1u, payloadLength: 2u, cookie: 4u, timestamp: 4u, sequence: 4u, payload: n]
+ if (message.length < 16) {
+ console.warn('收到不完整的 UDP Header', rinfo);
+ return;
+ }
+
+ try {
+ const type = message.readUInt8(0);
+ if (type !== 1) return;
+
+ const payloadLength = message.readUInt16BE(2);
+ if (message.length < 16 + payloadLength) return;
+
+ const connectionId = message.readUInt32BE(4);
+ const connection = this.connections.get(connectionId);
+ if (!connection) return;
+
+ const timestamp = message.readUInt32BE(8);
+ const sequence = message.readUInt32BE(12);
+
+ connection.onUdpMessage(rinfo, message, payloadLength, timestamp, sequence);
+ } catch (error) {
+ console.error('UDP 消息处理错误:', error);
+ }
+ }
+
+ /**
+ * 停止服务器
+ */
+ async stop() {
+ if (this.stopping) {
+ return;
+ }
+ this.stopping = true;
+ // 清除心跳检查定时器
+ this.clearKeepAliveTimer();
+
+ if (this.connections.size > 0) {
+ console.warn(`等待 ${this.connections.size} 个连接关闭`);
+ for (const connection of this.connections.values()) {
+ connection.close();
+ }
+ await new Promise(resolve => setTimeout(resolve, 300));
+ debug('等待连接关闭完成');
+ this.connections.clear();
+ }
+
+ if (this.udpServer) {
+ this.udpServer.close();
+ this.udpServer = null;
+ console.warn('UDP 服务器已停止');
+ }
+
+ // 关闭MQTT服务器
+ if (this.mqttServer) {
+ this.mqttServer.close();
+ this.mqttServer = null;
+ console.warn('MQTT 服务器已停止');
+ }
+
+ process.exit(0);
+ }
+}
+
+// 创建并启动服务器
+const server = new MQTTServer();
+server.start();
+process.on('SIGINT', () => {
+ console.warn('收到 SIGINT 信号,开始关闭');
+ server.stop();
+});
diff --git a/main/mqtt-gateway/config/mqtt.json.example b/main/mqtt-gateway/config/mqtt.json.example
new file mode 100644
index 000000000..05c6b9b58
--- /dev/null
+++ b/main/mqtt-gateway/config/mqtt.json.example
@@ -0,0 +1,15 @@
+{
+ "production": {
+ "chat_servers": [
+ "ws://example:8080"
+ ]
+ },
+ "development": {
+ "chat_servers": [
+ "ws://example:8180"
+ ],
+ "mac_addresss": [
+ ]
+ },
+ "debug": false
+}
diff --git a/main/mqtt-gateway/config/mqtt.json.test b/main/mqtt-gateway/config/mqtt.json.test
new file mode 100644
index 000000000..d4680a20a
--- /dev/null
+++ b/main/mqtt-gateway/config/mqtt.json.test
@@ -0,0 +1,12 @@
+{
+ "production": {
+ "chat_servers": [
+ "ws://192.168.68.66:8000/xiaozhi/v1/"
+ ]
+ },
+ "development": {
+ "chat_servers": ["ws://192.168.68.66:8000/xiaozhi/v1/"],
+ "mac_addresss": ["d8:43:ae:3e:4b:5a"]
+ },
+ "debug": false
+}
diff --git a/main/mqtt-gateway/ecosystem.config.js b/main/mqtt-gateway/ecosystem.config.js
new file mode 100644
index 000000000..a3d9edb47
--- /dev/null
+++ b/main/mqtt-gateway/ecosystem.config.js
@@ -0,0 +1,9 @@
+module.exports = {
+ "apps": [
+ {
+ "name": "xz-mqtt",
+ "script": "app.js",
+ "time": true
+ }
+ ]
+}
diff --git a/main/mqtt-gateway/generate_signature_key.js b/main/mqtt-gateway/generate_signature_key.js
new file mode 100644
index 000000000..89aa9a266
--- /dev/null
+++ b/main/mqtt-gateway/generate_signature_key.js
@@ -0,0 +1,81 @@
+#!/usr/bin/env node
+/**
+ * MQTT签名密钥生成器
+ * 用于生成MQTT_SIGNATURE_KEY环境变量
+ */
+
+const crypto = require('crypto');
+
+function generateSecureKey(length = 32) {
+ // 生成随机字节
+ const randomBytes = crypto.randomBytes(length);
+
+ // 转换为base64字符串
+ const base64Key = randomBytes.toString('base64');
+
+ return base64Key;
+}
+
+function generateHexKey(length = 32) {
+ // 生成随机字节
+ const randomBytes = crypto.randomBytes(length);
+
+ // 转换为十六进制字符串
+ const hexKey = randomBytes.toString('hex');
+
+ return hexKey;
+}
+
+function generateUUIDKey() {
+ // 使用UUID v4作为密钥
+ const uuid = crypto.randomUUID();
+ return uuid;
+}
+
+console.log('='.repeat(60));
+console.log('MQTT签名密钥生成器');
+console.log('='.repeat(60));
+
+console.log('\n1. Base64格式密钥 (推荐):');
+const base64Key = generateSecureKey();
+console.log(` ${base64Key}`);
+
+console.log('\n2. 十六进制格式密钥:');
+const hexKey = generateHexKey();
+console.log(` ${hexKey}`);
+
+console.log('\n3. UUID格式密钥:');
+const uuidKey = generateUUIDKey();
+console.log(` ${uuidKey}`);
+
+console.log('\n='.repeat(60));
+console.log('使用方法:');
+console.log('='.repeat(60));
+console.log('\n在Windows PowerShell中设置环境变量:');
+console.log(`$env:MQTT_SIGNATURE_KEY="${base64Key}"`);
+
+console.log('\n在Windows CMD中设置环境变量:');
+console.log(`set MQTT_SIGNATURE_KEY=${base64Key}`);
+
+console.log('\n在Linux/macOS中设置环境变量:');
+console.log(`export MQTT_SIGNATURE_KEY="${base64Key}"`);
+
+console.log('\n在.env文件中设置:');
+console.log(`MQTT_SIGNATURE_KEY=${base64Key}`);
+
+console.log('\n='.repeat(60));
+console.log('注意事项:');
+console.log('='.repeat(60));
+console.log('1. 请妥善保管生成的密钥,不要泄露给他人');
+console.log('2. 在生产环境中,建议使用更长的密钥 (64字节)');
+console.log('3. 密钥设置后需要重启MQTT服务器才能生效');
+console.log('4. 客户端连接时需要使用相同的密钥生成密码签名');
+
+// 如果提供了命令行参数,生成指定长度的密钥
+if (process.argv[2]) {
+ const customLength = parseInt(process.argv[2]);
+ if (customLength > 0) {
+ console.log(`\n自定义长度密钥 (${customLength}字节):`);
+ console.log(` ${generateSecureKey(customLength)}`);
+ }
+}
\ No newline at end of file
diff --git a/main/mqtt-gateway/mqtt-protocol.js b/main/mqtt-gateway/mqtt-protocol.js
new file mode 100644
index 000000000..09ba8a20f
--- /dev/null
+++ b/main/mqtt-gateway/mqtt-protocol.js
@@ -0,0 +1,499 @@
+const debug = require('debug')('mqtt-server');
+const EventEmitter = require('events');
+
+// MQTT 固定头部的类型
+const PacketType = {
+ CONNECT: 1,
+ CONNACK: 2,
+ PUBLISH: 3,
+ SUBSCRIBE: 8,
+ SUBACK: 9,
+ PINGREQ: 12,
+ PINGRESP: 13,
+ DISCONNECT: 14 // 添加 DISCONNECT
+};
+
+/**
+ * MQTT协议处理类
+ * 负责MQTT协议的解析和封装,以及心跳维持
+ */
+class MQTTProtocol extends EventEmitter {
+ constructor(socket) {
+ super();
+ this.socket = socket;
+ this.buffer = Buffer.alloc(0);
+ this.isConnected = false;
+ this.keepAliveInterval = 0;
+ this.lastActivity = Date.now();
+
+ this.setupSocketHandlers();
+ }
+
+ /**
+ * 设置Socket事件处理
+ */
+ setupSocketHandlers() {
+ this.socket.on('data', (data) => {
+ this.lastActivity = Date.now();
+ this.buffer = Buffer.concat([this.buffer, data]);
+ this.processBuffer();
+ });
+
+ this.socket.on('close', () => {
+ this.emit('close');
+ });
+
+ this.socket.on('error', (err) => {
+ this.emit('error', err);
+ });
+ }
+
+ /**
+ * 处理缓冲区中的所有完整消息
+ */
+ processBuffer() {
+ // 持续处理缓冲区中的数据,直到没有完整的消息可以处理
+ while (this.buffer.length > 0) {
+ // 至少需要2个字节才能开始解析(1字节固定头部 + 至少1字节的剩余长度)
+ if (this.buffer.length < 2) return;
+
+ try {
+ // 获取消息类型
+ const firstByte = this.buffer[0];
+ const type = (firstByte >> 4);
+
+ // 解析剩余长度
+ const { value: remainingLength, bytesRead } = this.decodeRemainingLength(this.buffer);
+
+ // 计算整个消息的长度
+ const messageLength = 1 + bytesRead + remainingLength;
+
+ // 检查缓冲区中是否有完整的消息
+ if (this.buffer.length < messageLength) {
+ // 消息不完整,等待更多数据
+ return;
+ }
+
+ // 提取完整的消息
+ const message = this.buffer.subarray(0, messageLength);
+ if (!this.isConnected && type !== PacketType.CONNECT) {
+ debug('未连接时收到非CONNECT消息,关闭连接');
+ this.socket.end();
+ return;
+ }
+
+ // 根据消息类型处理
+ switch (type) {
+ case PacketType.CONNECT:
+ this.parseConnect(message);
+ break;
+ case PacketType.PUBLISH:
+ this.parsePublish(message);
+ break;
+ case PacketType.SUBSCRIBE:
+ this.parseSubscribe(message);
+ break;
+ case PacketType.PINGREQ:
+ this.parsePingReq(message);
+ break;
+ case PacketType.DISCONNECT:
+ this.parseDisconnect(message);
+ break;
+ default:
+ debug('未处理的包类型:', type, message);
+ this.emit('protocolError', new Error(`未处理的包类型: ${type}`));
+ }
+
+ // 从缓冲区中移除已处理的消息
+ this.buffer = this.buffer.subarray(messageLength);
+
+ } catch (err) {
+ // 如果解析出错,可能是数据不完整,等待更多数据
+ if (err.message === 'Malformed Remaining Length') {
+ return;
+ }
+ // 其他错误可能是协议错误,清空缓冲区并发出错误事件
+ this.buffer = Buffer.alloc(0);
+ this.emit('protocolError', err);
+ return;
+ }
+ }
+ }
+
+ /**
+ * 解析MQTT报文中的Remaining Length字段
+ * @param {Buffer} buffer - 消息缓冲区
+ * @returns {{value: number, bytesRead: number}} 包含解析的值和读取的字节数
+ */
+ decodeRemainingLength(buffer) {
+ let multiplier = 1;
+ let value = 0;
+ let bytesRead = 0;
+ let digit;
+
+ do {
+ if (bytesRead >= 4 || bytesRead >= buffer.length - 1) {
+ throw new Error('Malformed Remaining Length');
+ }
+
+ digit = buffer[bytesRead + 1];
+ bytesRead++;
+
+ value += (digit & 127) * multiplier;
+ multiplier *= 128;
+
+ } while ((digit & 128) !== 0);
+
+ return { value, bytesRead };
+ }
+
+ /**
+ * 编码MQTT报文中的Remaining Length字段
+ * @param {number} length - 要编码的长度值
+ * @returns {{bytes: Buffer, bytesLength: number}} 包含编码后的字节和字节长度
+ */
+ encodeRemainingLength(length) {
+ let digit;
+ const bytes = Buffer.alloc(4); // 最多4个字节
+ let bytesLength = 0;
+
+ do {
+ digit = length % 128;
+ length = Math.floor(length / 128);
+ // 如果还有更多字节,设置最高位
+ if (length > 0) {
+ digit |= 0x80;
+ }
+ bytes[bytesLength++] = digit;
+ } while (length > 0 && bytesLength < 4);
+
+ return { bytes, bytesLength };
+ }
+
+ /**
+ * 解析CONNECT消息
+ * @param {Buffer} message - 完整的CONNECT消息
+ */
+ parseConnect(message) {
+ // 解析剩余长度
+ const { value: remainingLength, bytesRead } = this.decodeRemainingLength(message);
+
+ // 固定头部之后的位置 (MQTT固定头部第一个字节 + Remaining Length字段的字节)
+ const headerLength = 1 + bytesRead;
+
+ // 从可变头部开始位置读取协议名长度
+ const protocolLength = message.readUInt16BE(headerLength);
+ const protocol = message.toString('utf8', headerLength + 2, headerLength + 2 + protocolLength);
+
+ // 更新位置指针,跳过协议名
+ let pos = headerLength + 2 + protocolLength;
+
+ // 协议级别,4为MQTT 3.1.1
+ const protocolLevel = message[pos];
+
+ // 检查协议版本
+ if (protocolLevel !== 4) { // 4 表示 MQTT 3.1.1
+ debug('不支持的协议版本:', protocolLevel);
+ // 发送 CONNACK,使用不支持的协议版本的返回码 (0x01)
+ this.sendConnack(1, false);
+ // 关闭连接
+ this.socket.end();
+ return;
+ }
+
+ pos += 1;
+
+ // 连接标志
+ const connectFlags = message[pos];
+ const hasUsername = (connectFlags & 0x80) !== 0;
+ const hasPassword = (connectFlags & 0x40) !== 0;
+ const cleanSession = (connectFlags & 0x02) !== 0;
+ pos += 1;
+
+ // 保持连接时间
+ const keepAlive = message.readUInt16BE(pos);
+ pos += 2;
+
+ // 解析 clientId
+ const clientIdLength = message.readUInt16BE(pos);
+ pos += 2;
+ const clientId = message.toString('utf8', pos, pos + clientIdLength);
+ pos += clientIdLength;
+
+ // 解析 username(如果存在)
+ let username = '';
+ if (hasUsername) {
+ const usernameLength = message.readUInt16BE(pos);
+ pos += 2;
+ username = message.toString('utf8', pos, pos + usernameLength);
+ pos += usernameLength;
+ }
+
+ // 解析 password(如果存在)
+ let password = '';
+ if (hasPassword) {
+ const passwordLength = message.readUInt16BE(pos);
+ pos += 2;
+ password = message.toString('utf8', pos, pos + passwordLength);
+ pos += passwordLength;
+ }
+
+ // 设置心跳间隔(客户端指定的keepAlive值的1.5倍,单位为秒)
+ this.keepAliveInterval = keepAlive * 1000 * 1.5;
+
+ // 发送 CONNACK
+ this.sendConnack(0, false);
+
+ // 标记为已连接
+ this.isConnected = true;
+
+ // 发出连接事件
+ this.emit('connect', {
+ clientId,
+ protocol,
+ protocolLevel,
+ keepAlive,
+ username,
+ password,
+ cleanSession
+ });
+ }
+
+ /**
+ * 解析PUBLISH消息
+ * @param {Buffer} message - 完整的PUBLISH消息
+ */
+ parsePublish(message) {
+ // 从第一个字节中提取QoS级别(bits 1-2)
+ const firstByte = message[0];
+ const qos = (firstByte & 0x06) >> 1; // 0x06 是二进制 00000110,用于掩码提取QoS位
+ const dup = (firstByte & 0x08) !== 0; // 0x08 是二进制 00001000,用于掩码提取DUP标志
+ const retain = (firstByte & 0x01) !== 0; // 0x01 是二进制 00000001,用于掩码提取RETAIN标志
+
+ // 使用通用方法解析剩余长度
+ const { value: remainingLength, bytesRead } = this.decodeRemainingLength(message);
+
+ // 固定头部之后的位置 (MQTT固定头部第一个字节 + Remaining Length字段的字节)
+ const headerLength = 1 + bytesRead;
+
+ // 解析主题
+ const topicLength = message.readUInt16BE(headerLength);
+ const topic = message.toString('utf8', headerLength + 2, headerLength + 2 + topicLength);
+
+ // 对于QoS > 0,包含消息ID
+ let packetId = null;
+ let payloadStart = headerLength + 2 + topicLength;
+
+ if (qos > 0) {
+ packetId = message.readUInt16BE(payloadStart);
+ payloadStart += 2;
+ }
+
+ // 解析有效载荷
+ const payload = message.slice(payloadStart).toString('utf8');
+
+ // 发出发布事件
+ this.emit('publish', {
+ topic,
+ payload,
+ qos,
+ dup,
+ retain,
+ packetId
+ });
+ }
+
+ /**
+ * 解析SUBSCRIBE消息
+ * @param {Buffer} message - 完整的SUBSCRIBE消息
+ */
+ parseSubscribe(message) {
+ const packetId = message.readUInt16BE(2);
+ const topicLength = message.readUInt16BE(4);
+ const topic = message.toString('utf8', 6, 6 + topicLength);
+ const qos = message[6 + topicLength]; // QoS值
+
+ // 发出订阅事件
+ this.emit('subscribe', {
+ packetId,
+ topic,
+ qos
+ });
+ }
+
+ /**
+ * 解析PINGREQ消息
+ * @param {Buffer} message - 完整的PINGREQ消息
+ */
+ parsePingReq(message) {
+ debug('收到心跳请求');
+
+ // 发送 PINGRESP
+ this.sendPingResp();
+
+ debug('已发送心跳响应');
+ }
+
+ /**
+ * 解析DISCONNECT消息
+ * @param {Buffer} message - 完整的DISCONNECT消息
+ */
+ parseDisconnect(message) {
+ // 标记为未连接
+ this.isConnected = false;
+
+ // 发出断开连接事件
+ this.emit('disconnect');
+
+ // 关闭 socket
+ this.socket.end();
+ }
+
+ /**
+ * 发送CONNACK消息
+ * @param {number} returnCode - 返回码
+ * @param {boolean} sessionPresent - 会话存在标志
+ */
+ sendConnack(returnCode = 0, sessionPresent = false) {
+ if (!this.socket.writable) return;
+
+ const packet = Buffer.from([
+ PacketType.CONNACK << 4,
+ 2, // Remaining length
+ sessionPresent ? 1 : 0, // Connect acknowledge flags
+ returnCode // Return code
+ ]);
+
+ this.socket.write(packet);
+ }
+
+ /**
+ * 发送PUBLISH消息
+ * @param {string} topic - 主题
+ * @param {string} payload - 有效载荷
+ * @param {number} qos - QoS级别
+ * @param {boolean} dup - 重复标志
+ * @param {boolean} retain - 保留标志
+ * @param {number} packetId - 包ID(仅QoS > 0时需要)
+ */
+ sendPublish(topic, payload, qos = 0, dup = false, retain = false, packetId = null) {
+ if (!this.isConnected || !this.socket.writable) return;
+
+ const topicLength = Buffer.byteLength(topic);
+ const payloadLength = Buffer.byteLength(payload);
+
+ // 计算剩余长度
+ let remainingLength = 2 + topicLength + payloadLength;
+
+ // 如果QoS > 0,需要包含包ID
+ if (qos > 0 && packetId) {
+ remainingLength += 2;
+ }
+
+ // 编码可变长度
+ const { bytes: remainingLengthBytes, bytesLength: remainingLengthSize } = this.encodeRemainingLength(remainingLength);
+
+ // 分配缓冲区:固定头部(1字节) + 可变长度字段 + 剩余长度值
+ const packet = Buffer.alloc(1 + remainingLengthSize + remainingLength);
+
+ // 写入固定头部
+ let firstByte = PacketType.PUBLISH << 4;
+ if (dup) firstByte |= 0x08;
+ if (qos > 0) firstByte |= (qos << 1);
+ if (retain) firstByte |= 0x01;
+
+ packet[0] = firstByte;
+
+ // 写入可变长度字段
+ remainingLengthBytes.copy(packet, 1, 0, remainingLengthSize);
+
+ // 写入主题长度和主题
+ const variableHeaderStart = 1 + remainingLengthSize;
+ packet.writeUInt16BE(topicLength, variableHeaderStart);
+ packet.write(topic, variableHeaderStart + 2);
+
+ // 如果QoS > 0,写入包ID
+ let payloadStart = variableHeaderStart + 2 + topicLength;
+ if (qos > 0 && packetId) {
+ packet.writeUInt16BE(packetId, payloadStart);
+ payloadStart += 2;
+ }
+
+ // 写入有效载荷
+ packet.write(payload, payloadStart);
+
+ this.socket.write(packet);
+ this.lastActivity = Date.now();
+ }
+
+ /**
+ * 发送SUBACK消息
+ * @param {number} packetId - 包ID
+ * @param {number} returnCode - 返回码
+ */
+ sendSuback(packetId, returnCode = 0) {
+ if (!this.isConnected || !this.socket.writable) return;
+
+ const packet = Buffer.from([
+ PacketType.SUBACK << 4,
+ 3, // Remaining length
+ packetId >> 8, // Packet ID MSB
+ packetId & 0xFF, // Packet ID LSB
+ returnCode // Return code
+ ]);
+
+ this.socket.write(packet);
+ this.lastActivity = Date.now();
+ }
+
+ /**
+ * 发送PINGRESP消息
+ */
+ sendPingResp() {
+ if (!this.isConnected || !this.socket.writable) return;
+
+ const packet = Buffer.from([
+ PacketType.PINGRESP << 4, // Fixed header
+ 0 // Remaining length
+ ]);
+
+ this.socket.write(packet);
+ this.lastActivity = Date.now();
+ }
+
+ /**
+ * 获取上次活动时间
+ */
+ getLastActivity() {
+ return this.lastActivity;
+ }
+
+ /**
+ * 获取心跳间隔
+ */
+ getKeepAliveInterval() {
+ return this.keepAliveInterval;
+ }
+
+ /**
+ * 清空缓冲区
+ */
+ clearBuffer() {
+ this.buffer = Buffer.alloc(0);
+ }
+
+ /**
+ * 关闭连接
+ */
+ close() {
+ if (this.socket.writable) {
+ this.socket.end();
+ }
+ }
+}
+
+// 导出 PacketType 和 MQTTProtocol 类
+module.exports = {
+ PacketType,
+ MQTTProtocol
+};
\ No newline at end of file
diff --git a/main/mqtt-gateway/utils/config-manager.js b/main/mqtt-gateway/utils/config-manager.js
new file mode 100644
index 000000000..59d3c6614
--- /dev/null
+++ b/main/mqtt-gateway/utils/config-manager.js
@@ -0,0 +1,78 @@
+const fs = require('fs');
+const path = require('path');
+const EventEmitter = require('events');
+
+class ConfigManager extends EventEmitter {
+ constructor(fileName) {
+ super();
+ this.config = {}; // 移除默认的 apiKeys 配置
+ this.configPath = path.join(__dirname, "..", "config", fileName);
+ this.loadConfig();
+ this.watchConfig();
+ // 添加防抖计时器变量
+ this.watchDebounceTimer = null;
+ }
+
+ loadConfig() {
+ try {
+ const data = fs.readFileSync(this.configPath, 'utf8');
+ const newConfig = JSON.parse(data);
+
+ // 检测配置是否发生变化
+ if (JSON.stringify(this.config) !== JSON.stringify(newConfig)) {
+ console.log('配置已更新', this.configPath);
+ this.config = newConfig;
+ // 发出配置更新事件
+ this.emit('configChanged', this.config);
+ }
+ } catch (error) {
+ console.error('加载配置出错:', error, this.configPath);
+ if (error.code === 'ENOENT') {
+ this.createEmptyConfig();
+ }
+ }
+ }
+
+ createEmptyConfig() {
+ try {
+ const dir = path.dirname(this.configPath);
+ if (!fs.existsSync(dir)) {
+ fs.mkdirSync(dir, { recursive: true });
+ }
+ const defaultConfig = {}; // 空配置对象
+ fs.writeFileSync(this.configPath, JSON.stringify(defaultConfig, null, 2));
+ console.log('已创建空配置文件', this.configPath);
+ } catch (error) {
+ console.error('创建空配置文件出错:', error, this.configPath);
+ }
+ }
+
+ watchConfig() {
+ fs.watch(path.dirname(this.configPath), (eventType, filename) => {
+ if (filename === path.basename(this.configPath) && eventType === 'change') {
+ // 清除之前的计时器
+ if (this.watchDebounceTimer) {
+ clearTimeout(this.watchDebounceTimer);
+ }
+ // 设置新的计时器,300ms 后执行
+ this.watchDebounceTimer = setTimeout(() => {
+ this.loadConfig();
+ }, 300);
+ }
+ });
+ }
+
+ // 获取配置的方法
+ getConfig() {
+ return this.config;
+ }
+
+ // 获取特定配置项的方法
+ get(key) {
+ return this.config[key];
+ }
+}
+
+module.exports = {
+ ConfigManager
+};
\ No newline at end of file
diff --git a/main/mqtt-gateway/utils/mqtt_config_v2.js b/main/mqtt-gateway/utils/mqtt_config_v2.js
new file mode 100644
index 000000000..0fecd459f
--- /dev/null
+++ b/main/mqtt-gateway/utils/mqtt_config_v2.js
@@ -0,0 +1,103 @@
+require('dotenv').config();
+const crypto = require('crypto');
+
+
+function generatePasswordSignature(content, secretKey) {
+ // Create an HMAC object using SHA256 and the secretKey
+ const hmac = crypto.createHmac('sha256', secretKey);
+
+ // Update the HMAC object with the clientId
+ hmac.update(content);
+
+ // Generate the HMAC digest in binary format
+ const binarySignature = hmac.digest();
+
+ // Encode the binary signature to Base64
+ const base64Signature = binarySignature.toString('base64');
+
+ return base64Signature;
+}
+
+function validateMqttCredentials(clientId, username, password) {
+ // 验证密码签名
+ const signatureKey = process.env.MQTT_SIGNATURE_KEY;
+ if (signatureKey) {
+ const expectedSignature = generatePasswordSignature(clientId + '|' + username, signatureKey);
+ if (password !== expectedSignature) {
+ throw new Error('密码签名验证失败');
+ }
+ } else {
+ console.warn('缺少MQTT_SIGNATURE_KEY环境变量,跳过密码签名验证');
+ }
+
+ // 验证clientId
+ if (!clientId || typeof clientId !== 'string') {
+ throw new Error('clientId必须是非空字符串');
+ }
+
+ // 验证clientId格式(必须包含@@@分隔符)
+ const clientIdParts = clientId.split('@@@');
+ // 新版本 MQTT 参数
+ if (clientIdParts.length !== 3) {
+ throw new Error('clientId格式错误,必须包含@@@分隔符');
+ }
+
+ // 验证username
+ if (!username || typeof username !== 'string') {
+ throw new Error('username必须是非空字符串');
+ }
+
+ // 尝试解码username(应该是base64编码的JSON)
+ let userData;
+ try {
+ const decodedUsername = Buffer.from(username, 'base64').toString();
+ userData = JSON.parse(decodedUsername);
+ } catch (error) {
+ throw new Error('username不是有效的base64编码JSON');
+ }
+
+ // 解析clientId中的信息
+ const [groupId, macAddress, uuid] = clientIdParts;
+
+ // 如果验证成功,返回解析后的有用信息
+ return {
+ groupId,
+ macAddress: macAddress.replace(/_/g, ':'),
+ uuid,
+ userData
+ };
+}
+
+function generateMqttConfig(groupId, macAddress, uuid, userData) {
+ const endpoint = process.env.MQTT_ENDPOINT;
+ const signatureKey = process.env.MQTT_SIGNATURE_KEY;
+ if (!signatureKey) {
+ console.warn('No signature key, skip generating MQTT config');
+ return;
+ }
+ const deviceIdNoColon = macAddress.replace(/:/g, '_');
+ const clientId = `${groupId}@@@${deviceIdNoColon}@@@${uuid}`;
+ const username = Buffer.from(JSON.stringify(userData)).toString('base64');
+ const password = generatePasswordSignature(clientId + '|' + username, signatureKey);
+ return {
+ endpoint,
+ port: 8883,
+ client_id: clientId,
+ username,
+ password,
+ publish_topic: 'device-server',
+ subscribe_topic: 'null' // 旧版本固件不返回此字段会出错
+ }
+}
+
+module.exports = {
+ generateMqttConfig,
+ validateMqttCredentials
+}
+
+if (require.main === module) {
+ const config = generateMqttConfig('GID_test', '11:22:33:44:55:66', '36c98363-3656-43cb-a00f-8bced2391a90', { ip: '222.222.222.222' });
+ console.log('config', config);
+ const credentials = validateMqttCredentials(config.client_id, config.username, config.password);
+ console.log('credentials', credentials);
+}
diff --git a/main/mqtt-gateway/测试说明.md b/main/mqtt-gateway/测试说明.md
new file mode 100644
index 000000000..202147295
--- /dev/null
+++ b/main/mqtt-gateway/测试说明.md
@@ -0,0 +1,239 @@
+# MQTT网关转发功能测试指南
+
+本文档说明如何测试MQTT网关的转发功能是否配置成功。
+
+## 快速测试
+
+### 1. 基础连接测试
+
+运行快速测试脚本:
+
+```bash
+node quick-test.js
+```
+
+这个脚本会:
+- ✅ 检查配置文件
+- ✅ 测试MQTT服务器连接(端口1883)
+- ✅ 测试WebSocket后端服务连接
+- ✅ 显示测试结果和建议
+
+### 2. 完整功能测试
+
+运行完整测试脚本:
+
+```bash
+node test-mqtt.js
+```
+
+这个脚本会:
+- 🔗 连接到MQTT服务器
+- 🔐 使用配置的MAC地址进行认证
+- 📝 订阅回复主题
+- 📤 发送hello消息测试WebSocket转发
+- 📥 等待并显示服务器响应
+- 🧪 发送其他测试消息
+
+## 手动测试步骤
+
+### 1. 启动MQTT网关
+
+```bash
+node app.js
+```
+
+应该看到类似输出:
+```
+MQTT 服务器启动在端口 1883
+UDP 服务器启动在端口 1883
+连接数: 0, 活跃数: 0
+```
+
+### 2. 检查配置文件
+
+确认 `config/mqtt.json` 配置正确:
+
+```json
+{
+ "production": {
+ "chat_servers": [
+ "ws://192.168.68.66:8000/xiaozhi/v1/"
+ ]
+ },
+ "development": {
+ "chat_servers": ["ws://192.168.68.66:8000/xiaozhi/v1/"],
+ "mac_addresss": ["d8:43:ae:3e:4b:5a"]
+ },
+ "debug": false
+}
+```
+
+### 3. 使用MQTT客户端工具测试
+
+#### 使用mosquitto客户端:
+
+**连接测试:**
+```bash
+mosquitto_pub -h localhost -p 1883 -t "test/topic" -m "hello"
+```
+
+**订阅测试:**
+```bash
+mosquitto_sub -h localhost -p 1883 -t "devices/p2p/d8_43_ae_3e_4b_5a"
+```
+
+#### 使用MQTT.fx或其他GUI工具:
+
+1. **连接设置:**
+ - 服务器:localhost
+ - 端口:1883
+ - 客户端ID:`GID_test@@@d8_43_ae_3e_4b_5a`
+ - 用户名:test_user
+ - 密码:test_password
+
+2. **发布测试消息:**
+ - 主题:`test/topic`
+ - 消息:
+ ```json
+ {
+ "type": "hello",
+ "version": 3,
+ "transport": "mqtt",
+ "audio_params": {
+ "sample_rate": 16000,
+ "channels": 1,
+ "format": "opus"
+ },
+ "features": ["tts", "asr"]
+ }
+ ```
+
+3. **订阅回复主题:**
+ - 主题:`devices/p2p/d8_43_ae_3e_4b_5a`
+
+## 测试结果判断
+
+### ✅ 成功指标
+
+1. **MQTT连接成功:**
+ ```
+ ✓ 成功连接到MQTT服务器 localhost:1883
+ ✓ MQTT连接成功
+ ```
+
+2. **WebSocket转发成功:**
+ ```
+ ✓ WebSocket服务器连接成功
+ ✓ 收到PUBLISH消息
+ ```
+
+3. **服务器日志正常:**
+ ```
+ 客户端连接: { clientId: 'GID_test@@@d8_43_ae_3e_4b_5a', ... }
+ 收到发布消息: { topic: 'test/topic', payload: '...', qos: 0 }
+ ```
+
+### ❌ 常见问题
+
+1. **MQTT服务器连接失败:**
+ ```
+ ✗ 连接错误: connect ECONNREFUSED 127.0.0.1:1883
+ ```
+ **解决方案:** 确保运行 `node app.js` 启动MQTT网关
+
+2. **WebSocket连接失败:**
+ ```
+ ✗ WebSocket服务器连接失败: connect ECONNREFUSED
+ ```
+ **解决方案:** 检查WebSocket后端服务是否运行,网络是否可达
+
+3. **认证失败:**
+ ```
+ 无效的 clientId: xxx
+ ```
+ **解决方案:** 检查客户端ID格式是否为 `GID_test@@@mac_address`
+
+4. **MAC地址不匹配:**
+ ```
+ 未找到 xx:xx:xx:xx:xx:xx 的聊天服务器
+ ```
+ **解决方案:** 确认MAC地址在配置文件的 `mac_addresss` 列表中
+
+## 调试技巧
+
+### 1. 开启调试模式
+
+修改 `config/mqtt.json`:
+```json
+{
+ "debug": true
+}
+```
+
+或设置环境变量:
+```bash
+DEBUG=mqtt-server node app.js
+```
+
+### 2. 查看详细日志
+
+调试模式下会显示详细的连接和消息处理信息:
+```
+mqtt-server 客户端连接: { clientId: '...', username: '...', ... }
+mqtt-server 收到发布消息: { topic: '...', payload: '...', qos: 0 }
+mqtt-server 发送消息到 devices/p2p/...: {...}
+```
+
+### 3. 网络连通性测试
+
+**测试WebSocket服务器:**
+```bash
+curl -I http://192.168.68.66:8000/xiaozhi/v1/
+```
+
+**测试MQTT端口:**
+```bash
+telnet localhost 1883
+```
+
+## 性能测试
+
+### 并发连接测试
+
+可以修改测试脚本创建多个并发连接:
+
+```javascript
+// 创建多个测试客户端
+const clients = [];
+for (let i = 0; i < 10; i++) {
+ const client = new MQTTTestClient();
+ clients.push(client);
+ // 连接和测试...
+}
+```
+
+### 消息吞吐量测试
+
+发送大量消息测试转发性能:
+
+```javascript
+// 发送100条消息
+for (let i = 0; i < 100; i++) {
+ client.publish('test/topic', `测试消息 ${i}`);
+}
+```
+
+## 故障排除清单
+
+- [ ] MQTT网关服务是否运行 (`node app.js`)
+- [ ] 端口1883是否被占用
+- [ ] 配置文件格式是否正确
+- [ ] WebSocket后端服务是否运行
+- [ ] 网络连接是否正常
+- [ ] MAC地址是否在配置的白名单中
+- [ ] 客户端ID格式是否正确
+- [ ] 防火墙是否阻止连接
+
+## 总结
+
+通过以上测试方法,你可以全面验证MQTT网关的转发功能是否配置成功。建议先运行快速测试,如果有问题再进行详细的手动测试和调试。
\ No newline at end of file
From 5f96f5657476070931c4aeee1111a014213e9217 Mon Sep 17 00:00:00 2001
From: marlonz <235833017@qq.com>
Date: Sat, 5 Jul 2025 13:50:47 +0930
Subject: [PATCH 006/366] remove gitignore
---
main/mqtt-gateway/.gitignore | 4 ----
1 file changed, 4 deletions(-)
delete mode 100644 main/mqtt-gateway/.gitignore
diff --git a/main/mqtt-gateway/.gitignore b/main/mqtt-gateway/.gitignore
deleted file mode 100644
index 71b7ebc22..000000000
--- a/main/mqtt-gateway/.gitignore
+++ /dev/null
@@ -1,4 +0,0 @@
-node_modules/
-build/
-dist/
-package-lock.json
From eed95033916756362a9764f6e980100fb50b5500 Mon Sep 17 00:00:00 2001
From: FAN-yeB <1442100690@qq.com>
Date: Mon, 8 Sep 2025 11:04:42 +0800
Subject: [PATCH 007/366] mqtt
---
.../xiaozhi/common/constant/Constant.java | 6 ++
.../device/controller/OTAController.java | 4 +
.../device/dto/DeviceReportRespDTO.java | 22 ++++-
.../service/impl/DeviceServiceImpl.java | 92 ++++++++++++++++++-
.../resources/db/changelog/202509080921.sql | 7 ++
.../resources/db/changelog/202509080927.sql | 2 +
.../db/changelog/db.changelog-master.yaml | 16 ++++
main/xiaozhi-server/core/connection.py | 82 +++++++++++++++++
.../core/handle/receiveAudioHandle.py | 34 +++----
.../core/handle/sendAudioHandle.py | 50 ++++++++--
.../xiaozhi-server/core/providers/tts/base.py | 3 +-
11 files changed, 290 insertions(+), 28 deletions(-)
create mode 100644 main/manager-api/src/main/resources/db/changelog/202509080921.sql
create mode 100644 main/manager-api/src/main/resources/db/changelog/202509080927.sql
diff --git a/main/manager-api/src/main/java/xiaozhi/common/constant/Constant.java b/main/manager-api/src/main/java/xiaozhi/common/constant/Constant.java
index afd7addf5..6d4e7ef0d 100644
--- a/main/manager-api/src/main/java/xiaozhi/common/constant/Constant.java
+++ b/main/manager-api/src/main/java/xiaozhi/common/constant/Constant.java
@@ -91,6 +91,12 @@ public interface Constant {
*/
String SERVER_WEBSOCKET = "server.websocket";
+ /**
+ * mqtt gateway 配置
+ */
+ String SERVER_MQTT_GATEWAY = "server.mqtt_gateway";
+
+
/**
* ota地址
*/
diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/controller/OTAController.java b/main/manager-api/src/main/java/xiaozhi/modules/device/controller/OTAController.java
index 023510cd1..26e5dbe64 100644
--- a/main/manager-api/src/main/java/xiaozhi/modules/device/controller/OTAController.java
+++ b/main/manager-api/src/main/java/xiaozhi/modules/device/controller/OTAController.java
@@ -77,6 +77,10 @@ public class OTAController {
@GetMapping
@Hidden
public ResponseEntity getOTA() {
+ String mqttUdpConfig = sysParamsService.getValue(Constant.SERVER_MQTT_GATEWAY, false);
+ if(StringUtils.isBlank(mqttUdpConfig)) {
+ return ResponseEntity.ok("OTA接口不正常,缺少mqtt_gateway地址,请登录智控台,在参数管理找到【server.mqtt_gateway】配置");
+ }
String wsUrl = sysParamsService.getValue(Constant.SERVER_WEBSOCKET, true);
if (StringUtils.isBlank(wsUrl) || wsUrl.equals("null")) {
return ResponseEntity.ok("OTA接口不正常,缺少websocket地址,请登录智控台,在参数管理找到【server.websocket】配置");
diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceReportRespDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceReportRespDTO.java
index f938001e0..423868ca1 100644
--- a/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceReportRespDTO.java
+++ b/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceReportRespDTO.java
@@ -23,6 +23,9 @@ public class DeviceReportRespDTO {
@Schema(description = "WebSocket配置")
private Websocket websocket;
+ @Schema(description = "MQTT Gateway配置")
+ private MQTT mqtt;
+
@Getter
@Setter
public static class Firmware {
@@ -70,4 +73,21 @@ public class DeviceReportRespDTO {
@Schema(description = "WebSocket服务器地址")
private String url;
}
-}
+
+ @Getter
+ @Setter
+ public static class MQTT {
+ @Schema(description = "MQTT 配置网址")
+ private String endpoint;
+ @Schema(description = "MQTT 客户端唯一标识符")
+ private String client_id;
+ @Schema(description = "MQTT 认证用户名")
+ private String username;
+ @Schema(description = "MQTT 认证密码")
+ private String password;
+ @Schema(description = "ESP32 发布消息的主题")
+ private String publish_topic;
+ @Schema(description = "ESP32 订阅的主题")
+ private String subscribe_topic;
+ }
+}
\ No newline at end of file
diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java
index 3cff111db..eeacce9a2 100644
--- a/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java
+++ b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java
@@ -1,12 +1,16 @@
package xiaozhi.modules.device.service.impl;
+import java.nio.charset.StandardCharsets;
import java.time.Instant;
+import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.UUID;
+import javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.lang3.StringUtils;
import org.springframework.aop.framework.AopContext;
@@ -175,7 +179,22 @@ public class DeviceServiceImpl extends BaseServiceImpl
}
response.setWebsocket(websocket);
-
+
+ // 添加MQTT UDP配置
+ // 从系统参数获取MQTT Gateway地址,如果未配置不使用默认值
+ String mqttUdpConfig = sysParamsService.getValue(Constant.SERVER_MQTT_GATEWAY, false);
+ if(!StringUtils.isBlank(mqttUdpConfig) && deviceById != null) {
+ try {
+ DeviceReportRespDTO.MQTT mqtt = buildMqttConfig(macAddress, clientId, deviceById);
+ if (mqtt != null) {
+ mqtt.setEndpoint(mqttUdpConfig);
+ response.setMqtt(mqtt);
+ }
+ } catch (Exception e) {
+ log.error("生成MQTT配置失败: {}", e.getMessage());
+ }
+ }
+
if (deviceById != null) {
// 如果设备存在,则异步更新上次连接时间和版本信息
String appVersion = deviceReport.getApplication() != null ? deviceReport.getApplication().getVersion()
@@ -437,4 +456,75 @@ public class DeviceServiceImpl extends BaseServiceImpl
entity.setAutoUpdate(1);
baseDao.insert(entity);
}
+
+ /**
+ * 生成MQTT密码签名
+ * @param content 签名内容 (clientId + '|' + username)
+ * @param secretKey 密钥
+ * @return Base64编码的HMAC-SHA256签名
+ */
+ private String generatePasswordSignature(String content, String secretKey) throws Exception {
+ Mac hmac = Mac.getInstance("HmacSHA256");
+ SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
+ hmac.init(keySpec);
+ byte[] signature = hmac.doFinal(content.getBytes(StandardCharsets.UTF_8));
+ return Base64.getEncoder().encodeToString(signature);
+ }
+
+ /**
+ * 构建MQTT配置信息
+ * @param macAddress MAC地址
+ * @param clientId 客户端ID (UUID)
+ * @param device 设备信息
+ * @return MQTT配置对象
+ */
+ private DeviceReportRespDTO.MQTT buildMqttConfig(String macAddress, String clientId, DeviceEntity device) throws Exception {
+ // 从环境变量或系统参数获取签名密钥
+ String signatureKey = System.getenv("MQTT_SIGNATURE_KEY");
+ if (StringUtils.isBlank(signatureKey)) {
+ // 如果环境变量没有,尝试从系统参数获取
+ signatureKey = sysParamsService.getValue("mqtt.signature_key", false);
+ }
+
+ if (StringUtils.isBlank(signatureKey)) {
+ log.warn("缺少MQTT_SIGNATURE_KEY,跳过MQTT配置生成");
+ return null;
+ }
+
+ // 构建客户端ID格式:groupId@@@macAddress_without_colon@@@uuid
+ String groupId = device.getBoard() != null ? device.getBoard() : "GID_default";
+ String deviceIdNoColon = macAddress.replace(":", "_");
+ String mqttClientId = String.format("%s@@@%s@@@%s", groupId, deviceIdNoColon, clientId);
+
+ // 构建用户数据(包含IP等信息)
+ Map userData = new HashMap<>();
+ // 尝试获取客户端IP
+ try {
+ ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
+ if (attributes != null) {
+ HttpServletRequest request = attributes.getRequest();
+ String clientIp = request.getRemoteAddr();
+ userData.put("ip", clientIp);
+ }
+ } catch (Exception e) {
+ userData.put("ip", "unknown");
+ }
+
+ // 将用户数据编码为Base64 JSON
+ String userDataJson = new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(userData);
+ String username = Base64.getEncoder().encodeToString(userDataJson.getBytes(StandardCharsets.UTF_8));
+
+ // 生成密码签名
+ String password = generatePasswordSignature(mqttClientId + "|" + username, signatureKey);
+
+ // 构建MQTT配置
+ DeviceReportRespDTO.MQTT mqtt = new DeviceReportRespDTO.MQTT();
+ mqtt.setClient_id(mqttClientId);
+ mqtt.setUsername(username);
+ mqtt.setPassword(password);
+ mqtt.setPublish_topic("device-server");
+ mqtt.setSubscribe_topic("devices/p2p/" + deviceIdNoColon);
+
+ return mqtt;
+ }
}
diff --git a/main/manager-api/src/main/resources/db/changelog/202509080921.sql b/main/manager-api/src/main/resources/db/changelog/202509080921.sql
new file mode 100644
index 000000000..4d89ee57d
--- /dev/null
+++ b/main/manager-api/src/main/resources/db/changelog/202509080921.sql
@@ -0,0 +1,7 @@
+delete from `sys_params` where id = 108;
+delete from `sys_params` where param_code = 'server.mqtt_gateway';
+INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (108, 'server.mqtt_gateway', 'null', 'string', 1, 'mqtt gateway 配置');
+
+delete from `sys_params` where param_code = 'server.udp_gateway';
+INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (109, 'server.udp_gateway', 'null', 'string', 1, 'udp gateway 配置');
+
diff --git a/main/manager-api/src/main/resources/db/changelog/202509080927.sql b/main/manager-api/src/main/resources/db/changelog/202509080927.sql
new file mode 100644
index 000000000..4741af88e
--- /dev/null
+++ b/main/manager-api/src/main/resources/db/changelog/202509080927.sql
@@ -0,0 +1,2 @@
+delete from `sys_params` where param_code = 'mqtt.signature_key';
+INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (120, 'mqtt.signature_key', 'null', 'string', 1, 'mqtt 密钥 配置');
diff --git a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml
index 0e8d3dc35..ed66ebb78 100755
--- a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml
+++ b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml
@@ -303,3 +303,19 @@ databaseChangeLog:
- sqlFile:
encoding: utf8
path: classpath:db/changelog/202508131557.sql
+
+ - changeSet:
+ id: 202509080921
+ author: fan
+ changes:
+ - sqlFile:
+ encoding: utf8
+ path: classpath:db/changelog/202509080921.sql
+
+ - changeSet:
+ id: 202509080927
+ author: fan
+ changes:
+ - sqlFile:
+ encoding: utf8
+ path: classpath:db/changelog/202509080927.sql
\ No newline at end of file
diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py
index 4b3b9d1cc..3e6e8633b 100644
--- a/main/xiaozhi-server/core/connection.py
+++ b/main/xiaozhi-server/core/connection.py
@@ -281,8 +281,86 @@ class ConnectionHandler:
return
if self.asr is None:
return
+
+
+ if len(message) >= 16:
+ try:
+ timestamp = int.from_bytes(message[8:12], 'big')
+ audio_length = int.from_bytes(message[12:16], 'big')
+
+
+ # 提取音频数据
+ if audio_length > 0 and len(message) >= 16 + audio_length:
+ audio_data = message[16:16 + audio_length]
+
+ # 基于时间戳进行简单排序
+ self._process_websocket_audio(audio_data, timestamp)
+ return
+ elif len(message) > 16:
+ # 去掉16字节头部
+ audio_data = message[16:]
+ self.asr_audio_queue.put(audio_data)
+ return
+ except Exception as e:
+ self.logger.bind(tag=TAG).error(f"解析WebSocket音频包失败: {e}")
+
self.asr_audio_queue.put(message)
+ def _process_websocket_audio(self, audio_data, timestamp):
+ """处理WebSocket格式的音频包"""
+ # 初始化时间戳序列管理
+ if not hasattr(self, 'audio_timestamp_buffer'):
+ self.audio_timestamp_buffer = {}
+ self.last_processed_timestamp = 0
+ self.max_timestamp_buffer_size = 20
+
+ # 如果时间戳是递增的,直接处理
+ if timestamp >= self.last_processed_timestamp:
+ self.asr_audio_queue.put(audio_data)
+ self.last_processed_timestamp = timestamp
+
+ # 处理缓冲区中的后续包
+ processed_any = True
+ while processed_any:
+ processed_any = False
+ for ts in sorted(self.audio_timestamp_buffer.keys()):
+ if ts > self.last_processed_timestamp:
+ buffered_audio = self.audio_timestamp_buffer.pop(ts)
+ self.asr_audio_queue.put(buffered_audio)
+ self.last_processed_timestamp = ts
+ processed_any = True
+ break
+ else:
+ # 乱序包,暂存
+ if len(self.audio_timestamp_buffer) < self.max_timestamp_buffer_size:
+ self.audio_timestamp_buffer[timestamp] = audio_data
+ else:
+ self.asr_audio_queue.put(audio_data)
+
+ def _process_sequenced_audio(self, audio_data, sequence, timestamp):
+ """处理有序的音频包"""
+ # 初始化音频缓冲区
+ if not hasattr(self, 'audio_buffer'):
+ self.audio_buffer = {}
+ self.expected_sequence = sequence
+ self.max_buffer_size = 20 # 最大缓冲20个包
+
+ # 如果是下一个期望的包,直接处理
+ if sequence == self.expected_sequence:
+ self.asr_audio_queue.put(audio_data)
+ self.expected_sequence += 1
+
+ # 检查缓冲区中是否有后续的连续包
+ while self.expected_sequence in self.audio_buffer:
+ buffered_audio = self.audio_buffer.pop(self.expected_sequence)
+ self.asr_audio_queue.put(buffered_audio)
+ self.expected_sequence += 1
+
+ elif sequence > self.expected_sequence:
+ # 乱序包,暂存到缓冲区
+ if len(self.audio_buffer) < self.max_buffer_size:
+ self.audio_buffer[sequence] = audio_data
+
async def handle_restart(self, message):
"""处理服务器重启请求"""
try:
@@ -921,6 +999,10 @@ class ConnectionHandler:
async def close(self, ws=None):
"""资源清理方法"""
try:
+ # 清理音频缓冲区
+ if hasattr(self, 'audio_buffer'):
+ self.audio_buffer.clear()
+
# 取消超时任务
if self.timeout_task and not self.timeout_task.done():
self.timeout_task.cancel()
diff --git a/main/xiaozhi-server/core/handle/receiveAudioHandle.py b/main/xiaozhi-server/core/handle/receiveAudioHandle.py
index 8db506338..e6f396327 100644
--- a/main/xiaozhi-server/core/handle/receiveAudioHandle.py
+++ b/main/xiaozhi-server/core/handle/receiveAudioHandle.py
@@ -1,11 +1,12 @@
-import time
-import json
-import asyncio
-from core.utils.util import audio_to_data
-from core.handle.abortHandle import handleAbortMessage
+from core.handle.sendAudioHandle import send_stt_message
from core.handle.intentHandler import handle_user_intent
from core.utils.output_counter import check_device_output_limit
-from core.handle.sendAudioHandle import send_stt_message, SentenceType
+from core.handle.abortHandle import handleAbortMessage
+import time
+import asyncio
+import json
+from core.handle.sendAudioHandle import SentenceType
+from core.utils.util import audio_to_data
TAG = __name__
@@ -21,6 +22,7 @@ async def handleAudioMessage(conn, audio):
if not hasattr(conn, "vad_resume_task") or conn.vad_resume_task.done():
conn.vad_resume_task = asyncio.create_task(resume_vad_detection(conn))
return
+
if have_voice:
if conn.client_is_speaking:
await handleAbortMessage(conn)
@@ -29,16 +31,18 @@ async def handleAudioMessage(conn, audio):
# 接收音频
await conn.asr.receive_audio(conn, audio, have_voice)
+
async def resume_vad_detection(conn):
# 等待2秒后恢复VAD检测
await asyncio.sleep(1)
conn.just_woken_up = False
+
async def startToChat(conn, text):
# 检查输入是否是JSON格式(包含说话人信息)
speaker_name = None
actual_text = text
-
+
try:
# 尝试解析JSON格式的输入
if text.strip().startswith('{') and text.strip().endswith('}'):
@@ -47,13 +51,13 @@ async def startToChat(conn, text):
speaker_name = data['speaker']
actual_text = data['content']
conn.logger.bind(tag=TAG).info(f"解析到说话人信息: {speaker_name}")
-
+
# 直接使用JSON格式的文本,不解析
actual_text = text
except (json.JSONDecodeError, KeyError):
# 如果解析失败,继续使用原始文本
pass
-
+
# 保存说话人信息到连接对象
if speaker_name:
conn.current_speaker = speaker_name
@@ -114,12 +118,10 @@ async def no_voice_close_connect(conn, have_voice):
async def max_out_size(conn):
- # 播放超出最大输出字数的提示
- conn.client_abort = False
text = "不好意思,我现在有点事情要忙,明天这个时候我们再聊,约好了哦!明天不见不散,拜拜!"
await send_stt_message(conn, text)
file_path = "config/assets/max_output_size.wav"
- opus_packets = audio_to_data(file_path)
+ opus_packets, _ = audio_to_data(file_path)
conn.tts.tts_audio_queue.put((SentenceType.LAST, opus_packets, text))
conn.close_after_chat = True
@@ -138,7 +140,7 @@ async def check_bind_device(conn):
# 播放提示音
music_path = "config/assets/bind_code.wav"
- opus_packets = audio_to_data(music_path)
+ opus_packets, _ = audio_to_data(music_path)
conn.tts.tts_audio_queue.put((SentenceType.FIRST, opus_packets, text))
# 逐个播放数字
@@ -146,17 +148,15 @@ async def check_bind_device(conn):
try:
digit = conn.bind_code[i]
num_path = f"config/assets/bind_code/{digit}.wav"
- num_packets = audio_to_data(num_path)
+ num_packets, _ = audio_to_data(num_path)
conn.tts.tts_audio_queue.put((SentenceType.MIDDLE, num_packets, None))
except Exception as e:
conn.logger.bind(tag=TAG).error(f"播放数字音频失败: {e}")
continue
conn.tts.tts_audio_queue.put((SentenceType.LAST, [], None))
else:
- # 播放未绑定提示
- conn.client_abort = False
text = f"没有找到该设备的版本信息,请正确配置 OTA地址,然后重新编译固件。"
await send_stt_message(conn, text)
music_path = "config/assets/bind_not_found.wav"
- opus_packets = audio_to_data(music_path)
+ opus_packets, _ = audio_to_data(music_path)
conn.tts.tts_audio_queue.put((SentenceType.LAST, opus_packets, text))
diff --git a/main/xiaozhi-server/core/handle/sendAudioHandle.py b/main/xiaozhi-server/core/handle/sendAudioHandle.py
index 661c4e212..c8a05ded3 100644
--- a/main/xiaozhi-server/core/handle/sendAudioHandle.py
+++ b/main/xiaozhi-server/core/handle/sendAudioHandle.py
@@ -55,6 +55,7 @@ async def sendAudio(conn, audios, frame_duration=60):
"last_send_time": 0,
"packet_count": 0,
"start_time": time.perf_counter(),
+ "sequence": 0, # 添加序列号
}
flow_control = conn.audio_flow_control
@@ -67,11 +68,22 @@ async def sendAudio(conn, audios, frame_duration=60):
if delay > 0:
await asyncio.sleep(delay)
- # 发送数据包
- await conn.websocket.send(audios)
+ # 为opus数据包添加16字节头部
+ timestamp = int((flow_control["start_time"] + flow_control["packet_count"] * frame_duration / 1000) * 1000) % (2**32)
+ header = bytearray(16)
+ header[0] = 1 # type
+ header[2:4] = len(audios).to_bytes(2, 'big') # payload length
+ header[4:8] = flow_control["sequence"].to_bytes(4, 'big') # connection id/sequence
+ header[8:12] = timestamp.to_bytes(4, 'big') # 时间戳
+ header[12:16] = len(audios).to_bytes(4, 'big') # opus长度
+
+ # 发送包含头部的完整数据包
+ complete_packet = bytes(header) + audios
+ await conn.websocket.send(complete_packet)
# 更新流控状态
flow_control["packet_count"] += 1
+ flow_control["sequence"] += 1
flow_control["last_send_time"] = time.perf_counter()
else:
# 文件型音频走普通播放
@@ -81,11 +93,21 @@ async def sendAudio(conn, audios, frame_duration=60):
# 执行预缓冲
pre_buffer_frames = min(3, len(audios))
for i in range(pre_buffer_frames):
- await conn.websocket.send(audios[i])
+ # 为预缓冲包添加头部
+ timestamp = int((start_time + i * frame_duration / 1000) * 1000) % (2**32)
+ header = bytearray(16)
+ header[0] = 1 # type
+ header[2:4] = len(audios[i]).to_bytes(2, 'big') # payload length
+ header[4:8] = i.to_bytes(4, 'big') # sequence
+ header[8:12] = timestamp.to_bytes(4, 'big') # 时间戳
+ header[12:16] = len(audios[i]).to_bytes(4, 'big') # opus长度
+
+ complete_packet = bytes(header) + audios[i]
+ await conn.websocket.send(complete_packet)
remaining_audios = audios[pre_buffer_frames:]
-
+
# 播放剩余音频帧
- for opus_packet in remaining_audios:
+ for i, opus_packet in enumerate(remaining_audios):
if conn.client_abort:
break
@@ -98,9 +120,21 @@ async def sendAudio(conn, audios, frame_duration=60):
delay = expected_time - current_time
if delay > 0:
await asyncio.sleep(delay)
-
- await conn.websocket.send(opus_packet)
-
+
+ # 为opus数据包添加16字节头部 (timestamp at offset 8, length at offset 12)
+ timestamp = int((start_time + play_position / 1000) * 1000) % (2**32) # 使用播放位置计算时间戳
+ sequence = pre_buffer_frames + i # 确保序列号连续
+ header = bytearray(16)
+ header[0] = 1 # type
+ header[2:4] = len(opus_packet).to_bytes(2, 'big') # payload length
+ header[4:8] = sequence.to_bytes(4, 'big') # sequence
+ header[8:12] = timestamp.to_bytes(4, 'big') # 时间戳在第8-11字节
+ header[12:16] = len(opus_packet).to_bytes(4, 'big') # opus长度在第12-15字节
+
+ # 发送包含头部的完整数据包
+ complete_packet = bytes(header) + opus_packet
+ await conn.websocket.send(complete_packet)
+
play_position += frame_duration
diff --git a/main/xiaozhi-server/core/providers/tts/base.py b/main/xiaozhi-server/core/providers/tts/base.py
index 04a7fa360..c4b323551 100644
--- a/main/xiaozhi-server/core/providers/tts/base.py
+++ b/main/xiaozhi-server/core/providers/tts/base.py
@@ -336,7 +336,8 @@ class TTSProviderBase(ABC):
self.conn.audio_flow_control = {
'last_send_time': 0,
'packet_count': 0,
- 'start_time': time.perf_counter()
+ 'start_time': time.perf_counter(),
+ 'sequence': 0 # 添加序列号
}
# 上报TTS数据
From eee907b1a23156d712f2c282cbade8faf65de38e Mon Sep 17 00:00:00 2001
From: FAN-yeB <1442100690@qq.com>
Date: Tue, 9 Sep 2025 09:37:31 +0800
Subject: [PATCH 008/366] =?UTF-8?q?=E5=85=BC=E5=AE=B9udp=E5=92=8Cwebsocket?=
=?UTF-8?q?=E5=8D=8F=E8=AE=AE=E4=BC=A0=E8=BE=93=E9=9F=B3=E9=A2=91?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../service/impl/DeviceServiceImpl.java | 4 +-
main/xiaozhi-server/config.yaml | 2 +
main/xiaozhi-server/core/connection.py | 12 ++-
.../core/handle/sendAudioHandle.py | 94 ++++++++++++-------
4 files changed, 73 insertions(+), 39 deletions(-)
diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java
index eeacce9a2..b4343276d 100644
--- a/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java
+++ b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java
@@ -181,9 +181,9 @@ public class DeviceServiceImpl extends BaseServiceImpl
response.setWebsocket(websocket);
// 添加MQTT UDP配置
- // 从系统参数获取MQTT Gateway地址,如果未配置不使用默认值
+ // 从系统参数获取MQTT Gateway地址,仅在配置有效时使用
String mqttUdpConfig = sysParamsService.getValue(Constant.SERVER_MQTT_GATEWAY, false);
- if(!StringUtils.isBlank(mqttUdpConfig) && deviceById != null) {
+ if(mqttUdpConfig != null && !mqttUdpConfig.equals("null") && !mqttUdpConfig.isEmpty() && deviceById != null) {
try {
DeviceReportRespDTO.MQTT mqtt = buildMqttConfig(macAddress, clientId, deviceById);
if (mqtt != null) {
diff --git a/main/xiaozhi-server/config.yaml b/main/xiaozhi-server/config.yaml
index c0aa3f934..1afc3530b 100644
--- a/main/xiaozhi-server/config.yaml
+++ b/main/xiaozhi-server/config.yaml
@@ -25,6 +25,8 @@ server:
# 所以如果你使用docker部署时,将vision_explain设置成局域网地址
# 如果你使用公网部署时,将vision_explain设置成公网地址
vision_explain: http://你的ip或者域名:端口号/mcp/vision/explain
+ # mqtt网关地址,当这个值为null时,mqtt网关桥接功能不开启,使用websocket双向通信,不使用mqtt和udp协议
+ mqtt_gateway: null
# OTA返回信息时区偏移量
timezone_offset: +8
# 认证配置
diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py
index 3e6e8633b..e23826a11 100644
--- a/main/xiaozhi-server/core/connection.py
+++ b/main/xiaozhi-server/core/connection.py
@@ -282,8 +282,17 @@ class ConnectionHandler:
if self.asr is None:
return
+ # 检查是否需要处理头部(只有当mqtt_gateway有实际值时才处理头部)
+ mqtt_gateway = self.config.get("server", {}).get("mqtt_gateway")
+ # 当mqtt_gateway为None, "null", "", 或实际的null值时,不处理头部
+ need_header_processing = mqtt_gateway and mqtt_gateway not in [None, "null", ""] and str(mqtt_gateway).strip() != ""
+
+ # 调试日志:首次连接时记录配置
+ if not hasattr(self, '_logged_mqtt_config'):
+ self.logger.bind(tag=TAG).info(f"MQTT Gateway配置: '{mqtt_gateway}', 头部处理: {need_header_processing}")
+ self._logged_mqtt_config = True
- if len(message) >= 16:
+ if need_header_processing and len(message) >= 16:
try:
timestamp = int.from_bytes(message[8:12], 'big')
audio_length = int.from_bytes(message[12:16], 'big')
@@ -304,6 +313,7 @@ class ConnectionHandler:
except Exception as e:
self.logger.bind(tag=TAG).error(f"解析WebSocket音频包失败: {e}")
+ # 不需要头部处理或没有头部时,直接处理原始消息
self.asr_audio_queue.put(message)
def _process_websocket_audio(self, audio_data, timestamp):
diff --git a/main/xiaozhi-server/core/handle/sendAudioHandle.py b/main/xiaozhi-server/core/handle/sendAudioHandle.py
index c8a05ded3..56d219322 100644
--- a/main/xiaozhi-server/core/handle/sendAudioHandle.py
+++ b/main/xiaozhi-server/core/handle/sendAudioHandle.py
@@ -43,6 +43,11 @@ async def sendAudio(conn, audios, frame_duration=60):
if audios is None or len(audios) == 0:
return
+ # 检查是否需要添加头部(只有当mqtt_gateway有实际值时才添加头部)
+ mqtt_gateway = conn.config.get("server", {}).get("mqtt_gateway")
+ # 当mqtt_gateway为None, "null", "", 或实际的null值时,不添加头部
+ need_header = mqtt_gateway and mqtt_gateway not in [None, "null", ""] and str(mqtt_gateway).strip() != ""
+
if isinstance(audios, bytes):
if conn.client_abort:
return
@@ -68,18 +73,22 @@ async def sendAudio(conn, audios, frame_duration=60):
if delay > 0:
await asyncio.sleep(delay)
- # 为opus数据包添加16字节头部
- timestamp = int((flow_control["start_time"] + flow_control["packet_count"] * frame_duration / 1000) * 1000) % (2**32)
- header = bytearray(16)
- header[0] = 1 # type
- header[2:4] = len(audios).to_bytes(2, 'big') # payload length
- header[4:8] = flow_control["sequence"].to_bytes(4, 'big') # connection id/sequence
- header[8:12] = timestamp.to_bytes(4, 'big') # 时间戳
- header[12:16] = len(audios).to_bytes(4, 'big') # opus长度
-
- # 发送包含头部的完整数据包
- complete_packet = bytes(header) + audios
- await conn.websocket.send(complete_packet)
+ if need_header:
+ # 为opus数据包添加16字节头部
+ timestamp = int((flow_control["start_time"] + flow_control["packet_count"] * frame_duration / 1000) * 1000) % (2**32)
+ header = bytearray(16)
+ header[0] = 1 # type
+ header[2:4] = len(audios).to_bytes(2, 'big') # payload length
+ header[4:8] = flow_control["sequence"].to_bytes(4, 'big') # connection id/sequence
+ header[8:12] = timestamp.to_bytes(4, 'big') # 时间戳
+ header[12:16] = len(audios).to_bytes(4, 'big') # opus长度
+
+ # 发送包含头部的完整数据包
+ complete_packet = bytes(header) + audios
+ await conn.websocket.send(complete_packet)
+ else:
+ # 直接发送opus数据包,不添加头部
+ await conn.websocket.send(audios)
# 更新流控状态
flow_control["packet_count"] += 1
@@ -90,20 +99,29 @@ async def sendAudio(conn, audios, frame_duration=60):
start_time = time.perf_counter()
play_position = 0
+ # 检查是否需要添加头部(只有当mqtt_gateway有实际值时才添加头部)
+ mqtt_gateway = conn.config.get("server", {}).get("mqtt_gateway")
+ # 当mqtt_gateway为None, "null", "", 或实际的null值时,不添加头部
+ need_header = mqtt_gateway and mqtt_gateway not in [None, "null", ""] and str(mqtt_gateway).strip() != ""
+
# 执行预缓冲
pre_buffer_frames = min(3, len(audios))
for i in range(pre_buffer_frames):
- # 为预缓冲包添加头部
- timestamp = int((start_time + i * frame_duration / 1000) * 1000) % (2**32)
- header = bytearray(16)
- header[0] = 1 # type
- header[2:4] = len(audios[i]).to_bytes(2, 'big') # payload length
- header[4:8] = i.to_bytes(4, 'big') # sequence
- header[8:12] = timestamp.to_bytes(4, 'big') # 时间戳
- header[12:16] = len(audios[i]).to_bytes(4, 'big') # opus长度
-
- complete_packet = bytes(header) + audios[i]
- await conn.websocket.send(complete_packet)
+ if need_header:
+ # 为预缓冲包添加头部
+ timestamp = int((start_time + i * frame_duration / 1000) * 1000) % (2**32)
+ header = bytearray(16)
+ header[0] = 1 # type
+ header[2:4] = len(audios[i]).to_bytes(2, 'big') # payload length
+ header[4:8] = i.to_bytes(4, 'big') # sequence
+ header[8:12] = timestamp.to_bytes(4, 'big') # 时间戳
+ header[12:16] = len(audios[i]).to_bytes(4, 'big') # opus长度
+
+ complete_packet = bytes(header) + audios[i]
+ await conn.websocket.send(complete_packet)
+ else:
+ # 直接发送预缓冲包,不添加头部
+ await conn.websocket.send(audios[i])
remaining_audios = audios[pre_buffer_frames:]
# 播放剩余音频帧
@@ -121,19 +139,23 @@ async def sendAudio(conn, audios, frame_duration=60):
if delay > 0:
await asyncio.sleep(delay)
- # 为opus数据包添加16字节头部 (timestamp at offset 8, length at offset 12)
- timestamp = int((start_time + play_position / 1000) * 1000) % (2**32) # 使用播放位置计算时间戳
- sequence = pre_buffer_frames + i # 确保序列号连续
- header = bytearray(16)
- header[0] = 1 # type
- header[2:4] = len(opus_packet).to_bytes(2, 'big') # payload length
- header[4:8] = sequence.to_bytes(4, 'big') # sequence
- header[8:12] = timestamp.to_bytes(4, 'big') # 时间戳在第8-11字节
- header[12:16] = len(opus_packet).to_bytes(4, 'big') # opus长度在第12-15字节
-
- # 发送包含头部的完整数据包
- complete_packet = bytes(header) + opus_packet
- await conn.websocket.send(complete_packet)
+ if need_header:
+ # 为opus数据包添加16字节头部 (timestamp at offset 8, length at offset 12)
+ timestamp = int((start_time + play_position / 1000) * 1000) % (2**32) # 使用播放位置计算时间戳
+ sequence = pre_buffer_frames + i # 确保序列号连续
+ header = bytearray(16)
+ header[0] = 1 # type
+ header[2:4] = len(opus_packet).to_bytes(2, 'big') # payload length
+ header[4:8] = sequence.to_bytes(4, 'big') # sequence
+ header[8:12] = timestamp.to_bytes(4, 'big') # 时间戳在第8-11字节
+ header[12:16] = len(opus_packet).to_bytes(4, 'big') # opus长度在第12-15字节
+
+ # 发送包含头部的完整数据包
+ complete_packet = bytes(header) + opus_packet
+ await conn.websocket.send(complete_packet)
+ else:
+ # 直接发送opus数据包,不添加头部
+ await conn.websocket.send(opus_packet)
play_position += frame_duration
From c5e6a46450b9d50c53ecb1b7ee7d06877c02b470 Mon Sep 17 00:00:00 2001
From: myifeng
Date: Tue, 9 Sep 2025 19:35:32 +0800
Subject: [PATCH 009/366] Update requirements.txt
---
main/xiaozhi-server/requirements.txt | 26 +++++++++++++-------------
1 file changed, 13 insertions(+), 13 deletions(-)
diff --git a/main/xiaozhi-server/requirements.txt b/main/xiaozhi-server/requirements.txt
index 41508e3c6..acdcf974a 100755
--- a/main/xiaozhi-server/requirements.txt
+++ b/main/xiaozhi-server/requirements.txt
@@ -1,37 +1,37 @@
pyyml==0.0.2
torch==2.2.2
-silero_vad==5.1.2
+silero_vad==6.0.0
websockets==14.2
opuslib_next==1.1.2
-numpy==1.26.4
+numpy==2.2.6
pydub==0.25.1
funasr==1.2.3
torchaudio==2.2.2
-openai==1.61.0
-google-generativeai==0.8.4
+openai==1.107.0
+google-generativeai==0.8.5
edge_tts==7.0.0
httpx==0.27.2
-aiohttp==3.9.3
+aiohttp==3.12.15
aiohttp_cors==0.7.0
ormsgpack==1.7.0
-ruamel.yaml==0.18.10
+ruamel.yaml==0.18.15
loguru==0.7.3
-requests==2.32.3
-cozepy==0.12.0
+requests==2.32.5
+cozepy==0.19.0
mem0ai==0.1.62
bs4==0.0.2
modelscope==1.23.2
-sherpa_onnx==1.12.8
-mcp==1.8.1
+sherpa_onnx==1.12.11
+mcp==1.13.1
cnlunar==0.2.0
PySocks==1.7.1
dashscope==1.23.1
baidu-aip==4.16.13
chardet==5.2.0
aioconsole==0.8.1
-markitdown==0.1.1
-mcp-proxy==0.8.0
+markitdown==0.1.3
+mcp-proxy==0.8.2
PyJWT==2.8.0
psutil==7.0.0
-portalocker==2.10.1
+portalocker==3.2.0
Jinja2==3.1.6
From ef02a0143916ced34a00a697864ccbe9e3a699e3 Mon Sep 17 00:00:00 2001
From: hrz <1710360675@qq.com>
Date: Wed, 10 Sep 2025 17:38:29 +0800
Subject: [PATCH 010/366] =?UTF-8?q?update:=E4=BC=98=E5=8C=96=E6=99=BA?=
=?UTF-8?q?=E6=8E=A7=E5=8F=B0=E5=8F=82=E6=95=B0=E5=90=8D=E7=A7=B0?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../service/impl/DeviceServiceImpl.java | 30 +++++++++----------
.../resources/db/changelog/202509080921.sql | 7 -----
.../resources/db/changelog/202509080922.sql | 8 +++++
.../resources/db/changelog/202509080927.sql | 2 --
.../db/changelog/db.changelog-master.yaml | 14 ++-------
5 files changed, 26 insertions(+), 35 deletions(-)
delete mode 100644 main/manager-api/src/main/resources/db/changelog/202509080921.sql
create mode 100644 main/manager-api/src/main/resources/db/changelog/202509080922.sql
delete mode 100644 main/manager-api/src/main/resources/db/changelog/202509080927.sql
diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java
index b4343276d..663800417 100644
--- a/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java
+++ b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java
@@ -9,6 +9,7 @@ import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.UUID;
+
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
@@ -37,6 +38,7 @@ import xiaozhi.common.user.UserDetail;
import xiaozhi.common.utils.ConvertUtils;
import xiaozhi.common.utils.DateUtils;
import xiaozhi.modules.device.dao.DeviceDao;
+import xiaozhi.modules.device.dto.DeviceManualAddDTO;
import xiaozhi.modules.device.dto.DevicePageUserDTO;
import xiaozhi.modules.device.dto.DeviceReportReqDTO;
import xiaozhi.modules.device.dto.DeviceReportRespDTO;
@@ -48,7 +50,6 @@ import xiaozhi.modules.device.vo.UserShowDeviceListVO;
import xiaozhi.modules.security.user.SecurityUser;
import xiaozhi.modules.sys.service.SysParamsService;
import xiaozhi.modules.sys.service.SysUserUtilService;
-import xiaozhi.modules.device.dto.DeviceManualAddDTO;
@Slf4j
@Service
@@ -179,11 +180,11 @@ public class DeviceServiceImpl extends BaseServiceImpl
}
response.setWebsocket(websocket);
-
+
// 添加MQTT UDP配置
// 从系统参数获取MQTT Gateway地址,仅在配置有效时使用
String mqttUdpConfig = sysParamsService.getValue(Constant.SERVER_MQTT_GATEWAY, false);
- if(mqttUdpConfig != null && !mqttUdpConfig.equals("null") && !mqttUdpConfig.isEmpty() && deviceById != null) {
+ if (mqttUdpConfig != null && !mqttUdpConfig.equals("null") && !mqttUdpConfig.isEmpty() && deviceById != null) {
try {
DeviceReportRespDTO.MQTT mqtt = buildMqttConfig(macAddress, clientId, deviceById);
if (mqtt != null) {
@@ -194,7 +195,7 @@ public class DeviceServiceImpl extends BaseServiceImpl
log.error("生成MQTT配置失败: {}", e.getMessage());
}
}
-
+
if (deviceById != null) {
// 如果设备存在,则异步更新上次连接时间和版本信息
String appVersion = deviceReport.getApplication() != null ? deviceReport.getApplication().getVersion()
@@ -459,7 +460,8 @@ public class DeviceServiceImpl extends BaseServiceImpl
/**
* 生成MQTT密码签名
- * @param content 签名内容 (clientId + '|' + username)
+ *
+ * @param content 签名内容 (clientId + '|' + username)
* @param secretKey 密钥
* @return Base64编码的HMAC-SHA256签名
*/
@@ -473,19 +475,16 @@ public class DeviceServiceImpl extends BaseServiceImpl
/**
* 构建MQTT配置信息
+ *
* @param macAddress MAC地址
- * @param clientId 客户端ID (UUID)
- * @param device 设备信息
+ * @param clientId 客户端ID (UUID)
+ * @param device 设备信息
* @return MQTT配置对象
*/
- private DeviceReportRespDTO.MQTT buildMqttConfig(String macAddress, String clientId, DeviceEntity device) throws Exception {
+ private DeviceReportRespDTO.MQTT buildMqttConfig(String macAddress, String clientId, DeviceEntity device)
+ throws Exception {
// 从环境变量或系统参数获取签名密钥
- String signatureKey = System.getenv("MQTT_SIGNATURE_KEY");
- if (StringUtils.isBlank(signatureKey)) {
- // 如果环境变量没有,尝试从系统参数获取
- signatureKey = sysParamsService.getValue("mqtt.signature_key", false);
- }
-
+ String signatureKey = sysParamsService.getValue("server.mqtt_signature_key", false);
if (StringUtils.isBlank(signatureKey)) {
log.warn("缺少MQTT_SIGNATURE_KEY,跳过MQTT配置生成");
return null;
@@ -500,7 +499,8 @@ public class DeviceServiceImpl extends BaseServiceImpl
Map userData = new HashMap<>();
// 尝试获取客户端IP
try {
- ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
+ ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
+ .getRequestAttributes();
if (attributes != null) {
HttpServletRequest request = attributes.getRequest();
String clientIp = request.getRemoteAddr();
diff --git a/main/manager-api/src/main/resources/db/changelog/202509080921.sql b/main/manager-api/src/main/resources/db/changelog/202509080921.sql
deleted file mode 100644
index 4d89ee57d..000000000
--- a/main/manager-api/src/main/resources/db/changelog/202509080921.sql
+++ /dev/null
@@ -1,7 +0,0 @@
-delete from `sys_params` where id = 108;
-delete from `sys_params` where param_code = 'server.mqtt_gateway';
-INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (108, 'server.mqtt_gateway', 'null', 'string', 1, 'mqtt gateway 配置');
-
-delete from `sys_params` where param_code = 'server.udp_gateway';
-INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (109, 'server.udp_gateway', 'null', 'string', 1, 'udp gateway 配置');
-
diff --git a/main/manager-api/src/main/resources/db/changelog/202509080922.sql b/main/manager-api/src/main/resources/db/changelog/202509080922.sql
new file mode 100644
index 000000000..424b3cd85
--- /dev/null
+++ b/main/manager-api/src/main/resources/db/changelog/202509080922.sql
@@ -0,0 +1,8 @@
+delete from `sys_params` where param_code = 'server.mqtt_gateway';
+INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (116, 'server.mqtt_gateway', 'null', 'string', 1, 'mqtt gateway 配置');
+
+delete from `sys_params` where param_code = 'server.mqtt_signature_key';
+INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (117, 'server.mqtt_signature_key', 'null', 'string', 1, 'mqtt 密钥 配置');
+
+delete from `sys_params` where param_code = 'server.udp_gateway';
+INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (118, 'server.udp_gateway', 'null', 'string', 1, 'udp gateway 配置');
\ No newline at end of file
diff --git a/main/manager-api/src/main/resources/db/changelog/202509080927.sql b/main/manager-api/src/main/resources/db/changelog/202509080927.sql
deleted file mode 100644
index 4741af88e..000000000
--- a/main/manager-api/src/main/resources/db/changelog/202509080927.sql
+++ /dev/null
@@ -1,2 +0,0 @@
-delete from `sys_params` where param_code = 'mqtt.signature_key';
-INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (120, 'mqtt.signature_key', 'null', 'string', 1, 'mqtt 密钥 配置');
diff --git a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml
index ed66ebb78..c355a16a4 100755
--- a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml
+++ b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml
@@ -305,17 +305,9 @@ databaseChangeLog:
path: classpath:db/changelog/202508131557.sql
- changeSet:
- id: 202509080921
- author: fan
+ id: 202509080922
+ author: fyb
changes:
- sqlFile:
encoding: utf8
- path: classpath:db/changelog/202509080921.sql
-
- - changeSet:
- id: 202509080927
- author: fan
- changes:
- - sqlFile:
- encoding: utf8
- path: classpath:db/changelog/202509080927.sql
\ No newline at end of file
+ path: classpath:db/changelog/202509080922.sql
\ No newline at end of file
From f81be335397b07749bc5bd713fd6590a3245d409 Mon Sep 17 00:00:00 2001
From: FAN-yeB <1442100690@qq.com>
Date: Wed, 10 Sep 2025 17:46:55 +0800
Subject: [PATCH 011/366] =?UTF-8?q?=E4=BC=98=E5=8C=96mqtt=E5=90=AF?=
=?UTF-8?q?=E7=94=A8?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
main/xiaozhi-server/core/connection.py | 9 ++++-----
.../xiaozhi-server/core/handle/sendAudioHandle.py | 15 ++++++---------
2 files changed, 10 insertions(+), 14 deletions(-)
diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py
index e23826a11..9f1348b70 100644
--- a/main/xiaozhi-server/core/connection.py
+++ b/main/xiaozhi-server/core/connection.py
@@ -282,14 +282,13 @@ class ConnectionHandler:
if self.asr is None:
return
- # 检查是否需要处理头部(只有当mqtt_gateway有实际值时才处理头部)
- mqtt_gateway = self.config.get("server", {}).get("mqtt_gateway")
- # 当mqtt_gateway为None, "null", "", 或实际的null值时,不处理头部
- need_header_processing = mqtt_gateway and mqtt_gateway not in [None, "null", ""] and str(mqtt_gateway).strip() != ""
+ # 检查是否需要处理头部(只有当websocket URL以"?from=mqtt"为结尾时才处理头部)
+ request_path = self.websocket.request.path
+ need_header_processing = request_path.endswith("?from=mqtt")
# 调试日志:首次连接时记录配置
if not hasattr(self, '_logged_mqtt_config'):
- self.logger.bind(tag=TAG).info(f"MQTT Gateway配置: '{mqtt_gateway}', 头部处理: {need_header_processing}")
+ self.logger.bind(tag=TAG).info(f"WebSocket URL路径: '{request_path}', 头部处理: {need_header_processing}")
self._logged_mqtt_config = True
if need_header_processing and len(message) >= 16:
diff --git a/main/xiaozhi-server/core/handle/sendAudioHandle.py b/main/xiaozhi-server/core/handle/sendAudioHandle.py
index 56d219322..df18f2a08 100644
--- a/main/xiaozhi-server/core/handle/sendAudioHandle.py
+++ b/main/xiaozhi-server/core/handle/sendAudioHandle.py
@@ -42,11 +42,9 @@ async def sendAudio(conn, audios, frame_duration=60):
"""
if audios is None or len(audios) == 0:
return
-
- # 检查是否需要添加头部(只有当mqtt_gateway有实际值时才添加头部)
- mqtt_gateway = conn.config.get("server", {}).get("mqtt_gateway")
- # 当mqtt_gateway为None, "null", "", 或实际的null值时,不添加头部
- need_header = mqtt_gateway and mqtt_gateway not in [None, "null", ""] and str(mqtt_gateway).strip() != ""
+ # 检查是否需要处理头部(只有当websocket URL以"?from=mqtt"为结尾时才处理头部)
+ request_path = conn.websocket.request.path
+ need_header = request_path.endswith("?from=mqtt")
if isinstance(audios, bytes):
if conn.client_abort:
@@ -99,10 +97,9 @@ async def sendAudio(conn, audios, frame_duration=60):
start_time = time.perf_counter()
play_position = 0
- # 检查是否需要添加头部(只有当mqtt_gateway有实际值时才添加头部)
- mqtt_gateway = conn.config.get("server", {}).get("mqtt_gateway")
- # 当mqtt_gateway为None, "null", "", 或实际的null值时,不添加头部
- need_header = mqtt_gateway and mqtt_gateway not in [None, "null", ""] and str(mqtt_gateway).strip() != ""
+ # 检查是否需要添加头部(只有当websocket URL以"?from=mqtt"为结尾时才添加头部)
+ request_path = conn.websocket.request.path
+ need_header = request_path.endswith("?from=mqtt")
# 执行预缓冲
pre_buffer_frames = min(3, len(audios))
From eea7689c3dcfd8cd88da5466d62eb38620e8456f Mon Sep 17 00:00:00 2001
From: FAN-yeB <1442100690@qq.com>
Date: Wed, 10 Sep 2025 17:48:31 +0800
Subject: [PATCH 012/366] Revert "Merge branch 'mqtt' of
https://github.com/xinnan-tech/xiaozhi-esp32-server into mqtt"
This reverts commit 7b9e34c3e5247ddd2bab613ff05216d7c7c15b4d, reversing
changes made to f81be335397b07749bc5bd713fd6590a3245d409.
---
.../service/impl/DeviceServiceImpl.java | 30 +++++++++----------
.../resources/db/changelog/202509080921.sql | 7 +++++
.../resources/db/changelog/202509080922.sql | 8 -----
.../resources/db/changelog/202509080927.sql | 2 ++
.../db/changelog/db.changelog-master.yaml | 14 +++++++--
5 files changed, 35 insertions(+), 26 deletions(-)
create mode 100644 main/manager-api/src/main/resources/db/changelog/202509080921.sql
delete mode 100644 main/manager-api/src/main/resources/db/changelog/202509080922.sql
create mode 100644 main/manager-api/src/main/resources/db/changelog/202509080927.sql
diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java
index 663800417..b4343276d 100644
--- a/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java
+++ b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java
@@ -9,7 +9,6 @@ import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.UUID;
-
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
@@ -38,7 +37,6 @@ import xiaozhi.common.user.UserDetail;
import xiaozhi.common.utils.ConvertUtils;
import xiaozhi.common.utils.DateUtils;
import xiaozhi.modules.device.dao.DeviceDao;
-import xiaozhi.modules.device.dto.DeviceManualAddDTO;
import xiaozhi.modules.device.dto.DevicePageUserDTO;
import xiaozhi.modules.device.dto.DeviceReportReqDTO;
import xiaozhi.modules.device.dto.DeviceReportRespDTO;
@@ -50,6 +48,7 @@ import xiaozhi.modules.device.vo.UserShowDeviceListVO;
import xiaozhi.modules.security.user.SecurityUser;
import xiaozhi.modules.sys.service.SysParamsService;
import xiaozhi.modules.sys.service.SysUserUtilService;
+import xiaozhi.modules.device.dto.DeviceManualAddDTO;
@Slf4j
@Service
@@ -180,11 +179,11 @@ public class DeviceServiceImpl extends BaseServiceImpl
}
response.setWebsocket(websocket);
-
+
// 添加MQTT UDP配置
// 从系统参数获取MQTT Gateway地址,仅在配置有效时使用
String mqttUdpConfig = sysParamsService.getValue(Constant.SERVER_MQTT_GATEWAY, false);
- if (mqttUdpConfig != null && !mqttUdpConfig.equals("null") && !mqttUdpConfig.isEmpty() && deviceById != null) {
+ if(mqttUdpConfig != null && !mqttUdpConfig.equals("null") && !mqttUdpConfig.isEmpty() && deviceById != null) {
try {
DeviceReportRespDTO.MQTT mqtt = buildMqttConfig(macAddress, clientId, deviceById);
if (mqtt != null) {
@@ -195,7 +194,7 @@ public class DeviceServiceImpl extends BaseServiceImpl
log.error("生成MQTT配置失败: {}", e.getMessage());
}
}
-
+
if (deviceById != null) {
// 如果设备存在,则异步更新上次连接时间和版本信息
String appVersion = deviceReport.getApplication() != null ? deviceReport.getApplication().getVersion()
@@ -460,8 +459,7 @@ public class DeviceServiceImpl extends BaseServiceImpl
/**
* 生成MQTT密码签名
- *
- * @param content 签名内容 (clientId + '|' + username)
+ * @param content 签名内容 (clientId + '|' + username)
* @param secretKey 密钥
* @return Base64编码的HMAC-SHA256签名
*/
@@ -475,16 +473,19 @@ public class DeviceServiceImpl extends BaseServiceImpl
/**
* 构建MQTT配置信息
- *
* @param macAddress MAC地址
- * @param clientId 客户端ID (UUID)
- * @param device 设备信息
+ * @param clientId 客户端ID (UUID)
+ * @param device 设备信息
* @return MQTT配置对象
*/
- private DeviceReportRespDTO.MQTT buildMqttConfig(String macAddress, String clientId, DeviceEntity device)
- throws Exception {
+ private DeviceReportRespDTO.MQTT buildMqttConfig(String macAddress, String clientId, DeviceEntity device) throws Exception {
// 从环境变量或系统参数获取签名密钥
- String signatureKey = sysParamsService.getValue("server.mqtt_signature_key", false);
+ String signatureKey = System.getenv("MQTT_SIGNATURE_KEY");
+ if (StringUtils.isBlank(signatureKey)) {
+ // 如果环境变量没有,尝试从系统参数获取
+ signatureKey = sysParamsService.getValue("mqtt.signature_key", false);
+ }
+
if (StringUtils.isBlank(signatureKey)) {
log.warn("缺少MQTT_SIGNATURE_KEY,跳过MQTT配置生成");
return null;
@@ -499,8 +500,7 @@ public class DeviceServiceImpl extends BaseServiceImpl
Map userData = new HashMap<>();
// 尝试获取客户端IP
try {
- ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
- .getRequestAttributes();
+ ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (attributes != null) {
HttpServletRequest request = attributes.getRequest();
String clientIp = request.getRemoteAddr();
diff --git a/main/manager-api/src/main/resources/db/changelog/202509080921.sql b/main/manager-api/src/main/resources/db/changelog/202509080921.sql
new file mode 100644
index 000000000..4d89ee57d
--- /dev/null
+++ b/main/manager-api/src/main/resources/db/changelog/202509080921.sql
@@ -0,0 +1,7 @@
+delete from `sys_params` where id = 108;
+delete from `sys_params` where param_code = 'server.mqtt_gateway';
+INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (108, 'server.mqtt_gateway', 'null', 'string', 1, 'mqtt gateway 配置');
+
+delete from `sys_params` where param_code = 'server.udp_gateway';
+INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (109, 'server.udp_gateway', 'null', 'string', 1, 'udp gateway 配置');
+
diff --git a/main/manager-api/src/main/resources/db/changelog/202509080922.sql b/main/manager-api/src/main/resources/db/changelog/202509080922.sql
deleted file mode 100644
index 424b3cd85..000000000
--- a/main/manager-api/src/main/resources/db/changelog/202509080922.sql
+++ /dev/null
@@ -1,8 +0,0 @@
-delete from `sys_params` where param_code = 'server.mqtt_gateway';
-INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (116, 'server.mqtt_gateway', 'null', 'string', 1, 'mqtt gateway 配置');
-
-delete from `sys_params` where param_code = 'server.mqtt_signature_key';
-INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (117, 'server.mqtt_signature_key', 'null', 'string', 1, 'mqtt 密钥 配置');
-
-delete from `sys_params` where param_code = 'server.udp_gateway';
-INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (118, 'server.udp_gateway', 'null', 'string', 1, 'udp gateway 配置');
\ No newline at end of file
diff --git a/main/manager-api/src/main/resources/db/changelog/202509080927.sql b/main/manager-api/src/main/resources/db/changelog/202509080927.sql
new file mode 100644
index 000000000..4741af88e
--- /dev/null
+++ b/main/manager-api/src/main/resources/db/changelog/202509080927.sql
@@ -0,0 +1,2 @@
+delete from `sys_params` where param_code = 'mqtt.signature_key';
+INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (120, 'mqtt.signature_key', 'null', 'string', 1, 'mqtt 密钥 配置');
diff --git a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml
index c355a16a4..ed66ebb78 100755
--- a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml
+++ b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml
@@ -305,9 +305,17 @@ databaseChangeLog:
path: classpath:db/changelog/202508131557.sql
- changeSet:
- id: 202509080922
- author: fyb
+ id: 202509080921
+ author: fan
changes:
- sqlFile:
encoding: utf8
- path: classpath:db/changelog/202509080922.sql
\ No newline at end of file
+ path: classpath:db/changelog/202509080921.sql
+
+ - changeSet:
+ id: 202509080927
+ author: fan
+ changes:
+ - sqlFile:
+ encoding: utf8
+ path: classpath:db/changelog/202509080927.sql
\ No newline at end of file
From c93cb3bb52e272f25398e40e8628fdbf6f035532 Mon Sep 17 00:00:00 2001
From: FAN-yeB <1442100690@qq.com>
Date: Wed, 10 Sep 2025 17:51:45 +0800
Subject: [PATCH 013/366] Reapply "Merge branch 'mqtt' of
https://github.com/xinnan-tech/xiaozhi-esp32-server into mqtt"
This reverts commit eea7689c3dcfd8cd88da5466d62eb38620e8456f.
---
.../service/impl/DeviceServiceImpl.java | 30 +++++++++----------
.../resources/db/changelog/202509080921.sql | 7 -----
.../resources/db/changelog/202509080922.sql | 8 +++++
.../resources/db/changelog/202509080927.sql | 2 --
.../db/changelog/db.changelog-master.yaml | 14 ++-------
5 files changed, 26 insertions(+), 35 deletions(-)
delete mode 100644 main/manager-api/src/main/resources/db/changelog/202509080921.sql
create mode 100644 main/manager-api/src/main/resources/db/changelog/202509080922.sql
delete mode 100644 main/manager-api/src/main/resources/db/changelog/202509080927.sql
diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java
index b4343276d..663800417 100644
--- a/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java
+++ b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java
@@ -9,6 +9,7 @@ import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.UUID;
+
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
@@ -37,6 +38,7 @@ import xiaozhi.common.user.UserDetail;
import xiaozhi.common.utils.ConvertUtils;
import xiaozhi.common.utils.DateUtils;
import xiaozhi.modules.device.dao.DeviceDao;
+import xiaozhi.modules.device.dto.DeviceManualAddDTO;
import xiaozhi.modules.device.dto.DevicePageUserDTO;
import xiaozhi.modules.device.dto.DeviceReportReqDTO;
import xiaozhi.modules.device.dto.DeviceReportRespDTO;
@@ -48,7 +50,6 @@ import xiaozhi.modules.device.vo.UserShowDeviceListVO;
import xiaozhi.modules.security.user.SecurityUser;
import xiaozhi.modules.sys.service.SysParamsService;
import xiaozhi.modules.sys.service.SysUserUtilService;
-import xiaozhi.modules.device.dto.DeviceManualAddDTO;
@Slf4j
@Service
@@ -179,11 +180,11 @@ public class DeviceServiceImpl extends BaseServiceImpl
}
response.setWebsocket(websocket);
-
+
// 添加MQTT UDP配置
// 从系统参数获取MQTT Gateway地址,仅在配置有效时使用
String mqttUdpConfig = sysParamsService.getValue(Constant.SERVER_MQTT_GATEWAY, false);
- if(mqttUdpConfig != null && !mqttUdpConfig.equals("null") && !mqttUdpConfig.isEmpty() && deviceById != null) {
+ if (mqttUdpConfig != null && !mqttUdpConfig.equals("null") && !mqttUdpConfig.isEmpty() && deviceById != null) {
try {
DeviceReportRespDTO.MQTT mqtt = buildMqttConfig(macAddress, clientId, deviceById);
if (mqtt != null) {
@@ -194,7 +195,7 @@ public class DeviceServiceImpl extends BaseServiceImpl
log.error("生成MQTT配置失败: {}", e.getMessage());
}
}
-
+
if (deviceById != null) {
// 如果设备存在,则异步更新上次连接时间和版本信息
String appVersion = deviceReport.getApplication() != null ? deviceReport.getApplication().getVersion()
@@ -459,7 +460,8 @@ public class DeviceServiceImpl extends BaseServiceImpl
/**
* 生成MQTT密码签名
- * @param content 签名内容 (clientId + '|' + username)
+ *
+ * @param content 签名内容 (clientId + '|' + username)
* @param secretKey 密钥
* @return Base64编码的HMAC-SHA256签名
*/
@@ -473,19 +475,16 @@ public class DeviceServiceImpl extends BaseServiceImpl
/**
* 构建MQTT配置信息
+ *
* @param macAddress MAC地址
- * @param clientId 客户端ID (UUID)
- * @param device 设备信息
+ * @param clientId 客户端ID (UUID)
+ * @param device 设备信息
* @return MQTT配置对象
*/
- private DeviceReportRespDTO.MQTT buildMqttConfig(String macAddress, String clientId, DeviceEntity device) throws Exception {
+ private DeviceReportRespDTO.MQTT buildMqttConfig(String macAddress, String clientId, DeviceEntity device)
+ throws Exception {
// 从环境变量或系统参数获取签名密钥
- String signatureKey = System.getenv("MQTT_SIGNATURE_KEY");
- if (StringUtils.isBlank(signatureKey)) {
- // 如果环境变量没有,尝试从系统参数获取
- signatureKey = sysParamsService.getValue("mqtt.signature_key", false);
- }
-
+ String signatureKey = sysParamsService.getValue("server.mqtt_signature_key", false);
if (StringUtils.isBlank(signatureKey)) {
log.warn("缺少MQTT_SIGNATURE_KEY,跳过MQTT配置生成");
return null;
@@ -500,7 +499,8 @@ public class DeviceServiceImpl extends BaseServiceImpl
Map userData = new HashMap<>();
// 尝试获取客户端IP
try {
- ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
+ ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
+ .getRequestAttributes();
if (attributes != null) {
HttpServletRequest request = attributes.getRequest();
String clientIp = request.getRemoteAddr();
diff --git a/main/manager-api/src/main/resources/db/changelog/202509080921.sql b/main/manager-api/src/main/resources/db/changelog/202509080921.sql
deleted file mode 100644
index 4d89ee57d..000000000
--- a/main/manager-api/src/main/resources/db/changelog/202509080921.sql
+++ /dev/null
@@ -1,7 +0,0 @@
-delete from `sys_params` where id = 108;
-delete from `sys_params` where param_code = 'server.mqtt_gateway';
-INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (108, 'server.mqtt_gateway', 'null', 'string', 1, 'mqtt gateway 配置');
-
-delete from `sys_params` where param_code = 'server.udp_gateway';
-INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (109, 'server.udp_gateway', 'null', 'string', 1, 'udp gateway 配置');
-
diff --git a/main/manager-api/src/main/resources/db/changelog/202509080922.sql b/main/manager-api/src/main/resources/db/changelog/202509080922.sql
new file mode 100644
index 000000000..424b3cd85
--- /dev/null
+++ b/main/manager-api/src/main/resources/db/changelog/202509080922.sql
@@ -0,0 +1,8 @@
+delete from `sys_params` where param_code = 'server.mqtt_gateway';
+INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (116, 'server.mqtt_gateway', 'null', 'string', 1, 'mqtt gateway 配置');
+
+delete from `sys_params` where param_code = 'server.mqtt_signature_key';
+INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (117, 'server.mqtt_signature_key', 'null', 'string', 1, 'mqtt 密钥 配置');
+
+delete from `sys_params` where param_code = 'server.udp_gateway';
+INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (118, 'server.udp_gateway', 'null', 'string', 1, 'udp gateway 配置');
\ No newline at end of file
diff --git a/main/manager-api/src/main/resources/db/changelog/202509080927.sql b/main/manager-api/src/main/resources/db/changelog/202509080927.sql
deleted file mode 100644
index 4741af88e..000000000
--- a/main/manager-api/src/main/resources/db/changelog/202509080927.sql
+++ /dev/null
@@ -1,2 +0,0 @@
-delete from `sys_params` where param_code = 'mqtt.signature_key';
-INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (120, 'mqtt.signature_key', 'null', 'string', 1, 'mqtt 密钥 配置');
diff --git a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml
index ed66ebb78..c355a16a4 100755
--- a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml
+++ b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml
@@ -305,17 +305,9 @@ databaseChangeLog:
path: classpath:db/changelog/202508131557.sql
- changeSet:
- id: 202509080921
- author: fan
+ id: 202509080922
+ author: fyb
changes:
- sqlFile:
encoding: utf8
- path: classpath:db/changelog/202509080921.sql
-
- - changeSet:
- id: 202509080927
- author: fan
- changes:
- - sqlFile:
- encoding: utf8
- path: classpath:db/changelog/202509080927.sql
\ No newline at end of file
+ path: classpath:db/changelog/202509080922.sql
\ No newline at end of file
From 0738c52d142541a7e393735cfdc4219d0725ef01 Mon Sep 17 00:00:00 2001
From: 3030332422 <3030332422@qq.com>
Date: Wed, 10 Sep 2025 18:00:39 +0800
Subject: [PATCH 014/366] =?UTF-8?q?fix:=E4=BF=AE=E5=A4=8DLLM=E6=84=8F?=
=?UTF-8?q?=E5=9B=BE=E8=AF=86=E5=88=AB=E7=9A=84=E8=8B=A5=E5=B9=B2=E9=97=AE?=
=?UTF-8?q?=E9=A2=98?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../core/handle/intentHandler.py | 24 +++++++
.../providers/intent/intent_llm/intent_llm.py | 67 ++++++++++---------
.../core/utils/prompt_manager.py | 7 +-
3 files changed, 65 insertions(+), 33 deletions(-)
diff --git a/main/xiaozhi-server/core/handle/intentHandler.py b/main/xiaozhi-server/core/handle/intentHandler.py
index 724249686..b1486ab91 100644
--- a/main/xiaozhi-server/core/handle/intentHandler.py
+++ b/main/xiaozhi-server/core/handle/intentHandler.py
@@ -91,6 +91,30 @@ async def process_intent_result(conn, intent_result, original_text):
if function_name == "continue_chat":
return False
+ if function_name == "result_for_context":
+ await send_stt_message(conn, original_text)
+ conn.client_abort = False
+
+ def process_context_result():
+ conn.dialogue.put(Message(role="user", content=original_text))
+
+ # 使用现有的 prompt_manager 获取完整上下文
+ from core.utils.prompt_manager import PromptManager
+ prompt_manager = PromptManager(conn.config, conn.logger)
+
+ # 构建带上下文的基础提示
+ context_prompt = prompt_manager.build_enhanced_prompt(
+ "当前时间:{{current_time}}\n今天日期:{{today_date}} ({{today_weekday}})\n今天农历:{{lunar_date}}\n用户所在城市:{{local_address}}",
+ conn.device_id,
+ getattr(conn, 'client_ip', None)
+ )
+
+ response = conn.intent.replyResult(context_prompt, original_text)
+ speak_txt(conn, response)
+
+ conn.executor.submit(process_context_result)
+ return True
+
function_args = {}
if "arguments" in intent_data["function_call"]:
function_args = intent_data["function_call"]["arguments"]
diff --git a/main/xiaozhi-server/core/providers/intent/intent_llm/intent_llm.py b/main/xiaozhi-server/core/providers/intent/intent_llm/intent_llm.py
index 26fbaf703..8d426d085 100644
--- a/main/xiaozhi-server/core/providers/intent/intent_llm/intent_llm.py
+++ b/main/xiaozhi-server/core/providers/intent/intent_llm/intent_llm.py
@@ -53,24 +53,33 @@ class IntentProvider(IntentProviderBase):
functions_desc += "---\n"
prompt = (
+ "【严格格式要求】你必须只能返回JSON格式,绝对不能返回任何自然语言!\n\n"
"你是一个意图识别助手。请分析用户的最后一句话,判断用户意图并调用相应的函数。\n\n"
+
+ "【重要规则】以下类型的查询请直接返回result_for_context,无需调用函数:\n"
+ "- 询问当前时间(如:现在几点、当前时间、查询时间等)\n"
+ "- 询问今天日期(如:今天几号、今天星期几、今天是什么日期等)\n"
+ "- 询问今天农历(如:今天农历几号、今天什么节气等)\n"
+ "- 询问所在城市(如:我现在在哪里、你知道我在哪个城市吗等)"
+ "系统会根据上下文信息直接构建回答。\n\n"
"- 如果用户使用疑问词(如'怎么'、'为什么'、'如何')询问退出相关的问题(例如'怎么退出了?'),注意这不是让你退出,请返回 {'function_call': {'name': 'continue_chat'}\n"
"- 仅当用户明确使用'退出系统'、'结束对话'、'我不想和你说话了'等指令时,才触发 handle_exit_intent\n\n"
f"{functions_desc}\n"
"处理步骤:\n"
"1. 分析用户输入,确定用户意图\n"
- "2. 从可用函数列表中选择最匹配的函数\n"
- "3. 如果找到匹配的函数,生成对应的function_call 格式\n"
- '4. 如果没有找到匹配的函数,返回{"function_call": {"name": "continue_chat"}}\n\n'
+ "2. 检查是否为上述基础信息查询(时间、日期等),如是则返回result_for_context\n"
+ "3. 从可用函数列表中选择最匹配的函数\n"
+ "4. 如果找到匹配的函数,生成对应的function_call 格式\n"
+ '5. 如果没有找到匹配的函数,返回{"function_call": {"name": "continue_chat"}}\n\n'
"返回格式要求:\n"
- "1. 必须返回纯JSON格式\n"
+ "1. 必须返回纯JSON格式,不要包含任何其他文字\n"
"2. 必须包含function_call字段\n"
"3. function_call必须包含name字段\n"
"4. 如果函数需要参数,必须包含arguments字段\n\n"
"示例:\n"
"```\n"
"用户: 现在几点了?\n"
- '返回: {"function_call": {"name": "get_time"}}\n'
+ '返回: {"function_call": {"name": "result_for_context"}}\n'
"```\n"
"```\n"
"用户: 当前电池电量是多少?\n"
@@ -94,12 +103,15 @@ class IntentProvider(IntentProviderBase):
"```\n\n"
"注意:\n"
"1. 只返回JSON格式,不要包含任何其他文字\n"
- '2. 如果没有找到匹配的函数,返回{"function_call": {"name": "continue_chat"}}\n'
- "3. 确保返回的JSON格式正确,包含所有必要的字段\n"
+ '2. 优先检查用户查询是否为基础信息(时间、日期等),如是则返回{"function_call": {"name": "result_for_context"}},不需要arguments参数\n'
+ '3. 如果没有找到匹配的函数,返回{"function_call": {"name": "continue_chat"}}\n'
+ "4. 确保返回的JSON格式正确,包含所有必要的字段\n"
+ "5. result_for_context不需要任何参数,系统会自动从上下文获取信息\n"
"特殊说明:\n"
"- 当用户单次输入包含多个指令时(如'打开灯并且调高音量')\n"
"- 请返回多个function_call组成的JSON数组\n"
- "- 示例:{'function_calls': [{name:'light_on'}, {name:'volume_up'}]}"
+ "- 示例:{'function_calls': [{name:'light_on'}, {name:'volume_up'}]}\n\n"
+ "【最终警告】绝对禁止输出任何自然语言、表情符号或解释文字!只能输出有效JSON格式!违反此规则将导致系统错误!"
)
return prompt
@@ -223,8 +235,13 @@ class IntentProvider(IntentProviderBase):
f"llm 识别到意图: {function_name}, 参数: {function_args}"
)
- # 如果是继续聊天,清理工具调用相关的历史消息
- if function_name == "continue_chat":
+ # 处理不同类型的意图
+ if function_name == "result_for_context":
+ # 处理基础信息查询,直接从context构建结果
+ logger.bind(tag=TAG).info("检测到result_for_context意图,将使用上下文信息直接回答")
+
+ elif function_name == "continue_chat":
+ # 处理普通对话
# 保留非工具相关的消息
clean_history = [
msg
@@ -232,26 +249,16 @@ class IntentProvider(IntentProviderBase):
if msg.role not in ["tool", "function"]
]
conn.dialogue.dialogue = clean_history
+
+ else:
+ # 处理函数调用
+ logger.bind(tag=TAG).info(f"检测到函数调用意图: {function_name}")
- # 添加到缓存
- self.cache_manager.set(self.CacheType.INTENT, cache_key, intent)
-
- # 后处理时间
- postprocess_time = time.time() - postprocess_start_time
- logger.bind(tag=TAG).debug(f"意图后处理耗时: {postprocess_time:.4f}秒")
-
- # 确保返回完全序列化的JSON字符串
- return intent
- else:
- # 添加到缓存
- self.cache_manager.set(self.CacheType.INTENT, cache_key, intent)
-
- # 后处理时间
- postprocess_time = time.time() - postprocess_start_time
- logger.bind(tag=TAG).debug(f"意图后处理耗时: {postprocess_time:.4f}秒")
-
- # 返回普通意图
- return intent
+ # 统一缓存处理和返回
+ self.cache_manager.set(self.CacheType.INTENT, cache_key, intent)
+ postprocess_time = time.time() - postprocess_start_time
+ logger.bind(tag=TAG).debug(f"意图后处理耗时: {postprocess_time:.4f}秒")
+ return intent
except json.JSONDecodeError:
# 后处理时间
postprocess_time = time.time() - postprocess_start_time
@@ -259,4 +266,4 @@ class IntentProvider(IntentProviderBase):
f"无法解析意图JSON: {intent}, 后处理耗时: {postprocess_time:.4f}秒"
)
# 如果解析失败,默认返回继续聊天意图
- return '{"intent": "继续聊天"}'
+ return '{"function_call": {"name": "continue_chat"}}'
diff --git a/main/xiaozhi-server/core/utils/prompt_manager.py b/main/xiaozhi-server/core/utils/prompt_manager.py
index 3f6c429a9..fca3a9772 100644
--- a/main/xiaozhi-server/core/utils/prompt_manager.py
+++ b/main/xiaozhi-server/core/utils/prompt_manager.py
@@ -120,6 +120,7 @@ class PromptManager:
from datetime import datetime
now = datetime.now()
+ current_time = now.strftime("%Y年%m月%d日 %H:%M:%S")
today_date = now.strftime("%Y-%m-%d")
today_weekday = WEEKDAY_MAP[now.strftime("%A")]
today_lunar = cnlunar.Lunar(now, godType="8char")
@@ -129,7 +130,7 @@ class PromptManager:
today_lunar.lunarDayCn,
)
- return today_date, today_weekday, lunar_date
+ return current_time, today_date, today_weekday, lunar_date
def _get_location_info(self, client_ip: str) -> str:
"""获取位置信息"""
@@ -198,7 +199,7 @@ class PromptManager:
try:
# 获取最新的时间信息(不缓存)
- today_date, today_weekday, lunar_date = (
+ current_time, today_date, today_weekday, lunar_date = (
self._get_current_time_info()
)
@@ -223,7 +224,7 @@ class PromptManager:
template = Template(self.base_prompt_template)
enhanced_prompt = template.render(
base_prompt=user_prompt,
- current_time="{{current_time}}",
+ current_time=current_time,
today_date=today_date,
today_weekday=today_weekday,
lunar_date=lunar_date,
From 5bd78cac1a44fcbdcfadd48dc8ac3b7d09243f8d Mon Sep 17 00:00:00 2001
From: hrz <1710360675@qq.com>
Date: Wed, 10 Sep 2025 21:40:25 +0800
Subject: [PATCH 015/366] =?UTF-8?q?update:=E4=BC=98=E5=8C=96=E4=BB=A3?=
=?UTF-8?q?=E7=A0=81?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
main/xiaozhi-server/config.yaml | 2 -
main/xiaozhi-server/core/connection.py | 123 +++++++++---------
.../core/handle/receiveAudioHandle.py | 40 +++---
.../core/handle/sendAudioHandle.py | 100 +++++++-------
4 files changed, 133 insertions(+), 132 deletions(-)
diff --git a/main/xiaozhi-server/config.yaml b/main/xiaozhi-server/config.yaml
index 1afc3530b..c0aa3f934 100644
--- a/main/xiaozhi-server/config.yaml
+++ b/main/xiaozhi-server/config.yaml
@@ -25,8 +25,6 @@ server:
# 所以如果你使用docker部署时,将vision_explain设置成局域网地址
# 如果你使用公网部署时,将vision_explain设置成公网地址
vision_explain: http://你的ip或者域名:端口号/mcp/vision/explain
- # mqtt网关地址,当这个值为null时,mqtt网关桥接功能不开启,使用websocket双向通信,不使用mqtt和udp协议
- mqtt_gateway: null
# OTA返回信息时区偏移量
timezone_offset: +8
# 认证配置
diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py
index 9f1348b70..d80ec8622 100644
--- a/main/xiaozhi-server/core/connection.py
+++ b/main/xiaozhi-server/core/connection.py
@@ -154,6 +154,9 @@ class ConnectionHandler:
# {"mcp":true} 表示启用MCP功能
self.features = None
+ # 标记连接是否来自MQTT
+ self.conn_from_mqtt_gateway = False
+
# 初始化提示词管理器
self.prompt_manager = PromptManager(config, self.logger)
@@ -198,6 +201,13 @@ class ConnectionHandler:
self.websocket = ws
self.device_id = self.headers.get("device-id", None)
+ # 检查是否来自MQTT连接
+ request_path = ws.request.path
+ self.conn_from_mqtt_gateway = request_path.endswith("?from=mqtt")
+ self.logger.bind(tag=TAG).info(
+ f"WebSocket URL路径: '{request_path}', 来自MQTT连接: {self.conn_from_mqtt_gateway}"
+ )
+
# 初始化活动时间戳
self.last_activity_time = time.time() * 1000
@@ -277,57 +287,64 @@ class ConnectionHandler:
if isinstance(message, str):
await handleTextMessage(self, message)
elif isinstance(message, bytes):
- if self.vad is None:
+ if self.vad is None or self.asr is None:
return
- if self.asr is None:
- return
-
- # 检查是否需要处理头部(只有当websocket URL以"?from=mqtt"为结尾时才处理头部)
- request_path = self.websocket.request.path
- need_header_processing = request_path.endswith("?from=mqtt")
-
- # 调试日志:首次连接时记录配置
- if not hasattr(self, '_logged_mqtt_config'):
- self.logger.bind(tag=TAG).info(f"WebSocket URL路径: '{request_path}', 头部处理: {need_header_processing}")
- self._logged_mqtt_config = True
- if need_header_processing and len(message) >= 16:
- try:
- timestamp = int.from_bytes(message[8:12], 'big')
- audio_length = int.from_bytes(message[12:16], 'big')
-
-
- # 提取音频数据
- if audio_length > 0 and len(message) >= 16 + audio_length:
- audio_data = message[16:16 + audio_length]
-
- # 基于时间戳进行简单排序
- self._process_websocket_audio(audio_data, timestamp)
- return
- elif len(message) > 16:
- # 去掉16字节头部
- audio_data = message[16:]
- self.asr_audio_queue.put(audio_data)
- return
- except Exception as e:
- self.logger.bind(tag=TAG).error(f"解析WebSocket音频包失败: {e}")
-
+ # 处理来自MQTT网关的音频包
+ if self.conn_from_mqtt_gateway and len(message) >= 16:
+ handled = await self._process_mqtt_audio_message(message)
+ if handled:
+ return
+
# 不需要头部处理或没有头部时,直接处理原始消息
self.asr_audio_queue.put(message)
+ async def _process_mqtt_audio_message(self, message):
+ """
+ 处理来自MQTT网关的音频消息,解析16字节头部并提取音频数据
+
+ Args:
+ message: 包含头部的音频消息
+
+ Returns:
+ bool: 是否成功处理了消息
+ """
+ try:
+ # 提取头部信息
+ timestamp = int.from_bytes(message[8:12], "big")
+ audio_length = int.from_bytes(message[12:16], "big")
+
+ # 提取音频数据
+ if audio_length > 0 and len(message) >= 16 + audio_length:
+ # 有指定长度,提取精确的音频数据
+ audio_data = message[16 : 16 + audio_length]
+ # 基于时间戳进行排序处理
+ self._process_websocket_audio(audio_data, timestamp)
+ return True
+ elif len(message) > 16:
+ # 没有指定长度或长度无效,去掉头部后处理剩余数据
+ audio_data = message[16:]
+ self.asr_audio_queue.put(audio_data)
+ return True
+ except Exception as e:
+ self.logger.bind(tag=TAG).error(f"解析WebSocket音频包失败: {e}")
+
+ # 处理失败,返回False表示需要继续处理
+ return False
+
def _process_websocket_audio(self, audio_data, timestamp):
"""处理WebSocket格式的音频包"""
# 初始化时间戳序列管理
- if not hasattr(self, 'audio_timestamp_buffer'):
+ if not hasattr(self, "audio_timestamp_buffer"):
self.audio_timestamp_buffer = {}
self.last_processed_timestamp = 0
self.max_timestamp_buffer_size = 20
-
+
# 如果时间戳是递增的,直接处理
if timestamp >= self.last_processed_timestamp:
self.asr_audio_queue.put(audio_data)
self.last_processed_timestamp = timestamp
-
+
# 处理缓冲区中的后续包
processed_any = True
while processed_any:
@@ -346,30 +363,6 @@ class ConnectionHandler:
else:
self.asr_audio_queue.put(audio_data)
- def _process_sequenced_audio(self, audio_data, sequence, timestamp):
- """处理有序的音频包"""
- # 初始化音频缓冲区
- if not hasattr(self, 'audio_buffer'):
- self.audio_buffer = {}
- self.expected_sequence = sequence
- self.max_buffer_size = 20 # 最大缓冲20个包
-
- # 如果是下一个期望的包,直接处理
- if sequence == self.expected_sequence:
- self.asr_audio_queue.put(audio_data)
- self.expected_sequence += 1
-
- # 检查缓冲区中是否有后续的连续包
- while self.expected_sequence in self.audio_buffer:
- buffered_audio = self.audio_buffer.pop(self.expected_sequence)
- self.asr_audio_queue.put(buffered_audio)
- self.expected_sequence += 1
-
- elif sequence > self.expected_sequence:
- # 乱序包,暂存到缓冲区
- if len(self.audio_buffer) < self.max_buffer_size:
- self.audio_buffer[sequence] = audio_data
-
async def handle_restart(self, message):
"""处理服务器重启请求"""
try:
@@ -940,7 +933,11 @@ class ConnectionHandler:
{
"id": function_id,
"function": {
- "arguments": "{}" if function_arguments == "" else function_arguments,
+ "arguments": (
+ "{}"
+ if function_arguments == ""
+ else function_arguments
+ ),
"name": function_name,
},
"type": "function",
@@ -1009,9 +1006,9 @@ class ConnectionHandler:
"""资源清理方法"""
try:
# 清理音频缓冲区
- if hasattr(self, 'audio_buffer'):
+ if hasattr(self, "audio_buffer"):
self.audio_buffer.clear()
-
+
# 取消超时任务
if self.timeout_task and not self.timeout_task.done():
self.timeout_task.cancel()
diff --git a/main/xiaozhi-server/core/handle/receiveAudioHandle.py b/main/xiaozhi-server/core/handle/receiveAudioHandle.py
index e6f396327..8b6359091 100644
--- a/main/xiaozhi-server/core/handle/receiveAudioHandle.py
+++ b/main/xiaozhi-server/core/handle/receiveAudioHandle.py
@@ -1,12 +1,11 @@
-from core.handle.sendAudioHandle import send_stt_message
+import time
+import json
+import asyncio
+from core.utils.util import audio_to_data
+from core.handle.abortHandle import handleAbortMessage
from core.handle.intentHandler import handle_user_intent
from core.utils.output_counter import check_device_output_limit
-from core.handle.abortHandle import handleAbortMessage
-import time
-import asyncio
-import json
-from core.handle.sendAudioHandle import SentenceType
-from core.utils.util import audio_to_data
+from core.handle.sendAudioHandle import send_stt_message, SentenceType
TAG = __name__
@@ -22,7 +21,6 @@ async def handleAudioMessage(conn, audio):
if not hasattr(conn, "vad_resume_task") or conn.vad_resume_task.done():
conn.vad_resume_task = asyncio.create_task(resume_vad_detection(conn))
return
-
if have_voice:
if conn.client_is_speaking:
await handleAbortMessage(conn)
@@ -42,22 +40,22 @@ async def startToChat(conn, text):
# 检查输入是否是JSON格式(包含说话人信息)
speaker_name = None
actual_text = text
-
+
try:
# 尝试解析JSON格式的输入
- if text.strip().startswith('{') and text.strip().endswith('}'):
+ if text.strip().startswith("{") and text.strip().endswith("}"):
data = json.loads(text)
- if 'speaker' in data and 'content' in data:
- speaker_name = data['speaker']
- actual_text = data['content']
+ if "speaker" in data and "content" in data:
+ speaker_name = data["speaker"]
+ actual_text = data["content"]
conn.logger.bind(tag=TAG).info(f"解析到说话人信息: {speaker_name}")
-
+
# 直接使用JSON格式的文本,不解析
actual_text = text
except (json.JSONDecodeError, KeyError):
# 如果解析失败,继续使用原始文本
pass
-
+
# 保存说话人信息到连接对象
if speaker_name:
conn.current_speaker = speaker_name
@@ -118,10 +116,12 @@ async def no_voice_close_connect(conn, have_voice):
async def max_out_size(conn):
+ # 播放超出最大输出字数的提示
+ conn.client_abort = False
text = "不好意思,我现在有点事情要忙,明天这个时候我们再聊,约好了哦!明天不见不散,拜拜!"
await send_stt_message(conn, text)
file_path = "config/assets/max_output_size.wav"
- opus_packets, _ = audio_to_data(file_path)
+ opus_packets = audio_to_data(file_path)
conn.tts.tts_audio_queue.put((SentenceType.LAST, opus_packets, text))
conn.close_after_chat = True
@@ -140,7 +140,7 @@ async def check_bind_device(conn):
# 播放提示音
music_path = "config/assets/bind_code.wav"
- opus_packets, _ = audio_to_data(music_path)
+ opus_packets = audio_to_data(music_path)
conn.tts.tts_audio_queue.put((SentenceType.FIRST, opus_packets, text))
# 逐个播放数字
@@ -148,15 +148,17 @@ async def check_bind_device(conn):
try:
digit = conn.bind_code[i]
num_path = f"config/assets/bind_code/{digit}.wav"
- num_packets, _ = audio_to_data(num_path)
+ num_packets = audio_to_data(num_path)
conn.tts.tts_audio_queue.put((SentenceType.MIDDLE, num_packets, None))
except Exception as e:
conn.logger.bind(tag=TAG).error(f"播放数字音频失败: {e}")
continue
conn.tts.tts_audio_queue.put((SentenceType.LAST, [], None))
else:
+ # 播放未绑定提示
+ conn.client_abort = False
text = f"没有找到该设备的版本信息,请正确配置 OTA地址,然后重新编译固件。"
await send_stt_message(conn, text)
music_path = "config/assets/bind_not_found.wav"
- opus_packets, _ = audio_to_data(music_path)
+ opus_packets = audio_to_data(music_path)
conn.tts.tts_audio_queue.put((SentenceType.LAST, opus_packets, text))
diff --git a/main/xiaozhi-server/core/handle/sendAudioHandle.py b/main/xiaozhi-server/core/handle/sendAudioHandle.py
index df18f2a08..810e8803f 100644
--- a/main/xiaozhi-server/core/handle/sendAudioHandle.py
+++ b/main/xiaozhi-server/core/handle/sendAudioHandle.py
@@ -30,6 +30,28 @@ async def sendAudioMessage(conn, sentenceType, audios, text):
await conn.close()
+async def _send_to_mqtt_gateway(conn, opus_packet, timestamp, sequence):
+ """
+ 发送带16字节头部的opus数据包给mqtt_gateway
+ Args:
+ conn: 连接对象
+ opus_packet: opus数据包
+ timestamp: 时间戳
+ sequence: 序列号
+ """
+ # 为opus数据包添加16字节头部
+ header = bytearray(16)
+ header[0] = 1 # type
+ header[2:4] = len(opus_packet).to_bytes(2, "big") # payload length
+ header[4:8] = sequence.to_bytes(4, "big") # sequence
+ header[8:12] = timestamp.to_bytes(4, "big") # 时间戳
+ header[12:16] = len(opus_packet).to_bytes(4, "big") # opus长度
+
+ # 发送包含头部的完整数据包
+ complete_packet = bytes(header) + opus_packet
+ await conn.websocket.send(complete_packet)
+
+
# 播放音频
async def sendAudio(conn, audios, frame_duration=60):
"""
@@ -42,9 +64,6 @@ async def sendAudio(conn, audios, frame_duration=60):
"""
if audios is None or len(audios) == 0:
return
- # 检查是否需要处理头部(只有当websocket URL以"?from=mqtt"为结尾时才处理头部)
- request_path = conn.websocket.request.path
- need_header = request_path.endswith("?from=mqtt")
if isinstance(audios, bytes):
if conn.client_abort:
@@ -71,19 +90,19 @@ async def sendAudio(conn, audios, frame_duration=60):
if delay > 0:
await asyncio.sleep(delay)
- if need_header:
- # 为opus数据包添加16字节头部
- timestamp = int((flow_control["start_time"] + flow_control["packet_count"] * frame_duration / 1000) * 1000) % (2**32)
- header = bytearray(16)
- header[0] = 1 # type
- header[2:4] = len(audios).to_bytes(2, 'big') # payload length
- header[4:8] = flow_control["sequence"].to_bytes(4, 'big') # connection id/sequence
- header[8:12] = timestamp.to_bytes(4, 'big') # 时间戳
- header[12:16] = len(audios).to_bytes(4, 'big') # opus长度
-
- # 发送包含头部的完整数据包
- complete_packet = bytes(header) + audios
- await conn.websocket.send(complete_packet)
+ if conn.conn_from_mqtt_gateway:
+ # 计算时间戳
+ timestamp = int(
+ (
+ flow_control["start_time"]
+ + flow_control["packet_count"] * frame_duration / 1000
+ )
+ * 1000
+ ) % (2**32)
+ # 调用通用函数发送带头部的数据包
+ await _send_to_mqtt_gateway(
+ conn, audios, timestamp, flow_control["sequence"]
+ )
else:
# 直接发送opus数据包,不添加头部
await conn.websocket.send(audios)
@@ -97,30 +116,21 @@ async def sendAudio(conn, audios, frame_duration=60):
start_time = time.perf_counter()
play_position = 0
- # 检查是否需要添加头部(只有当websocket URL以"?from=mqtt"为结尾时才添加头部)
- request_path = conn.websocket.request.path
- need_header = request_path.endswith("?from=mqtt")
-
# 执行预缓冲
pre_buffer_frames = min(3, len(audios))
for i in range(pre_buffer_frames):
- if need_header:
- # 为预缓冲包添加头部
- timestamp = int((start_time + i * frame_duration / 1000) * 1000) % (2**32)
- header = bytearray(16)
- header[0] = 1 # type
- header[2:4] = len(audios[i]).to_bytes(2, 'big') # payload length
- header[4:8] = i.to_bytes(4, 'big') # sequence
- header[8:12] = timestamp.to_bytes(4, 'big') # 时间戳
- header[12:16] = len(audios[i]).to_bytes(4, 'big') # opus长度
-
- complete_packet = bytes(header) + audios[i]
- await conn.websocket.send(complete_packet)
+ if conn.conn_from_mqtt_gateway:
+ # 计算时间戳
+ timestamp = int((start_time + i * frame_duration / 1000) * 1000) % (
+ 2**32
+ )
+ # 调用通用函数发送带头部的数据包
+ await _send_to_mqtt_gateway(conn, audios[i], timestamp, i)
else:
# 直接发送预缓冲包,不添加头部
await conn.websocket.send(audios[i])
remaining_audios = audios[pre_buffer_frames:]
-
+
# 播放剩余音频帧
for i, opus_packet in enumerate(remaining_audios):
if conn.client_abort:
@@ -135,25 +145,19 @@ async def sendAudio(conn, audios, frame_duration=60):
delay = expected_time - current_time
if delay > 0:
await asyncio.sleep(delay)
-
- if need_header:
- # 为opus数据包添加16字节头部 (timestamp at offset 8, length at offset 12)
- timestamp = int((start_time + play_position / 1000) * 1000) % (2**32) # 使用播放位置计算时间戳
+
+ if conn.conn_from_mqtt_gateway:
+ # 计算时间戳和序列号
+ timestamp = int((start_time + play_position / 1000) * 1000) % (
+ 2**32
+ ) # 使用播放位置计算时间戳
sequence = pre_buffer_frames + i # 确保序列号连续
- header = bytearray(16)
- header[0] = 1 # type
- header[2:4] = len(opus_packet).to_bytes(2, 'big') # payload length
- header[4:8] = sequence.to_bytes(4, 'big') # sequence
- header[8:12] = timestamp.to_bytes(4, 'big') # 时间戳在第8-11字节
- header[12:16] = len(opus_packet).to_bytes(4, 'big') # opus长度在第12-15字节
-
- # 发送包含头部的完整数据包
- complete_packet = bytes(header) + opus_packet
- await conn.websocket.send(complete_packet)
+ # 调用通用函数发送带头部的数据包
+ await _send_to_mqtt_gateway(conn, opus_packet, timestamp, sequence)
else:
# 直接发送opus数据包,不添加头部
await conn.websocket.send(opus_packet)
-
+
play_position += frame_duration
From 26fd3110b47803c6aefe9b06f3ac15eafbab0154 Mon Sep 17 00:00:00 2001
From: hrz <1710360675@qq.com>
Date: Wed, 10 Sep 2025 22:20:43 +0800
Subject: [PATCH 016/366] =?UTF-8?q?update:=E4=BC=98=E5=8C=96=E4=BB=A3?=
=?UTF-8?q?=E7=A0=81?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
main/xiaozhi-server/core/connection.py | 7 +--
.../core/handle/sendAudioHandle.py | 62 +++++++++++++------
2 files changed, 45 insertions(+), 24 deletions(-)
diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py
index d80ec8622..3db8f86c2 100644
--- a/main/xiaozhi-server/core/connection.py
+++ b/main/xiaozhi-server/core/connection.py
@@ -203,10 +203,9 @@ class ConnectionHandler:
# 检查是否来自MQTT连接
request_path = ws.request.path
- self.conn_from_mqtt_gateway = request_path.endswith("?from=mqtt")
- self.logger.bind(tag=TAG).info(
- f"WebSocket URL路径: '{request_path}', 来自MQTT连接: {self.conn_from_mqtt_gateway}"
- )
+ self.conn_from_mqtt_gateway = request_path.endswith("?from=mqtt_gateway")
+ if self.conn_from_mqtt_gateway:
+ self.logger.bind(tag=TAG).info("连接来自:MQTT网关")
# 初始化活动时间戳
self.last_activity_time = time.time() * 1000
diff --git a/main/xiaozhi-server/core/handle/sendAudioHandle.py b/main/xiaozhi-server/core/handle/sendAudioHandle.py
index 810e8803f..d159d3fff 100644
--- a/main/xiaozhi-server/core/handle/sendAudioHandle.py
+++ b/main/xiaozhi-server/core/handle/sendAudioHandle.py
@@ -30,6 +30,31 @@ async def sendAudioMessage(conn, sentenceType, audios, text):
await conn.close()
+def calculate_timestamp_and_sequence(conn, start_time, packet_index, frame_duration=60):
+ """
+ 计算音频数据包的时间戳和序列号
+ Args:
+ conn: 连接对象
+ start_time: 起始时间(性能计数器值)
+ packet_index: 数据包索引
+ frame_duration: 帧时长(毫秒),匹配 Opus 编码
+ Returns:
+ tuple: (timestamp, sequence)
+ """
+ # 计算时间戳(使用播放位置计算)
+ timestamp = int((start_time + packet_index * frame_duration / 1000) * 1000) % (
+ 2**32
+ )
+
+ # 计算序列号
+ if hasattr(conn, "audio_flow_control"):
+ sequence = conn.audio_flow_control["sequence"]
+ else:
+ sequence = packet_index # 如果没有流控状态,直接使用索引
+
+ return timestamp, sequence
+
+
async def _send_to_mqtt_gateway(conn, opus_packet, timestamp, sequence):
"""
发送带16字节头部的opus数据包给mqtt_gateway
@@ -91,18 +116,15 @@ async def sendAudio(conn, audios, frame_duration=60):
await asyncio.sleep(delay)
if conn.conn_from_mqtt_gateway:
- # 计算时间戳
- timestamp = int(
- (
- flow_control["start_time"]
- + flow_control["packet_count"] * frame_duration / 1000
- )
- * 1000
- ) % (2**32)
- # 调用通用函数发送带头部的数据包
- await _send_to_mqtt_gateway(
- conn, audios, timestamp, flow_control["sequence"]
+ # 计算时间戳和序列号
+ timestamp, sequence = calculate_timestamp_and_sequence(
+ conn,
+ flow_control["start_time"],
+ flow_control["packet_count"],
+ frame_duration,
)
+ # 调用通用函数发送带头部的数据包
+ await _send_to_mqtt_gateway(conn, audios, timestamp, sequence)
else:
# 直接发送opus数据包,不添加头部
await conn.websocket.send(audios)
@@ -120,12 +142,12 @@ async def sendAudio(conn, audios, frame_duration=60):
pre_buffer_frames = min(3, len(audios))
for i in range(pre_buffer_frames):
if conn.conn_from_mqtt_gateway:
- # 计算时间戳
- timestamp = int((start_time + i * frame_duration / 1000) * 1000) % (
- 2**32
+ # 计算时间戳和序列号
+ timestamp, sequence = calculate_timestamp_and_sequence(
+ conn, start_time, i, frame_duration
)
# 调用通用函数发送带头部的数据包
- await _send_to_mqtt_gateway(conn, audios[i], timestamp, i)
+ await _send_to_mqtt_gateway(conn, audios[i], timestamp, sequence)
else:
# 直接发送预缓冲包,不添加头部
await conn.websocket.send(audios[i])
@@ -147,11 +169,11 @@ async def sendAudio(conn, audios, frame_duration=60):
await asyncio.sleep(delay)
if conn.conn_from_mqtt_gateway:
- # 计算时间戳和序列号
- timestamp = int((start_time + play_position / 1000) * 1000) % (
- 2**32
- ) # 使用播放位置计算时间戳
- sequence = pre_buffer_frames + i # 确保序列号连续
+ # 计算时间戳和序列号(使用当前的数据包索引确保连续性)
+ packet_index = pre_buffer_frames + i
+ timestamp, sequence = calculate_timestamp_and_sequence(
+ conn, start_time, packet_index, frame_duration
+ )
# 调用通用函数发送带头部的数据包
await _send_to_mqtt_gateway(conn, opus_packet, timestamp, sequence)
else:
From 8dd39c5a5b005bd085361aff1ef1a6bd70b028c2 Mon Sep 17 00:00:00 2001
From: hrz <1710360675@qq.com>
Date: Thu, 11 Sep 2025 13:46:35 +0800
Subject: [PATCH 017/366] =?UTF-8?q?update:=E6=B7=BB=E5=8A=A0mqtt=E7=BD=91?=
=?UTF-8?q?=E5=85=B3=E6=9E=B6=E8=AE=BE=E6=95=99=E7=A8=8B?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
README.md | 4 +-
docs/FAQ.md | 1 +
docs/mqtt-gateway-integration.md | 127 ++++++++++++++++++
.../device/controller/OTAController.java | 2 +-
.../service/impl/DeviceServiceImpl.java | 21 +--
5 files changed, 143 insertions(+), 12 deletions(-)
create mode 100644 docs/mqtt-gateway-integration.md
diff --git a/README.md b/README.md
index 862e989a0..b3d6ff1f9 100644
--- a/README.md
+++ b/README.md
@@ -6,7 +6,7 @@
本项目基于人机共生智能理论和技术研发智能终端软硬件体系
为开源智能硬件项目
xiaozhi-esp32提供后端服务
根据小智通信协议使用Python、Java、Vue实现
-支持MCP接入点和声纹识别
+支持MQTT+UDP协议、Websocket协议、MCP接入点、声纹识别
@@ -241,7 +241,7 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/

| 功能模块 | 描述 |
|:---:|:---|
-| 核心架构 | 基于WebSocket和HTTP服务器,提供完整的控制台管理和认证系统 |
+| 核心架构 | 基于MQTT+UDP网关、WebSocket、HTTP服务器,提供完整的控制台管理和认证系统 |
| 语音交互 | 支持流式ASR(语音识别)、流式TTS(语音合成)、VAD(语音活动检测),支持多语言识别和语音处理 |
| 声纹识别 | 支持多用户声纹注册、管理和识别,与ASR并行处理,实时识别说话人身份并传递给LLM进行个性化回应 |
| 智能对话 | 支持多种LLM(大语言模型),实现智能对话 |
diff --git a/docs/FAQ.md b/docs/FAQ.md
index 356ff9594..50202ac1c 100644
--- a/docs/FAQ.md
+++ b/docs/FAQ.md
@@ -62,6 +62,7 @@ VAD:
### 7、部署相关教程
1、[如何进行最简化部署](./Deployment.md)
2、[如何进行全模块部署](./Deployment_all.md)
+2、[如何部署MQTT网关开启MQTT+UDP协议](./mqtt-gateway-integration)
3、[如何自动拉取本项目最新代码自动编译和启动](./dev-ops-integration.md)
4、[如何与Nginx集成](https://github.com/xinnan-tech/xiaozhi-esp32-server/issues/791)
diff --git a/docs/mqtt-gateway-integration.md b/docs/mqtt-gateway-integration.md
new file mode 100644
index 000000000..68003803c
--- /dev/null
+++ b/docs/mqtt-gateway-integration.md
@@ -0,0 +1,127 @@
+# MQTT 网关部署教程
+
+`xiaozhi-esp32-server`项目,可结合虾哥开源的[xiaozhi-mqtt-gateway](https://github.com/78/xiaozhi-mqtt-gateway) 项目进行简单改造,即可实现小智硬件MQTT+UDP连接。
+
+## 准备工作
+
+查看你智控台首页底部的版本号,确认你的智控台版本是否是`0.7.7`及以上版本。如果不是,需要升级智控台。
+
+准备好你的`xiaozhi-server`的`mqtt-websocket`连接地址。在你原来的`websocket地址`基础上,添加`?from=mqtt_gateway`字符,就可以得到`mqtt-websocket`连接地址
+
+1、如果你是源码部署,你的`mqtt-websocket`地址是:
+```
+ws://127.0.0.1:8000/xiaozhi/v1?from=mqtt_gateway
+```
+
+2、如果你是docker部署,你的`mqtt-websocket`地址是
+```
+ws://你宿主机局域网IP:8000/xiaozhi/v1?from=mqtt_gateway
+```
+
+## 第一步 部署MQTT网关
+
+1. 克隆[改造后的xiaozhi-mqtt-gateway项目](https://github.com/xinnan-tech/xiaozhi-mqtt-gateway.git):
+```bash
+git clone https://ghfast.top/https://github.com/xinnan-tech/xiaozhi-mqtt-gateway.git
+cd xiaozhi-mqtt-gateway
+```
+
+2. 安装依赖:
+```bash
+npm install
+npm install -g pm2
+```
+
+3. 配置 `config.json`:
+```bash
+cp config/mqtt.json.example config/mqtt.json
+```
+
+4. 编辑配置文件 config/mqtt.json,把你在`本文准备阶段`的`mqtt-websocket`地址替换到`chat_servers`里。例如源码部署的`xiaozhi-server`就是如下配置:
+
+```
+{
+ "production": {
+ "chat_servers": [
+ "ws://127.0.0.1:8000/xiaozhi/v1?from=mqtt_gateway"
+ ]
+ },
+ "debug": false,
+ "max_mqtt_payload_size": 8192,
+ "mcp_client": {
+ "capabilities": {
+ },
+ "client_info": {
+ "name": "xiaozhi-mqtt-client",
+ "version": "1.0.0"
+ },
+ "max_tools_count": 128
+ }
+}
+```
+5. 在项目根目录创建下`.env`文件,并设置以下环境变量:
+```
+PUBLIC_IP=your-ip # 服务器公网IP
+MQTT_PORT=1883 # MQTT服务器端口
+UDP_PORT=8884 # UDP服务器端口
+MQTT_SIGNATURE_KEY=test # MQTT签名密钥
+```
+请注意`PUBLIC_IP`配置,确保其与实际公网IP一致,如果有域名就填域名。
+
+`MQTT_SIGNATURE_KEY` 是用于MQTT连接认证的密钥,最好设置成复杂一点的,这个密钥稍后还会用到。
+
+6. 启动MQTT网关
+```
+# 启动服务
+pm2 start ecosystem.config.js
+
+# 查看日志
+pm2 logs xz-mqtt
+```
+
+当你看到如下日志,说明MQTT网关启动成功:
+```
+0|xz-mqtt | 2025-09-11T12:14:48: MQTT 服务器正在监听端口 1883
+0|xz-mqtt | 2025-09-11T12:14:48: UDP 服务器正在监听 x.x.x.x:8884
+```
+
+如果需要重启MQTT网关,执行如下命令:
+```
+pm2 restart xz-mqtt
+```
+
+## 第二步 配置智控台
+
+1. 在智控台顶部,点击`参数管理`,搜索`server.mqtt_gateway`,点击编辑,填入你在`.env`文件中设置的`PUBLIC_IP`+`:`+`MQTT_PORT`。类似这样
+```
+192.168.0.7:1883
+```
+2. 在智控台顶部,点击`参数管理`,搜索`server.mqtt_signature_key`,点击编辑,填入你在`.env`文件中设置的`MQTT_SIGNATURE_KEY`。
+
+3. 在智控台顶部,点击`参数管理`,搜索`server.udp_gateway`,点击编辑,填入你在`.env`文件中设置的`PUBLIC_IP`+`:`+`UDP_PORT`。类似这样
+```
+192.168.0.7:8884
+```
+
+上面的配置完成后,你可以使用curl命令,验证你的ota地址是否会下发mqtt配置,把下面的`http://localhost:8002/xiaozhi/ota/`改成你的ota地址
+```
+curl 'http://localhost:8002/xiaozhi/ota/' \
+ -H 'Content-Type: application/json' \
+ -H 'Client-Id: 7b94d69a-9808-4c59-9c9b-704333b38aff' \
+ -H 'Device-Id: 11:22:33:44:55:66' \
+ --data-raw $'{\n "application": {\n "version": "1.0.1",\n "elf_sha256": "1"\n },\n "board": {\n "mac": "11:22:33:44:55:66"\n }\n}'
+```
+
+如果返回的内容包含`mqtt`相关的配置,说明配置成功。类似这样
+
+```
+{"server_time":{"timestamp":1757567894012,"timeZone":"Asia/Shanghai","timezone_offset":480},"activation":{"code":"460609","message":"http://xiaozhi.server.com\n460609","challenge":"11:22:33:44:55:66"},"firmware":{"version":"1.0.1","url":"http://xiaozhi.server.com:8002/xiaozhi/otaMag/download/NOT_ACTIVATED_FIRMWARE_THIS_IS_A_INVALID_URL"},"websocket":{"url":"ws://192.168.4.23:8000/xiaozhi/v1/"},"mqtt":{"endpoint":"192.168.0.7:1883","client_id":"GID_default@@@11_22_33_44_55_66@@@7b94d69a-9808-4c59-9c9b-704333b38aff","username":"eyJpcCI6IjA6MDowOjA6MDowOjA6MSJ9","password":"Y8XP9xcUhVIN9OmbCHT9ETBiYNE3l3Z07Wk46wV9PE8=","publish_topic":"device-server","subscribe_topic":"devices/p2p/11_22_33_44_55_66"}}
+```
+
+## 第三步 重启小智设备
+由于MQTT信息是需要靠OTA地址下发的,因此只有你保证能正常连接服务器的OTA地址,重启唤醒即可。
+
+唤醒后留意mqtt-gateway的日志,确认是否有连接成功的日志。
+```
+pm2 logs xz-mqtt
+```
\ No newline at end of file
diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/controller/OTAController.java b/main/manager-api/src/main/java/xiaozhi/modules/device/controller/OTAController.java
index 26e5dbe64..4a4bfee89 100644
--- a/main/manager-api/src/main/java/xiaozhi/modules/device/controller/OTAController.java
+++ b/main/manager-api/src/main/java/xiaozhi/modules/device/controller/OTAController.java
@@ -78,7 +78,7 @@ public class OTAController {
@Hidden
public ResponseEntity getOTA() {
String mqttUdpConfig = sysParamsService.getValue(Constant.SERVER_MQTT_GATEWAY, false);
- if(StringUtils.isBlank(mqttUdpConfig)) {
+ if (StringUtils.isBlank(mqttUdpConfig)) {
return ResponseEntity.ok("OTA接口不正常,缺少mqtt_gateway地址,请登录智控台,在参数管理找到【server.mqtt_gateway】配置");
}
String wsUrl = sysParamsService.getValue(Constant.SERVER_WEBSOCKET, true);
diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java
index 663800417..9e4528883 100644
--- a/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java
+++ b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java
@@ -184,9 +184,11 @@ public class DeviceServiceImpl extends BaseServiceImpl
// 添加MQTT UDP配置
// 从系统参数获取MQTT Gateway地址,仅在配置有效时使用
String mqttUdpConfig = sysParamsService.getValue(Constant.SERVER_MQTT_GATEWAY, false);
- if (mqttUdpConfig != null && !mqttUdpConfig.equals("null") && !mqttUdpConfig.isEmpty() && deviceById != null) {
+ if (mqttUdpConfig != null && !mqttUdpConfig.equals("null") && !mqttUdpConfig.isEmpty()) {
try {
- DeviceReportRespDTO.MQTT mqtt = buildMqttConfig(macAddress, clientId, deviceById);
+ String groupId = deviceById != null && deviceById.getBoard() != null ? deviceById.getBoard()
+ : "GID_default";
+ DeviceReportRespDTO.MQTT mqtt = buildMqttConfig(macAddress, clientId, groupId);
if (mqtt != null) {
mqtt.setEndpoint(mqttUdpConfig);
response.setMqtt(mqtt);
@@ -478,10 +480,10 @@ public class DeviceServiceImpl extends BaseServiceImpl
*
* @param macAddress MAC地址
* @param clientId 客户端ID (UUID)
- * @param device 设备信息
+ * @param groupId 分组ID
* @return MQTT配置对象
*/
- private DeviceReportRespDTO.MQTT buildMqttConfig(String macAddress, String clientId, DeviceEntity device)
+ private DeviceReportRespDTO.MQTT buildMqttConfig(String macAddress, String clientId, String groupId)
throws Exception {
// 从环境变量或系统参数获取签名密钥
String signatureKey = sysParamsService.getValue("server.mqtt_signature_key", false);
@@ -490,10 +492,11 @@ public class DeviceServiceImpl extends BaseServiceImpl
return null;
}
- // 构建客户端ID格式:groupId@@@macAddress_without_colon@@@uuid
- String groupId = device.getBoard() != null ? device.getBoard() : "GID_default";
- String deviceIdNoColon = macAddress.replace(":", "_");
- String mqttClientId = String.format("%s@@@%s@@@%s", groupId, deviceIdNoColon, clientId);
+ // 构建客户端ID格式:groupId@@@macAddress@@@uuid
+ String groupIdSafeStr = groupId.replace(":", "_");
+ String deviceIdSafeStr = macAddress.replace(":", "_");
+ String clientIdSafeStr = clientId.replace(":", "_");
+ String mqttClientId = String.format("%s@@@%s@@@%s", groupIdSafeStr, deviceIdSafeStr, clientIdSafeStr);
// 构建用户数据(包含IP等信息)
Map userData = new HashMap<>();
@@ -523,7 +526,7 @@ public class DeviceServiceImpl extends BaseServiceImpl
mqtt.setUsername(username);
mqtt.setPassword(password);
mqtt.setPublish_topic("device-server");
- mqtt.setSubscribe_topic("devices/p2p/" + deviceIdNoColon);
+ mqtt.setSubscribe_topic("devices/p2p/" + deviceIdSafeStr);
return mqtt;
}
From e7f5f5da34b6cc43b9d1ff3e8d7a91c908b38b85 Mon Sep 17 00:00:00 2001
From: hrz <1710360675@qq.com>
Date: Thu, 11 Sep 2025 13:49:42 +0800
Subject: [PATCH 018/366] =?UTF-8?q?fix:=E8=A1=A5=E5=85=85=E6=96=87?=
=?UTF-8?q?=E6=A1=A3=E9=93=BE=E6=8E=A5?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
docs/FAQ.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/FAQ.md b/docs/FAQ.md
index 50202ac1c..008895dfe 100644
--- a/docs/FAQ.md
+++ b/docs/FAQ.md
@@ -62,7 +62,7 @@ VAD:
### 7、部署相关教程
1、[如何进行最简化部署](./Deployment.md)
2、[如何进行全模块部署](./Deployment_all.md)
-2、[如何部署MQTT网关开启MQTT+UDP协议](./mqtt-gateway-integration)
+2、[如何部署MQTT网关开启MQTT+UDP协议](./mqtt-gateway-integration.md)
3、[如何自动拉取本项目最新代码自动编译和启动](./dev-ops-integration.md)
4、[如何与Nginx集成](https://github.com/xinnan-tech/xiaozhi-esp32-server/issues/791)
From f0a7ee1c0c113e129a997f09dc5ed65cab481a72 Mon Sep 17 00:00:00 2001
From: 3030332422 <3030332422@qq.com>
Date: Thu, 11 Sep 2025 14:38:27 +0800
Subject: [PATCH 019/366] =?UTF-8?q?fix:=E4=BF=AE=E5=A4=8DLLM=E6=84=8F?=
=?UTF-8?q?=E5=9B=BE=E8=AF=86=E5=88=AB?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../core/handle/intentHandler.py | 16 ++---
.../xiaozhi-server/core/utils/current_time.py | 68 +++++++++++++++++++
.../core/utils/prompt_manager.py | 23 +++----
3 files changed, 84 insertions(+), 23 deletions(-)
create mode 100644 main/xiaozhi-server/core/utils/current_time.py
diff --git a/main/xiaozhi-server/core/handle/intentHandler.py b/main/xiaozhi-server/core/handle/intentHandler.py
index b1486ab91..23b2d0aa1 100644
--- a/main/xiaozhi-server/core/handle/intentHandler.py
+++ b/main/xiaozhi-server/core/handle/intentHandler.py
@@ -98,16 +98,16 @@ async def process_intent_result(conn, intent_result, original_text):
def process_context_result():
conn.dialogue.put(Message(role="user", content=original_text))
- # 使用现有的 prompt_manager 获取完整上下文
- from core.utils.prompt_manager import PromptManager
- prompt_manager = PromptManager(conn.config, conn.logger)
+ from core.utils.current_time import get_current_time_info
+
+ current_time, today_date, today_weekday, lunar_date = get_current_time_info()
# 构建带上下文的基础提示
- context_prompt = prompt_manager.build_enhanced_prompt(
- "当前时间:{{current_time}}\n今天日期:{{today_date}} ({{today_weekday}})\n今天农历:{{lunar_date}}\n用户所在城市:{{local_address}}",
- conn.device_id,
- getattr(conn, 'client_ip', None)
- )
+ context_prompt = f"""当前时间:{current_time}
+ 今天日期:{today_date} ({today_weekday})
+ 今天农历:{lunar_date}
+
+ 请根据以上信息回答用户的问题:{original_text}"""
response = conn.intent.replyResult(context_prompt, original_text)
speak_txt(conn, response)
diff --git a/main/xiaozhi-server/core/utils/current_time.py b/main/xiaozhi-server/core/utils/current_time.py
new file mode 100644
index 000000000..714dd50fd
--- /dev/null
+++ b/main/xiaozhi-server/core/utils/current_time.py
@@ -0,0 +1,68 @@
+"""
+时间工具模块
+提供统一的时间获取功能
+"""
+
+import cnlunar
+from datetime import datetime
+
+WEEKDAY_MAP = {
+ "Monday": "星期一",
+ "Tuesday": "星期二",
+ "Wednesday": "星期三",
+ "Thursday": "星期四",
+ "Friday": "星期五",
+ "Saturday": "星期六",
+ "Sunday": "星期日",
+}
+
+
+def get_current_time() -> str:
+ """
+ 获取当前时间字符串 (格式: HH:MM)
+ """
+ return datetime.now().strftime("%H:%M")
+
+
+def get_current_date() -> str:
+ """
+ 获取今天日期字符串 (格式: YYYY-MM-DD)
+ """
+ return datetime.now().strftime("%Y-%m-%d")
+
+
+def get_current_weekday() -> str:
+ """
+ 获取今天星期几
+ """
+ now = datetime.now()
+ return WEEKDAY_MAP[now.strftime("%A")]
+
+
+def get_current_lunar_date() -> str:
+ """
+ 获取农历日期字符串
+ """
+ try:
+ now = datetime.now()
+ today_lunar = cnlunar.Lunar(now, godType="8char")
+ return "%s年%s%s" % (
+ today_lunar.lunarYearCn,
+ today_lunar.lunarMonthCn[:-1],
+ today_lunar.lunarDayCn,
+ )
+ except Exception:
+ return "农历获取失败"
+
+
+def get_current_time_info() -> tuple:
+ """
+ 获取当前时间信息
+ 返回: (当前时间字符串, 今天日期, 今天星期, 农历日期)
+ """
+ current_time = get_current_time()
+ today_date = get_current_date()
+ today_weekday = get_current_weekday()
+ lunar_date = get_current_lunar_date()
+
+ return current_time, today_date, today_weekday, lunar_date
diff --git a/main/xiaozhi-server/core/utils/prompt_manager.py b/main/xiaozhi-server/core/utils/prompt_manager.py
index fca3a9772..b6c4bef06 100644
--- a/main/xiaozhi-server/core/utils/prompt_manager.py
+++ b/main/xiaozhi-server/core/utils/prompt_manager.py
@@ -117,20 +117,13 @@ class PromptManager:
def _get_current_time_info(self) -> tuple:
"""获取当前时间信息"""
- from datetime import datetime
+ from .current_time import get_current_date, get_current_weekday, get_current_lunar_date
+
+ today_date = get_current_date()
+ today_weekday = get_current_weekday()
+ lunar_date = get_current_lunar_date() + "\n"
- now = datetime.now()
- current_time = now.strftime("%Y年%m月%d日 %H:%M:%S")
- today_date = now.strftime("%Y-%m-%d")
- today_weekday = WEEKDAY_MAP[now.strftime("%A")]
- today_lunar = cnlunar.Lunar(now, godType="8char")
- lunar_date = "%s年%s%s\n" % (
- today_lunar.lunarYearCn,
- today_lunar.lunarMonthCn[:-1],
- today_lunar.lunarDayCn,
- )
-
- return current_time, today_date, today_weekday, lunar_date
+ return today_date, today_weekday, lunar_date
def _get_location_info(self, client_ip: str) -> str:
"""获取位置信息"""
@@ -199,7 +192,7 @@ class PromptManager:
try:
# 获取最新的时间信息(不缓存)
- current_time, today_date, today_weekday, lunar_date = (
+ today_date, today_weekday, lunar_date = (
self._get_current_time_info()
)
@@ -224,7 +217,7 @@ class PromptManager:
template = Template(self.base_prompt_template)
enhanced_prompt = template.render(
base_prompt=user_prompt,
- current_time=current_time,
+ current_time="{{current_time}}",
today_date=today_date,
today_weekday=today_weekday,
lunar_date=lunar_date,
From 26a49ba34cfd162cbc9654c637a41ad9c53b5faa Mon Sep 17 00:00:00 2001
From: hrz <1710360675@qq.com>
Date: Thu, 11 Sep 2025 14:56:53 +0800
Subject: [PATCH 020/366] =?UTF-8?q?numpy1.26.4=E5=92=8Ctourch2.2.2?=
=?UTF-8?q?=E5=85=BC=E5=AE=B9=EF=BC=8C=E5=85=B6=E4=BB=96=E7=89=88=E6=9C=AC?=
=?UTF-8?q?=E4=B8=8E=E5=85=BC=E5=AE=B9=E6=80=A7=E9=97=AE=E9=A2=98?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
main/xiaozhi-server/requirements.txt | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/main/xiaozhi-server/requirements.txt b/main/xiaozhi-server/requirements.txt
index acdcf974a..813cfd771 100755
--- a/main/xiaozhi-server/requirements.txt
+++ b/main/xiaozhi-server/requirements.txt
@@ -3,7 +3,7 @@ torch==2.2.2
silero_vad==6.0.0
websockets==14.2
opuslib_next==1.1.2
-numpy==2.2.6
+numpy==1.26.4
pydub==0.25.1
funasr==1.2.3
torchaudio==2.2.2
From 07242dbfc0024c00f8b3d964e63ebe9f8a5874ae Mon Sep 17 00:00:00 2001
From: FAN-yeB <1442100690@qq.com>
Date: Thu, 11 Sep 2025 16:32:07 +0800
Subject: [PATCH 021/366] =?UTF-8?q?update:=E6=9B=B4=E6=96=B0=E6=B5=81?=
=?UTF-8?q?=E5=BC=8FASR=E9=A6=96=E8=AF=8D=E5=BB=B6=E8=BF=9F=E6=B5=8B?=
=?UTF-8?q?=E8=AF=95=E5=B7=A5=E5=85=B7?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../performance_tester_stream_asr.py | 490 ++++++++----------
1 file changed, 210 insertions(+), 280 deletions(-)
diff --git a/main/xiaozhi-server/performance_tester/performance_tester_stream_asr.py b/main/xiaozhi-server/performance_tester/performance_tester_stream_asr.py
index e03096852..e5ccdaa66 100644
--- a/main/xiaozhi-server/performance_tester/performance_tester_stream_asr.py
+++ b/main/xiaozhi-server/performance_tester/performance_tester_stream_asr.py
@@ -5,104 +5,116 @@ import uuid
import os
import websockets
import gzip
-import hmac
-import base64
-import hashlib
import random
from urllib import parse
from tabulate import tabulate
from config.settings import load_config
-description = "流式ASR首词耗时测试"
+import tempfile
+import wave
+description = "流式ASR首词延迟测试"
+try:
+ import dashscope
+except ImportError:
+ dashscope = None
-class AccessToken:
- @staticmethod
- def _encode_text(text):
- encoded_text = parse.quote_plus(text)
- return encoded_text.replace("+", "%20").replace("*", "%2A").replace("%7E", "~")
-
- @staticmethod
- def _encode_dict(dic):
- keys = dic.keys()
- dic_sorted = [(key, dic[key]) for key in sorted(keys)]
- encoded_text = parse.urlencode(dic_sorted)
- return encoded_text.replace("+", "%20").replace("*", "%2A").replace("%7E", "~")
-
- @staticmethod
- def create_token(access_key_id, access_key_secret):
- parameters = {
- "AccessKeyId": access_key_id,
- "Action": "CreateToken",
- "Format": "JSON",
- "RegionId": "cn-shanghai",
- "SignatureMethod": "HMAC-SHA1",
- "SignatureNonce": str(uuid.uuid1()),
- "SignatureVersion": "1.0",
- "Timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
- "Version": "2019-02-28",
- }
- query_string = AccessToken._encode_dict(parameters)
- string_to_sign = (
- "GET" + "&" + AccessToken._encode_text("/") + "&" + AccessToken._encode_text(query_string)
- )
- secreted_string = hmac.new(
- bytes(access_key_secret + "&", encoding="utf-8"),
- bytes(string_to_sign, encoding="utf-8"),
- hashlib.sha1,
- ).digest()
- signature = base64.b64encode(secreted_string)
- signature = AccessToken._encode_text(signature)
- full_url = "http://nls-meta.cn-shanghai.aliyuncs.com/?Signature=%s&%s" % (signature, query_string)
- response = requests.get(full_url)
- if response.ok:
- root_obj = response.json()
- if "Token" in root_obj:
- return root_obj["Token"]["Id"], root_obj["Token"]["ExpireTime"]
- return None, None
-
-
-class DoubaoStreamASRPerformanceTester:
- def __init__(self):
+class BaseASRTester:
+ def __init__(self, config_key: str):
self.config = load_config()
+ self.config_key = config_key
+ self.asr_config = self.config.get("ASR", {}).get(config_key, {})
self.test_audio_files = self._load_test_audio_files()
self.results = []
-
+
def _load_test_audio_files(self):
- """加载测试用的音频文件"""
audio_root = os.path.join(os.getcwd(), "config", "assets")
test_files = []
-
if os.path.exists(audio_root):
for file_name in os.listdir(audio_root):
- if file_name.endswith('.wav') or file_name.endswith('.pcm'):
- with open(os.path.join(audio_root, file_name), 'rb') as f:
- test_files.append(f.read())
+ if file_name.endswith(('.wav', '.pcm')):
+ file_path = os.path.join(audio_root, file_name)
+ with open(file_path, 'rb') as f:
+ test_files.append({
+ 'data': f.read(),
+ 'path': file_path,
+ 'name': file_name
+ })
return test_files
-
- async def test_doubao_stream_asr(self, test_count=5):
- """测试豆包流式ASR首词响应时间"""
+
+ async def test(self, test_count=5):
+ raise NotImplementedError
+
+ def _calculate_result(self, service_name, latencies, test_count):
+ valid_latencies = [l for l in latencies if l > 0]
+ if valid_latencies:
+ avg_latency = sum(valid_latencies) / len(valid_latencies)
+ status = f"成功({len(valid_latencies)}/{test_count}次有效)"
+ else:
+ avg_latency = 0
+ status = "失败: 所有测试均失败"
+ return {"name": service_name, "latency": avg_latency, "status": status}
+
+
+class DoubaoStreamASRTester(BaseASRTester):
+ def __init__(self):
+ super().__init__("DoubaoStreamASR")
+
+ def _generate_header(self):
+ header = bytearray()
+ header.append((0x01 << 4) | 0x01)
+ header.append((0x01 << 4) | 0x00)
+ header.append((0x01 << 4) | 0x01)
+ header.append(0x00)
+ return header
+
+ def _generate_audio_default_header(self):
+ return self._generate_header()
+
+ def _parse_response(self, res: bytes) -> dict:
+ try:
+ if len(res) < 4:
+ return {"error": "响应数据长度不足"}
+ header = res[:4]
+ message_type = header[1] >> 4
+ if message_type == 0x0F:
+ code = int.from_bytes(res[4:8], "big", signed=False)
+ msg_length = int.from_bytes(res[8:12], "big", signed=False)
+ error_msg = json.loads(res[12:].decode("utf-8"))
+ return {
+ "code": code,
+ "msg_length": msg_length,
+ "payload_msg": error_msg
+ }
+ try:
+ json_data = res[12:].decode("utf-8")
+ return {"payload_msg": json.loads(json_data)}
+ except (UnicodeDecodeError, json.JSONDecodeError):
+ return {"error": "JSON解析失败"}
+ except Exception:
+ return {"error": "解析响应失败"}
+
+ async def test(self, test_count=5):
if not self.test_audio_files:
- print("没有找到测试音频文件")
- return
-
- asr_config = self.config["ASR"]["DoubaoStreamASR"]
+ return {"name": "豆包流式ASR", "latency": 0, "status": "失败: 未找到测试音频"}
+ if not self.asr_config:
+ return {"name": "豆包流式ASR", "latency": 0, "status": "失败: 未配置"}
+
latencies = []
-
for i in range(test_count):
try:
ws_url = "wss://openspeech.bytedance.com/api/v3/sauc/bigmodel"
- appid = asr_config["appid"]
- access_token = asr_config["access_token"]
- uid = asr_config.get("uid", "streaming_asr_service")
-
+ appid = self.asr_config["appid"]
+ access_token = self.asr_config["access_token"]
+ uid = self.asr_config.get("uid", "streaming_asr_service")
+
start_time = time.time()
-
+
headers = {
"X-Api-App-Key": appid,
"X-Api-Access-Key": access_token,
"X-Api-Resource-Id": "volc.bigasr.sauc.duration",
"X-Api-Connect-Id": str(uuid.uuid4())
}
-
+
async with websockets.connect(
ws_url,
additional_headers=headers,
@@ -111,12 +123,8 @@ class DoubaoStreamASRPerformanceTester:
ping_timeout=None,
close_timeout=10
) as ws:
- # 发送初始化请求
request_params = {
- "app": {
- "appid": appid,
- "token": access_token
- },
+ "app": {"appid": appid, "token": access_token},
"user": {"uid": uid},
"request": {
"reqid": str(uuid.uuid4()),
@@ -135,203 +143,141 @@ class DoubaoStreamASRPerformanceTester:
"sample_rate": 16000
}
}
-
+
payload_bytes = str.encode(json.dumps(request_params))
payload_bytes = gzip.compress(payload_bytes)
full_client_request = self._generate_header()
full_client_request.extend((len(payload_bytes)).to_bytes(4, "big"))
full_client_request.extend(payload_bytes)
-
await ws.send(full_client_request)
-
+
init_res = await ws.recv()
result = self._parse_response(init_res)
-
if "code" in result and result["code"] != 1000:
- raise Exception(f"ASR服务初始化失败: {result.get('payload_msg', {}).get('error', '未知错误')}")
-
- # 发送音频数据
- audio_data = self.test_audio_files[0]
+ raise Exception(f"初始化失败: {result.get('payload_msg', {}).get('error', '未知错误')}")
+
+ audio_data = self.test_audio_files[0]['data']
if audio_data.startswith(b'RIFF'):
audio_data = audio_data[44:]
-
- # 直接发送原始音频数据,不进行opus解码
+
payload = gzip.compress(audio_data)
audio_request = bytearray(self._generate_audio_default_header())
audio_request.extend(len(payload).to_bytes(4, "big"))
audio_request.extend(payload)
await ws.send(audio_request)
-
- # 等待第一个数据块
+
first_chunk = await ws.recv()
latency = time.time() - start_time
latencies.append(latency)
await ws.close()
-
+
except Exception as e:
- print(f"第{i+1}次测试: {str(e)}")
+ print(f"[豆包ASR] 第{i+1}次测试失败: {str(e)}")
latencies.append(0)
-
+
return self._calculate_result("豆包流式ASR", latencies, test_count)
-
- async def test_aliyun_stream_asr(self, test_count=5):
- """测试阿里云流式ASR首词响应时间"""
+
+
+class QwenASRFlashTester(BaseASRTester):
+ def __init__(self):
+ super().__init__("Qwen3ASRFlash")
+
+ async def _test_single(self, audio_file_info):
+ start_time = time.time()
+ temp_file_path = None
+
+ try:
+ audio_data = audio_file_info['data']
+ with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as f:
+ temp_file_path = f.name
+
+ with wave.open(temp_file_path, 'wb') as wav_file:
+ wav_file.setnchannels(1)
+ wav_file.setsampwidth(2)
+ wav_file.setframerate(16000)
+ wav_file.writeframes(audio_data)
+
+ messages = [
+ {
+ "role": "user",
+ "content": [
+ {"audio": temp_file_path}
+ ]
+ }
+ ]
+
+ api_key = self.asr_config.get("api_key") or os.getenv("DASHSCOPE_API_KEY")
+ if not api_key:
+ raise ValueError("未配置 api_key")
+
+ if dashscope is None:
+ raise RuntimeError("未安装 dashscope 库")
+
+ dashscope.api_key = api_key
+
+ response = dashscope.MultiModalConversation.call(
+ model="qwen3-asr-flash",
+ messages=messages,
+ result_format="message",
+ asr_options={"enable_lid": True, "enable_itn": False},
+ stream=True
+ )
+
+ for chunk in response:
+ latency = time.time() - start_time
+ return latency
+
+ raise Exception("流式结束,未收到任何响应")
+
+ except Exception as e:
+ raise Exception(f"通义ASR流式失败: {str(e)}")
+
+ finally:
+ if temp_file_path and os.path.exists(temp_file_path):
+ try:
+ os.unlink(temp_file_path)
+ except:
+ pass
+
+ async def test(self, test_count=5):
if not self.test_audio_files:
- print("没有找到测试音频文件")
- return
-
- asr_config = self.config["ASR"]["AliyunStreamASR"]
+ return {"name": "通义千问ASR", "latency": 0, "status": "失败: 未找到测试音频"}
+ if not self.asr_config and not os.getenv("DASHSCOPE_API_KEY"):
+ return {"name": "通义千问ASR", "latency": 0, "status": "失败: 未配置 api_key"}
+
latencies = []
-
for i in range(test_count):
try:
- access_key_id = asr_config["access_key_id"]
- access_key_secret = asr_config["access_key_secret"]
- appkey = asr_config["appkey"]
- host = asr_config.get("host", "nls-gateway-cn-shanghai.aliyuncs.com")
-
- # 获取Token
- token, _ = AccessToken.create_token(access_key_id, access_key_secret)
- if not token:
- raise Exception("无法获取阿里云ASR Token")
-
- # 确定WebSocket URL
- if "-internal." in host:
- ws_url = f"ws://{host}/ws/v1"
- else:
- ws_url = f"wss://{host}/ws/v1"
-
- start_time = time.time()
- async with websockets.connect(
- ws_url,
- additional_headers={"X-NLS-Token": token},
- max_size=1000000000,
- ping_interval=None,
- ping_timeout=None,
- close_timeout=10
- ) as ws:
- # 发送开始请求
- start_request = {
- "header": {
- "namespace": "SpeechTranscriber",
- "name": "StartTranscription",
- "status": 20000000,
- "message_id": ''.join(random.choices('0123456789abcdef', k=32)),
- "task_id": ''.join(random.choices('0123456789abcdef', k=32)),
- "status_text": "Gateway:SUCCESS:Success.",
- "appkey": appkey
- },
- "payload": {
- "format": "pcm",
- "sample_rate": 16000,
- "enable_intermediate_result": True,
- "enable_punctuation_prediction": True,
- "enable_inverse_text_normalization": True,
- "max_sentence_silence": asr_config.get("max_sentence_silence", 8000),
- "enable_voice_detection": False,
- }
- }
- await ws.send(json.dumps(start_request, ensure_ascii=False))
-
- # 等待服务器准备
- start_response = await ws.recv()
- response_data = json.loads(start_response)
- if response_data["header"]["name"] != "TranscriptionStarted":
- raise Exception("阿里云ASR服务初始化失败")
-
- # 发送音频数据
- audio_data = self.test_audio_files[0]
- if audio_data.startswith(b'RIFF'):
- audio_data = audio_data[44:] # 去掉WAV头
-
- await ws.send(audio_data)
-
- # 等待第一个结果
- while True:
- response = await ws.recv()
- if isinstance(response, str):
- result = json.loads(response)
- if result["header"]["name"] == "TranscriptionResultChanged":
- latency = time.time() - start_time
- latencies.append(latency)
- break
- elif result["header"]["name"] == "TaskFailed":
- raise Exception(f"阿里云ASR识别失败: {result.get('payload', {}).get('error_info', '未知错误')}")
-
- # 发送停止请求
- stop_msg = {
- "header": {
- "namespace": "SpeechTranscriber",
- "name": "StopTranscription",
- "status": 20000000,
- "message_id": ''.join(random.choices('0123456789abcdef', k=32)),
- "status_text": "Client:Stop",
- "appkey": appkey
- }
- }
- await ws.send(json.dumps(stop_msg, ensure_ascii=False))
- await ws.close()
-
+ # print(f"\n[通义ASR] 开始第 {i+1} 次测试...")
+ latency = await self._test_single(self.test_audio_files[0])
+ latencies.append(latency)
+ # print(f"[通义ASR] 第{i+1}次成功 延迟: {latency:.3f}s")
except Exception as e:
- print(f"第{i+1}次测试: {str(e)}")
+ # print(f"[通义ASR] 第{i+1}次测试失败: {str(e)}")
latencies.append(0)
-
- return self._calculate_result("阿里云流式ASR", latencies, test_count)
-
- def _generate_header(self):
- """生成请求头"""
- header = bytearray()
- header.append((0x01 << 4) | 0x01)
- header.append((0x01 << 4) | 0x00)
- header.append((0x01 << 4) | 0x01)
- header.append(0x00)
- return header
-
- def _generate_audio_default_header(self):
- """生成音频请求头"""
- return self._generate_header()
-
- def _parse_response(self, res: bytes) -> dict:
- """解析响应"""
+
+ return self._calculate_result("通义千问ASR", latencies, test_count)
+
+
+class ASRPerformanceSuite:
+ def __init__(self):
+ self.testers = []
+ self.results = []
+
+ def register_tester(self, tester_class):
try:
- if len(res) < 4:
- return {"error": "响应数据长度不足"}
-
- header = res[:4]
- message_type = header[1] >> 4
-
- if message_type == 0x0F:
- code = int.from_bytes(res[4:8], "big", signed=False)
- msg_length = int.from_bytes(res[8:12], "big", signed=False)
- error_msg = json.loads(res[12:].decode("utf-8"))
- return {
- "code": code,
- "msg_length": msg_length,
- "payload_msg": error_msg
- }
-
- try:
- json_data = res[12:].decode("utf-8")
- return {"payload_msg": json.loads(json_data)}
- except (UnicodeDecodeError, json.JSONDecodeError):
- return {"error": "JSON解析失败"}
-
- except Exception:
- return {"error": "解析响应失败"}
-
- def _calculate_result(self, service_name, latencies, test_count):
- """计算结果"""
- valid_latencies = [l for l in latencies if l > 0]
- if valid_latencies:
- avg_latency = sum(valid_latencies) / len(valid_latencies)
- status = f"成功({len(valid_latencies)}/{test_count}次有效)"
- else:
- avg_latency = 0
- status = "失败: 所有测试均失败"
- return {"name": service_name, "latency": avg_latency, "status": status}
-
+ tester = tester_class()
+ self.testers.append(tester)
+ print(f"已注册测试器: {tester.config_key}")
+ except Exception as e:
+ name_map = {
+ "DoubaoStreamASRTester": "豆包流式ASR",
+ "QwenASRFlashTester": "通义千问ASR"
+ }
+ name = name_map.get(tester_class.__name__, tester_class.__name__)
+ print(f"跳过 {name}: {str(e)}")
+
def _print_results(self, test_count):
- """打印测试结果"""
if not self.results:
print("没有有效的ASR测试结果")
return
@@ -341,7 +287,6 @@ class DoubaoStreamASRPerformanceTester:
print(f"{'='*60}")
print(f"测试次数: 每个ASR服务测试 {test_count} 次")
- # 排序结果:成功优先,按延迟升序
success_results = sorted(
[r for r in self.results if "成功" in r["status"]],
key=lambda x: x["latency"]
@@ -349,56 +294,41 @@ class DoubaoStreamASRPerformanceTester:
failed_results = [r for r in self.results if "成功" not in r["status"]]
table_data = [
- [r["name"], f"{r['latency']:.3f}", r["status"]]
+ [r["name"], f"{r['latency']:.3f}s" if r['latency'] > 0 else "N/A", r["status"]]
for r in success_results + failed_results
]
- print(tabulate(table_data, headers=["ASR服务", "首词延迟(秒)", "状态"], tablefmt="grid"))
- print("\n测试说明:测量从发送请求到接收第一个识别结果的时间,取多次测试平均值")
- print("- 超时控制: 单个请求最大等待时间为10秒")
- print("- 错误处理: 无法连接和超时的列为网络错误")
- print("- 排序规则: 按平均耗时从快到慢排序")
-
+ print(tabulate(table_data, headers=["ASR服务", "首词延迟", "状态"], tablefmt="grid"))
+ print("\n测试说明:")
+ print("- 测量从发送请求到接收第一个有效识别文本的时间")
+ print("- 超时控制: DashScope 默认超时,豆包 WebSocket 超时10秒")
+ print("- 排序规则: 成功的按延迟升序,失败的排在后面")
+
async def run(self, test_count=5):
- """执行测试"""
print(f"开始流式ASR首词响应时间测试...")
- print(f"每个ASR服务测试次数: {test_count}次")
-
- if not self.config.get("ASR"):
- print("配置文件中未找到ASR配置")
- return
-
- # 测试每种ASR服务
+ print(f"每个ASR服务测试次数: {test_count}次\n")
+
self.results = []
-
- # 测试豆包ASR
- if self.config["ASR"].get("DoubaoStreamASR"):
- result = await self.test_doubao_stream_asr(test_count)
+ for tester in self.testers:
+ print(f"\n--- 测试 {tester.config_key} ---")
+ result = await tester.test(test_count)
self.results.append(result)
- else:
- print("配置文件中未找到豆包流式ASR配置,跳过测试")
-
- # 测试阿里云ASR
- if self.config["ASR"].get("AliyunStreamASR"):
- result = await self.test_aliyun_stream_asr(test_count)
- self.results.append(result)
- else:
- print("配置文件中未找到阿里云流式ASR配置,跳过测试")
-
- # 打印结果
+
self._print_results(test_count)
+
async def main():
import argparse
-
parser = argparse.ArgumentParser(description="流式ASR首词响应时间测试工具")
parser.add_argument("--count", type=int, default=5, help="测试次数")
-
args = parser.parse_args()
- await DoubaoStreamASRPerformanceTester().run(args.count)
+
+ suite = ASRPerformanceSuite()
+ suite.register_tester(DoubaoStreamASRTester)
+ suite.register_tester(QwenASRFlashTester)
+
+ await suite.run(args.count)
+
if __name__ == "__main__":
- import os
- import gzip
- import opuslib_next
asyncio.run(main())
\ No newline at end of file
From 98a14830328c95f7ad83baf7bb243c4f41da8de4 Mon Sep 17 00:00:00 2001
From: rainv123 <2148537152@qq.com>
Date: Thu, 11 Sep 2025 17:10:50 +0800
Subject: [PATCH 022/366] =?UTF-8?q?updata:=E6=99=BA=E6=8E=A7=E5=8F=B0?=
=?UTF-8?q?=E9=A1=B5=E9=9D=A2=E6=B7=BB=E5=8A=A0=E8=AF=AD=E8=A8=80=E5=88=87?=
=?UTF-8?q?=E6=8D=A2=EF=BC=8C=E6=94=AF=E6=8C=81=E4=B8=AD=E8=8B=B1=E7=B9=81?=
=?UTF-8?q?=E3=80=82?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
main/manager-web/package.json | 1 +
main/manager-web/src/App.vue | 63 +-
.../src/components/AddDeviceDialog.vue | 16 +-
.../src/components/AddModelDialog.vue | 38 +-
.../src/components/AddWisdomBodyDialog.vue | 14 +-
.../src/components/CacheViewer.vue | 62 +-
.../src/components/ChangePasswordDialog.vue | 31 +-
.../src/components/ChatHistoryDialog.vue | 12 +-
.../manager-web/src/components/DeviceItem.vue | 48 +-
.../src/components/DictDataDialog.vue | 22 +-
.../src/components/DictTypeDialog.vue | 20 +-
.../src/components/EditVoiceDialog.vue | 34 +-
.../src/components/FirmwareDialog.vue | 60 +-
.../src/components/FunctionDialog.vue | 57 +-
main/manager-web/src/components/HeaderBar.vue | 131 ++-
.../src/components/ManualAddDeviceDialog.vue | 38 +-
.../src/components/ModelEditDialog.vue | 40 +-
.../src/components/ParamDialog.vue | 40 +-
.../src/components/ProviderDialog.vue | 134 +--
main/manager-web/src/components/TtsModel.vue | 88 +-
.../src/components/VoicePrintDialog.vue | 24 +-
main/manager-web/src/i18n/en.js | 801 +++++++++++++++++
main/manager-web/src/i18n/index.js | 43 +
main/manager-web/src/i18n/zh_CN.js | 801 +++++++++++++++++
main/manager-web/src/i18n/zh_TW.js | 802 ++++++++++++++++++
main/manager-web/src/main.js | 5 +
.../src/views/DeviceManagement.vue | 120 +--
main/manager-web/src/views/DictManagement.vue | 157 ++--
main/manager-web/src/views/ModelConfig.vue | 170 ++--
main/manager-web/src/views/OtaManagement.vue | 91 +-
.../src/views/ParamsManagement.vue | 251 +++---
.../src/views/ProviderManagement.vue | 156 ++--
.../src/views/ServerSideManager.vue | 79 +-
main/manager-web/src/views/UserManagement.vue | 76 +-
main/manager-web/src/views/VoicePrint.vue | 46 +-
main/manager-web/src/views/auth.scss | 2 +-
main/manager-web/src/views/home.vue | 21 +-
main/manager-web/src/views/login.vue | 108 ++-
main/manager-web/src/views/register.vue | 35 +-
.../src/views/retrievePassword.vue | 33 +-
main/manager-web/src/views/roleConfig.vue | 91 +-
41 files changed, 3800 insertions(+), 1061 deletions(-)
create mode 100644 main/manager-web/src/i18n/en.js
create mode 100644 main/manager-web/src/i18n/index.js
create mode 100644 main/manager-web/src/i18n/zh_CN.js
create mode 100644 main/manager-web/src/i18n/zh_TW.js
diff --git a/main/manager-web/package.json b/main/manager-web/package.json
index 55e275d93..75471a5e7 100644
--- a/main/manager-web/package.json
+++ b/main/manager-web/package.json
@@ -18,6 +18,7 @@
"opus-recorder": "^8.0.5",
"vue": "^2.6.14",
"vue-axios": "^3.5.2",
+ "vue-i18n": "^8.28.2",
"vue-router": "^3.6.5",
"vuex": "^3.6.2",
"xiaozhi": "file:"
diff --git a/main/manager-web/src/App.vue b/main/manager-web/src/App.vue
index 74ad2af8d..180f8f0d9 100644
--- a/main/manager-web/src/App.vue
+++ b/main/manager-web/src/App.vue
@@ -50,6 +50,7 @@ import CacheViewer from '@/components/CacheViewer.vue';
import { logCacheStatus } from '@/utils/cacheViewer';
export default {
+ name: 'App',
components: {
CacheViewer
},
@@ -78,7 +79,7 @@ export default {
// 在控制台输出提示信息
console.info(
- '%c[小智服务] CDN缓存检查工具已加载',
+ '%c[' + this.$t('system.name') + '] ' + this.$t('cache.cdnEnabled'),
'color: #409EFF; font-weight: bold;'
);
console.info(
@@ -89,7 +90,7 @@ export default {
this.checkServiceWorkerStatus();
} else {
console.info(
- '%c[小智服务] CDN模式已禁用,使用本地打包资源',
+ '%c[' + this.$t('system.name') + '] ' + this.$t('cache.cdnDisabled'),
'color: #67C23A; font-weight: bold;'
);
}
@@ -119,7 +120,7 @@ export default {
const registrations = await navigator.serviceWorker.getRegistrations();
if (registrations.length > 0) {
console.info(
- '%c[小智服务] Service Worker已注册',
+ '%c[' + this.$t('system.name') + '] ' + this.$t('cache.serviceWorkerRegistered'),
'color: #67C23A; font-weight: bold;'
);
@@ -128,46 +129,46 @@ export default {
const hasCaches = await logCacheStatus();
if (!hasCaches) {
console.info(
- '%c[小智服务] 还未检测到缓存,请刷新页面或等待缓存建立',
+ '%c[' + this.$t('system.name') + '] ' + this.$t('cache.noCacheDetected'),
+ 'color: #E6A23C; font-weight: bold;'
+ );
+
+ // 开发环境下提供额外提示
+ if (process.env.NODE_ENV === 'development') {
+ console.info(
+ '%c[' + this.$t('system.name') + '] ' + this.$t('cache.swDevEnvWarning'),
'color: #E6A23C; font-weight: bold;'
);
-
- // 开发环境下提供额外提示
- if (process.env.NODE_ENV === 'development') {
- console.info(
- '%c[小智服务] 在开发环境中,Service Worker可能无法正常初始化缓存',
- 'color: #E6A23C; font-weight: bold;'
- );
- console.info('请尝试以下方法检查Service Worker是否生效:');
- console.info('1. 在开发者工具的Application/Application标签页中查看Service Worker状态');
- console.info('2. 在开发者工具的Application/Cache/Cache Storage中查看缓存内容');
- console.info('3. 使用生产构建(npm run build)并通过HTTP服务器访问以测试完整功能');
- }
+ console.info(this.$t('cache.swCheckMethods'));
+ console.info('1. ' + this.$t('cache.swCheckMethod1'));
+ console.info('2. ' + this.$t('cache.swCheckMethod2'));
+ console.info('3. ' + this.$t('cache.swCheckMethod3'));
+ }
}
}, 2000);
} else {
console.info(
- '%c[小智服务] Service Worker未注册,CDN资源可能无法缓存',
- 'color: #F56C6C; font-weight: bold;'
- );
+ '%c[' + this.$t('system.name') + '] ' + this.$t('cache.serviceWorkerNotRegistered'),
+ 'color: #F56C6C; font-weight: bold;'
+ );
- if (process.env.NODE_ENV === 'development') {
- console.info(
- '%c[小智服务] 在开发环境中,这是正常现象',
- 'color: #E6A23C; font-weight: bold;'
- );
- console.info('Service Worker通常只在生产环境中生效');
- console.info('要测试Service Worker功能:');
- console.info('1. 运行npm run build构建生产版本');
- console.info('2. 通过HTTP服务器访问构建后的页面');
- }
+ if (process.env.NODE_ENV === 'development') {
+ console.info(
+ '%c[' + this.$t('system.name') + '] ' + this.$t('cache.swDevEnvNormal'),
+ 'color: #E6A23C; font-weight: bold;'
+ );
+ console.info(this.$t('cache.swProdOnly'));
+ console.info(this.$t('cache.swTestingTitle'));
+ console.info('1. ' + this.$t('cache.swTestingStep1'));
+ console.info('2. ' + this.$t('cache.swTestingStep2'));
+ }
}
} catch (error) {
console.error('检查Service Worker状态失败:', error);
}
} else {
- console.warn('当前浏览器不支持Service Worker,CDN资源缓存功能不可用');
- }
+ console.warn(this.$t('cache.swNotSupported'));
+ }
}
}
};
diff --git a/main/manager-web/src/components/AddDeviceDialog.vue b/main/manager-web/src/components/AddDeviceDialog.vue
index b273a8dcb..29b9cf305 100644
--- a/main/manager-web/src/components/AddDeviceDialog.vue
+++ b/main/manager-web/src/components/AddDeviceDialog.vue
@@ -6,24 +6,24 @@
style="width: 40px;height: 40px;border-radius: 50%;background: #5778ff;display: flex;align-items: center;justify-content: center;">
- 添加设备
+ {{ $t('device.dialogTitle') }}
*
-
验证码:
+
{{ $t('device.verificationCode') }}
-
+
- 确定
+ {{ $t('device.confirmButton') }}
- 取消
+ {{ $t('device.cancelButton') }}
@@ -47,7 +47,7 @@ export default {
methods: {
confirm() {
if (!/^\d{6}$/.test(this.deviceCode)) {
- this.$message.error('请输入6位数字验证码');
+ this.$message.error(this.$t('device.input6DigitCode'));
return;
}
this.loading = true;
@@ -58,13 +58,13 @@ export default {
if (data.code === 0) {
this.$emit('refresh');
this.$message.success({
- message: '设备绑定成功',
+ message: this.$t('device.bindSuccess'),
showClose: true
});
this.closeDialog();
} else {
this.$message.error({
- message: data.msg || '绑定失败',
+ message: data.msg || this.$t('device.bindFailed'),
showClose: true
});
}
diff --git a/main/manager-web/src/components/AddModelDialog.vue b/main/manager-web/src/components/AddModelDialog.vue
index dbd1ad730..3dda7a9a7 100644
--- a/main/manager-web/src/components/AddModelDialog.vue
+++ b/main/manager-web/src/components/AddModelDialog.vue
@@ -3,8 +3,8 @@
custom-class="custom-dialog" :show-close="false" class="center-dialog">
- 添加模型
-
+ {{ $t('modelConfigDialog.addModel') }}
+
@@ -11,19 +11,19 @@
-
+
-
-
+
+
- 重启
+ {{ $t('serverSideManager.restart') }}
更新配置
+ @click="emitAction(scope.row, actionMap.update_config)">{{ $t('serverSideManager.updateConfig') }}
@@ -44,33 +44,20 @@ import Api from "@/apis/api";
import HeaderBar from "@/components/HeaderBar.vue";
import ParamDialog from "@/components/ParamDialog.vue";
import VersionFooter from "@/components/VersionFooter.vue";
+import i18n from '@/i18n';
export default {
components: { HeaderBar, ParamDialog, VersionFooter },
data() {
return {
paramsList: [],
- actionMap: {
- restart: {
- value: 'restart',
- title: "重启服务端",
- message: "确定要重启服务端吗?",
- confirmText: "重启",
- },
- update_config: {
- value: 'update_config',
- title: "更新配置",
- message: "确定要更新配置吗?",
- confirmText: "更新",
- }
- },
currentPage: 1,
loading: false,
pageSize: 10,
pageSizeOptions: [10, 20, 50, 100],
total: 0,
dialogVisible: false,
- dialogTitle: "新增参数",
+ dialogTitle: '',
isAllSelected: false,
sensitive_keys: ["api_key", "personal_access_token", "access_token", "token", "secret", "access_key_secret", "secret_key"],
paramForm: {
@@ -84,6 +71,10 @@ export default {
created() {
this.fetchParams();
},
+ mounted() {
+ this.getServerList();
+ this.dialogTitle = this.$t('paramManagement.addParam');
+ },
computed: {
pageCount() {
@@ -104,6 +95,22 @@ export default {
}
return pages;
},
+ actionMap() {
+ return {
+ restart: {
+ value: 'restart',
+ title: this.$t('serverSideManager.restartServer'),
+ message: this.$t('serverSideManager.confirmRestart'),
+ confirmText: this.$t('serverSideManager.restart'),
+ },
+ update_config: {
+ value: 'update_config',
+ title: this.$t('serverSideManager.updateConfigTitle'),
+ message: this.$t('serverSideManager.confirmUpdateConfig'),
+ confirmText: this.$t('serverSideManager.updateConfig'),
+ }
+ };
+ }
},
methods: {
handlePageSizeChange(val) {
@@ -122,7 +129,7 @@ export default {
this.total = data.data.length;
} else {
this.$message.error({
- message: data.msg || '获取参数列表失败',
+ message: data.msg || this.$t('serverSideManager.getServerListFailed'),
showClose: true
});
}
@@ -136,6 +143,7 @@ export default {
// 弹开询问框
this.$confirm(actionItem.message, actionItem.title, {
confirmButtonText: actionItem.confirmText, // 确认按钮文本
+ cancelButtonText: this.$t('common.cancel') // 取消按钮文本
}).then(() => {
// 用户点击了确认按钮
Api.admin.sendWsServerAction({
@@ -144,13 +152,13 @@ export default {
}, ({ data }) => {
if (data.code !== 0) {
this.$message.error({
- message: data.msg || '操作失败',
+ message: data.msg || this.$t('serverSideManager.operationFailed'),
showClose: true
});
return;
}
this.$message.success({
- message: `${actionItem.title}成功`,
+ message: actionItem.value === 'restart' ? this.$t('serverSideManager.restartSuccess') : this.$t('serverSideManager.updateConfigSuccess'),
showClose: true
})
})
@@ -450,26 +458,7 @@ export default {
.el-table__body-wrapper {
max-height: calc(var(--table-max-height) - 40px);
+ overflow-y: auto;
}
}
-
-:deep(.el-loading-mask) {
- background-color: rgba(255, 255, 255, 0.6) !important;
- backdrop-filter: blur(2px);
-}
-
-:deep(.el-loading-spinner .circular) {
- width: 28px;
- height: 28px;
-}
-
-:deep(.el-loading-spinner .path) {
- stroke: #6b8cff;
-}
-
-:deep(.el-loading-text) {
- color: #6b8cff !important;
- font-size: 14px;
- margin-top: 8px;
-}
diff --git a/main/manager-web/src/views/UserManagement.vue b/main/manager-web/src/views/UserManagement.vue
index 34d60e746..eb7ba147c 100644
--- a/main/manager-web/src/views/UserManagement.vue
+++ b/main/manager-web/src/views/UserManagement.vue
@@ -3,11 +3,11 @@
-
用户管理
+
{{ $t('header.userManagement') }}
-
- 搜索
+ {{ $t('user.search') }}
@@ -18,29 +18,29 @@
-
+
-
-
-
-
-
+
+
+
+
+
- 正常
- 禁用
+ {{ $t('user.normal') }}
+ {{ $t('user.disabled') }}
-
+
- 重置密码
+ {{ $t('user.resetPassword') }}
禁用账户
+ @click="handleChangeStatus(scope.row, 0)">{{ $t('user.disableAccount') }}
恢复账号
- 删除用户
+ @click="handleChangeStatus(scope.row, 1)">{{ $t('user.enableAccount') }}
+ {{ $t('user.deleteUser') }}
@@ -48,32 +48,32 @@
- {{ isAllSelected ? '取消全选' : '全选' }}
+ {{ isAllSelected ? $t('user.deselectAll') : $t('user.selectAll') }}
- 启用
+ {{ $t('user.enable') }}
禁用
- 删除
+ class="el-icon-remove-outline rotated-icon">{{ $t('user.disable') }}
+ {{ $t('user.delete') }}
@@ -93,6 +93,7 @@ import Api from "@/apis/api";
import HeaderBar from "@/components/HeaderBar.vue";
import VersionFooter from "@/components/VersionFooter.vue";
import ViewPasswordDialog from "@/components/ViewPasswordDialog.vue";
+import i18n from '@/i18n';
export default {
components: { HeaderBar, ViewPasswordDialog, VersionFooter },
data() {
@@ -116,6 +117,9 @@ export default {
pageCount() {
return Math.ceil(this.total / this.pageSize);
},
+ isEnglish() {
+ return i18n.locale === 'en';
+ },
visiblePages() {
const pages = [];
const maxVisible = 3;
@@ -172,19 +176,19 @@ export default {
batchDelete() {
const selectedUsers = this.userList.filter(user => user.selected);
if (selectedUsers.length === 0) {
- this.$message.warning("请先选择需要删除的用户");
+ this.$message.warning(this.$t('user.selectUsersFirst'));
return;
}
- this.$confirm(`确定要删除选中的${selectedUsers.length}个用户吗?`, "警告", {
- confirmButtonText: "确定",
- cancelButtonText: "取消",
+ this.$confirm(this.$t('user.confirmDeleteSelected', { count: selectedUsers.length }), "警告", {
+ confirmButtonText: this.$t('common.confirm'),
+ cancelButtonText: this.$t('common.cancel'),
type: "warning",
})
.then(async () => {
const loading = this.$loading({
lock: true,
- text: "正在删除中...",
+ text: this.$t('user.deleting'),
spinner: "el-icon-loading",
background: "rgba(0, 0, 0, 0.7)",
});
@@ -656,6 +660,16 @@ export default {
color: #606266;
font-size: 14px;
}
+
+ &.page-size-select-en {
+ width: 130px;
+
+ :deep(.el-input__inner) {
+ height: 36px;
+ line-height: 36px;
+ font-size: 15px;
+ }
+ }
:deep(.el-input__suffix) {
right: 6px;
diff --git a/main/manager-web/src/views/VoicePrint.vue b/main/manager-web/src/views/VoicePrint.vue
index be55a9073..43f818a98 100644
--- a/main/manager-web/src/views/VoicePrint.vue
+++ b/main/manager-web/src/views/VoicePrint.vue
@@ -3,7 +3,7 @@
-
声纹识别
+ {{ $t('voicePrint.pageTitle') }}
@@ -11,23 +11,23 @@
-
-
-
-
+ :element-loading-text="$t('voicePrint.loading')" element-loading-spinner="el-icon-loading"
+ element-loading-background="rgba(255, 255, 255, 0.7)">
+
+
+
+
- 编辑
+ {{ $t('voicePrint.edit') }}
删除
+ @click="deleteVoicePrint(scope.row.id)">{{ $t('voicePrint.delete') }}
- 新增
+ {{ $t('voicePrint.add') }}
@@ -56,7 +56,7 @@ export default {
voicePrintList: [],
loading: false,
dialogVisible: false,
- dialogTitle: "添加说话人",
+ dialogTitle: this.$t('voicePrint.addSpeaker'),
isAllSelected: false,
paramForm: {
id: null,
@@ -87,7 +87,7 @@ export default {
}));
} else {
this.$message.error({
- message: data.msg || '获取声纹列表失败',
+ message: data.msg || this.$t('voicePrint.fetchFailed'),
showClose: true
});
}
@@ -95,7 +95,7 @@ export default {
);
},
showAddDialog() {
- this.dialogTitle = "添加说话人";
+ this.dialogTitle = this.$t('voicePrint.addSpeaker');
this.paramForm = {
id: null,
audioId: '',
@@ -105,7 +105,7 @@ export default {
this.dialogVisible = true;
},
editVoicePrint(row) {
- this.dialogTitle = "编辑说话人";
+ this.dialogTitle = this.$t('voicePrint.editSpeaker');
this.paramForm = { ...row };
this.dialogVisible = true;
},
@@ -116,7 +116,7 @@ export default {
Api.agent.updateAgentVoicePrint(form, ({ data }) => {
if (data.code === 0) {
this.$message.success({
- message: "修改成功",
+ message: this.$t('voicePrint.updateSuccess'),
showClose: true
});
this.dialogVisible = false;
@@ -134,7 +134,7 @@ export default {
}, ({ data }) => {
if (data.code === 0) {
this.$message.success({
- message: "新增成功",
+ message: this.$t('voicePrint.addSuccess'),
showClose: true
});
this.dialogVisible = false;
@@ -146,22 +146,22 @@ export default {
},
// 删除按钮
deleteVoicePrint(id) {
- this.$confirm(`确定要删除选中的此声纹吗?`, '警告', {
- confirmButtonText: '确定',
- cancelButtonText: '取消',
+ this.$confirm(this.$t('voicePrint.confirmDelete'), this.$t('voicePrint.warning'), {
+ confirmButtonText: this.$t('voicePrint.confirm'),
+ cancelButtonText: this.$t('voicePrint.cancel'),
type: 'warning',
distinguishCancelAndClose: true
}).then(() => {
Api.agent.deleteAgentVoicePrint(id, ({ data }) => {
if (data.code === 0) {
this.$message.success({
- message: `成功删除此声纹`,
+ message: this.$t('voicePrint.deleteSuccess'),
showClose: true
});
this.fetchVoicePrints();
} else {
this.$message.error({
- message: data.msg || '删除失败,请重试',
+ message: data.msg || this.$t('voicePrint.deleteFailed'),
showClose: true
});
}
@@ -170,13 +170,13 @@ export default {
if (action === 'cancel') {
this.$message({
type: 'info',
- message: '已取消删除操作',
+ message: this.$t('voicePrint.cancelDelete'),
duration: 1000
});
} else {
this.$message({
type: 'info',
- message: '操作已关闭',
+ message: this.$t('voicePrint.closeOperation'),
duration: 1000
});
}
diff --git a/main/manager-web/src/views/auth.scss b/main/manager-web/src/views/auth.scss
index b18fe2d77..5e915063e 100644
--- a/main/manager-web/src/views/auth.scss
+++ b/main/manager-web/src/views/auth.scss
@@ -18,7 +18,7 @@
.login-text {
font-weight: 700;
- font-size: 32px;
+ font-size: 25px;
text-align: left;
color: #3d4566;
}
diff --git a/main/manager-web/src/views/home.vue b/main/manager-web/src/views/home.vue
index 005d763c2..becefaea1 100644
--- a/main/manager-web/src/views/home.vue
+++ b/main/manager-web/src/views/home.vue
@@ -8,20 +8,17 @@
- 你好,小智
+ 你好小智
- 让我们度过
-
- 美好的一天!
-
+ 让我们度过美好的一天!
- Hello, Let's have a wonderful day!
+ let's have a wonderful day!
- 添加智能体
+ {{ $t('home.addAgent') }}
@@ -152,21 +149,21 @@ export default {
},
// 删除智能体
handleDeleteAgent(agentId) {
- this.$confirm('确定要删除该智能体吗?', '提示', {
- confirmButtonText: '确定',
- cancelButtonText: '取消',
+ this.$confirm(this.$t('home.confirmDeleteAgent'), '提示', {
+ confirmButtonText: this.$t('button.ok'),
+ cancelButtonText: this.$t('button.cancel'),
type: 'warning'
}).then(() => {
Api.agent.deleteAgent(agentId, (res) => {
if (res.data.code === 0) {
this.$message.success({
- message: '删除成功',
+ message: this.$t('home.deleteSuccess'),
showClose: true
});
this.fetchAgentList(); // 刷新列表
} else {
this.$message.error({
- message: res.data.msg || '删除失败',
+ message: res.data.msg || this.$t('home.deleteFailed'),
showClose: true
});
}
diff --git a/main/manager-web/src/views/login.vue b/main/manager-web/src/views/login.vue
index 24c601d9c..647fd2dc0 100644
--- a/main/manager-web/src/views/login.vue
+++ b/main/manager-web/src/views/login.vue
@@ -14,17 +14,37 @@

-
登录
+
{{ $t('login.title') }}
+
- WELCOME TO LOGIN
+ {{ $t('login.welcome') }}
+
+
+
+
+
+
+
+
+
+ {{ $t('language.zhCN') }}
+
+
+ {{ $t('language.zhTW') }}
+
+
+ {{ $t('language.en') }}
+
+
+
@@ -33,51 +53,52 @@
-
-
新用户注册
-
忘记密码?
+
{{ $t('login.register') }}
+
{{ $t('login.forgetPassword') }}
-
登录
+
{{ $t('login.login') }}
-
-
-
-
-
-
+
+
+
+
+
+
+
+
-
- 登录即同意
-
《用户协议》
- 和
-
《隐私政策》
+ {{ $t('login.agreeTo') }}
+
{{ $t('login.userAgreement') }}
+ {{ $t('login.and') }}
+
{{ $t('login.privacyPolicy') }}
@@ -93,6 +114,7 @@ import Api from '@/apis/api';
import VersionFooter from '@/components/VersionFooter.vue';
import { getUUID, goToPage, showDanger, showSuccess, validateMobile } from '@/utils';
import { mapState } from 'vuex';
+import { changeLanguage } from '@/i18n';
export default {
name: 'login',
@@ -119,7 +141,8 @@ export default {
},
captchaUuid: '',
captchaUrl: '',
- isMobileLogin: false
+ isMobileLogin: false,
+ languageDropdownVisible: false
}
},
mounted() {
@@ -149,6 +172,21 @@ export default {
}
},
+ // 切换语言下拉菜单的可见状态变化
+ handleLanguageDropdownVisibleChange(visible) {
+ this.languageDropdownVisible = visible;
+ },
+
+ // 切换语言
+ changeLanguage(lang) {
+ changeLanguage(lang);
+ this.languageDropdownVisible = false;
+ this.$message.success({
+ message: this.$t('message.success'),
+ showClose: true
+ });
+ },
+
// 切换登录方式
switchLoginType(type) {
this.isMobileLogin = type === 'mobile';
@@ -226,6 +264,26 @@ export default {
.login-type-container {
margin: 10px 20px;
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+}
+
+.title-language-dropdown {
+ margin-left: 20px;
+}
+
+.language-dropdown {
+ margin-left: auto;
+}
+
+.rotate-down {
+ transform: rotate(180deg);
+ transition: transform 0.3s ease;
+}
+
+.el-icon-arrow-down {
+ transition: transform 0.3s ease;
}
:deep(.el-button--primary) {
diff --git a/main/manager-web/src/views/register.vue b/main/manager-web/src/views/register.vue
index e9f7dbcb4..043cead76 100644
--- a/main/manager-web/src/views/register.vue
+++ b/main/manager-web/src/views/register.vue
@@ -16,9 +16,9 @@

-
注册
+
{{ $t('register.title') }}
- WELCOME TO REGISTER
+ {{ $t('register.welcome') }}
@@ -27,7 +27,7 @@
@@ -38,14 +38,14 @@
-
+
![验证码]()
@@ -56,12 +56,12 @@
- {{ countdown > 0 ? `${countdown}秒后重试` : '发送验证码' }}
+ {{ countdown > 0 ? `${countdown}秒后重试` : $t('register.sendCaptcha') }}
@@ -70,13 +70,13 @@
@@ -84,7 +84,7 @@
style="display: flex; align-items: center; margin-top: 20px; width: 100%; gap: 10px;">
![验证码]()
@@ -92,20 +92,20 @@
-
已有账号?立即登录
+
{{ $t('register.goToLogin') }}
-
立即注册
+
{{ $t('register.registerButton') }}
- 注册即同意
-
《用户协议》
- 和
-
《隐私政策》
+ {{ $t('register.agreeTo') }}
+
{{ $t('register.userAgreement') }}
+ {{ $t('register.and') }}
+
{{ $t('register.privacyPolicy') }}
@@ -124,6 +124,9 @@ import VersionFooter from '@/components/VersionFooter.vue';
import { getUUID, goToPage, showDanger, showSuccess, validateMobile } from '@/utils';
import { mapState } from 'vuex';
+// 导入语言切换功能
+import { changeLanguage } from '@/i18n';
+
export default {
name: 'register',
components: {
diff --git a/main/manager-web/src/views/retrievePassword.vue b/main/manager-web/src/views/retrievePassword.vue
index dbf3ffcfc..195ba06b1 100644
--- a/main/manager-web/src/views/retrievePassword.vue
+++ b/main/manager-web/src/views/retrievePassword.vue
@@ -17,9 +17,9 @@

-
重置密码
+
{{ $t('retrievePassword.title') }}
- PASSWORD RETRIEVE
+ {{ $t('retrievePassword.subtitle') }}
@@ -31,14 +31,14 @@
-
+
![验证码]()
@@ -48,12 +48,12 @@
- {{ countdown > 0 ? `${countdown}秒后重试` : '发送验证码' }}
+ {{ countdown > 0 ? `${countdown}秒后重试` : $t('retrievePassword.sendCaptcha') }}
@@ -61,30 +61,30 @@
-
返回登录
+
{{ $t('retrievePassword.goToLogin') }}
-
立即修改
+
{{ $t('retrievePassword.resetButton') }}
- 同意
-
《用户协议》
- 和
-
《隐私政策》
+ {{ $t('retrievePassword.agreeTo') }}
+
{{ $t('register.userAgreement') }}
+ {{ $t('register.and') }}
+
{{ $t('register.privacyPolicy') }}
@@ -104,6 +104,9 @@ import VersionFooter from '@/components/VersionFooter.vue';
import { getUUID, goToPage, showDanger, showSuccess, validateMobile } from '@/utils';
import { mapState } from 'vuex';
+// 导入语言切换功能
+import { changeLanguage } from '@/i18n';
+
export default {
name: 'retrieve',
components: {
@@ -125,7 +128,7 @@ export default {
mobile: '',
captcha: '',
captchaId: '',
- smsCode: '',
+ mobileCaptcha: '',
newPassword: '',
confirmPassword: ''
},
diff --git a/main/manager-web/src/views/roleConfig.vue b/main/manager-web/src/views/roleConfig.vue
index bbba01bda..80e850278 100644
--- a/main/manager-web/src/views/roleConfig.vue
+++ b/main/manager-web/src/views/roleConfig.vue
@@ -3,7 +3,7 @@
-
角色配置
+ {{ $t('roleConfig.title') }}
@@ -18,10 +18,10 @@