Livekit Integration

This commit is contained in:
Abilash 2025-09-15 16:25:51 +05:30
parent e5fc8680ec
commit 12e785fff2
24 changed files with 3113 additions and 204 deletions

24
config.yaml Normal file
View file

@ -0,0 +1,24 @@
read_config_from_api: true # Set to true when Java API is running
server:
ip: 0.0.0.0
port: 8000
http_port: 8003
# Update this with your actual IP if needed for vision endpoint
vision_explain: http://192.168.1.111:8003/mcp/vision/explain
mqtt_gateway:
enabled: true
broker: 192.168.1.111
port: 1883
udp_port: 8884
manager-api:
# Manager API endpoint
url: http://192.168.1.111:8002/toy
# Server secret from database
# secret: d153e93c-bb2f-42e7-8045-a1ee47a1dcfc
secret: 1b4414eb-d082-49b0-8e52-c9cae70afb8m
timeout: 30
max_retries: 3
retry_delay: 5

View file

@ -280,7 +280,7 @@ LLM:
但是如果你用docker部署,那么你的日志里给出的接口地址信息就不是真实的接口地址。 但是如果你用docker部署,那么你的日志里给出的接口地址信息就不是真实的接口地址。
最正确的方法,是根据电脑的局域网IP来确定你的接口地址。 最正确的方法,是根据电脑的局域网IP来确定你的接口地址。
如果你的电脑的局域网IP比如是`192.168.1.25`,那么你的接口地址就是:`ws://192.168.1.25:8000/xiaozhi/v1/`,对应的OTA地址就是:`http://192.168.1.25:8003/xiaozhi/ota/`。 如果你的电脑的局域网IP比如是`192.168.1.1115`,那么你的接口地址就是:`ws://192.168.1.1115:8000/xiaozhi/v1/`,对应的OTA地址就是:`http://192.168.1.1115:8003/xiaozhi/ota/`。
这个信息很有用的,后面`编译esp32固件`需要用到。 这个信息很有用的,后面`编译esp32固件`需要用到。

View file

@ -9,7 +9,7 @@
### 如果你用的是简单Server部署 ### 如果你用的是简单Server部署
此刻,请你用浏览器打开你的ota地址,例如我的ota地址 此刻,请你用浏览器打开你的ota地址,例如我的ota地址
``` ```
http://192.168.1.25:8003/xiaozhi/ota/ http://192.168.1.1115:8003/xiaozhi/ota/
``` ```
如果显示“OTA接口运行正常,向设备发送的websocket地址是:ws://xxx:8000/xiaozhi/v1/ 如果显示“OTA接口运行正常,向设备发送的websocket地址是:ws://xxx:8000/xiaozhi/v1/
@ -22,7 +22,7 @@ http://192.168.1.25:8003/xiaozhi/ota/
### 如果你用的是全模块部署 ### 如果你用的是全模块部署
此刻,请你用浏览器打开你的ota地址,例如我的ota地址 此刻,请你用浏览器打开你的ota地址,例如我的ota地址
``` ```
http://192.168.1.25:8002/xiaozhi/ota/ http://192.168.1.1115:8002/xiaozhi/ota/
``` ```
如果显示“OTA接口运行正常,websocket集群数量:X”。那就往下进行2步。 如果显示“OTA接口运行正常,websocket集群数量:X”。那就往下进行2步。
@ -36,7 +36,7 @@ http://192.168.1.25:8002/xiaozhi/ota/
- 3、在列表中找到`server.websocket`项目,输入你的`Websocket`地址。例如我的就是 - 3、在列表中找到`server.websocket`项目,输入你的`Websocket`地址。例如我的就是
``` ```
ws://192.168.1.25:8000/xiaozhi/v1/ ws://192.168.1.1115:8000/xiaozhi/v1/
``` ```
配置完后,再使用浏览器刷新你的ota接口地址,看看是不是正常了。如果还不正常就,就再次确认一下Websocket是否正常启动,是否配置了Websocket地址。 配置完后,再使用浏览器刷新你的ota接口地址,看看是不是正常了。如果还不正常就,就再次确认一下Websocket是否正常启动,是否配置了Websocket地址。
@ -54,7 +54,7 @@ ws://192.168.1.25:8000/xiaozhi/v1/
## 第4步 修改OTA地址 ## 第4步 修改OTA地址
找到`OTA_URL`的`default`的内容,把`https://api.tenclass.net/xiaozhi/ota/` 找到`OTA_URL`的`default`的内容,把`https://api.tenclass.net/xiaozhi/ota/`
改成你自己的地址,例如,我的接口地址是`http://192.168.1.25:8002/xiaozhi/ota/`,就把内容改成这个。 改成你自己的地址,例如,我的接口地址是`http://192.168.1.1115:8002/xiaozhi/ota/`,就把内容改成这个。
修改前: 修改前:
``` ```
@ -68,7 +68,7 @@ config OTA_URL
``` ```
config OTA_URL config OTA_URL
string "Default OTA URL" string "Default OTA URL"
default "http://192.168.1.25:8002/xiaozhi/ota/" default "http://192.168.1.1115:8002/xiaozhi/ota/"
help help
The application will access this URL to check for new firmwares and server address. The application will access this URL to check for new firmwares and server address.
``` ```

View file

@ -52,13 +52,13 @@ Please copy the interface URL:
**Important: Since you're using Docker deployment, DO NOT use the above address directly!** **Important: Since you're using Docker deployment, DO NOT use the above address directly!**
First copy the address and save it in a draft. You need to know your computer's local network IP. For example, if my computer's local IP is `192.168.1.25`, then the original interface address: First copy the address and save it in a draft. You need to know your computer's local network IP. For example, if my computer's local IP is `192.168.1.1115`, then the original interface address:
``` ```
http://172.1.1.1:8004/mcp_endpoint/health?key=xxxx http://172.1.1.1:8004/mcp_endpoint/health?key=xxxx
``` ```
should be changed to: should be changed to:
``` ```
http://192.168.1.25:8004/mcp_endpoint/health?key=xxxx http://192.168.1.1115:8004/mcp_endpoint/health?key=xxxx
``` ```
After making the change, please access this interface directly using your browser. When the browser displays code similar to this, it means success: After making the change, please access this interface directly using your browser. When the browser displays code similar to this, it means success:

View file

@ -1,31 +1,9 @@
# Spring Profile Configuration # Environment variables for Java manager-api server
# Set to 'dev' for development or 'prod' for production # These match your Python server's .env configuration
SPRING_PROFILES_ACTIVE=dev
# Server Configuration # Qdrant Cloud Vector Database
SERVER_PORT=8002 QDRANT_URL=https://1198879c-353e-49b1-bfab-8f74004aaf6d.eu-central-1-0.aws.cloud.qdrant.io:6333
QDRANT_API_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2Nlc3MiOiJtIn0.wKcnr3q8Sq4tb7JzPGnZbuxm9XpfDNutdfFD8mCDlrc
# Database Configuration (Override if needed) # Voyage AI Embeddings
# DB_HOST=localhost VOYAGE_API_KEY=pa-1ai2681JWAAiaAGVPzmVHhiEWmOmwPwVGAfYBBi-oBL
# DB_PORT=3306
# DB_NAME=xiaozhi
# DB_USERNAME=root
# DB_PASSWORD=your_password_here
# Redis Configuration (Override if needed)
# REDIS_HOST=localhost
# REDIS_PORT=6379
# REDIS_PASSWORD=your_redis_password
# External Services
XIAOZHI_PYTHON_SERVER_URL=http://localhost:8003
# Vector Database (Qdrant)
QDRANT_URL=your_qdrant_url_here
QDRANT_API_KEY=your_qdrant_api_key_here
# Voyage AI API Key
VOYAGE_API_KEY=your_voyage_api_key_here
# Textbook Upload Directory
TEXTBOOK_UPLOAD_DIR=/path/to/uploadfile/textbooks

View file

@ -61,6 +61,7 @@ public class ServerSecretFilter extends AuthenticatingFilter {
// 验证token是否匹配 // 验证token是否匹配
String serverSecret = getServerSecret(); String serverSecret = getServerSecret();
if (StringUtils.isBlank(serverSecret) || !serverSecret.equals(token)) { if (StringUtils.isBlank(serverSecret) || !serverSecret.equals(token)) {
// token无效,返回401 // token无效,返回401
this.sendUnauthorizedResponse((HttpServletResponse) servletResponse, "无效的服务器密钥"); this.sendUnauthorizedResponse((HttpServletResponse) servletResponse, "无效的服务器密钥");

View file

@ -22,9 +22,12 @@ spring:
# password: cTefiuLmZSMqGpcQImUmBIsUBhNyUvrK # password: cTefiuLmZSMqGpcQImUmBIsUBhNyUvrK
driver-class-name: com.mysql.cj.jdbc.Driver driver-class-name: com.mysql.cj.jdbc.Driver
# Railway MySQL Configuration - Updated for Railway database # Railway MySQL Configuration - Updated for Railway database
url: jdbc:mysql://crossover.proxy.rlwy.net:56145/railway?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true&useSSL=true&allowPublicKeyRetrieval=true # url: jdbc:mysql://crossover.proxy.rlwy.net:56145/railway?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true&useSSL=true&allowPublicKeyRetrieval=true
# username: root
# password: XjOWQwtGNcoMIELTjoMoaaBTfKiBjVcA
url: jdbc:mysql://localhost:3306/cheeko
username: root username: root
password: XjOWQwtGNcoMIELTjoMoaaBTfKiBjVcA password:
initial-size: 10 initial-size: 10
max-active: 100 max-active: 100
@ -49,18 +52,13 @@ spring:
multi-statement-allow: true multi-statement-allow: true
data: data:
redis: redis:
# Railway Redis Configuration host: localhost
host: yamanote.proxy.rlwy.net # Railway Redis服务器地址 port: 6379
port: 34938 # Railway Redis服务器连接端口 database: 0
password: YbdhwguVUNowduNpDZjuSefZFhBXiOEP # Railway Redis服务器连接密码 timeout: 10000ms
username: default # Railway Redis用户名
database: 0 # Redis数据库索引(默认为0)
timeout: 30000ms # 连接超时时间(毫秒)- 增加超时时间
ssl:
enabled: false # 尝试禁用SSL,Railway可能不需要
lettuce: lettuce:
pool: pool:
max-active: 8 # 连接池最大连接数(使用负值表示没有限制) max-active: 8
max-idle: 8 # 连接池中的最大空闲连接 max-idle: 8
min-idle: 0 # 连接池中的最小空闲连接 min-idle: 0
shutdown-timeout: 100ms # 客户端优雅关闭的等待时间 max-wait: -1ms

View file

@ -17,7 +17,7 @@ spring:
# Profile will be set by SPRING_PROFILES_ACTIVE environment variable # Profile will be set by SPRING_PROFILES_ACTIVE environment variable
# Default to 'dev' if not specified # Default to 'dev' if not specified
profiles: profiles:
default: prod default: dev
messages: messages:
encoding: UTF-8 encoding: UTF-8
basename: i18n/messages basename: i18n/messages

File diff suppressed because it is too large Load diff

View file

@ -1,15 +1,8 @@
{ {
"production": { "debug": false,
"chat_servers": [ "livekit": {
"ws://139.59.7.72:8000/toy/v1/" "url": "wss://cheeko-ycahauzs.livekit.cloud",
] "api_key": "APInJFs2nTcUxcE",
}, "api_secret": "CDpl09fZm8WCMHHYBdi6OBrMqjq5u7D78ROH02O6I8Z"
"development": { }
"chat_servers": [ }
"ws://139.59.7.72:8000/toy/v1/"
],
"mac_addresss": [
]
},
"debug": false
}

View file

@ -1,15 +1,8 @@
{ {
"production": { "debug": true,
"chat_servers": [ "livekit": {
"ws://example:8080" "url": "wss://cheeko-ycahauzs.livekit.cloud",
] "api_key": "APInJFs2nTcUxcE",
}, "api_secret": "CDpl09fZm8WCMHHYBdi6OBrMqjq5u7D78ROH02O6I8Z"
"development": { }
"chat_servers": [ }
"ws://example:8180"
],
"mac_addresss": [
]
},
"debug": false
}

View file

@ -0,0 +1,5 @@
This indicates an issue with your network environment or the credentials in mqtt.json.
Detailed Error: ConnectError: engine: signal failure: failed to retrieve region info: error decoding response body: expected value at line 1 column 1
at Room.connect (/Users/abilashs/development/xiaozhi-esp32-server/main/mqtt-gateway/node_modules/@livekit/rtc-node/dist/room.cjs:406:15)
at async testConnection (/Users/abilashs/development/xiaozhi-esp32-server/main/mqtt-gateway/test_livekit_connection.js:38:5)
[16:12:11.116] DEBUG (lk-rtc/42200): Connect callback received

View file

@ -338,10 +338,10 @@ class MQTTProtocol extends EventEmitter {
* @param {Buffer} message - Complete PINGREQ message * @param {Buffer} message - Complete PINGREQ message
*/ */
parsePingReq(message) { parsePingReq(message) {
debug("Received heartbeat request"); // debug("Received heartbeat request");
// Send PINGRESP // // Send PINGRESP
this.sendPingResp(); // this.sendPingResp();
debug("Sent heartbeat response"); // debug("Sent heartbeat response");
} }
/** /**

View file

@ -0,0 +1,11 @@
W (328178) MQTT: Mqtt client already started
I (329128) MQTT: Connecting to endpoint 192.168.1.111:1883
I (329146) MQTT: Connected to endpoint
I (329146) MQTT: Subscribing to P2P topic: devices/p2p/GID_test@@@78_1c_3c_4c_43_60@@@d903b23c-3fd1-46c8-9fd3-5e297c186825
I (329154) MQTT: Publishing to topic: device-server, message: {"type":"hello","client_id":"78_1c_3c_4c_43_60","version":3,"transport":"udp","features":{"mcp":true},"audio_params":{"format":"opus","sample_rate":16000,"channels":1,"frame_duration":60}}
I (329698) MQTT: [MQTT] Received message on topic: devices/p2p/78_1c_3c_4c_43_60
I (329698) MQTT: [MQTT] Raw payload: {"type":"hello","version":3,"session_id":"2747d6f9-2733-43eb-aa3f-f533265131d4","transport":"udp","udp":{"server":"192.168.1.111","port":8884,"encryption":"aes-128-ctr","key":"158f97dd962de460fc62d5e136217e4e","nonce":"01000000ef3f61c50000000000000000"},"audio_params":{"format":"opus","sample_rate":16000,"channels":1,"frame_duration":60}}
I (329743) MQTT: [MQTT] Message type: hello
I (329749) MQTT: [MQTT] Session ID: 2747d6f9-2733-43eb-aa3f-f533265131d4
I (329759) MQTT: Session ID: 2747d6f9-2733-43eb-aa3f-f533265131d4
I (329770) wifi:Set ps type: 0, coexist: 0

File diff suppressed because it is too large Load diff

View file

@ -10,8 +10,14 @@
"author": "", "author": "",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"@discordjs/opus": "^0.10.0",
"@livekit/rtc-node": "^0.13.18",
"@voicehype/audify-plus": "^2.0.9",
"debug": "^4.4.1", "debug": "^4.4.1",
"dotenv": "^17.2.1", "dotenv": "^17.2.1",
"json5": "^2.2.3",
"livekit-server-sdk": "^2.13.3",
"mqtt": "^5.14.1",
"ws": "^8.18.3" "ws": "^8.18.3"
} }
} }

View file

@ -0,0 +1,58 @@
const mqtt = require('mqtt');
// MQTT broker details from config.yaml
const brokerUrl = 'mqtt://192.168.1.111:1883';
// Client details
const clientId = 'GID_test@@@00:11:22:33:44:55'; // Example clientId
const username = 'testuser'; // Example username
const password = 'testpassword'; // Example password
const options = {
clientId: clientId,
username: username,
password: password,
clean: true,
connectTimeout: 4000,
};
const client = mqtt.connect(brokerUrl, options);
const topic = 'devices/p2p/00:11:22:33:44:55';
client.on('connect', () => {
console.log('Connected to MQTT broker');
client.subscribe(topic, (err) => {
if (!err) {
console.log(`Subscribed to topic: ${topic}`);
// Send a hello message
const helloMessage = {
type: 'hello',
version: 3,
audio_params: {},
features: {}
};
client.publish(topic, JSON.stringify(helloMessage));
console.log(`Published 'hello' message to ${topic}`);
} else {
console.error(`Subscription error: ${err}`);
}
});
});
client.on('message', (topic, message) => {
console.log(`Received message on topic ${topic}: ${message.toString()}`);
// Close the connection after receiving a message
client.end();
});
client.on('error', (err) => {
console.error('Connection error:', err);
client.end();
});
client.on('close', () => {
console.log('Connection closed');
});

View file

@ -0,0 +1,86 @@
const { Room } = require('@livekit/rtc-node');
const { AccessToken } = require('livekit-server-sdk');
const fs = require('fs');
const path = require('path');
async function testConnection() {
let config;
try {
const configFile = fs.readFileSync(path.join(__dirname, 'config', 'mqtt.json'), 'utf8');
config = JSON.parse(configFile);
} catch (e) {
console.error('Error: Could not read or parse config/mqtt.json.', e);
return;
}
if (!config.livekit || !config.livekit.url || !config.livekit.api_key || !config.livekit.api_secret) {
console.error('Error: livekit configuration is missing or incomplete in config/mqtt.json.');
return;
}
const { url, api_key, api_secret } = config.livekit;
const roomName = `test-connection-${Date.now()}`;
const participantName = 'diagnostic-script';
console.log(`---> [TEST SCRIPT] Connecting with URL: '${url}'`);
console.log(`Room: ${roomName}, Participant: ${participantName}`);
const at = new AccessToken(api_key, api_secret, {
identity: participantName,
});
at.addGrant({
room: roomName,
roomJoin: true,
roomCreate: true,
canPublish: true,
canSubscribe: true
});
const token = await at.toJwt(); // Make this async
console.log('Generated Access Token.');
const room = new Room();
// Add connection state monitoring
room.on('connectionStateChanged', (state) => {
console.log('Connection state changed:', state);
});
room.on('connected', () => {
console.log('Room connected event fired');
});
room.on('disconnected', (reason) => {
console.log('Room disconnected:', reason);
});
try {
console.log('Attempting to connect...');
await room.connect(url, token, {
autoSubscribe: true,
dynacast: true
});
console.log('✅ ✅ ✅ Successfully connected to LiveKit room! ✅ ✅ ✅');
console.log('Connection state:', room.connectionState);
console.log('Is connected:', room.isConnected);
console.log('Local participant:', room.localParticipant?.identity);
// Wait a moment to ensure connection is stable
await new Promise(resolve => setTimeout(resolve, 2000));
console.log('The issue is likely within the mqtt-gateway application logic.');
await room.disconnect();
console.log('Disconnected successfully');
} catch (error) {
console.error('❌ ❌ ❌ Failed to connect to LiveKit. ❌ ❌ ❌');
console.error('This indicates an issue with your network environment or the credentials in mqtt.json.');
console.error('Error name:', error.name);
console.error('Error message:', error.message);
console.error('Full error:', error);
}
}
testConnection().catch(console.error);

View file

View file

@ -44,11 +44,13 @@ def load_config():
def get_config_from_api(config): def get_config_from_api(config):
"""Get configuration from Java API""" """Get configuration from Java API"""
print("Fetching configuration from API...")
# Initialize API client # Initialize API client
init_service(config) init_service(config)
print(config)
# Get server configuration # Get server configuration
config_data = get_server_config() config_data = get_server_config()
print(config_data)
if config_data is None: if config_data is None:
raise Exception("Failed to fetch server config from API") raise Exception("Failed to fetch server config from API")

View file

@ -0,0 +1,319 @@
# MQTT Gateway Communication Flow & Message Types
This document provides a comprehensive analysis of the MQTT gateway communication flow and all message types exchanged between the main server (xiaozhi-server), MQTT gateway, and clients.
## 🔄 Communication Architecture
```
┌─────────────────┐ WebSocket ┌─────────────────┐ MQTT ┌─────────────────┐
│ Main Server │ ◄──────────────► │ MQTT Gateway │ ◄─────────► │ Client │
│ (xiaozhi-server)│ │ (Node.js) │ │ (ESP32/Test) │
└─────────────────┘ └─────────────────┘ └─────────────────┘
│
▼
┌─────────────────┐
│ UDP Audio │
│ Streaming │
└─────────────────┘
```
### Key Components:
1. **Main Server (xiaozhi-server)**: Python-based AI server handling TTS/STT/LLM processing
2. **MQTT Gateway**: Node.js bridge converting between WebSocket (server) and MQTT (client)
3. **Client**: ESP32 device or test client connecting via MQTT
4. **UDP Audio Stream**: Encrypted real-time audio data transmission
## 📤 Message Flow Triggers
### 1. Client → MQTT Gateway → Server
Clients publish to the `"device-server"` topic, which the MQTT gateway forwards to the main server via WebSocket:
```javascript
// Client publishes to "device-server" topic
mqtt_client.publish("device-server", JSON.stringify({
"type": "hello",
"version": 3,
"transport": "mqtt",
"audio_params": {...},
"features": [...]
}))
```
### 2. Server → MQTT Gateway → Client
The server sends messages via WebSocket to the MQTT gateway, which publishes to the client's unique P2P topic:
```javascript
// Gateway publishes to client's P2P topic: "devices/p2p/{mac_address}"
connection.sendMqttMessage(JSON.stringify({
"type": "tts",
"state": "start",
"session_id": session_id
}))
```
### 3. Audio Streaming (Server ↔ Client)
Real-time audio data bypasses MQTT and flows directly via encrypted UDP packets for low latency.
## 📨 Complete MQTT Message Types
### 🔄 Connection & Session Management
#### 1. `hello` - Session Initiation
**Direction**: Client → Server, Server → Client
**Purpose**: Establish session and exchange capabilities
**Client Request:**
```json
{
"type": "hello",
"version": 3,
"transport": "mqtt",
"audio_params": {
"sample_rate": 16000,
"channels": 1,
"frame_duration": 20,
"format": "opus"
},
"features": ["tts", "asr", "vad"]
}
```
**Server Response:**
```json
{
"type": "hello",
"version": 3,
"session_id": "db4ead3e-c5e2-4dd4-bbf1-0295195e5058",
"transport": "udp",
"udp": {
"server": "64.227.170.31",
"port": 8884,
"encryption": "aes-128-ctr",
"key": "b6e228c4e0f5d0b93e6fac787786d303",
"nonce": "010000008e863dda0000000000000000"
},
"audio_params": {
"sample_rate": 16000,
"channels": 1,
"frame_duration": 20,
"format": "opus"
}
}
```
#### 2. `goodbye` - Session Termination
**Direction**: Client ↔ Server
**Purpose**: Clean session termination
```json
{
"type": "goodbye",
"session_id": "db4ead3e-c5e2-4dd4-bbf1-0295195e5058"
}
```
### 🎤 Speech Recognition Messages
#### 3. `stt` - Speech-to-Text Results
**Direction**: Server → Client
**Purpose**: Send transcribed speech back to client
```json
{
"type": "stt",
"text": "hello baby",
"session_id": "db4ead3e-c5e2-4dd4-bbf1-0295195e5058"
}
```
#### 4. `listen` - Request Speech Processing
**Direction**: Client → Server
**Purpose**: Request server to start listening/processing speech
```json
{
"type": "listen",
"session_id": "db4ead3e-c5e2-4dd4-bbf1-0295195e5058",
"state": "detect",
"text": "hello baby"
}
```
### 🔊 Text-to-Speech Control Messages
#### 5. `tts` - TTS Playback Control
**Direction**: Server → Client
**Purpose**: Control TTS playback states
**TTS Start:**
```json
{
"type": "tts",
"state": "start",
"session_id": "db4ead3e-c5e2-4dd4-bbf1-0295195e5058"
}
```
**Sentence Start (with text preview):**
```json
{
"type": "tts",
"state": "sentence_start",
"session_id": "db4ead3e-c5e2-4dd4-bbf1-0295195e5058",
"text": "Hi there"
}
```
**TTS Stop:**
```json
{
"type": "tts",
"state": "stop",
"session_id": "db4ead3e-c5e2-4dd4-bbf1-0295195e5058"
}
```
### 🤖 AI Response Messages
#### 6. `llm` - Large Language Model Response
**Direction**: Server → Client
**Purpose**: Send AI-generated response with emotion context
```json
{
"type": "llm",
"text": "😊",
"emotion": "happy",
"session_id": "db4ead3e-c5e2-4dd4-bbf1-0295195e5058"
}
```
### ⏹️ Control Messages
#### 7. `abort` - Abort Current Operation
**Direction**: Client → Server
**Purpose**: Stop current TTS playback or processing
```json
{
"type": "abort",
"session_id": "db4ead3e-c5e2-4dd4-bbf1-0295195e5058"
}
```
#### 8. `record_stop` - Stop Audio Recording
**Direction**: Server → Client
**Purpose**: Instruct client to stop recording audio
```json
{
"type": "record_stop",
"session_id": "db4ead3e-c5e2-4dd4-bbf1-0295195e5058"
}
```
## 🎯 Server Message Trigger Points
### In `core/handle/sendAudioHandle.py`:
- **`send_tts_message()`**: Triggers TTS state messages (`start`, `sentence_start`, `stop`)
- **`send_stt_message()`**: Triggers STT transcription messages
- **`sendAudioMessage()`**: Coordinates TTS playback with state messages
- Called during the audio processing pipeline
### In `core/handle/helloHandle.py`:
- **`handleHelloMessage()`**: Triggers the initial hello response with session details
- **`checkWakeupWords()`**: Can trigger STT and TTS messages for wake word responses
- **`wakeupWordsResponse()`**: Generates dynamic wake word responses
### In MQTT Gateway (`mqtt-gateway/app.js`):
- **`parseHelloMessage()`**: Processes hello messages and sends session details
- **`parseOtherMessage()`**: Forwards messages between server and client
- **`sendMqttMessage()`**: Publishes messages to client's P2P topic
- **`sendUdpMessage()`**: Handles encrypted audio streaming via UDP
## 📊 Typical Message Flow Sequence
### 1. Session Establishment
```
Client → MQTT Gateway: hello (with capabilities)
MQTT Gateway → Server: hello (forwarded via WebSocket)
Server → MQTT Gateway: hello (with session_id and UDP details)
MQTT Gateway → Client: hello (published to P2P topic)
```
### 2. Audio Setup
```
Client: Establishes UDP connection using provided encryption keys
Client: Sends UDP ping to confirm connection
```
### 3. Conversation Flow
```
Client → Server: listen (request to start conversation)
Server → Client: stt (transcription of client speech)
Server → Client: tts (state: "start")
Server → Client: tts (state: "sentence_start", text: preview)
Server → Client: llm (AI response with emotion)
Server ⟶ Client: [UDP Audio Stream] (actual TTS audio)
Server → Client: tts (state: "stop")
```
### 4. Session Termination
```
Client → Server: goodbye
Server → Client: goodbye (acknowledgment)
```
## 🔧 Implementation Details
### MQTT Topics
- **Uplink**: `device-server` (client to server messages)
- **Downlink**: `devices/p2p/{mac_address}` (server to specific client)
### Audio Streaming
- **Protocol**: UDP with AES-128-CTR encryption
- **Format**: Opus codec, 16kHz, mono
- **Frame Duration**: 20ms per packet
- **Encryption**: Header used as nonce, payload encrypted
### Session Management
- **Session ID**: UUID generated for each connection
- **Authentication**: HMAC-SHA256 signed client credentials
- **Keep-alive**: MQTT ping/pong mechanism
### Error Handling
- **Timeout**: Automatic retry for failed messages
- **Connection Loss**: Graceful degradation and reconnection
- **Audio Issues**: Buffer management for packet loss
## 🚨 Key Observations
- **Hybrid Protocol**: MQTT for control messages, UDP for real-time audio streaming
- **Session-based**: All messages include `session_id` for correlation
- **Bidirectional**: Both client and server can initiate certain message types
- **State Machine**: TTS has multiple states for precise playback control
- **Real-time Audio**: Audio packets bypass MQTT for optimal latency
- **P2P Topics**: Each client has a unique MQTT topic for targeted messaging
- **Encryption**: End-to-end encryption for audio data
- **Scalable**: Architecture supports multiple concurrent clients
## 📚 Related Files
### Server-side:
- `core/handle/sendAudioHandle.py` - TTS/STT message handling
- `core/handle/helloHandle.py` - Session establishment
- `core/websocket_server.py` - WebSocket connection management
### MQTT Gateway:
- `mqtt-gateway/app.js` - Main gateway implementation
- `mqtt-gateway/mqtt-protocol.js` - MQTT protocol handling
- `mqtt-gateway/utils/mqtt_config_v2.js` - Client authentication
### Client:
- `client.py` - Test client implementation
- Client logs show actual message flow in practice
---
*Generated on: 2025-09-12*
*Analysis based on xiaozhi-esp32-server codebase and client logs*

161
mqtt-integration.md Normal file
View file

@ -0,0 +1,161 @@
# MQTT Integration Guide
## Overview
The MQTT Gateway bridges ESP32 devices (using MQTT) with LiveKit cloud for audio streaming. **Important: xiaozhi-server is a WebSocket server and does NOT connect to the MQTT gateway as a client.**
## Architecture
```
xiaozhi-server (Python WebSocket Server :8000)
↓ (OTA config)
↓ LiveKit Cloud
↓ ↑
Devices (ESP32) ←→ MQTT ←→ MQTT Gateway (Node.js)
↓ ↓
UDP UDP Audio
```
## Connection Flow
### 1. xiaozhi-server Role
- Acts as WebSocket server on port 8000
- Provides OTA configuration to devices
- Does NOT connect to MQTT gateway
- Does NOT use MQTT client credentials
### 2. Device Obtains Configuration
ESP32 devices get MQTT credentials from xiaozhi-server's OTA endpoint (`/toy/ota/`)
### 3. ESP32 Device MQTT Authentication (Devices Only)
```python
# Client ID format - ONLY used by ESP32 devices, NOT by xiaozhi-server
client_id = "GID_test@@@00_16_3e_ac_b5_38@@@db4ead3e-c5e2-4dd4-bbf1"
# Username: Base64 encoded JSON
username = base64({"ip": "192.168.1.10"})
# Password: HMAC-SHA256 signature
password = base64(hmac_sha256(secret_key, client_id + "|" + username))
```
### 4. MQTT Gateway Configuration
```yaml
# config.yaml
server:
mqtt_gateway:
enabled: true
broker: 192.168.1.111
port: 1883
udp_port: 8884
```
## MQTT Topics
### Subscribed Topics
- `devices/p2p/{mac_address}` - Device-specific P2P messages
### Published Topics
- `device-server` - All device-to-server messages
## Message Types
### Session Management
```json
// hello - Establish session
{
"type": "hello",
"version": 3,
"transport": "mqtt",
"audio_params": {
"sample_rate": 16000,
"channels": 1,
"frame_duration": 20,
"format": "opus"
},
"features": ["tts", "asr", "vad"]
}
// goodbye - Terminate session
{
"type": "goodbye",
"session_id": "uuid"
}
```
### Audio Control
```json
// tts - Text-to-Speech control
{
"type": "tts",
"state": "start|sentence_start|stop",
"session_id": "uuid",
"text": "optional preview text"
}
// stt - Speech-to-Text result
{
"type": "stt",
"text": "transcribed text",
"session_id": "uuid"
}
// listen - Request speech processing
{
"type": "listen",
"session_id": "uuid",
"state": "detect",
"text": "trigger phrase"
}
```
### Control Messages
```json
// abort - Stop current operation
{
"type": "abort",
"session_id": "uuid"
}
// record_stop - Stop recording
{
"type": "record_stop",
"session_id": "uuid"
}
// llm - AI response
{
"type": "llm",
"text": "response",
"emotion": "happy",
"session_id": "uuid"
}
```
## Audio Streaming
- Protocol: UDP with AES-128-CTR encryption
- Format: Opus codec, 16kHz, mono, 20ms frames
- Encryption: Packet header as nonce
- Header: `[type:1, flags:1, len:2, ssrc:4, timestamp:4, sequence:4]`
## Implementation Files
### Server Side
- `core/api/ota_handler.py` - MQTT credential generation
- `config/config_loader.py` - MQTT configuration loading
### MQTT Gateway
- `mqtt-gateway/app.js` - Main gateway logic
- `mqtt-gateway/mqtt-protocol.js` - MQTT protocol handling
- `mqtt-gateway/config/mqtt.json` - Gateway configuration
### Message Flow
1. Device connects with MQTT credentials
2. Sends `hello` to establish session
3. Receives UDP encryption keys
4. Audio streams via encrypted UDP
5. Control messages via MQTT topics
6. Session ends with `goodbye`
## Port Summary
- MQTT: 1883 (TCP)
- WebSocket: 8000 (TCP)
- UDP Audio: 8884 (UDP)

0
sample.md Normal file
View file

23
start_all.sh Normal file
View file

@ -0,0 +1,23 @@
#!/bin/bash
# This script provides the commands to run all the necessary projects for the xiaozhi-esp32-server.
# Please open a separate terminal window for each of the following commands.
# --- Terminal 1: Start xiaozhi-server (Python backend) ---
# cd main/xiaozhi-server
# pip install -r requirements.txt # If you haven't installed dependencies
# python app.py
# --- Terminal 2: Start manager-api (Java backend) ---
# cd main/manager-api
# ./mvnw spring-boot:run
# --- Terminal 3: Start manager-web (Vue.js frontend) ---
# cd main/manager-web
# npm install # If you haven't installed dependencies
# npm run serve
# --- Terminal 4: Start mqtt-gateway (Node.js) ---
# cd main/mqtt-gateway
# npm install # If you haven't installed dependencies
# node app.js