Implementation:78 Xiaozhi esp32 MqttProtocol
| Knowledge Sources | |
|---|---|
| Domains | Network_Protocols, Audio_Streaming, domain:Security |
| Last Updated | 2026-10-17 00:00 GMT |
Overview
Concrete tool for MQTT/UDP-based voice assistant communication provided by the XiaoZhi firmware, implementing the Protocol interface using MQTT for JSON control messages and AES-CTR encrypted UDP for low-latency audio streaming.
Description
MqttProtocol implements the Protocol abstract interface for devices using cellular modems (ML307) or constrained networks where WebSocket is impractical. It uses a hybrid transport:
- MQTT: Carries JSON control messages (hello, listen, abort, mcp) via publish/subscribe topics. MQTT provides reliable delivery for control plane.
- UDP: Carries binary audio packets for lower latency than MQTT QoS 0. Audio is AES-CTR encrypted using a key negotiated during the hello handshake.
Key design aspects:
- Reconnection: A 60-second reconnect timer (
MQTT_RECONNECT_INTERVAL_MS) re-establishes the MQTT client on disconnection. - Ping interval: 90 seconds (
MQTT_PING_INTERVAL_SECONDS) keeps the connection alive. - Alive flag:
alive_shared pointer prevents scheduled callbacks from running after destruction. - Channel mutex:
channel_mutex_guards the open/close state;udp_is shared soSendAudio()can callSend()without holding the mutex (to avoid blocking AT response parsing). - Sequence numbers:
local_sequence_andremote_sequence_track UDP packet ordering.
Usage
Reference this implementation when:
- Using MQTT/UDP transport for voice communication (cellular boards)
- Understanding AES-CTR audio encryption
- Tracing MQTT reconnection logic
- Comparing transport implementations
Code Reference
Source Location
- Repository: XiaoZhi ESP32
- Files:
main/protocols/mqtt_protocol.h,main/protocols/mqtt_protocol.cc
Signature
class MqttProtocol : public Protocol {
public:
MqttProtocol();
~MqttProtocol();
bool Start() override;
bool SendAudio(std::unique_ptr<AudioStreamPacket> packet) override;
bool OpenAudioChannel() override;
void CloseAudioChannel(bool send_goodbye = true) override;
bool IsAudioChannelOpened() const override;
private:
std::shared_ptr<std::atomic<bool>> alive_;
EventGroupHandle_t event_group_handle_;
std::string publish_topic_;
mutable std::mutex channel_mutex_;
std::mutex crypto_mutex_;
std::unique_ptr<Mqtt> mqtt_;
std::shared_ptr<Udp> udp_;
psa_key_id_t aes_key_id_ = PSA_KEY_ID_NULL;
std::string aes_nonce_;
std::string udp_server_;
int udp_port_;
uint32_t local_sequence_;
uint32_t remote_sequence_;
esp_timer_handle_t reconnect_timer_;
bool StartMqttClient(bool report_error = false);
void ParseServerHello(const cJSON* root);
bool DecodeHexString(const std::string& hex, std::string& decoded);
bool CryptAesCtr(const uint8_t* input, size_t input_size,
const uint8_t* nonce, uint8_t* output);
bool SendText(const std::string& text) override;
std::string GetHelloMessage();
};
Import
#include "mqtt_protocol.h"
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| packet | unique_ptr<AudioStreamPacket> | Opus packet to send over UDP | |
| mqtt/host | NVS String | MQTT broker host from activation | |
| mqtt/port | NVS Int | MQTT broker port | |
| mqtt/client_id | NVS String | MQTT client ID | |
| mqtt/username | NVS String | MQTT username (optional) | |
| mqtt/password | NVS String | MQTT password (optional) | |
| mqtt/publish_topic | NVS String | Topic for publishing messages | |
| mqtt/udp_server | NVS String | UDP audio server address | |
| mqtt/udp_port | NVS Int | UDP audio server port | |
| mqtt/aes_key | NVS String | AES key (hex-encoded, 128-bit) | |
| mqtt/aes_nonce | NVS String | AES nonce (hex-encoded) |
Outputs
| Name | Type | Description |
|---|---|---|
| SendAudio() | AES-CTR encrypted UDP datagram sent | |
| SendText() | JSON published via MQTT | |
| OpenAudioChannel() | True if MQTT connected and hello handshake done |
Usage Examples
Sending Encrypted Audio over UDP
// In MqttProtocol::SendAudio (simplified)
std::string encrypted;
encrypted.resize(packet->payload.size());
{
std::lock_guard<std::mutex> lock(crypto_mutex_);
CryptAesCtr(packet->payload.data(), packet->payload.size(),
(const uint8_t*)aes_nonce_.data(),
(uint8_t*)encrypted.data());
}
// Send encrypted audio as UDP datagram
udp_->Send(encrypted.data(), encrypted.size());
MQTT Reconnection Timer
// Reconnect timer fires after 60s on disconnect
esp_timer_start_once(reconnect_timer_, MQTT_RECONNECT_INTERVAL_MS * 1000);
// In timer callback:
if (*alive_ && !mqtt_->IsConnected()) {
StartMqttClient();
}
Related Pages
Implements Principle
- Principle:78_Xiaozhi_esp32_Protocol_Transport_Abstraction
- Principle:78_Xiaozhi_esp32_Binary_Audio_Framing