From 6e45303aeac808f47b25908989b7610cd35c441c Mon Sep 17 00:00:00 2001 From: rahulpscraftech360 Date: Fri, 12 Sep 2025 17:43:16 +0530 Subject: [PATCH] configred local db abd reddis for manger api --- main/manager-api/README.md | 191 +++++++++-- main/manager-api/dev-setup.ps1 | 82 +++++ main/manager-api/docker-compose.yml | 90 +++++ .../src/main/resources/application-dev.yml | 41 ++- main/mqtt-gateway/config/mqtt.json | 4 +- main/xiaozhi-server/client.py | 4 +- .../docs/mqtt-gateway-message-flow.md | 323 ++++++++++++++++++ 7 files changed, 694 insertions(+), 41 deletions(-) create mode 100644 main/manager-api/dev-setup.ps1 create mode 100644 main/manager-api/docker-compose.yml create mode 100644 main/xiaozhi-server/docs/mqtt-gateway-message-flow.md diff --git a/main/manager-api/README.md b/main/manager-api/README.md index e8822b8ea..cf8153009 100644 --- a/main/manager-api/README.md +++ b/main/manager-api/README.md @@ -1,26 +1,179 @@ This is a development document. If you need to deploy the Xiaozhi server, [click here to view the deployment tutorial](../../README.md#deployment-documentation) -# Project Introduction +# XiaoZhi ESP32 Manager API -run app +This project is developed based on the SpringBoot framework and serves as the backend API for the XiaoZhi ESP32 management system. -npm run serve -manager-api: This project is developed based on the SpringBoot framework. +## Development Environment Requirements + +- **JDK 21+** +- **Maven 3.8+** +- **Docker & Docker Compose** (for local database and cache) +- **MySQL 8.0+** (via Docker) +- **Redis 7.0+** (via Docker) + +## Quick Start (Development Mode) + +### Option 1: Automated Setup (Recommended) + +```powershell +# Run the automated setup script +.\dev-setup.ps1 + +# Then start the application +mvn spring-boot:run "-Dspring-boot.run.arguments=--spring.profiles.active=dev" +``` + +### Option 2: Manual Setup + +#### Step 1: Start Docker Containers + +First, start the required MySQL and Redis containers: + +```bash +# Navigate to the manager-api directory +cd D:\cheekofinal\xiaozhi-esp32-server\main\manager-api + +# Start Docker containers (MySQL, Redis, phpMyAdmin, Redis Commander) +docker-compose up -d + +# Verify containers are running +docker-compose ps +``` + +#### Step 2: Run the Spring Boot Application + +```bash +# Clean and compile the project +mvn clean compile + +# Run the application with dev profile +mvn spring-boot:run "-Dspring-boot.run.arguments=--spring.profiles.active=dev" +``` + +## Docker Services + +The `docker-compose.yml` includes the following services: + +| Service | Port | Description | Credentials | +|---------|------|-------------|--------------| +| **manager-api-db** (MySQL) | 3307 | MySQL database | User: `manager`
Password: `managerpassword`
Database: `manager_api` | +| **manager-api-redis** | 6380 | Redis cache | Password: `redispassword` | +| **phpMyAdmin** | 8080 | MySQL web interface | User: `root`
Password: `rootpassword` | +| **redis-commander** | 8081 | Redis web interface | Auto-configured | + +## Access Points + +- **API Documentation**: http://localhost:8002/xiaozhi/doc.html +- **Application Base URL**: http://localhost:8002/toy +- **phpMyAdmin**: http://localhost:8080 +- **Redis Commander**: http://localhost:8081 + +## Configuration + +The development configuration is located in: +``` +src/main/resources/application-dev.yml +``` + +This configuration is set up to use the local Docker containers: +- MySQL on localhost:3307 +- Redis on localhost:6380 + +## Database Management + +### Manual Database Connection +```bash +# Connect to MySQL container +docker exec -it manager-api-db mysql -u manager -p'managerpassword' manager_api + +# Connect to Redis container +docker exec -it manager-api-redis redis-cli -a redispassword +``` + +### Database Migration +The application uses Liquibase for database migrations. Migrations run automatically on startup. + +## Troubleshooting + +### Container Issues +```bash +# Check container logs +docker-compose logs manager-api-db +docker-compose logs manager-api-redis + +# Restart containers +docker-compose restart + +# Stop and remove all containers +docker-compose down + +# Stop and remove containers with volumes +docker-compose down -v +``` + +### Application Issues +```bash +# Check if ports are available +netstat -an | findstr :8002 +netstat -an | findstr :3307 +netstat -an | findstr :6380 + +# Clean Maven build +mvn clean install +``` + +### Common Error Solutions + +1. **Port Conflicts**: If ports 3307, 6380, 8080, or 8081 are in use, modify the ports in `docker-compose.yml` + +2. **Database Connection Failed**: + - Ensure Docker containers are running + - Wait for MySQL health check to pass (can take 30-60 seconds) + - Check if credentials match in `application-dev.yml` + +3. **Redis Connection Failed**: + - Verify Redis container is healthy + - Check Redis password configuration + +## Development Workflow + +1. **First Time Setup**: + ```bash + docker-compose up -d + mvn clean compile + mvn spring-boot:run "-Dspring-boot.run.arguments=--spring.profiles.active=dev" + ``` + +2. **Daily Development**: + ```bash + # Start containers (if not running) + docker-compose start + + # Run application + mvn spring-boot:run "-Dspring-boot.run.arguments=--spring.profiles.active=dev" + ``` + +3. **Cleanup**: + ```bash + # Stop application (Ctrl+C) + # Stop containers + docker-compose stop + ``` + +## Project Structure When developing, use a code editor and select the `manager-api` folder as the project directory when importing the project. -# Development Environment - -JDK 21 -Maven 3.8+ -MySQL 8.0+ -Redis 5.0+ -Vue 3.x - -# API Documentation - -After starting, open: http://localhost:8002/xiaozhi/doc.html - -to run app - -mvn spring-boot:run +``` +manager-api/ +├── docker-compose.yml # Docker services configuration +├── src/main/resources/ +│ ├── application.yml # Base configuration +│ ├── application-dev.yml # Development configuration +│ └── application-prod.yml # Production configuration +├── docker/ +│ ├── mysql/init/ # MySQL initialization scripts +│ └── redis/ # Redis configuration +└── target/ # Compiled classes +``` diff --git a/main/manager-api/dev-setup.ps1 b/main/manager-api/dev-setup.ps1 new file mode 100644 index 000000000..74db984bf --- /dev/null +++ b/main/manager-api/dev-setup.ps1 @@ -0,0 +1,82 @@ +# XiaoZhi Manager API - Development Setup Script +# This script sets up the development environment for the Manager API + +Write-Host "🚀 XiaoZhi Manager API Development Setup" -ForegroundColor Green +Write-Host "=======================================" -ForegroundColor Green + +# Check if Docker is running +Write-Host "📦 Checking Docker..." -ForegroundColor Yellow +try { + docker --version | Out-Null + Write-Host "✅ Docker is available" -ForegroundColor Green +} catch { + Write-Host "❌ Docker is not available. Please install Docker Desktop and try again." -ForegroundColor Red + exit 1 +} + +# Check if Maven is available +Write-Host "🔨 Checking Maven..." -ForegroundColor Yellow +try { + mvn --version | Out-Null + Write-Host "✅ Maven is available" -ForegroundColor Green +} catch { + Write-Host "❌ Maven is not available. Please install Maven and try again." -ForegroundColor Red + exit 1 +} + +# Start Docker containers +Write-Host "🐳 Starting Docker containers..." -ForegroundColor Yellow +docker-compose up -d + +if ($LASTEXITCODE -eq 0) { + Write-Host "✅ Docker containers started successfully" -ForegroundColor Green +} else { + Write-Host "❌ Failed to start Docker containers" -ForegroundColor Red + exit 1 +} + +# Wait for containers to be healthy +Write-Host "⏳ Waiting for containers to be healthy..." -ForegroundColor Yellow +$timeout = 60 +$elapsed = 0 +do { + $status = docker-compose ps --services --filter "status=running" | Measure-Object -Line + if ($status.Lines -eq 4) { + Write-Host "✅ All containers are running" -ForegroundColor Green + break + } + Start-Sleep -Seconds 2 + $elapsed += 2 + Write-Host "." -NoNewline -ForegroundColor Yellow +} while ($elapsed -lt $timeout) + +if ($elapsed -ge $timeout) { + Write-Host "`n⚠️ Containers may still be starting. Check with 'docker-compose ps'" -ForegroundColor Yellow +} else { + Write-Host "" +} + +# Display container status +Write-Host "📋 Container Status:" -ForegroundColor Cyan +docker-compose ps + +Write-Host "`n🌐 Service URLs:" -ForegroundColor Cyan +Write-Host " • API Documentation: http://localhost:8002/xiaozhi/doc.html" -ForegroundColor White +Write-Host " • Application: http://localhost:8002/toy" -ForegroundColor White +Write-Host " • phpMyAdmin: http://localhost:8080" -ForegroundColor White +Write-Host " • Redis Commander: http://localhost:8081" -ForegroundColor White + +Write-Host "`n🔑 Database Credentials:" -ForegroundColor Cyan +Write-Host " • MySQL: manager/managerpassword @ localhost:3307" -ForegroundColor White +Write-Host " • Redis: redispassword @ localhost:6380" -ForegroundColor White + +Write-Host "`n🚀 To start the application, run:" -ForegroundColor Green +Write-Host " mvn spring-boot:run `"-Dspring-boot.run.arguments=--spring.profiles.active=dev`"" -ForegroundColor Yellow + +Write-Host "`n📋 Quick Commands:" -ForegroundColor Cyan +Write-Host " • Check containers: docker-compose ps" -ForegroundColor White +Write-Host " • View logs: docker-compose logs [service-name]" -ForegroundColor White +Write-Host " • Stop containers: docker-compose stop" -ForegroundColor White +Write-Host " • Remove containers: docker-compose down" -ForegroundColor White + +Write-Host "`n✨ Setup completed successfully!" -ForegroundColor Green diff --git a/main/manager-api/docker-compose.yml b/main/manager-api/docker-compose.yml new file mode 100644 index 000000000..6c9d22433 --- /dev/null +++ b/main/manager-api/docker-compose.yml @@ -0,0 +1,90 @@ +version: '3.8' + +services: + # MySQL Database + manager-api-db: + image: mysql:8.0 + container_name: manager-api-db + restart: always + environment: + MYSQL_ROOT_PASSWORD: rootpassword + MYSQL_DATABASE: manager_api + MYSQL_USER: manager + MYSQL_PASSWORD: managerpassword + TZ: Asia/Shanghai + ports: + - "3307:3306" # Using 3307 to avoid conflicts with other MySQL instances + volumes: + - mysql_data:/var/lib/mysql + - ./docker/mysql/init:/docker-entrypoint-initdb.d # For initialization scripts + command: --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci + healthcheck: + test: ["CMD", "mysqladmin", "ping", "-h", "localhost"] + timeout: 20s + interval: 10s + retries: 10 + networks: + - manager-api-network + + # Redis Cache + manager-api-redis: + image: redis:7-alpine + container_name: manager-api-redis + restart: always + environment: + TZ: Asia/Shanghai + ports: + - "6380:6379" # Using 6380 to avoid conflicts with other Redis instances + volumes: + - redis_data:/data + - ./docker/redis/redis.conf:/usr/local/etc/redis/redis.conf # Optional custom config + command: redis-server --appendonly yes --requirepass redispassword + healthcheck: + test: ["CMD", "redis-cli", "auth", "redispassword", "ping"] + interval: 10s + timeout: 5s + retries: 3 + networks: + - manager-api-network + + # Redis Commander (Optional - Web UI for Redis) + redis-commander: + image: rediscommander/redis-commander:latest + container_name: manager-api-redis-commander + restart: unless-stopped + environment: + REDIS_HOSTS: local:manager-api-redis:6379:0:redispassword + ports: + - "8081:8081" + depends_on: + - manager-api-redis + networks: + - manager-api-network + + # phpMyAdmin (Optional - Web UI for MySQL) + phpmyadmin: + image: phpmyadmin/phpmyadmin + container_name: manager-api-phpmyadmin + restart: unless-stopped + environment: + PMA_HOST: manager-api-db + PMA_PORT: 3306 + PMA_USER: root + PMA_PASSWORD: rootpassword + MYSQL_ROOT_PASSWORD: rootpassword + ports: + - "8080:80" + depends_on: + - manager-api-db + networks: + - manager-api-network + +volumes: + mysql_data: + driver: local + redis_data: + driver: local + +networks: + manager-api-network: + driver: bridge diff --git a/main/manager-api/src/main/resources/application-dev.yml b/main/manager-api/src/main/resources/application-dev.yml index 195ff5fa6..995bf0d16 100644 --- a/main/manager-api/src/main/resources/application-dev.yml +++ b/main/manager-api/src/main/resources/application-dev.yml @@ -10,21 +10,21 @@ knife4j: # Server configuration server: - secret: d153e93c-bb2f-42e7-8045-a1ee47a1dcfc + secret: a3c1734a-1efe-4ab7-8f43-98f88b874e4b spring: datasource: druid: - #MySQL - # driver-class-name: com.mysql.cj.jdbc.Driver - # # Railway MySQL Configuration - Updated for Railway database - # url: jdbc:mysql://yamanote.proxy.rlwy.net:16958/railway?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true&useSSL=true&allowPublicKeyRetrieval=true - # username: root - # password: cTefiuLmZSMqGpcQImUmBIsUBhNyUvrK + #MySQL - Local Docker Configuration driver-class-name: com.mysql.cj.jdbc.Driver - # 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 - username: root - password: XjOWQwtGNcoMIELTjoMoaaBTfKiBjVcA + # Local Docker MySQL Configuration + url: jdbc:mysql://localhost:3307/manager_api?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true&useSSL=false&allowPublicKeyRetrieval=true + username: manager + password: managerpassword + + # Railway MySQL Configuration (commented out for local development) + # 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 initial-size: 10 max-active: 100 @@ -49,15 +49,20 @@ spring: multi-statement-allow: true data: redis: - # Railway Redis Configuration - host: yamanote.proxy.rlwy.net # Railway Redis服务器地址 - port: 34938 # Railway Redis服务器连接端口 - password: YbdhwguVUNowduNpDZjuSefZFhBXiOEP # Railway Redis服务器连接密码 - username: default # Railway Redis用户名 + # Local Docker Redis Configuration + host: localhost # Local Redis服务器地址 + port: 6380 # Local Redis服务器连接端口 + password: redispassword # Local Redis服务器连接密码 database: 0 # Redis数据库索引(默认为0) - timeout: 30000ms # 连接超时时间(毫秒)- 增加超时时间 + timeout: 10000ms # 连接超时时间(毫秒) ssl: - enabled: false # 尝试禁用SSL,Railway可能不需要 + enabled: false # 本地开发不需要SSL + + # Railway Redis Configuration (commented out for local development) + # host: yamanote.proxy.rlwy.net # Railway Redis服务器地址 + # port: 34938 # Railway Redis服务器连接端口 + # password: YbdhwguVUNowduNpDZjuSefZFhBXiOEP # Railway Redis服务器连接密码 + # username: default # Railway Redis用户名 lettuce: pool: max-active: 8 # 连接池最大连接数(使用负值表示没有限制) diff --git a/main/mqtt-gateway/config/mqtt.json b/main/mqtt-gateway/config/mqtt.json index 8b052ae56..3d25ae423 100644 --- a/main/mqtt-gateway/config/mqtt.json +++ b/main/mqtt-gateway/config/mqtt.json @@ -1,12 +1,12 @@ { "production": { "chat_servers": [ - "ws://139.59.7.72:8000/toy/v1/" + "ws://192.168.1.98:8000/toy/v1/" ] }, "development": { "chat_servers": [ - "ws://139.59.7.72:8000/toy/v1/" + "ws://192.168.1.98:8000/toy/v1/" ], "mac_addresss": [ ] diff --git a/main/xiaozhi-server/client.py b/main/xiaozhi-server/client.py index b1ff71f76..328462cf3 100644 --- a/main/xiaozhi-server/client.py +++ b/main/xiaozhi-server/client.py @@ -19,9 +19,9 @@ import opuslib # --- Configuration --- -SERVER_IP = "192.168.1.179" # !!! UPDATE with your server's local IP address !!! +SERVER_IP = "64.227.170.31" # !!! UPDATE with your server's local IP address !!! OTA_PORT = 8002 -MQTT_BROKER_HOST = "192.168.1.179" # MQTT gateway IP +MQTT_BROKER_HOST = "64.227.170.31" # MQTT gateway IP MQTT_BROKER_PORT = 1883 diff --git a/main/xiaozhi-server/docs/mqtt-gateway-message-flow.md b/main/xiaozhi-server/docs/mqtt-gateway-message-flow.md new file mode 100644 index 000000000..3b1588693 --- /dev/null +++ b/main/xiaozhi-server/docs/mqtt-gateway-message-flow.md @@ -0,0 +1,323 @@ +# 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 + +**Available States**: `start`, `sentence_start`, `stop` + +**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" +} +``` + +**Note**: There is no `sentence_stop` or `sentence_end` state. Individual sentences are marked with `sentence_start`, and the entire TTS session ends with `stop`. + +### 🤖 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*