196 lines
6.1 KiB
C++
196 lines
6.1 KiB
C++
#include "protocol.h"
|
|
#include <esp_log.h>
|
|
|
|
#define TAG "Protocol"
|
|
|
|
void Protocol::OnIncomingJson(std::function<void(const cJSON *)> cb) { on_incoming_json_ = std::move(cb); }
|
|
void Protocol::OnIncomingAudio(std::function<void(std::unique_ptr<AudioStreamPacket>)> cb) { on_incoming_audio_ = std::move(cb); }
|
|
void Protocol::OnAudioChannelOpened(std::function<void()> cb) { on_audio_channel_opened_ = std::move(cb); }
|
|
void Protocol::OnAudioChannelClosed(std::function<void()> cb) { on_audio_channel_closed_ = std::move(cb); }
|
|
void Protocol::OnNetworkError(std::function<void(const std::string &)> cb) { on_network_error_ = std::move(cb); }
|
|
void Protocol::OnConnected(std::function<void()> cb) { on_connected_ = std::move(cb); }
|
|
void Protocol::OnDisconnected(std::function<void()> cb) { on_disconnected_ = std::move(cb); }
|
|
|
|
void Protocol::SetError(const std::string &message)
|
|
{
|
|
error_occurred_ = true;
|
|
if (on_network_error_)
|
|
{
|
|
on_network_error_(message);
|
|
}
|
|
}
|
|
|
|
bool Protocol::IsTimeout() const
|
|
{
|
|
auto now = std::chrono::steady_clock::now();
|
|
auto duration = std::chrono::duration_cast<std::chrono::seconds>(now - last_incoming_time_);
|
|
return duration.count() > 120;
|
|
}
|
|
|
|
void Protocol::SendStartListening(ListeningMode mode)
|
|
{
|
|
std::string json = "{\"session_id\":\"" + session_id_ + "\",\"type\":\"listen\",\"state\":\"start\",\"mode\":\"";
|
|
switch (mode)
|
|
{
|
|
case kListeningModeAutoStop:
|
|
json += "auto";
|
|
break;
|
|
case kListeningModeManualStop:
|
|
json += "manual";
|
|
break;
|
|
case kListeningModeRealtime:
|
|
json += "realtime";
|
|
break;
|
|
}
|
|
json += "\"}";
|
|
SendText(json);
|
|
}
|
|
|
|
void Protocol::SendStopListening()
|
|
{
|
|
SendText("{\"session_id\":\"" + session_id_ + "\",\"type\":\"listen\",\"state\":\"stop\"}");
|
|
}
|
|
|
|
static std::string EscapeJsonString(const std::string &input)
|
|
{
|
|
std::string output;
|
|
output.reserve(input.size() + 10);
|
|
|
|
for (size_t i = 0; i < input.size();)
|
|
{
|
|
unsigned char c = static_cast<unsigned char>(input[i]);
|
|
|
|
// 1. 处理 ASCII 控制字符和特殊字符
|
|
if (c < 0x20) {
|
|
switch (c) {
|
|
case '"': output += "\\\""; break;
|
|
case '\\': output += "\\\\"; break;
|
|
case '\b': output += "\\b"; break;
|
|
case '\f': output += "\\f"; break;
|
|
case '\n': output += "\\n"; break;
|
|
case '\r': output += "\\r"; break;
|
|
case '\t': output += "\\t"; break;
|
|
default:
|
|
char buf[8];
|
|
snprintf(buf, sizeof(buf), "\\u%04x", c);
|
|
output += buf;
|
|
break;
|
|
}
|
|
i++;
|
|
continue;
|
|
}
|
|
|
|
// 2. 处理 UTF-8 多字节字符
|
|
// 检查当前字节是否是合法的 UTF-8 起始字节
|
|
size_t char_len = 0;
|
|
if ((c & 0x80) == 0) {
|
|
char_len = 1; // ASCII
|
|
} else if ((c & 0xE0) == 0xC0) {
|
|
char_len = 2;
|
|
} else if ((c & 0xF0) == 0xE0) {
|
|
char_len = 3;
|
|
} else if ((c & 0xF8) == 0xF0) {
|
|
char_len = 4;
|
|
} else {
|
|
// 非法的 UTF-8 起始字节,跳过或替换
|
|
output += "\xEF\xBF\xBD"; // 插入替换字符
|
|
i++;
|
|
continue;
|
|
}
|
|
|
|
// 检查剩余长度是否足够
|
|
if (i + char_len > input.size()) {
|
|
// 数据截断,不完整的多字节字符,插入替换字符并结束
|
|
output += "\xEF\xBF\xBD";
|
|
break;
|
|
}
|
|
|
|
// 验证后续字节是否为合法的续字节 (10xxxxxx)
|
|
bool valid = true;
|
|
for (size_t j = 1; j < char_len; ++j) {
|
|
if ((input[i+j] & 0xC0) != 0x80) {
|
|
valid = false;
|
|
break;
|
|
}
|
|
}
|
|
|
|
if (valid) {
|
|
// 合法字符,直接追加
|
|
output.append(&input[i], char_len);
|
|
i += char_len;
|
|
} else {
|
|
// 非法序列,跳过第一个字节,插入替换字符
|
|
output += "\xEF\xBF\xBD";
|
|
i++;
|
|
}
|
|
}
|
|
return output;
|
|
}
|
|
|
|
/**
|
|
* @brief 安全截断 UTF-8 字符串,避免切断多字节字符
|
|
* @param text 原始 UTF-8 字符串
|
|
* @param max_bytes 最大字节数
|
|
* @return 截断后的合法 UTF-8 字符串
|
|
*/
|
|
static std::string SafeTruncateUtf8(const std::string &text, size_t max_bytes)
|
|
{
|
|
if (text.empty() || max_bytes == 0) return "";
|
|
if (text.size() <= max_bytes) return text;
|
|
|
|
size_t cut_pos = max_bytes;
|
|
|
|
// 如果截断位置在一个多字节字符中间,向前回退直到找到起始字节
|
|
while (cut_pos > 0)
|
|
{
|
|
unsigned char ch = static_cast<unsigned char>(text[cut_pos - 1]);
|
|
|
|
// ASCII (0xxxxxxx): 合法边界
|
|
if ((ch & 0x80) == 0)
|
|
break;
|
|
|
|
// UTF-8 起始字节 (11xxxxxx): 合法边界
|
|
if ((ch & 0xC0) == 0xC0)
|
|
break;
|
|
|
|
// 续字节 (10xxxxxx): 非法边界,继续前移
|
|
cut_pos--;
|
|
}
|
|
|
|
return text.substr(0, cut_pos);
|
|
}
|
|
|
|
void Protocol::SendAbortSpeaking(AbortReason reason)
|
|
{
|
|
// 1. 构建基础 JSON 结构
|
|
std::string json = "{\"session_id\":\"" + session_id_ + "\",\"type\":\"abort\"";
|
|
|
|
if (reason == kAbortReasonWakeWordDetected)
|
|
{
|
|
json += ",\"reason\":\"wake_word_detected\"";
|
|
}
|
|
ESP_LOGI(TAG,"text:%s",current_playback_text_.c_str());
|
|
// 2. 处理播放文本
|
|
if (!current_playback_text_.empty())
|
|
{
|
|
const size_t MAX_BYTE = 100;
|
|
|
|
// 安全截断,确保不切断汉字
|
|
std::string safe_text = SafeTruncateUtf8(current_playback_text_, MAX_BYTE);
|
|
|
|
// 转义为 JSON 合法字符串
|
|
std::string escaped_text = EscapeJsonString(safe_text);
|
|
|
|
// 拼接到 JSON
|
|
json += ",\"playback_text\":\"" + escaped_text + "\"";
|
|
|
|
ESP_LOGI(TAG, "Safe text len: %zu, Escaped: %s", safe_text.size(), escaped_text.c_str());
|
|
}
|
|
|
|
json += "}";
|
|
|
|
// 3. 发送
|
|
ESP_LOGI(TAG, "[SendAbortSpeaking] Final JSON: %s", json.c_str());
|
|
SendText(json);
|
|
}
|