From 12e785fff24ba417497105177d6b97fbe8d6d1d5 Mon Sep 17 00:00:00 2001 From: Abilash Date: Mon, 15 Sep 2025 16:25:51 +0530 Subject: [PATCH] Livekit Integration --- config.yaml | 24 + docs/Deployment.md | 2 +- docs/firmware-build.md | 10 +- docs/mcp-endpoint-integration.md | 4 +- main/manager-api/.env.example | 36 +- .../security/secret/ServerSecretFilter.java | 1 + .../src/main/resources/application-dev.yml | 28 +- .../src/main/resources/application.yml | 2 +- main/mqtt-gateway/app.js | 950 ++++++++-- main/mqtt-gateway/config/mqtt.json | 21 +- main/mqtt-gateway/config/mqtt.json.example | 21 +- main/mqtt-gateway/error.txt | 5 + main/mqtt-gateway/mqtt-protocol.js | 8 +- main/mqtt-gateway/oldDevice.txt | 11 + main/mqtt-gateway/package-lock.json | 1537 ++++++++++++++++- main/mqtt-gateway/package.json | 6 + main/mqtt-gateway/sample_mqtt_client.js | 58 + main/mqtt-gateway/test_livekit_connection.js | 86 + main/xiaozhi-server/config/__init__.py | 0 main/xiaozhi-server/config/config_loader.py | 4 +- mqtt-gateway-message-flow.md | 319 ++++ mqtt-integration.md | 161 ++ sample.md | 0 start_all.sh | 23 + 24 files changed, 3113 insertions(+), 204 deletions(-) create mode 100644 config.yaml create mode 100644 main/mqtt-gateway/error.txt create mode 100644 main/mqtt-gateway/oldDevice.txt create mode 100644 main/mqtt-gateway/sample_mqtt_client.js create mode 100644 main/mqtt-gateway/test_livekit_connection.js create mode 100644 main/xiaozhi-server/config/__init__.py create mode 100644 mqtt-gateway-message-flow.md create mode 100644 mqtt-integration.md create mode 100644 sample.md create mode 100644 start_all.sh diff --git a/config.yaml b/config.yaml new file mode 100644 index 000000000..16cd534c6 --- /dev/null +++ b/config.yaml @@ -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 diff --git a/docs/Deployment.md b/docs/Deployment.md index 99aa86825..5407a288a 100644 --- a/docs/Deployment.md +++ b/docs/Deployment.md @@ -280,7 +280,7 @@ LLM: 但是如果你用docker部署,那么你的日志里给出的接口地址信息就不是真实的接口地址。 最正确的方法,是根据电脑的局域网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固件`需要用到。 diff --git a/docs/firmware-build.md b/docs/firmware-build.md index 64584b278..6895e0e83 100644 --- a/docs/firmware-build.md +++ b/docs/firmware-build.md @@ -9,7 +9,7 @@ ### 如果你用的是简单Server部署 此刻,请你用浏览器打开你的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/ @@ -22,7 +22,7 @@ http://192.168.1.25:8003/xiaozhi/ota/ ### 如果你用的是全模块部署 此刻,请你用浏览器打开你的ota地址,例如我的ota地址 ``` -http://192.168.1.25:8002/xiaozhi/ota/ +http://192.168.1.1115:8002/xiaozhi/ota/ ``` 如果显示“OTA接口运行正常,websocket集群数量:X”。那就往下进行2步。 @@ -36,7 +36,7 @@ http://192.168.1.25:8002/xiaozhi/ota/ - 3、在列表中找到`server.websocket`项目,输入你的`Websocket`地址。例如我的就是 ``` -ws://192.168.1.25:8000/xiaozhi/v1/ +ws://192.168.1.1115:8000/xiaozhi/v1/ ``` 配置完后,再使用浏览器刷新你的ota接口地址,看看是不是正常了。如果还不正常就,就再次确认一下Websocket是否正常启动,是否配置了Websocket地址。 @@ -54,7 +54,7 @@ ws://192.168.1.25:8000/xiaozhi/v1/ ## 第4步 修改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 string "Default OTA URL" - default "http://192.168.1.25:8002/xiaozhi/ota/" + default "http://192.168.1.1115:8002/xiaozhi/ota/" help The application will access this URL to check for new firmwares and server address. ``` diff --git a/docs/mcp-endpoint-integration.md b/docs/mcp-endpoint-integration.md index a248f212b..1c0dc4217 100644 --- a/docs/mcp-endpoint-integration.md +++ b/docs/mcp-endpoint-integration.md @@ -52,13 +52,13 @@ Please copy the interface URL: **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 ``` 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: diff --git a/main/manager-api/.env.example b/main/manager-api/.env.example index 05a426d79..abe948994 100644 --- a/main/manager-api/.env.example +++ b/main/manager-api/.env.example @@ -1,31 +1,9 @@ -# Spring Profile Configuration -# Set to 'dev' for development or 'prod' for production -SPRING_PROFILES_ACTIVE=dev +# Environment variables for Java manager-api server +# These match your Python server's .env configuration -# Server Configuration -SERVER_PORT=8002 +# Qdrant Cloud Vector Database +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) -# DB_HOST=localhost -# 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 \ No newline at end of file +# Voyage AI Embeddings +VOYAGE_API_KEY=pa-1ai2681JWAAiaAGVPzmVHhiEWmOmwPwVGAfYBBi-oBL \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/secret/ServerSecretFilter.java b/main/manager-api/src/main/java/xiaozhi/modules/security/secret/ServerSecretFilter.java index b2a18547e..0ae0d0268 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/security/secret/ServerSecretFilter.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/secret/ServerSecretFilter.java @@ -61,6 +61,7 @@ public class ServerSecretFilter extends AuthenticatingFilter { // 验证token是否匹配 String serverSecret = getServerSecret(); + if (StringUtils.isBlank(serverSecret) || !serverSecret.equals(token)) { // token无效,返回401 this.sendUnauthorizedResponse((HttpServletResponse) servletResponse, "无效的服务器密钥"); diff --git a/main/manager-api/src/main/resources/application-dev.yml b/main/manager-api/src/main/resources/application-dev.yml index 195ff5fa6..319c436cb 100644 --- a/main/manager-api/src/main/resources/application-dev.yml +++ b/main/manager-api/src/main/resources/application-dev.yml @@ -22,9 +22,12 @@ spring: # password: cTefiuLmZSMqGpcQImUmBIsUBhNyUvrK 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 + # 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 - password: XjOWQwtGNcoMIELTjoMoaaBTfKiBjVcA + password: initial-size: 10 max-active: 100 @@ -49,18 +52,13 @@ 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用户名 - database: 0 # Redis数据库索引(默认为0) - timeout: 30000ms # 连接超时时间(毫秒)- 增加超时时间 - ssl: - enabled: false # 尝试禁用SSL,Railway可能不需要 + host: localhost + port: 6379 + database: 0 + timeout: 10000ms lettuce: pool: - max-active: 8 # 连接池最大连接数(使用负值表示没有限制) - max-idle: 8 # 连接池中的最大空闲连接 - min-idle: 0 # 连接池中的最小空闲连接 - shutdown-timeout: 100ms # 客户端优雅关闭的等待时间 \ No newline at end of file + max-active: 8 + max-idle: 8 + min-idle: 0 + max-wait: -1ms diff --git a/main/manager-api/src/main/resources/application.yml b/main/manager-api/src/main/resources/application.yml index 56934b317..8590bbdc5 100644 --- a/main/manager-api/src/main/resources/application.yml +++ b/main/manager-api/src/main/resources/application.yml @@ -17,7 +17,7 @@ spring: # Profile will be set by SPRING_PROFILES_ACTIVE environment variable # Default to 'dev' if not specified profiles: - default: prod + default: dev messages: encoding: UTF-8 basename: i18n/messages diff --git a/main/mqtt-gateway/app.js b/main/mqtt-gateway/app.js index 9465c5c0a..71dba5703 100644 --- a/main/mqtt-gateway/app.js +++ b/main/mqtt-gateway/app.js @@ -1,8 +1,10 @@ -// Description: MQTT+UDP to WebSocket bridge +// Description: MQTT+UDP to LiveKit bridge // Author: terrence@tenclass.com // Date: 2025-03-12 +// Modified by: Gemini require("dotenv").config(); +const JSON5 = require("json5"); const net = require("net"); const debugModule = require("debug"); @@ -10,7 +12,49 @@ const debug = debugModule("mqtt-server"); const crypto = require("crypto"); const dgram = require("dgram"); const Emitter = require("events"); -const WebSocket = require("ws"); +const { AccessToken } = require("livekit-server-sdk"); +const { + Room, + RoomEvent, + AudioSource, + AudioFrame, + AudioStream, + LocalAudioTrack, + TrackPublishOptions, + TrackSource, + TrackKind, + AudioResampler, + AudioResamplerQuality, +} = require("@livekit/rtc-node"); +// Import Opus Encoder and Decoder from audify-plus +const { OpusEncoder, OpusDecoder, OpusApplication } = require("@voicehype/audify-plus"); + +// Initialize Opus encoder and decoder for 16kHz mono (same as before) +let opusEncoder = null; +let opusDecoder = null; +// Define constants for audio parameters +const SAMPLE_RATE = 16000; // Hz +const CHANNELS = 1; // Mono +const FRAME_DURATION_MS = 20; // 20ms frames (standard for Opus) +const FRAME_SIZE_SAMPLES = (SAMPLE_RATE * FRAME_DURATION_MS) / 1000; // 16000 * 20 / 1000 = 320 +const FRAME_SIZE_BYTES = FRAME_SIZE_SAMPLES * 2; // 320 samples * 2 bytes/sample = 640 bytes PCM + +try { + // For 24kHz, mono audio (resampled from 48kHz LiveKit audio) + opusEncoder = new OpusEncoder(24000, 1, OpusApplication.OPUS_APPLICATION_AUDIO); + opusDecoder = new OpusDecoder(16000, 1); + + console.log( + "✅ [OPUS] audify-plus encoder/decoder initialized successfully - encoder: 24kHz, decoder: 16kHz mono" + ); +} catch (err) { + console.error( + "❌ [OPUS] Failed to initialize audify-plus encoder/decoder:", + err.message + ); + // Fallback: Disable Opus if init fails (will fall back to PCM) +} + const { MQTTProtocol } = require("./mqtt-protocol"); const { ConfigManager } = require("./utils/config-manager"); const { validateMqttCredentials } = require("./utils/mqtt_config_v2"); @@ -25,129 +69,764 @@ function setDebugEnabled(enabled) { const configManager = new ConfigManager("mqtt.json"); configManager.on("configChanged", (config) => { - setDebugEnabled(config.debug); + setDebugEnabled(false); }); setDebugEnabled(configManager.get("debug")); -class WebSocketBridge extends Emitter { +class LiveKitBridge 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.room = null; + this.audioSource = new AudioSource(16000, 1); this.protocolVersion = protocolVersion; - this.deviceSaidGoodbye = false; - this.initializeChatServer(); + + // Initialize audio resampler for 48kHz -> 16kHz conversion + this.audioResampler = new AudioResampler(48000, 16000, 1); // 48kHz -> 16kHz, mono + + // Frame buffer for accumulating resampled audio into proper frame sizes + this.frameBuffer = Buffer.alloc(0); + this.targetFrameSize = 320; // 320 samples = 20ms at 16kHz + this.targetFrameBytes = this.targetFrameSize * 2; // 640 bytes for 16-bit PCM + + // Initialize Opus decoder for incoming audio (device -> LiveKit) + // this.opusDecoder = null; + // Initialize Opus encoder for outgoing audio (LiveKit -> device) + // this.opusEncoder = null; + + if (OpusEncoder) { + try { + // this.opusDecoder = new OpusEncoder(16000, 1); // 16kHz, mono + console.log(`✅ [OPUS] Decoder initialized for ${this.macAddress}`); + + // this.opusEncoder = new OpusEncoder(16000, 1); // 16kHz, mono + console.log(`✅ [OPUS] Encoder initialized for ${this.macAddress}`); + } catch (err) { + console.error( + `❌ [OPUS] Failed to initialize encoder/decoder: ${err.message}` + ); + } + } + + this.initializeLiveKit(); } - 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; + initializeLiveKit() { + const livekitConfig = configManager.get("livekit"); + if (!livekitConfig) { + throw new Error("LiveKit config not found"); } + this.livekitConfig = livekitConfig; + } - if (!chatServers) { - throw new Error(`Chat server not found for ${this.macAddress}`); + // Process buffered audio frames and send PCM directly + processBufferedFrames(timestamp, frameCount, participantIdentity) { + while (this.frameBuffer.length >= this.targetFrameBytes) { + // Extract one complete frame + const frameData = this.frameBuffer.slice(0, this.targetFrameBytes); + this.frameBuffer = this.frameBuffer.slice(this.targetFrameBytes); + + // Process this complete frame - send PCM directly without Opus encoding + if (frameData.length > 0) { + const samples = new Int16Array(frameData.buffer, frameData.byteOffset, frameData.length / 2); + const isSilent = samples.every(sample => sample === 0); + const maxAmplitude = Math.max(...samples.map(s => Math.abs(s))); + const isNearlySilent = maxAmplitude < 10; + + if (isSilent || isNearlySilent) { + // console.log(`🔇 [PCM] Silent frame detected, skipping`); + continue; + } + + if (frameCount <= 3 || frameCount % 100 === 0) { + // console.log(`✅ [BUFFERED] Frame ${frameCount}: 16kHz PCM ${frameData.length}B sent directly`); + } + + // Send PCM directly without Opus encoding + this.connection.sendUdpMessage(frameData, timestamp); + + // Commented out Opus encoding for testing + /* + if (opusEncoder) { + try { + const alignedBuffer = Buffer.allocUnsafe(frameData.length); + frameData.copy(alignedBuffer); + const opusBuffer = opusEncoder.encode(alignedBuffer, this.targetFrameSize); + this.connection.sendUdpMessage(opusBuffer, timestamp); + } catch (err) { + console.error(`❌ [BUFFERED] Encode error: ${err.message}`); + } + } + */ + } } - - 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; - } + const { url, api_key, api_secret } = this.livekitConfig; + const roomName = this.uuid || this.macAddress; + const participantName = this.macAddress; - if (this.userData && this.userData.ip) { - headers["x-forwarded-for"] = this.userData.ip; - } + 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(); // Fixed: Make this async - this.wsClient = new WebSocket(this.chatServer, { headers }); + this.room = new Room(); - this.wsClient.on("open", () => { - this.sendJson({ - type: "hello", - version: 2, - transport: "websocket", - audio_params, - features, - }); - }); + // Add connection state monitoring + this.room.on("connectionStateChanged", (state) => { + console.log(`[LiveKitBridge] Connection state changed: ${state}`); + }); - this.wsClient.on("message", (data, isBinary) => { - if (isBinary) { - // xiaozhi-server sends raw Opus data directly as binary WebSocket messages - // No header parsing needed - the entire binary message is the Opus payload - console.log( - `📦 WebSocket binary message: ${data.length} bytes of raw Opus data` - ); - console.log( - `📦 First 8 bytes: ${data - .subarray(0, Math.min(8, data.length)) - .toString("hex")}` - ); - // Generate timestamp for UDP packet (use relative timestamp to fit in 32-bit) - const timestamp = - (Date.now() - this.connection.udp.startTime) & 0xffffffff; - // Send the raw Opus data directly via UDP - this.connection.sendUdpMessage(data, timestamp); - } else { - // JSON data sent via MQTT - const message = JSON.parse(data.toString()); - if (message.type === "hello") { - resolve(message); - } else { - this.connection.sendMqttMessage(JSON.stringify(message)); + this.room.on("connected", () => { + console.log("[LiveKitBridge] Room connected event fired"); + }); + + this.room.on("disconnected", (reason) => { + console.log(`[LiveKitBridge] Room disconnected: ${reason}`); + }); + + this.room.on( + RoomEvent.DataReceived, + (payload, participant, kind, topic) => { + try { + const str = Buffer.from(payload).toString("utf-8"); + let data; + try { + data = JSON5.parse(str); + // console.log("Data:", data); + } catch (err) { + console.error("Invalid JSON5:", err.message); } + switch (data.type) { + case "agent_state_changed": + // console.log(`Agent state changed: ${JSON.stringify(data.data)}`); + if ( + data.data.old_state === "speaking" && + data.data.new_state === "listening" + ) { + // Send TTS stop message to device + this.sendTtsStopMessage(); + } + break; + case "user_input_transcribed": + // console.log(`Transcription: ${JSON.stringify(data.data)}`); + // Send STT result back to device + this.sendSttMessage(data.data.text || data.data.transcript); + break; + case "speech_created": + // console.log(`Speech created: ${JSON.stringify(data.data)}`); + // Send TTS start message to device + this.sendTtsStartMessage(data.data.text); + break; + // case "metrics_collected": + // console.log(`Metrics: ${JSON.stringify(data.data)}`); + // break; + default: + //console.log(`Unknown data type: ${data.type}`); + } + } catch (error) { + console.error(`Error processing data packet: ${error}`); } - }); + } + ); - this.wsClient.on("error", (error) => { - console.error(`WebSocket error for device ${this.macAddress}:`, error); - this.emit("close"); + return new Promise(async (resolve, reject) => { + try { + console.log(`[LiveKitBridge] Connecting to LiveKit room: ${roomName}`); + await this.room.connect(url, token, { + autoSubscribe: true, + dynacast: true, + }); + console.log(`✅ [ROOM] Connected to LiveKit room: ${roomName}`); + console.log(`🔗 [CONNECTION] State: ${this.room.connectionState}`); + console.log(`🟢 [STATUS] Is connected: ${this.room.isConnected}`); + + // Log existing participants in the room + console.log( + `👥 [PARTICIPANTS] Remote participants in room: ${this.room.remoteParticipants.size}` + ); + this.room.remoteParticipants.forEach((participant, sid) => { + console.log(` - ${participant.identity} (${sid})`); + + // Log existing tracks from participants + participant.trackPublications.forEach((pub, trackSid) => { + console.log( + ` 📡 Track: ${trackSid}, kind: ${pub.kind}, subscribed: ${pub.isSubscribed}` + ); + }); + }); + + this.room.on( + RoomEvent.TrackSubscribed, + (track, publication, participant) => { + console.log( + `🎵 [TRACK] Subscribed to track: ${track.sid} from ${participant.identity}, kind: ${track.kind}` + ); + + // Handle audio track from agent (TTS audio) + // Check for both string "audio" and TrackKind.KIND_AUDIO constant + if (track.kind === "audio" || track.kind === TrackKind.KIND_AUDIO) { + console.log( + `🔊 [AUDIO TRACK] Starting audio stream processing for ${participant.identity}` + ); + + + const stream = new AudioStream(track); + const reader = stream.getReader(); + + let frameCount = 0; + let totalBytes = 0; + let lastLogTime = Date.now(); + + const readStream = async () => { + try { + console.log( + `🎧 [AUDIO STREAM] Starting to read audio frames from ${participant.identity}` + ); + + while (true) { + const { done, value } = await reader.read(); + if (done) { + this.sendTtsStopMessage(); + console.log( + `🏁 [AUDIO STREAM] Stream ended for ${participant.identity}. Total frames: ${frameCount}, Total bytes: ${totalBytes}` + ); + + // Flush any remaining resampled data + const finalFrames = this.audioResampler.flush(); + for (const finalFrame of finalFrames) { + const finalBuffer = Buffer.from( + finalFrame.data.buffer, + finalFrame.data.byteOffset, + finalFrame.data.byteLength + ); + // Add final frames to buffer + this.frameBuffer = Buffer.concat([this.frameBuffer, finalBuffer]); + } + + // Process any remaining complete frames in buffer + const finalTimestamp = (Date.now() - this.connection.udp.startTime) & 0xffffffff; + this.processBufferedFrames(finalTimestamp, frameCount, participant.identity); + + // Send any remaining partial frame if it has significant data + if (this.frameBuffer.length > 160) { // At least 10ms worth of 16kHz audio (160 samples * 2 bytes = 320B) + console.log(`🔄 [FLUSH] Processing partial 16kHz PCM frame: ${this.frameBuffer.length}B`); + + // Send remaining PCM data directly without Opus encoding + this.connection.sendUdpMessage(this.frameBuffer, finalTimestamp); + + // Commented out Opus encoding for testing + /* + if (opusEncoder) { + try { + // Pad to nearest valid frame size for 16kHz + const targetSize = this.frameBuffer.length <= 320 ? 320 : 640; + const paddedBuffer = Buffer.alloc(targetSize); + this.frameBuffer.copy(paddedBuffer); + + const opusBuffer = opusEncoder.encode(paddedBuffer, targetSize / 2); + this.connection.sendUdpMessage(opusBuffer, finalTimestamp); + } catch (err) { + console.log(`⚠️ [FLUSH] Failed to encode partial frame: ${err.message}`); + } + } + */ + } + + // Clear the buffer + this.frameBuffer = Buffer.alloc(0); + break; + } + + frameCount++; + + // value is an AudioFrame from LiveKit (48kHz) + // Push the frame to resampler and get resampled frames back (16kHz) + const resampledFrames = this.audioResampler.push(value); + + // Add resampled frames to buffer instead of processing directly + for (const resampledFrame of resampledFrames) { + const resampledBuffer = Buffer.from( + resampledFrame.data.buffer, + resampledFrame.data.byteOffset, + resampledFrame.data.byteLength + ); + + // Append to frame buffer + this.frameBuffer = Buffer.concat([this.frameBuffer, resampledBuffer]); + totalBytes += resampledBuffer.length; + } + + const timestamp = (Date.now() - this.connection.udp.startTime) & 0xffffffff; + + // Process any complete frames from the buffer + this.processBufferedFrames(timestamp, frameCount, participant.identity); + + // Log every 50 frames or every 5 seconds + const now = Date.now(); + if (frameCount % 50 === 0 || now - lastLogTime > 5000) { + // console.log( + // `🎵 [AUDIO FRAMES] Received ${frameCount} frames, ${totalBytes} total bytes from ${participant.identity}` + // ); + lastLogTime = now; + } + + } + } catch (error) { + console.error( + `❌ [AUDIO STREAM] Error reading audio stream from ${participant.identity}:`, + error + ); + } finally { + console.log( + `🔒 [AUDIO STREAM] Releasing reader lock for ${participant.identity}` + ); + reader.releaseLock(); + } + }; + + readStream(); + } else { + console.log( + `⚠️ [TRACK] Non-audio track subscribed: ${track.kind} (type: ${typeof track.kind}) from ${participant.identity}` + ); + } + } + ); + + // Add track unsubscription handler + this.room.on( + RoomEvent.TrackUnsubscribed, + (track, publication, participant) => { + console.log( + `🔇 [TRACK] Unsubscribed from track: ${track.sid} from ${participant.identity}, kind: ${track.kind}` + ); + } + ); + + // Add participant connection handlers + this.room.on(RoomEvent.ParticipantConnected, (participant) => { + console.log( + `👤 [PARTICIPANT] Connected: ${participant.identity} (${participant.sid})` + ); + }); + + this.room.on(RoomEvent.ParticipantDisconnected, (participant) => { + console.log( + `👤 [PARTICIPANT] Disconnected: ${participant.identity} (${participant.sid})` + ); + }); + + // Fixed: Use proper track publishing method + const { + LocalAudioTrack, + TrackPublishOptions, + TrackSource, + } = require("@livekit/rtc-node"); + const track = LocalAudioTrack.createAudioTrack( + "microphone", + this.audioSource + ); + const options = new TrackPublishOptions(); + options.source = TrackSource.SOURCE_MICROPHONE; + + const publication = await this.room.localParticipant.publishTrack( + track, + options + ); + console.log( + `🎤 [PUBLISH] Published local audio track: ${publication.trackSid}` + ); + + resolve({ session_id: this.room.sid }); + } catch (error) { + console.error("[LiveKitBridge] Error connecting to LiveKit:", error); + console.error("[LiveKitBridge] Error name:", error.name); + console.error("[LiveKitBridge] Error message:", error.message); 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(opusData, timestamp) { + if (this.audioSource) { + // Audio format analysis (only log occasionally to reduce spam) + if (Math.random() < 0.01) { + // Log 1% of packets + // this.analyzeAudioFormat(opusData, timestamp); + } + + // Check if data is Opus and decode it + const isOpus = this.checkOpusFormat(opusData); + + if (isOpus) { + if (opusDecoder) { + try { + // console.log( + // `🎵 [OPUS DECODE] Decoding ${opusData.length}B Opus data to PCM` + // ); + + // Decode Opus to PCM + const pcmBuffer = opusDecoder.decode(opusData, 480); + + if (pcmBuffer && pcmBuffer.length > 0) { + // Convert Buffer to Int16Array + const samples = new Int16Array( + pcmBuffer.buffer, + pcmBuffer.byteOffset, + pcmBuffer.length / 2 + ); + const frame = new AudioFrame(samples, 16000, 1, samples.length); + + // console.log( + // `📤 [UDP IN] Opus->PCM->LiveKit: ${opusData.length}B opus -> ${pcmBuffer.length}B pcm -> ${samples.length} samples, ts=${timestamp}, mac=${this.macAddress}` + // ); + this.audioSource.captureFrame(frame); + } else { + // console.warn( + // `⚠️ [OPUS] Decoder returned empty buffer for ${opusData.length}B input` + // ); + } + } catch (err) { + console.error(`❌ [OPUS] Decode error: ${err.message}`); + console.log( + `🔍 [DEBUG] Opus data: ${opusData.slice(0, 8).toString("hex")}...` + ); + } + } else { + console.error( + `❌ [ERROR] Opus decoder not available! Install with: npm install @discordjs/opus` + ); + console.log( + `💡 [WORKAROUND] Treating Opus as PCM (will sound garbled)` + ); + + // Fallback: treat as PCM (will sound bad but won't crash) + const samples = new Int16Array( + opusData.buffer, + opusData.byteOffset, + Math.min(opusData.length / 2, 320) + ); // Limit to reasonable PCM size + const frame = new AudioFrame(samples, 16000, 1, samples.length); + this.audioSource.captureFrame(frame); + } + } else { + // Treat as PCM + console.log(`🎤 [PCM] Processing ${opusData.length}B as raw PCM`); + const samples = new Int16Array( + opusData.buffer, + opusData.byteOffset, + opusData.length / 2 + ); + const frame = new AudioFrame(samples, 16000, 1, samples.length); + console.log( + `📤 [UDP IN] Device->LiveKit: ${opusData.length}B, samples=${samples.length}, ts=${timestamp}, mac=${this.macAddress}` + ); + this.audioSource.captureFrame(frame); + } } } - sendAudio(opus, timestamp) { - if (this.wsClient && this.wsClient.readyState === WebSocket.OPEN) { - // Send raw Opus data directly without header - // This avoids the need to strip headers in xiaozhi-server - this.wsClient.send(opus, { binary: true }); + analyzeAudioFormat(audioData, timestamp) { + // Check for Opus magic signature + const isOpus = this.checkOpusFormat(audioData); + const isPCM = this.checkPCMFormat(audioData); + + console.log(`🔍 [AUDIO ANALYSIS] Format Detection:`); + console.log(` 📊 Size: ${audioData.length} bytes`); + console.log(` 🎵 Timestamp: ${timestamp}`); + console.log( + ` 📋 First 16 bytes: ${audioData.slice(0, Math.min(16, audioData.length)).toString("hex")}` + ); + console.log( + ` 🎼 Opus signature: ${isOpus ? "✅ DETECTED" : "❌ NOT FOUND"}` + ); + console.log( + ` 🎤 PCM characteristics: ${isPCM ? "✅ LIKELY PCM" : "❌ UNLIKELY PCM"}` + ); + + // Additional analysis + this.analyzeAudioStatistics(audioData); + } + + checkOpusFormat(data) { + if (data.length < 8) return false; + + // Check for Opus packet headers + // Opus packets typically start with specific TOC (Table of Contents) byte patterns + const firstByte = data[0]; + + // Opus TOC byte analysis + // Bits 7-3: config (0-31), Bits 2: stereo flag, Bits 1-0: frame count code + const config = (firstByte >> 3) & 0x1f; + const stereo = (firstByte >> 2) & 0x01; + const frameCount = firstByte & 0x03; + + // console.log( + // ` 🔍 Opus TOC Analysis: config=${config}, stereo=${stereo}, frames=${frameCount}` + // ); + + // Valid Opus configurations are 0-31 + // Check if it looks like a valid Opus TOC byte + const validOpusConfig = config >= 0 && config <= 31; + + // Additional Opus packet characteristics + const hasOpusMarkers = this.checkOpusMarkers(data); + + return validOpusConfig && hasOpusMarkers; + } + + checkOpusMarkers(data) { + // Look for common Opus packet patterns + if (data.length < 4) return false; + + // Check for Opus frame size patterns (common sizes: 120, 240, 480, 960, 1920, 2880 samples) + // At 16kHz: 120 samples = 7.5ms, 240 = 15ms, 480 = 30ms, etc. + const commonOpusSizes = [20, 40, 60, 80, 120, 160, 240, 320, 480, 640, 960]; + const isCommonOpusSize = commonOpusSizes.includes(data.length); + + // console.log( + // ` 📏 Common Opus size (${data.length}B): ${isCommonOpusSize ? "✅" : "❌"}` + // ); + + return isCommonOpusSize; + } + + checkPCMFormat(data) { + if (data.length < 32) return false; + + // PCM characteristics analysis + const samples = new Int16Array( + data.buffer, + data.byteOffset, + Math.min(data.length / 2, 16) + ); + + // Calculate basic statistics + let sum = 0; + let maxAbs = 0; + let zeroCount = 0; + + for (let i = 0; i < samples.length; i++) { + const sample = samples[i]; + sum += Math.abs(sample); + maxAbs = Math.max(maxAbs, Math.abs(sample)); + if (sample === 0) zeroCount++; } + + const avgAmplitude = sum / samples.length; + const zeroRatio = zeroCount / samples.length; + + console.log(` 📈 PCM Statistics:`); + console.log(` 🔊 Avg amplitude: ${avgAmplitude.toFixed(1)}`); + console.log(` 📊 Max amplitude: ${maxAbs}`); + console.log(` 🔇 Zero ratio: ${(zeroRatio * 100).toFixed(1)}%`); + console.log(` 📐 Sample count: ${samples.length}`); + + // PCM heuristics + const hasReasonableAmplitude = avgAmplitude > 10 && avgAmplitude < 10000; + const hasVariation = maxAbs > 100; + const notTooManyZeros = zeroRatio < 0.8; + const reasonableSize = data.length >= 160 && data.length <= 3840; // 10ms to 240ms at 16kHz + + console.log(` ✅ PCM Checks:`); + console.log( + ` 🔊 Reasonable amplitude: ${hasReasonableAmplitude ? "✅" : "❌"}` + ); + console.log(` 📊 Has variation: ${hasVariation ? "✅" : "❌"}`); + console.log( + ` 🔇 Not too many zeros: ${notTooManyZeros ? "✅" : "❌"}` + ); + console.log(` 📏 Reasonable size: ${reasonableSize ? "✅" : "❌"}`); + + return ( + hasReasonableAmplitude && + hasVariation && + notTooManyZeros && + reasonableSize + ); + } + + analyzeAudioStatistics(data) { + // Frame size analysis for common audio formats + const frameSizeAnalysis = this.analyzeFrameSize(data.length); + console.log(` ⏱️ Frame Analysis: ${frameSizeAnalysis}`); + + // Entropy analysis (compressed data has higher entropy) + const entropy = this.calculateEntropy(data); + console.log( + ` 🎲 Data entropy: ${entropy.toFixed(3)} (PCM: ~7-11, Opus: ~7.5-8)` + ); + } + + analyzeFrameSize(size) { + // Common frame sizes for different formats at 16kHz + const formats = { + "PCM 10ms": 320, // 160 samples * 2 bytes + "PCM 20ms": 640, // 320 samples * 2 bytes + "PCM 30ms": 960, // 480 samples * 2 bytes + "PCM 60ms": 1920, // 960 samples * 2 bytes + "Opus 20ms": 40, // Typical Opus frame + "Opus 40ms": 80, // Typical Opus frame + "Opus 60ms": 120, // Typical Opus frame + }; + + for (const [format, expectedSize] of Object.entries(formats)) { + if (size === expectedSize) { + return `${format} (exact match)`; + } + } + + // Check for close matches + for (const [format, expectedSize] of Object.entries(formats)) { + if (Math.abs(size - expectedSize) <= 10) { + return `${format} (close match, diff: ${size - expectedSize})`; + } + } + + return `Unknown format (${size}B)`; + } + + calculateEntropy(data) { + const freq = new Array(256).fill(0); + + // Count byte frequencies + for (let i = 0; i < data.length; i++) { + freq[data[i]]++; + } + + // Calculate entropy + let entropy = 0; + for (let i = 0; i < 256; i++) { + if (freq[i] > 0) { + const p = freq[i] / data.length; + entropy -= p * Math.log2(p); + } + } + + return entropy; } isAlive() { - return this.wsClient && this.wsClient.readyState === WebSocket.OPEN; + return this.room && this.room.isConnected; + } + + // Send TTS start message to device + sendTtsStartMessage(text = "") { + if (!this.connection) return; + + const message = { + type: "tts", + state: "start", + session_id: this.connection.udp.session_id, + }; + + if (text) { + message.text = text; + } + + // console.log( + // `📤 [MQTT OUT] Sending TTS start to device: ${this.macAddress}` + // ); + this.connection.sendMqttMessage(JSON.stringify(message)); + } + + // Send TTS sentence start message to device + sendTtsSentenceStartMessage(text) { + if (!this.connection) return; + + const message = { + type: "tts", + state: "sentence_start", + session_id: this.connection.udp.session_id, + text: text || "", + }; + + console.log( + `📤 [MQTT OUT] Sending TTS sentence start to device: ${this.macAddress} - "${text}"` + ); + this.connection.sendMqttMessage(JSON.stringify(message)); + } + + // Send TTS stop message to device + sendTtsStopMessage() { + if (!this.connection) return; + + const message = { + type: "tts", + state: "stop", + session_id: this.connection.udp.session_id, + }; + + console.log(`📤 [MQTT OUT] Sending TTS stop to device: ${this.macAddress}`); + this.connection.sendMqttMessage(JSON.stringify(message)); + } + + // Send STT (Speech-to-Text) result to device + sendSttMessage(text) { + if (!this.connection || !text) return; + + const message = { + type: "stt", + text: text, + session_id: this.connection.udp.session_id, + }; + + console.log( + `📤 [MQTT OUT] Sending STT result to device: ${this.macAddress} - "${text}"` + ); + this.connection.sendMqttMessage(JSON.stringify(message)); + } + + // Send LLM response to device + sendLlmMessage(text, emotion = "neutral") { + if (!this.connection || !text) return; + + const message = { + type: "llm", + text: text, + emotion: emotion, + session_id: this.connection.udp.session_id, + }; + + console.log( + `📤 [MQTT OUT] Sending LLM response to device: ${this.macAddress} - "${text}"` + ); + this.connection.sendMqttMessage(JSON.stringify(message)); + } + + // Send record stop message to device + sendRecordStopMessage() { + if (!this.connection) return; + + const message = { + type: "record_stop", + session_id: this.connection.udp.session_id, + }; + + console.log( + `📤 [MQTT OUT] Sending record stop to device: ${this.macAddress}` + ); + this.connection.sendMqttMessage(JSON.stringify(message)); } close() { - if (this.wsClient) { - this.wsClient.close(); - this.wsClient = null; + if (this.room) { + console.log("[LiveKitBridge] Disconnecting from LiveKit room"); + this.room.disconnect(); + this.room = null; } } } @@ -182,6 +861,7 @@ class MQTTConnection { setupProtocolHandlers() { // Set protocol event handlers this.protocol.on("connect", (connectData) => { + // console.log("Received CONNECT packet"); this.handleConnect(connectData); }); @@ -361,14 +1041,17 @@ class MQTTConnection { timestamp, this.udp.localSequence ); - console.log( - `🔐 Encrypting: payload=${payload.length}B, timestamp=${timestamp}, seq=${this.udp.localSequence}` - ); - console.log(`🔐 Header: ${header.toString("hex")}`); - console.log(`🔐 Key: ${this.udp.key.toString("hex")}`); - console.log( - `🔐 Payload first 8 bytes: ${payload.subarray(0, 8).toString("hex")}` - ); + // console.log( + // `📡 [UDP SEND] To ${this.udp.remoteAddress.address}:${this.udp.remoteAddress.port} - payload=${payload.length}B, ts=${timestamp}, seq=${this.udp.localSequence}` + // ); + // console.log( + // `🔐 Encrypting: payload=${payload.length}B, timestamp=${timestamp}, seq=${this.udp.localSequence}` + // ); + // console.log(`🔐 Header: ${header.toString("hex")}`); + // console.log(`🔐 Key: ${this.udp.key.toString("hex")}`); + // console.log( + // `🔐 Payload first 8 bytes: ${payload.subarray(0, 8).toString("hex")}` + // ); const cipher = crypto.createCipheriv( this.udp.encryption, this.udp.key, @@ -378,11 +1061,11 @@ class MQTTConnection { cipher.update(payload), cipher.final(), ]); - console.log( - `🔐 Encrypted first 8 bytes: ${encryptedPayload - .subarray(0, 8) - .toString("hex")}` - ); + // console.log( + // `🔐 Encrypted first 8 bytes: ${encryptedPayload + // .subarray(0, 8) + // .toString("hex")}` + // ); const message = Buffer.concat([header, encryptedPayload]); this.server.sendUdpMessage(message, this.udp.remoteAddress); } @@ -417,7 +1100,7 @@ class MQTTConnection { await new Promise((resolve) => setTimeout(resolve, 100)); } - this.bridge = new WebSocketBridge( + this.bridge = new LiveKitBridge( this, json.version, this.macAddress, @@ -439,9 +1122,7 @@ class MQTTConnection { }); try { - console.log( - `Call started: ${this.clientId} Protocol: ${json.version} ${this.bridge.chatServer}` - ); + console.log(`Call started: ${this.clientId} Protocol: ${json.version}`); const helloReply = await this.bridge.connect( json.audio_params, json.features @@ -493,22 +1174,36 @@ class MQTTConnection { return; } - this.bridge.sendJson(json); + // Not sending other messages to LiveKit for now + debug("Received other message, not forwarding to LiveKit:", json); } onUdpMessage(rinfo, message, payloadLength, timestamp, sequence) { if (!this.bridge) { + // console.log( + // `📡 [UDP RECV] No bridge available for ${this.clientId}, dropping message` + // ); return; } if (this.udp.remoteAddress !== rinfo) { + // console.log( + // `📡 [UDP RECV] New remote address: ${rinfo.address}:${rinfo.port} for ${this.clientId}` + // ); this.udp.remoteAddress = rinfo; } if (sequence < this.udp.remoteSequence) { + // console.log( + // `📡 [UDP RECV] Out of order packet: seq=${sequence}, expected>=${this.udp.remoteSequence}, dropping` + // ); return; } + // console.log( + // `📡 [UDP RECV] From ${rinfo.address}:${rinfo.port} - payload=${payloadLength}B, ts=${timestamp}, seq=${sequence}` + // ); + // Process encrypted data const header = message.slice(0, 16); const encryptedPayload = message.slice(16, 16 + payloadLength); @@ -525,13 +1220,16 @@ class MQTTConnection { // Check if this is a ping message const payloadStr = payload.toString(); if (payloadStr.startsWith("ping:")) { - debug( - `Received UDP ping message: ${payloadStr} from ${rinfo.address}:${rinfo.port}` + console.log( + `🏓 [UDP PING] Received ping: ${payloadStr} from ${rinfo.address}:${rinfo.port}` ); // Ping message received, connection is now established return; } + //console.log( + // `🔊 [AUDIO RECV] Decrypted ${payload.length}B audio data, forwarding to LiveKit` + //); this.bridge.sendAudio(payload, timestamp); this.udp.remoteSequence = sequence; } @@ -568,7 +1266,7 @@ class MQTTServer { new MQTTConnection(socket, connectionId, this); }); - this.mqttServer.listen(this.mqttPort, "0.0.0.0", () => { + this.mqttServer.listen(this.mqttPort, "192.168.1.111", () => { console.warn( `MQTT server listening on port ${this.mqttPort} (all interfaces)` ); @@ -614,9 +1312,9 @@ class MQTTServer { activeCount !== this.lastActiveConnectionCount || this.connections.size !== this.lastConnectionCount ) { - console.log( - `Connections: ${this.connections.size}, Active: ${activeCount}` - ); + // console.log( + // `Connections: ${this.connections.size}, Active: ${activeCount}` + // ); this.lastActiveConnectionCount = activeCount; this.lastConnectionCount = this.connections.size; } @@ -660,23 +1358,42 @@ class MQTTServer { 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("Received incomplete UDP header", rinfo); + //console.warn( + //`📡 [UDP SERVER] Received incomplete UDP header from ${rinfo.address}:${rinfo.port}, length=${message.length}` + // ); return; } try { const type = message.readUInt8(0); - if (type !== 1) return; + if (type !== 1) { + // console.warn( + // `📡 [UDP SERVER] Invalid packet type: ${type} from ${rinfo.address}:${rinfo.port}` + // ); + return; + } const payloadLength = message.readUInt16BE(2); - if (message.length < 16 + payloadLength) return; + if (message.length < 16 + payloadLength) { + // console.warn( + // `📡 [UDP SERVER] Incomplete message from ${rinfo.address}:${rinfo.port}, expected=${16 + payloadLength}, got=${message.length}` + // ); + return; + } const connectionId = message.readUInt32BE(4); const connection = this.connections.get(connectionId); - if (!connection) return; + if (!connection) { + // console.warn(`📡 [UDP SERVER] No connection found for ID: ${connectionId} from ${rinfo.address}:${rinfo.port}`); + return; + } const timestamp = message.readUInt32BE(8); const sequence = message.readUInt32BE(12); + + // console.log( + // `📡 [UDP SERVER] Routing message to connection ${connectionId} (${connection.clientId})` + // ); connection.onUdpMessage( rinfo, message, @@ -685,7 +1402,10 @@ class MQTTServer { sequence ); } catch (error) { - console.error("UDP message processing error:", error); + // console.error( + // `📡 [UDP SERVER] Message processing error from ${rinfo.address}:${rinfo.port}:`, + // error + // ); } } diff --git a/main/mqtt-gateway/config/mqtt.json b/main/mqtt-gateway/config/mqtt.json index 8b052ae56..b6c6fd613 100644 --- a/main/mqtt-gateway/config/mqtt.json +++ b/main/mqtt-gateway/config/mqtt.json @@ -1,15 +1,8 @@ { - "production": { - "chat_servers": [ - "ws://139.59.7.72:8000/toy/v1/" - ] - }, - "development": { - "chat_servers": [ - "ws://139.59.7.72:8000/toy/v1/" - ], - "mac_addresss": [ - ] - }, - "debug": false -} + "debug": false, + "livekit": { + "url": "wss://cheeko-ycahauzs.livekit.cloud", + "api_key": "APInJFs2nTcUxcE", + "api_secret": "CDpl09fZm8WCMHHYBdi6OBrMqjq5u7D78ROH02O6I8Z" + } +} \ No newline at end of file diff --git a/main/mqtt-gateway/config/mqtt.json.example b/main/mqtt-gateway/config/mqtt.json.example index 05c6b9b58..eaa8aa2aa 100644 --- a/main/mqtt-gateway/config/mqtt.json.example +++ b/main/mqtt-gateway/config/mqtt.json.example @@ -1,15 +1,8 @@ { - "production": { - "chat_servers": [ - "ws://example:8080" - ] - }, - "development": { - "chat_servers": [ - "ws://example:8180" - ], - "mac_addresss": [ - ] - }, - "debug": false -} + "debug": true, + "livekit": { + "url": "wss://cheeko-ycahauzs.livekit.cloud", + "api_key": "APInJFs2nTcUxcE", + "api_secret": "CDpl09fZm8WCMHHYBdi6OBrMqjq5u7D78ROH02O6I8Z" + } +} \ No newline at end of file diff --git a/main/mqtt-gateway/error.txt b/main/mqtt-gateway/error.txt new file mode 100644 index 000000000..d4a745735 --- /dev/null +++ b/main/mqtt-gateway/error.txt @@ -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 \ No newline at end of file diff --git a/main/mqtt-gateway/mqtt-protocol.js b/main/mqtt-gateway/mqtt-protocol.js index 6f80a59c5..1d8900840 100644 --- a/main/mqtt-gateway/mqtt-protocol.js +++ b/main/mqtt-gateway/mqtt-protocol.js @@ -338,10 +338,10 @@ class MQTTProtocol extends EventEmitter { * @param {Buffer} message - Complete PINGREQ message */ parsePingReq(message) { - debug("Received heartbeat request"); - // Send PINGRESP - this.sendPingResp(); - debug("Sent heartbeat response"); + // debug("Received heartbeat request"); + // // Send PINGRESP + // this.sendPingResp(); + // debug("Sent heartbeat response"); } /** diff --git a/main/mqtt-gateway/oldDevice.txt b/main/mqtt-gateway/oldDevice.txt new file mode 100644 index 000000000..284759540 --- /dev/null +++ b/main/mqtt-gateway/oldDevice.txt @@ -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 \ No newline at end of file diff --git a/main/mqtt-gateway/package-lock.json b/main/mqtt-gateway/package-lock.json index 16cbdf57d..8334e0157 100644 --- a/main/mqtt-gateway/package-lock.json +++ b/main/mqtt-gateway/package-lock.json @@ -9,11 +9,509 @@ "version": "1.0.0", "license": "ISC", "dependencies": { + "@discordjs/opus": "^0.10.0", + "@livekit/rtc-node": "^0.13.18", + "@voicehype/audify-plus": "^2.0.9", "debug": "^4.4.1", "dotenv": "^17.2.1", + "json5": "^2.2.3", + "livekit-server-sdk": "^2.13.3", + "mqtt": "^5.14.1", "ws": "^8.18.3" } }, + "node_modules/@babel/runtime": { + "version": "7.28.4", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.28.4.tgz", + "integrity": "sha512-Q/N6JNWvIvPnLDvjlE1OUBLPQHH6l3CltCEsHIujp45zQUSSh8K+gHnaEX45yAT1nyngnINhvWtzN+Nb9D8RAQ==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@bufbuild/protobuf": { + "version": "1.10.1", + "resolved": "https://registry.npmjs.org/@bufbuild/protobuf/-/protobuf-1.10.1.tgz", + "integrity": "sha512-wJ8ReQbHxsAfXhrf9ixl0aYbZorRuOWpBNzm8pL8ftmSxQx/wnJD5Eg861NwJU/czy2VXFIebCeZnZrI9rktIQ==", + "license": "(Apache-2.0 AND BSD-3-Clause)" + }, + "node_modules/@discordjs/node-pre-gyp": { + "version": "0.4.5", + "resolved": "https://registry.npmjs.org/@discordjs/node-pre-gyp/-/node-pre-gyp-0.4.5.tgz", + "integrity": "sha512-YJOVVZ545x24mHzANfYoy0BJX5PDyeZlpiJjDkUBM/V/Ao7TFX9lcUvCN4nr0tbr5ubeaXxtEBILUrHtTphVeQ==", + "license": "BSD-3-Clause", + "dependencies": { + "detect-libc": "^2.0.0", + "https-proxy-agent": "^5.0.0", + "make-dir": "^3.1.0", + "node-fetch": "^2.6.7", + "nopt": "^5.0.0", + "npmlog": "^5.0.1", + "rimraf": "^3.0.2", + "semver": "^7.3.5", + "tar": "^6.1.11" + }, + "bin": { + "node-pre-gyp": "bin/node-pre-gyp" + } + }, + "node_modules/@discordjs/opus": { + "version": "0.10.0", + "resolved": "https://registry.npmjs.org/@discordjs/opus/-/opus-0.10.0.tgz", + "integrity": "sha512-HHEnSNrSPmFEyndRdQBJN2YE6egyXS9JUnJWyP6jficK0Y+qKMEZXyYTgmzpjrxXP1exM/hKaNP7BRBUEWkU5w==", + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "@discordjs/node-pre-gyp": "^0.4.5", + "node-addon-api": "^8.1.0" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/@livekit/mutex": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@livekit/mutex/-/mutex-1.1.1.tgz", + "integrity": "sha512-EsshAucklmpuUAfkABPxJNhzj9v2sG7JuzFDL4ML1oJQSV14sqrpTYnsaOudMAw9yOaW53NU3QQTlUQoRs4czw==", + "license": "Apache-2.0" + }, + "node_modules/@livekit/protocol": { + "version": "1.41.0", + "resolved": "https://registry.npmjs.org/@livekit/protocol/-/protocol-1.41.0.tgz", + "integrity": "sha512-bozBB39VSbd0IjRBwShMlLskqkd9weWJNskaB1CVpcEO9UUI1gMwAtBJOKYblzZJT9kE1SJa3L4oWWwsZMzSXw==", + "license": "Apache-2.0", + "dependencies": { + "@bufbuild/protobuf": "^1.10.0" + } + }, + "node_modules/@livekit/rtc-node": { + "version": "0.13.18", + "resolved": "https://registry.npmjs.org/@livekit/rtc-node/-/rtc-node-0.13.18.tgz", + "integrity": "sha512-Kk0z4LWq0yKxQaqAuM9p4TpgCTDrhMBcGeEm6OpQjdjCS42vo8NLB3Q/XP305HWM0Cis65U4gzMkfJ/W2fAqRw==", + "license": "Apache-2.0", + "dependencies": { + "@bufbuild/protobuf": "^1.10.0", + "@livekit/mutex": "^1.0.0", + "@livekit/typed-emitter": "^3.0.0", + "pino": "^9.0.0", + "pino-pretty": "^13.0.0" + }, + "engines": { + "node": ">= 18" + }, + "optionalDependencies": { + "@livekit/rtc-node-darwin-arm64": "0.13.18", + "@livekit/rtc-node-darwin-x64": "0.13.18", + "@livekit/rtc-node-linux-arm64-gnu": "0.13.18", + "@livekit/rtc-node-linux-x64-gnu": "0.13.18", + "@livekit/rtc-node-win32-x64-msvc": "0.13.18" + } + }, + "node_modules/@livekit/rtc-node-darwin-arm64": { + "version": "0.13.18", + "resolved": "https://registry.npmjs.org/@livekit/rtc-node-darwin-arm64/-/rtc-node-darwin-arm64-0.13.18.tgz", + "integrity": "sha512-grHN5y2vasZR2eohrSuJHASzQUeKFjhcYt0ijzVrYBU+UBaXiL38YmhpvmGBxTgPT9rwQFdHQ3SpvJvYOPfPzA==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@livekit/rtc-node-darwin-x64": { + "version": "0.13.18", + "resolved": "https://registry.npmjs.org/@livekit/rtc-node-darwin-x64/-/rtc-node-darwin-x64-0.13.18.tgz", + "integrity": "sha512-0mpBBgxFN4RpOHh4EU+2yUKYEEWZJUzMj9cInz5JSSIMGxmiftyogHXFdPw1n3f1Yro7KeEF76tUNrRzoW2jSQ==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@livekit/rtc-node-linux-arm64-gnu": { + "version": "0.13.18", + "resolved": "https://registry.npmjs.org/@livekit/rtc-node-linux-arm64-gnu/-/rtc-node-linux-arm64-gnu-0.13.18.tgz", + "integrity": "sha512-MwoxxgwyphwqIe0C+gFpprH//34hFWAy0b6TBIPFJwxu1gHW88qJpPJcDONZu6SyCaKBlEnOEjMgz2vDiSggTg==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@livekit/rtc-node-linux-x64-gnu": { + "version": "0.13.18", + "resolved": "https://registry.npmjs.org/@livekit/rtc-node-linux-x64-gnu/-/rtc-node-linux-x64-gnu-0.13.18.tgz", + "integrity": "sha512-WHgvglYNYW+byZ3ql9GnSnecdLZD9N3Hdt3wdg44+pekbVxdDTzb6EmY0nZeS7YlA4KIh04wNQuwkLFVN1q4Jw==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@livekit/rtc-node-win32-x64-msvc": { + "version": "0.13.18", + "resolved": "https://registry.npmjs.org/@livekit/rtc-node-win32-x64-msvc/-/rtc-node-win32-x64-msvc-0.13.18.tgz", + "integrity": "sha512-xm+TymR3eH523qnFDrkkKoCpV+v9Yc+KBAoDn28Rtda/BgX0tDS8jWWxJ6vi0EmW3UhEsS3kdnoYM+QU38b2vg==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@livekit/typed-emitter": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@livekit/typed-emitter/-/typed-emitter-3.0.0.tgz", + "integrity": "sha512-9bl0k4MgBPZu3Qu3R3xy12rmbW17e3bE9yf4YY85gJIQ3ezLEj/uzpKHWBsLaDoL5Mozz8QCgggwIBudYQWeQg==", + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "24.3.3", + "resolved": "https://registry.npmjs.org/@types/node/-/node-24.3.3.tgz", + "integrity": "sha512-GKBNHjoNw3Kra1Qg5UXttsY5kiWMEfoHq2TmXb+b1rcm6N7B3wTrFYIf/oSZ1xNQ+hVVijgLkiDZh7jRRsh+Gw==", + "license": "MIT", + "dependencies": { + "undici-types": "~7.10.0" + } + }, + "node_modules/@types/readable-stream": { + "version": "4.0.21", + "resolved": "https://registry.npmjs.org/@types/readable-stream/-/readable-stream-4.0.21.tgz", + "integrity": "sha512-19eKVv9tugr03IgfXlA9UVUVRbW6IuqRO5B92Dl4a6pT7K8uaGrNS0GkxiZD0BOk6PLuXl5FhWl//eX/pzYdTQ==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/ws": { + "version": "8.18.1", + "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz", + "integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@voicehype/audify-plus": { + "version": "2.0.9", + "resolved": "https://registry.npmjs.org/@voicehype/audify-plus/-/audify-plus-2.0.9.tgz", + "integrity": "sha512-iRuoVdzw1C1gY3NxFVxmAknIEfMoiSy+ga3FUcSMU1CW9jE5+qOg23mOy2bFS3b0WRqDd9RIJoupzhcHIRBRGw==", + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "node-abi": "^3.62.0" + } + }, + "node_modules/abbrev": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", + "integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==", + "license": "ISC" + }, + "node_modules/abort-controller": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz", + "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==", + "license": "MIT", + "dependencies": { + "event-target-shim": "^5.0.0" + }, + "engines": { + "node": ">=6.5" + } + }, + "node_modules/agent-base": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", + "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", + "license": "MIT", + "dependencies": { + "debug": "4" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/aproba": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/aproba/-/aproba-2.1.0.tgz", + "integrity": "sha512-tLIEcj5GuR2RSTnxNKdkK0dJ/GrC7P38sUkiDmDuHfsHmbagTFAxDVIBltoklXEVIQ/f14IL8IMJ5pn9Hez1Ew==", + "license": "ISC" + }, + "node_modules/are-we-there-yet": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/are-we-there-yet/-/are-we-there-yet-2.0.0.tgz", + "integrity": "sha512-Ci/qENmwHnsYo9xKIcUJN5LeDKdJ6R1Z1j9V/J5wyq8nh/mYPEpIKJbBZXtZjG04HiK7zV/p6Vs9952MrMeUIw==", + "deprecated": "This package is no longer supported.", + "license": "ISC", + "dependencies": { + "delegates": "^1.0.0", + "readable-stream": "^3.6.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/are-we-there-yet/node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/atomic-sleep": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/atomic-sleep/-/atomic-sleep-1.0.0.tgz", + "integrity": "sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ==", + "license": "MIT", + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "license": "MIT" + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/bl": { + "version": "6.1.3", + "resolved": "https://registry.npmjs.org/bl/-/bl-6.1.3.tgz", + "integrity": "sha512-nHB8B5roHlGX5TFsWeiQJijdddZIOHuv1eL2cM2kHnG3qR91CYLsysGe+CvxQfEd23EKD0eJf4lto0frTbddKA==", + "license": "MIT", + "dependencies": { + "@types/readable-stream": "^4.0.0", + "buffer": "^6.0.3", + "inherits": "^2.0.4", + "readable-stream": "^4.2.0" + } + }, + "node_modules/brace-expansion": { + "version": "1.1.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", + "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/broker-factory": { + "version": "3.1.9", + "resolved": "https://registry.npmjs.org/broker-factory/-/broker-factory-3.1.9.tgz", + "integrity": "sha512-MzvndyD6EcbkBtX4NXm/HfdO1+cOR5ONNdMCXEKfHpxGdMtuDz7+o+nJf7HMtyPH1sUVf/lEIP+DMluC5PgaBQ==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.28.3", + "fast-unique-numbers": "^9.0.23", + "tslib": "^2.8.1", + "worker-factory": "^7.0.45" + } + }, + "node_modules/buffer": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz", + "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.2.1" + } + }, + "node_modules/buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "license": "MIT" + }, + "node_modules/camelcase": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-8.0.0.tgz", + "integrity": "sha512-8WB3Jcas3swSvjIeA2yvCJ+Miyz5l1ZmB6HFb9R1317dt9LCQoswg/BGrmAmkWVEszSrrg4RwmO46qIm2OEnSA==", + "license": "MIT", + "engines": { + "node": ">=16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/camelcase-keys": { + "version": "9.1.3", + "resolved": "https://registry.npmjs.org/camelcase-keys/-/camelcase-keys-9.1.3.tgz", + "integrity": "sha512-Rircqi9ch8AnZscQcsA1C47NFdaO3wukpmIRzYcDOrmvgt78hM/sj5pZhZNec2NM12uk5vTwRHZ4anGcrC4ZTg==", + "license": "MIT", + "dependencies": { + "camelcase": "^8.0.0", + "map-obj": "5.0.0", + "quick-lru": "^6.1.1", + "type-fest": "^4.3.2" + }, + "engines": { + "node": ">=16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/chownr": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-2.0.0.tgz", + "integrity": "sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ==", + "license": "ISC", + "engines": { + "node": ">=10" + } + }, + "node_modules/color-support": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-support/-/color-support-1.1.3.tgz", + "integrity": "sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg==", + "license": "ISC", + "bin": { + "color-support": "bin.js" + } + }, + "node_modules/colorette": { + "version": "2.0.20", + "resolved": "https://registry.npmjs.org/colorette/-/colorette-2.0.20.tgz", + "integrity": "sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w==", + "license": "MIT" + }, + "node_modules/commist": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/commist/-/commist-3.2.0.tgz", + "integrity": "sha512-4PIMoPniho+LqXmpS5d3NuGYncG6XWlkBSVGiWycL22dd42OYdUGil2CWuzklaJoNxyxUSpO4MKIBU94viWNAw==", + "license": "MIT" + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "license": "MIT" + }, + "node_modules/concat-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-2.0.0.tgz", + "integrity": "sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A==", + "engines": [ + "node >= 6.0" + ], + "license": "MIT", + "dependencies": { + "buffer-from": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^3.0.2", + "typedarray": "^0.0.6" + } + }, + "node_modules/concat-stream/node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/console-control-strings": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz", + "integrity": "sha512-ty/fTekppD2fIwRvnZAVdeOiGd1c7YXEixbgJTNzqcxJWKQnjJ/V1bNEEE6hygpM3WjwHFUVK6HTjWSzV4a8sQ==", + "license": "ISC" + }, + "node_modules/dateformat": { + "version": "4.6.3", + "resolved": "https://registry.npmjs.org/dateformat/-/dateformat-4.6.3.tgz", + "integrity": "sha512-2P0p0pFGzHS5EMnhdxQi7aJN+iMheud0UhG4dlE1DLAlvL8JHjJJTX/CSm4JXwV0Ka5nGk3zC5mcb5bUQUxxMA==", + "license": "MIT", + "engines": { + "node": "*" + } + }, "node_modules/debug": { "version": "4.4.1", "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.1.tgz", @@ -31,10 +529,25 @@ } } }, + "node_modules/delegates": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delegates/-/delegates-1.0.0.tgz", + "integrity": "sha512-bd2L678uiWATM6m5Z1VzNCErI3jiGzt6HGY8OVICs40JQq/HALfbyNJmp0UDakEY4pMMaN0Ly5om/B1VI/+xfQ==", + "license": "MIT" + }, + "node_modules/detect-libc": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.0.4.tgz", + "integrity": "sha512-3UDv+G9CsCKO1WKMGw9fwq/SWJYbI0c5Y7LU1AXYoDdbhE2AHQ6N6Nb34sG8Fj7T5APy8qXDCKuuIHd1BR0tVA==", + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, "node_modules/dotenv": { - "version": "17.2.1", - "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.2.1.tgz", - "integrity": "sha512-kQhDYKZecqnM0fCnzI5eIv5L4cAe/iRI+HqMbO/hbRdTAeXDG+M9FjipUxNfbARuEg4iHIbhnhs78BCHNbSxEQ==", + "version": "17.2.2", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.2.2.tgz", + "integrity": "sha512-Sf2LSQP+bOlhKWWyhFsn0UsfdK/kCWRv1iuA2gXAwt3dyNabr6QSj00I2V10pidqz69soatm9ZwZvpQMTIOd5Q==", "license": "BSD-2-Clause", "engines": { "node": ">=12" @@ -43,12 +556,1024 @@ "url": "https://dotenvx.com" } }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" + }, + "node_modules/end-of-stream": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz", + "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==", + "license": "MIT", + "dependencies": { + "once": "^1.4.0" + } + }, + "node_modules/event-target-shim": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz", + "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/events": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz", + "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==", + "license": "MIT", + "engines": { + "node": ">=0.8.x" + } + }, + "node_modules/fast-copy": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/fast-copy/-/fast-copy-3.0.2.tgz", + "integrity": "sha512-dl0O9Vhju8IrcLndv2eU4ldt1ftXMqqfgN4H1cpmGV7P6jeB9FwpN9a2c8DPGE1Ys88rNUJVYDHq73CGAGOPfQ==", + "license": "MIT" + }, + "node_modules/fast-redact": { + "version": "3.5.0", + "resolved": "https://registry.npmjs.org/fast-redact/-/fast-redact-3.5.0.tgz", + "integrity": "sha512-dwsoQlS7h9hMeYUq1W++23NDcBLV4KqONnITDV9DjfS3q1SgDGVrBdvvTLUotWtPSD7asWDV9/CmsZPy8Hf70A==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/fast-safe-stringify": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/fast-safe-stringify/-/fast-safe-stringify-2.1.1.tgz", + "integrity": "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==", + "license": "MIT" + }, + "node_modules/fast-unique-numbers": { + "version": "9.0.23", + "resolved": "https://registry.npmjs.org/fast-unique-numbers/-/fast-unique-numbers-9.0.23.tgz", + "integrity": "sha512-jcRIaHo46nfvyvKRMaFSKXmez4jALQ3Qw49gxM5F4siz8HqkyKPPEexpCOYwBSJI1HovrDr4fEedM8QAJ7oX3w==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.28.3", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=18.2.0" + } + }, + "node_modules/fs-minipass": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-2.1.0.tgz", + "integrity": "sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg==", + "license": "ISC", + "dependencies": { + "minipass": "^3.0.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/fs-minipass/node_modules/minipass": { + "version": "3.3.6", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", + "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", + "license": "ISC", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", + "license": "ISC" + }, + "node_modules/gauge": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/gauge/-/gauge-3.0.2.tgz", + "integrity": "sha512-+5J6MS/5XksCuXq++uFRsnUd7Ovu1XenbeuIuNRJxYWjgQbPuFhT14lAvsWfqfAmnwluf1OwMjz39HjfLPci0Q==", + "deprecated": "This package is no longer supported.", + "license": "ISC", + "dependencies": { + "aproba": "^1.0.3 || ^2.0.0", + "color-support": "^1.1.2", + "console-control-strings": "^1.0.0", + "has-unicode": "^2.0.1", + "object-assign": "^4.1.1", + "signal-exit": "^3.0.0", + "string-width": "^4.2.3", + "strip-ansi": "^6.0.1", + "wide-align": "^1.1.2" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "deprecated": "Glob versions prior to v9 are no longer supported", + "license": "ISC", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/has-unicode": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/has-unicode/-/has-unicode-2.0.1.tgz", + "integrity": "sha512-8Rf9Y83NBReMnx0gFzA8JImQACstCYWUplepDa9xprwwtmgEZUF0h/i5xSA625zB/I37EtrswSST6OXxwaaIJQ==", + "license": "ISC" + }, + "node_modules/help-me": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/help-me/-/help-me-5.0.0.tgz", + "integrity": "sha512-7xgomUX6ADmcYzFik0HzAxh/73YlKR9bmFzf51CZwR+b6YtzU2m0u49hQCqV6SvlqIqsaxovfwdvbnsw3b/zpg==", + "license": "MIT" + }, + "node_modules/https-proxy-agent": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", + "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", + "license": "MIT", + "dependencies": { + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", + "deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.", + "license": "ISC", + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ip-address": { + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.0.1.tgz", + "integrity": "sha512-NWv9YLW4PoW2B7xtzaS3NCot75m6nK7Icdv0o3lfMceJVRfSoQwqD4wEH5rLwoKJwUiZ/rfpiVBhnaF0FK4HoA==", + "license": "MIT", + "engines": { + "node": ">= 12" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/jose": { + "version": "5.10.0", + "resolved": "https://registry.npmjs.org/jose/-/jose-5.10.0.tgz", + "integrity": "sha512-s+3Al/p9g32Iq+oqXxkW//7jk2Vig6FF1CFqzVXoTUXt2qz89YWbL+OwS17NFYEvxC35n0FKeGO2LGYSxeM2Gg==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, + "node_modules/joycon": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/joycon/-/joycon-3.1.1.tgz", + "integrity": "sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/js-sdsl": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/js-sdsl/-/js-sdsl-4.3.0.tgz", + "integrity": "sha512-mifzlm2+5nZ+lEcLJMoBK0/IH/bDg8XnJfd/Wq6IP+xoCjLZsTOnV2QpxlVbX9bMnkl5PdEjNtBJ9Cj1NjifhQ==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/js-sdsl" + } + }, + "node_modules/json5": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "license": "MIT", + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/livekit-server-sdk": { + "version": "2.13.3", + "resolved": "https://registry.npmjs.org/livekit-server-sdk/-/livekit-server-sdk-2.13.3.tgz", + "integrity": "sha512-ItSQ2gE1oz/Ev9mfBRdAw+P05rt/BaYRkldggKz0+3rh/Yt0ag0BLID3VrgCVFVRAQ2YEJKcJJyj5p4epIJ8QA==", + "license": "Apache-2.0", + "dependencies": { + "@bufbuild/protobuf": "^1.10.1", + "@livekit/protocol": "^1.39.0", + "camelcase-keys": "^9.0.0", + "jose": "^5.1.2" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/lru-cache": { + "version": "10.4.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", + "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", + "license": "ISC" + }, + "node_modules/make-dir": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz", + "integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==", + "license": "MIT", + "dependencies": { + "semver": "^6.0.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/make-dir/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/map-obj": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/map-obj/-/map-obj-5.0.0.tgz", + "integrity": "sha512-2L3MIgJynYrZ3TYMriLDLWocz15okFakV6J12HXvMXDHui2x/zgChzg1u9mFFGbbGWE+GsLpQByt4POb9Or+uA==", + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/minipass": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-5.0.0.tgz", + "integrity": "sha512-3FnjYuehv9k6ovOEbyOswadCDPX1piCfhV8ncmYtHOjuPwylVWsghTLo7rabjC3Rx5xD4HDx8Wm1xnMF7S5qFQ==", + "license": "ISC", + "engines": { + "node": ">=8" + } + }, + "node_modules/minizlib": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-2.1.2.tgz", + "integrity": "sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg==", + "license": "MIT", + "dependencies": { + "minipass": "^3.0.0", + "yallist": "^4.0.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/minizlib/node_modules/minipass": { + "version": "3.3.6", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", + "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", + "license": "ISC", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/mkdirp": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz", + "integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==", + "license": "MIT", + "bin": { + "mkdirp": "bin/cmd.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/mqtt": { + "version": "5.14.1", + "resolved": "https://registry.npmjs.org/mqtt/-/mqtt-5.14.1.tgz", + "integrity": "sha512-NxkPxE70Uq3Ph7goefQa7ggSsVzHrayCD0OyxlJgITN/EbzlZN+JEPmaAZdxP1LsIT5FamDyILoQTF72W7Nnbw==", + "license": "MIT", + "dependencies": { + "@types/readable-stream": "^4.0.21", + "@types/ws": "^8.18.1", + "commist": "^3.2.0", + "concat-stream": "^2.0.0", + "debug": "^4.4.1", + "help-me": "^5.0.0", + "lru-cache": "^10.4.3", + "minimist": "^1.2.8", + "mqtt-packet": "^9.0.2", + "number-allocator": "^1.0.14", + "readable-stream": "^4.7.0", + "rfdc": "^1.4.1", + "socks": "^2.8.6", + "split2": "^4.2.0", + "worker-timers": "^8.0.23", + "ws": "^8.18.3" + }, + "bin": { + "mqtt": "build/bin/mqtt.js", + "mqtt_pub": "build/bin/pub.js", + "mqtt_sub": "build/bin/sub.js" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/mqtt-packet": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/mqtt-packet/-/mqtt-packet-9.0.2.tgz", + "integrity": "sha512-MvIY0B8/qjq7bKxdN1eD+nrljoeaai+qjLJgfRn3TiMuz0pamsIWY2bFODPZMSNmabsLANXsLl4EMoWvlaTZWA==", + "license": "MIT", + "dependencies": { + "bl": "^6.0.8", + "debug": "^4.3.4", + "process-nextick-args": "^2.0.1" + } + }, "node_modules/ms": { "version": "2.1.3", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", "license": "MIT" }, + "node_modules/node-abi": { + "version": "3.77.0", + "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.77.0.tgz", + "integrity": "sha512-DSmt0OEcLoK4i3NuscSbGjOf3bqiDEutejqENSplMSFA/gmB8mkED9G4pKWnPl7MDU4rSHebKPHeitpDfyH0cQ==", + "license": "MIT", + "dependencies": { + "semver": "^7.3.5" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/node-addon-api": { + "version": "8.5.0", + "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-8.5.0.tgz", + "integrity": "sha512-/bRZty2mXUIFY/xU5HLvveNHlswNJej+RnxBjOMkidWfwZzgTbPG1E3K5TOxRLOR+5hX7bSofy8yf1hZevMS8A==", + "license": "MIT", + "engines": { + "node": "^18 || ^20 || >= 21" + } + }, + "node_modules/node-fetch": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", + "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "license": "MIT", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, + "node_modules/nopt": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/nopt/-/nopt-5.0.0.tgz", + "integrity": "sha512-Tbj67rffqceeLpcRXrT7vKAN8CwfPeIBgM7E6iBkmKLV7bEMwpGgYLGv0jACUsECaa/vuxP0IjEont6umdMgtQ==", + "license": "ISC", + "dependencies": { + "abbrev": "1" + }, + "bin": { + "nopt": "bin/nopt.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/npmlog": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/npmlog/-/npmlog-5.0.1.tgz", + "integrity": "sha512-AqZtDUWOMKs1G/8lwylVjrdYgqA4d9nu8hc+0gzRxlDb1I10+FHBGMXs6aiQHFdCUUlqH99MUMuLfzWDNDtfxw==", + "deprecated": "This package is no longer supported.", + "license": "ISC", + "dependencies": { + "are-we-there-yet": "^2.0.0", + "console-control-strings": "^1.1.0", + "gauge": "^3.0.0", + "set-blocking": "^2.0.0" + } + }, + "node_modules/number-allocator": { + "version": "1.0.14", + "resolved": "https://registry.npmjs.org/number-allocator/-/number-allocator-1.0.14.tgz", + "integrity": "sha512-OrL44UTVAvkKdOdRQZIJpLkAdjXGTRda052sN4sO77bKEzYYqWKMBjQvrJFzqygI99gL6Z4u2xctPW1tB8ErvA==", + "license": "MIT", + "dependencies": { + "debug": "^4.3.1", + "js-sdsl": "4.3.0" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/on-exit-leak-free": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz", + "integrity": "sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA==", + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/pino": { + "version": "9.9.5", + "resolved": "https://registry.npmjs.org/pino/-/pino-9.9.5.tgz", + "integrity": "sha512-d1s98p8/4TfYhsJ09r/Azt30aYELRi6NNnZtEbqFw6BoGsdPVf5lKNK3kUwH8BmJJfpTLNuicjUQjaMbd93dVg==", + "license": "MIT", + "dependencies": { + "atomic-sleep": "^1.0.0", + "fast-redact": "^3.1.1", + "on-exit-leak-free": "^2.1.0", + "pino-abstract-transport": "^2.0.0", + "pino-std-serializers": "^7.0.0", + "process-warning": "^5.0.0", + "quick-format-unescaped": "^4.0.3", + "real-require": "^0.2.0", + "safe-stable-stringify": "^2.3.1", + "sonic-boom": "^4.0.1", + "thread-stream": "^3.0.0" + }, + "bin": { + "pino": "bin.js" + } + }, + "node_modules/pino-abstract-transport": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/pino-abstract-transport/-/pino-abstract-transport-2.0.0.tgz", + "integrity": "sha512-F63x5tizV6WCh4R6RHyi2Ml+M70DNRXt/+HANowMflpgGFMAym/VKm6G7ZOQRjqN7XbGxK1Lg9t6ZrtzOaivMw==", + "license": "MIT", + "dependencies": { + "split2": "^4.0.0" + } + }, + "node_modules/pino-pretty": { + "version": "13.1.1", + "resolved": "https://registry.npmjs.org/pino-pretty/-/pino-pretty-13.1.1.tgz", + "integrity": "sha512-TNNEOg0eA0u+/WuqH0MH0Xui7uqVk9D74ESOpjtebSQYbNWJk/dIxCXIxFsNfeN53JmtWqYHP2OrIZjT/CBEnA==", + "license": "MIT", + "dependencies": { + "colorette": "^2.0.7", + "dateformat": "^4.6.3", + "fast-copy": "^3.0.2", + "fast-safe-stringify": "^2.1.1", + "help-me": "^5.0.0", + "joycon": "^3.1.1", + "minimist": "^1.2.6", + "on-exit-leak-free": "^2.1.0", + "pino-abstract-transport": "^2.0.0", + "pump": "^3.0.0", + "secure-json-parse": "^4.0.0", + "sonic-boom": "^4.0.1", + "strip-json-comments": "^5.0.2" + }, + "bin": { + "pino-pretty": "bin.js" + } + }, + "node_modules/pino-std-serializers": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/pino-std-serializers/-/pino-std-serializers-7.0.0.tgz", + "integrity": "sha512-e906FRY0+tV27iq4juKzSYPbUj2do2X2JX4EzSca1631EB2QJQUqGbDuERal7LCtOpxl6x3+nvo9NPZcmjkiFA==", + "license": "MIT" + }, + "node_modules/process": { + "version": "0.11.10", + "resolved": "https://registry.npmjs.org/process/-/process-0.11.10.tgz", + "integrity": "sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A==", + "license": "MIT", + "engines": { + "node": ">= 0.6.0" + } + }, + "node_modules/process-nextick-args": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", + "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==", + "license": "MIT" + }, + "node_modules/process-warning": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-5.0.0.tgz", + "integrity": "sha512-a39t9ApHNx2L4+HBnQKqxxHNs1r7KF+Intd8Q/g1bUh6q0WIp9voPXJ/x0j+ZL45KF1pJd9+q2jLIRMfvEshkA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT" + }, + "node_modules/pump": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.3.tgz", + "integrity": "sha512-todwxLMY7/heScKmntwQG8CXVkWUOdYxIvY2s0VWAAMh/nd8SoYiRaKjlr7+iCs984f2P8zvrfWcDDYVb73NfA==", + "license": "MIT", + "dependencies": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "node_modules/quick-format-unescaped": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/quick-format-unescaped/-/quick-format-unescaped-4.0.4.tgz", + "integrity": "sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg==", + "license": "MIT" + }, + "node_modules/quick-lru": { + "version": "6.1.2", + "resolved": "https://registry.npmjs.org/quick-lru/-/quick-lru-6.1.2.tgz", + "integrity": "sha512-AAFUA5O1d83pIHEhJwWCq/RQcRukCkn/NSm2QsTEMle5f2hP0ChI2+3Xb051PZCkLryI/Ir1MVKviT2FIloaTQ==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/readable-stream": { + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-4.7.0.tgz", + "integrity": "sha512-oIGGmcpTLwPga8Bn6/Z75SVaH1z5dUut2ibSyAMVhmUggWpmDn2dapB0n7f8nwaSiRtepAsfJyfXIO5DCVAODg==", + "license": "MIT", + "dependencies": { + "abort-controller": "^3.0.0", + "buffer": "^6.0.3", + "events": "^3.3.0", + "process": "^0.11.10", + "string_decoder": "^1.3.0" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + } + }, + "node_modules/real-require": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/real-require/-/real-require-0.2.0.tgz", + "integrity": "sha512-57frrGM/OCTLqLOAh0mhVA9VBMHd+9U7Zb2THMGdBUoZVOtGbJzjxsYGDJ3A9AYYCP4hn6y1TVbaOfzWtm5GFg==", + "license": "MIT", + "engines": { + "node": ">= 12.13.0" + } + }, + "node_modules/rfdc": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.4.1.tgz", + "integrity": "sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==", + "license": "MIT" + }, + "node_modules/rimraf": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", + "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", + "deprecated": "Rimraf versions prior to v4 are no longer supported", + "license": "ISC", + "dependencies": { + "glob": "^7.1.3" + }, + "bin": { + "rimraf": "bin.js" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/safe-stable-stringify": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/safe-stable-stringify/-/safe-stable-stringify-2.5.0.tgz", + "integrity": "sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/secure-json-parse": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/secure-json-parse/-/secure-json-parse-4.0.0.tgz", + "integrity": "sha512-dxtLJO6sc35jWidmLxo7ij+Eg48PM/kleBsxpC8QJE0qJICe+KawkDQmvCMZUr9u7WKVHgMW6vy3fQ7zMiFZMA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/semver": { + "version": "7.7.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.2.tgz", + "integrity": "sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/set-blocking": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", + "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==", + "license": "ISC" + }, + "node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "license": "ISC" + }, + "node_modules/smart-buffer": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz", + "integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==", + "license": "MIT", + "engines": { + "node": ">= 6.0.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/socks": { + "version": "2.8.7", + "resolved": "https://registry.npmjs.org/socks/-/socks-2.8.7.tgz", + "integrity": "sha512-HLpt+uLy/pxB+bum/9DzAgiKS8CX1EvbWxI4zlmgGCExImLdiad2iCwXT5Z4c9c3Eq8rP2318mPW2c+QbtjK8A==", + "license": "MIT", + "dependencies": { + "ip-address": "^10.0.1", + "smart-buffer": "^4.2.0" + }, + "engines": { + "node": ">= 10.0.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/sonic-boom": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-4.2.0.tgz", + "integrity": "sha512-INb7TM37/mAcsGmc9hyyI6+QR3rR1zVRu36B0NeGXKnOOLiZOfER5SA+N7X7k3yUYRzLWafduTDvJAfDswwEww==", + "license": "MIT", + "dependencies": { + "atomic-sleep": "^1.0.0" + } + }, + "node_modules/split2": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz", + "integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==", + "license": "ISC", + "engines": { + "node": ">= 10.x" + } + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-json-comments": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-5.0.3.tgz", + "integrity": "sha512-1tB5mhVo7U+ETBKNf92xT4hrQa3pm0MZ0PQvuDnWgAAGHDsfp4lPSpiS6psrSiet87wyGPh9ft6wmhOMQ0hDiw==", + "license": "MIT", + "engines": { + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/tar": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/tar/-/tar-6.2.1.tgz", + "integrity": "sha512-DZ4yORTwrbTj/7MZYq2w+/ZFdI6OZ/f9SFHR+71gIVUZhOQPHzVCLpvRnPgyaMpfWxxk/4ONva3GQSyNIKRv6A==", + "license": "ISC", + "dependencies": { + "chownr": "^2.0.0", + "fs-minipass": "^2.0.0", + "minipass": "^5.0.0", + "minizlib": "^2.1.1", + "mkdirp": "^1.0.3", + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/thread-stream": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-3.1.0.tgz", + "integrity": "sha512-OqyPZ9u96VohAyMfJykzmivOrY2wfMSf3C5TtFJVgN+Hm6aj+voFhlK+kZEIv2FBh1X6Xp3DlnCOfEQ3B2J86A==", + "license": "MIT", + "dependencies": { + "real-require": "^0.2.0" + } + }, + "node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", + "license": "MIT" + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "license": "0BSD" + }, + "node_modules/type-fest": { + "version": "4.41.0", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-4.41.0.tgz", + "integrity": "sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA==", + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/typedarray": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz", + "integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==", + "license": "MIT" + }, + "node_modules/undici-types": { + "version": "7.10.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.10.0.tgz", + "integrity": "sha512-t5Fy/nfn+14LuOc2KNYg75vZqClpAiqscVvMygNnlsHBFpSXdJaYtXMcdNLpl/Qvc3P2cB3s6lOV51nqsFq4ag==", + "license": "MIT" + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "license": "MIT" + }, + "node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", + "license": "BSD-2-Clause" + }, + "node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "license": "MIT", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, + "node_modules/wide-align": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/wide-align/-/wide-align-1.1.5.tgz", + "integrity": "sha512-eDMORYaPNZ4sQIuuYPDHdQvf4gyCF9rEEV/yPxGfwPkRodwEgiMUUXTx/dex+Me0wxx53S+NgUHaP7y3MGlDmg==", + "license": "ISC", + "dependencies": { + "string-width": "^1.0.2 || 2 || 3 || 4" + } + }, + "node_modules/worker-factory": { + "version": "7.0.45", + "resolved": "https://registry.npmjs.org/worker-factory/-/worker-factory-7.0.45.tgz", + "integrity": "sha512-FFPCiSv7MD6ZDEfiik/ErM8IrIAWajaXhezLyCo3v0FjhUWud6GXnG2BiTE91jLywXGAVCT8IF48Hhr+D/omMw==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.28.3", + "fast-unique-numbers": "^9.0.23", + "tslib": "^2.8.1" + } + }, + "node_modules/worker-timers": { + "version": "8.0.24", + "resolved": "https://registry.npmjs.org/worker-timers/-/worker-timers-8.0.24.tgz", + "integrity": "sha512-Ydu/7TRHlxIRjYSGDge1F92L7y9kzInpwR4CkocRVObPE0eRqC6d+0GFh52Hm+m520RHVKiytOERtCUu5sQDVQ==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.28.3", + "tslib": "^2.8.1", + "worker-timers-broker": "^8.0.10", + "worker-timers-worker": "^9.0.10" + } + }, + "node_modules/worker-timers-broker": { + "version": "8.0.10", + "resolved": "https://registry.npmjs.org/worker-timers-broker/-/worker-timers-broker-8.0.10.tgz", + "integrity": "sha512-xvo/9GiuduENbJNdWnvZtkriIkjBKKVbMyw7GXvrBu3n1JHemzZgxqaCcCBNlpfXnRXXF4ekqvXWLh1gb65b8w==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.28.3", + "broker-factory": "^3.1.9", + "fast-unique-numbers": "^9.0.23", + "tslib": "^2.8.1", + "worker-timers-worker": "^9.0.10" + } + }, + "node_modules/worker-timers-worker": { + "version": "9.0.10", + "resolved": "https://registry.npmjs.org/worker-timers-worker/-/worker-timers-worker-9.0.10.tgz", + "integrity": "sha512-cfCmAkuoN+nGGJShta/g7CQVP3h7rvQA642EQg72fOHCWP5S2P83rLxDiaGv811Hd+19Cgdqt/tpRBIZ5kj/dw==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.28.3", + "tslib": "^2.8.1", + "worker-factory": "^7.0.45" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + }, "node_modules/ws": { "version": "8.18.3", "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.3.tgz", @@ -69,6 +1594,12 @@ "optional": true } } + }, + "node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "license": "ISC" } } } diff --git a/main/mqtt-gateway/package.json b/main/mqtt-gateway/package.json index 4957be67c..6b37d075d 100644 --- a/main/mqtt-gateway/package.json +++ b/main/mqtt-gateway/package.json @@ -10,8 +10,14 @@ "author": "", "license": "ISC", "dependencies": { + "@discordjs/opus": "^0.10.0", + "@livekit/rtc-node": "^0.13.18", + "@voicehype/audify-plus": "^2.0.9", "debug": "^4.4.1", "dotenv": "^17.2.1", + "json5": "^2.2.3", + "livekit-server-sdk": "^2.13.3", + "mqtt": "^5.14.1", "ws": "^8.18.3" } } diff --git a/main/mqtt-gateway/sample_mqtt_client.js b/main/mqtt-gateway/sample_mqtt_client.js new file mode 100644 index 000000000..55cd7f40c --- /dev/null +++ b/main/mqtt-gateway/sample_mqtt_client.js @@ -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'); +}); diff --git a/main/mqtt-gateway/test_livekit_connection.js b/main/mqtt-gateway/test_livekit_connection.js new file mode 100644 index 000000000..c58cee025 --- /dev/null +++ b/main/mqtt-gateway/test_livekit_connection.js @@ -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); diff --git a/main/xiaozhi-server/config/__init__.py b/main/xiaozhi-server/config/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/main/xiaozhi-server/config/config_loader.py b/main/xiaozhi-server/config/config_loader.py index 63000fba6..29146d97b 100644 --- a/main/xiaozhi-server/config/config_loader.py +++ b/main/xiaozhi-server/config/config_loader.py @@ -44,11 +44,13 @@ def load_config(): def get_config_from_api(config): """Get configuration from Java API""" + print("Fetching configuration from API...") # Initialize API client init_service(config) - + print(config) # Get server configuration config_data = get_server_config() + print(config_data) if config_data is None: raise Exception("Failed to fetch server config from API") diff --git a/mqtt-gateway-message-flow.md b/mqtt-gateway-message-flow.md new file mode 100644 index 000000000..07a2fc768 --- /dev/null +++ b/mqtt-gateway-message-flow.md @@ -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* diff --git a/mqtt-integration.md b/mqtt-integration.md new file mode 100644 index 000000000..18a232b9b --- /dev/null +++ b/mqtt-integration.md @@ -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) \ No newline at end of file diff --git a/sample.md b/sample.md new file mode 100644 index 000000000..e69de29bb diff --git a/start_all.sh b/start_all.sh new file mode 100644 index 000000000..cc14ccc2e --- /dev/null +++ b/start_all.sh @@ -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