bolar_2 backup
This commit is contained in:
176
main/protocol/binary_audio_protocol.cc
Normal file
176
main/protocol/binary_audio_protocol.cc
Normal file
@@ -0,0 +1,176 @@
|
||||
#include "protocol/binary_audio_protocol.h"
|
||||
|
||||
#include <cstring>
|
||||
|
||||
namespace borla {
|
||||
namespace {
|
||||
|
||||
uint16_t ReadBigEndian(const uint8_t* data)
|
||||
{
|
||||
return static_cast<uint16_t>(
|
||||
(static_cast<uint16_t>(data[0]) << 8U) |
|
||||
static_cast<uint16_t>(data[1]));
|
||||
}
|
||||
|
||||
void WriteBigEndian(uint8_t* data, uint16_t value)
|
||||
{
|
||||
data[0] = static_cast<uint8_t>(value >> 8U);
|
||||
data[1] = static_cast<uint8_t>(value & 0xffU);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool BinaryAudioBatchBuilder::Push(
|
||||
const uint8_t* opus,
|
||||
size_t size)
|
||||
{
|
||||
if (opus == nullptr || size == 0 ||
|
||||
size > kBinaryAudioMaximumUplinkOpusBytes ||
|
||||
Full()) {
|
||||
return false;
|
||||
}
|
||||
Frame& frame = frames_[frame_count_++];
|
||||
frame.size = static_cast<uint16_t>(size);
|
||||
std::memcpy(frame.payload.data(), opus, size);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool BinaryAudioBatchBuilder::Build(
|
||||
uint8_t* output,
|
||||
size_t capacity,
|
||||
size_t* output_size) const
|
||||
{
|
||||
if (output == nullptr || output_size == nullptr || Empty()) {
|
||||
return false;
|
||||
}
|
||||
size_t payload_size = 0;
|
||||
for (size_t index = 0; index < frame_count_; ++index) {
|
||||
payload_size += sizeof(uint16_t) + frames_[index].size;
|
||||
}
|
||||
const size_t packet_size =
|
||||
kBinaryAudioHeaderSize + payload_size;
|
||||
if (packet_size > capacity || payload_size > UINT16_MAX) {
|
||||
return false;
|
||||
}
|
||||
|
||||
output[0] = kBinaryAudioTypeOpus;
|
||||
output[1] = kBinaryAudioFlagBatch;
|
||||
WriteBigEndian(output + 2, static_cast<uint16_t>(payload_size));
|
||||
size_t cursor = kBinaryAudioHeaderSize;
|
||||
for (size_t index = 0; index < frame_count_; ++index) {
|
||||
WriteBigEndian(output + cursor, frames_[index].size);
|
||||
cursor += sizeof(uint16_t);
|
||||
std::memcpy(
|
||||
output + cursor,
|
||||
frames_[index].payload.data(),
|
||||
frames_[index].size);
|
||||
cursor += frames_[index].size;
|
||||
}
|
||||
*output_size = cursor;
|
||||
return true;
|
||||
}
|
||||
|
||||
void BinaryAudioBatchBuilder::Reset()
|
||||
{
|
||||
frame_count_ = 0;
|
||||
}
|
||||
|
||||
bool BuildBinaryAudioSingleFrame(
|
||||
const uint8_t* opus,
|
||||
size_t size,
|
||||
uint8_t* output,
|
||||
size_t capacity,
|
||||
size_t* output_size)
|
||||
{
|
||||
if (opus == nullptr || size == 0 ||
|
||||
size > kBinaryAudioMaximumOpusBytes ||
|
||||
output == nullptr || output_size == nullptr ||
|
||||
capacity < kBinaryAudioHeaderSize + size ||
|
||||
size > UINT16_MAX) {
|
||||
return false;
|
||||
}
|
||||
output[0] = kBinaryAudioTypeOpus;
|
||||
output[1] = 0;
|
||||
WriteBigEndian(output + 2, static_cast<uint16_t>(size));
|
||||
std::memcpy(output + kBinaryAudioHeaderSize, opus, size);
|
||||
*output_size = kBinaryAudioHeaderSize + size;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool VisitBinaryAudioPacket(
|
||||
const uint8_t* packet,
|
||||
size_t size,
|
||||
IBinaryAudioFrameVisitor& visitor,
|
||||
size_t* frame_count)
|
||||
{
|
||||
if (frame_count != nullptr) {
|
||||
*frame_count = 0;
|
||||
}
|
||||
if (packet == nullptr || size < kBinaryAudioHeaderSize ||
|
||||
packet[0] != kBinaryAudioTypeOpus ||
|
||||
(packet[1] & ~kBinaryAudioFlagBatch) != 0) {
|
||||
return false;
|
||||
}
|
||||
const size_t payload_size = ReadBigEndian(packet + 2);
|
||||
if (payload_size == 0 ||
|
||||
payload_size != size - kBinaryAudioHeaderSize) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const uint8_t* cursor = packet + kBinaryAudioHeaderSize;
|
||||
size_t remaining = payload_size;
|
||||
size_t visited = 0;
|
||||
if ((packet[1] & kBinaryAudioFlagBatch) == 0) {
|
||||
if (remaining > kBinaryAudioMaximumOpusBytes) {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
// Validate the complete envelope first. A malformed trailing frame
|
||||
// must not leave the playback pipeline with partially delivered data.
|
||||
while (remaining != 0) {
|
||||
if (remaining < sizeof(uint16_t)) {
|
||||
return false;
|
||||
}
|
||||
const size_t frame_size = ReadBigEndian(cursor);
|
||||
cursor += sizeof(uint16_t);
|
||||
remaining -= sizeof(uint16_t);
|
||||
if (frame_size == 0 ||
|
||||
frame_size > kBinaryAudioMaximumOpusBytes ||
|
||||
frame_size > remaining ||
|
||||
visited >= kBinaryAudioBatchFrames) {
|
||||
return false;
|
||||
}
|
||||
cursor += frame_size;
|
||||
remaining -= frame_size;
|
||||
visited++;
|
||||
}
|
||||
}
|
||||
|
||||
cursor = packet + kBinaryAudioHeaderSize;
|
||||
remaining = payload_size;
|
||||
visited = 0;
|
||||
if ((packet[1] & kBinaryAudioFlagBatch) == 0) {
|
||||
if (!visitor.OnOpusFrame(cursor, remaining)) {
|
||||
return false;
|
||||
}
|
||||
visited = 1;
|
||||
} else {
|
||||
while (remaining != 0) {
|
||||
const size_t frame_size = ReadBigEndian(cursor);
|
||||
cursor += sizeof(uint16_t);
|
||||
remaining -= sizeof(uint16_t);
|
||||
if (!visitor.OnOpusFrame(cursor, frame_size)) {
|
||||
return false;
|
||||
}
|
||||
cursor += frame_size;
|
||||
remaining -= frame_size;
|
||||
visited++;
|
||||
}
|
||||
}
|
||||
if (frame_count != nullptr) {
|
||||
*frame_count = visited;
|
||||
}
|
||||
return visited != 0;
|
||||
}
|
||||
|
||||
} // namespace borla
|
||||
66
main/protocol/binary_audio_protocol.h
Normal file
66
main/protocol/binary_audio_protocol.h
Normal file
@@ -0,0 +1,66 @@
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
namespace borla {
|
||||
|
||||
inline constexpr uint8_t kBinaryAudioTypeOpus = 0;
|
||||
inline constexpr uint8_t kBinaryAudioFlagBatch = 0x01;
|
||||
inline constexpr size_t kBinaryAudioHeaderSize = 4;
|
||||
inline constexpr size_t kBinaryAudioMaximumOpusBytes = 1536;
|
||||
inline constexpr size_t kBinaryAudioMaximumUplinkOpusBytes = 512;
|
||||
inline constexpr size_t kBinaryAudioBatchFrames = 5;
|
||||
inline constexpr size_t kBinaryAudioMaximumPacketBytes =
|
||||
kBinaryAudioHeaderSize +
|
||||
kBinaryAudioBatchFrames *
|
||||
(sizeof(uint16_t) + kBinaryAudioMaximumUplinkOpusBytes);
|
||||
|
||||
class BinaryAudioBatchBuilder final {
|
||||
public:
|
||||
bool Push(const uint8_t* opus, size_t size);
|
||||
bool Full() const { return frame_count_ == kBinaryAudioBatchFrames; }
|
||||
bool Empty() const { return frame_count_ == 0; }
|
||||
size_t FrameCount() const { return frame_count_; }
|
||||
bool Build(
|
||||
uint8_t* output,
|
||||
size_t capacity,
|
||||
size_t* output_size) const;
|
||||
void Reset();
|
||||
|
||||
private:
|
||||
struct Frame {
|
||||
uint16_t size = 0;
|
||||
std::array<
|
||||
uint8_t,
|
||||
kBinaryAudioMaximumUplinkOpusBytes>
|
||||
payload{};
|
||||
};
|
||||
|
||||
std::array<Frame, kBinaryAudioBatchFrames> frames_{};
|
||||
size_t frame_count_ = 0;
|
||||
};
|
||||
|
||||
class IBinaryAudioFrameVisitor {
|
||||
public:
|
||||
virtual ~IBinaryAudioFrameVisitor() = default;
|
||||
virtual bool OnOpusFrame(
|
||||
const uint8_t* data,
|
||||
size_t size) = 0;
|
||||
};
|
||||
|
||||
bool BuildBinaryAudioSingleFrame(
|
||||
const uint8_t* opus,
|
||||
size_t size,
|
||||
uint8_t* output,
|
||||
size_t capacity,
|
||||
size_t* output_size);
|
||||
|
||||
bool VisitBinaryAudioPacket(
|
||||
const uint8_t* packet,
|
||||
size_t size,
|
||||
IBinaryAudioFrameVisitor& visitor,
|
||||
size_t* frame_count = nullptr);
|
||||
|
||||
} // namespace borla
|
||||
416
main/protocol/protocol_message_builder.cc
Normal file
416
main/protocol/protocol_message_builder.cc
Normal file
@@ -0,0 +1,416 @@
|
||||
#include "protocol/protocol_message_builder.h"
|
||||
|
||||
#include "protocol/utf8_text.h"
|
||||
|
||||
#include <cstring>
|
||||
|
||||
#include <cJSON.h>
|
||||
|
||||
namespace borla {
|
||||
|
||||
bool ProtocolMessageBuilder::BuildHello(
|
||||
uint8_t protocol_version,
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size) const
|
||||
{
|
||||
return BuildHello(
|
||||
protocol_version,
|
||||
nullptr,
|
||||
output,
|
||||
capacity,
|
||||
output_size);
|
||||
}
|
||||
|
||||
bool ProtocolMessageBuilder::BuildHello(
|
||||
uint8_t protocol_version,
|
||||
const MemorySnapshot* memory,
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size) const
|
||||
{
|
||||
cJSON* root = cJSON_CreateObject();
|
||||
cJSON* features = cJSON_CreateObject();
|
||||
cJSON* audio = cJSON_CreateObject();
|
||||
if (root == nullptr || features == nullptr || audio == nullptr) {
|
||||
cJSON_Delete(root);
|
||||
cJSON_Delete(features);
|
||||
cJSON_Delete(audio);
|
||||
return false;
|
||||
}
|
||||
|
||||
cJSON_AddStringToObject(root, "type", "hello");
|
||||
cJSON_AddNumberToObject(root, "version", protocol_version);
|
||||
cJSON_AddStringToObject(root, "transport", "websocket");
|
||||
cJSON_AddBoolToObject(features, "mcp", true);
|
||||
cJSON_AddBoolToObject(features, "local_audio", true);
|
||||
cJSON_AddBoolToObject(
|
||||
features, "play_local_sequence", true);
|
||||
cJSON_AddBoolToObject(
|
||||
features, "barge_in_two_phase", true);
|
||||
cJSON_AddItemToObject(root, "features", features);
|
||||
cJSON_AddStringToObject(audio, "format", "opus");
|
||||
cJSON_AddNumberToObject(audio, "sample_rate", 16000);
|
||||
cJSON_AddNumberToObject(audio, "channels", 1);
|
||||
cJSON_AddNumberToObject(audio, "frame_duration", 60);
|
||||
cJSON_AddItemToObject(root, "audio_params", audio);
|
||||
if (memory != nullptr && memory->HasData() &&
|
||||
IsValidMemorySnapshot(*memory)) {
|
||||
cJSON* cache = cJSON_CreateObject();
|
||||
if (cache == nullptr) {
|
||||
cJSON_Delete(root);
|
||||
return false;
|
||||
}
|
||||
if (memory->child_name[0] != '\0') {
|
||||
cJSON_AddStringToObject(
|
||||
cache,
|
||||
"child_name",
|
||||
memory->child_name.data());
|
||||
}
|
||||
if (memory->brain_text[0] != '\0') {
|
||||
cJSON_AddStringToObject(
|
||||
cache,
|
||||
"brain_text",
|
||||
memory->brain_text.data());
|
||||
}
|
||||
cJSON_AddNumberToObject(
|
||||
cache,
|
||||
"interaction_count",
|
||||
memory->interaction_count);
|
||||
cJSON_AddItemToObject(root, "memory_cache", cache);
|
||||
}
|
||||
return Print(root, output, capacity, output_size);
|
||||
}
|
||||
|
||||
bool ProtocolMessageBuilder::BuildStartListening(
|
||||
const char* session_id,
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size) const
|
||||
{
|
||||
cJSON* root = cJSON_CreateObject();
|
||||
if (root == nullptr || session_id == nullptr) {
|
||||
cJSON_Delete(root);
|
||||
return false;
|
||||
}
|
||||
cJSON_AddStringToObject(root, "session_id", session_id);
|
||||
cJSON_AddStringToObject(root, "type", "listen");
|
||||
cJSON_AddStringToObject(root, "state", "start");
|
||||
cJSON_AddStringToObject(root, "mode", "auto");
|
||||
return Print(root, output, capacity, output_size);
|
||||
}
|
||||
|
||||
bool ProtocolMessageBuilder::BuildStopListening(
|
||||
const char* session_id,
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size) const
|
||||
{
|
||||
cJSON* root = cJSON_CreateObject();
|
||||
if (root == nullptr || session_id == nullptr) {
|
||||
cJSON_Delete(root);
|
||||
return false;
|
||||
}
|
||||
cJSON_AddStringToObject(root, "session_id", session_id);
|
||||
cJSON_AddStringToObject(root, "type", "listen");
|
||||
cJSON_AddStringToObject(root, "state", "stop");
|
||||
return Print(root, output, capacity, output_size);
|
||||
}
|
||||
|
||||
bool ProtocolMessageBuilder::BuildAbort(
|
||||
const char* session_id,
|
||||
ConversationInterruptSource source,
|
||||
const char* playback_text,
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size) const
|
||||
{
|
||||
cJSON* root = cJSON_CreateObject();
|
||||
if (root == nullptr || session_id == nullptr) {
|
||||
cJSON_Delete(root);
|
||||
return false;
|
||||
}
|
||||
cJSON_AddStringToObject(root, "session_id", session_id);
|
||||
cJSON_AddStringToObject(root, "type", "abort");
|
||||
cJSON_AddStringToObject(
|
||||
root,
|
||||
"reason",
|
||||
source == ConversationInterruptSource::kWakeWordDetected
|
||||
? "wake_word_detected"
|
||||
: "user_initiated");
|
||||
if (playback_text != nullptr && playback_text[0] != '\0') {
|
||||
const size_t kept = utf8_text::SafeTruncatedLength(
|
||||
playback_text,
|
||||
std::strlen(playback_text),
|
||||
kPlaybackTextBytes);
|
||||
if (kept != 0) {
|
||||
// cJSON escapes quotes and control characters on its own, so the
|
||||
// only way this field can corrupt the frame is an encoding split —
|
||||
// which is exactly what SafeTruncatedLength rules out.
|
||||
char truncated[kPlaybackTextBytes + 1] = {};
|
||||
std::memcpy(truncated, playback_text, kept);
|
||||
cJSON_AddStringToObject(
|
||||
root, "playback_text", truncated);
|
||||
}
|
||||
}
|
||||
return Print(root, output, capacity, output_size);
|
||||
}
|
||||
|
||||
bool ProtocolMessageBuilder::BuildPing(
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size) const
|
||||
{
|
||||
cJSON* root = cJSON_CreateObject();
|
||||
if (root == nullptr) {
|
||||
return false;
|
||||
}
|
||||
cJSON_AddStringToObject(root, "type", "ping");
|
||||
return Print(root, output, capacity, output_size);
|
||||
}
|
||||
|
||||
bool ProtocolMessageBuilder::BuildTraceMarker(
|
||||
const char* trace_id,
|
||||
const char* stage,
|
||||
uint64_t sequence,
|
||||
size_t frames,
|
||||
size_t bytes,
|
||||
uint64_t client_send_ms,
|
||||
int64_t client_epoch_ms,
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size) const
|
||||
{
|
||||
cJSON* root = cJSON_CreateObject();
|
||||
if (root == nullptr || stage == nullptr) {
|
||||
cJSON_Delete(root);
|
||||
return false;
|
||||
}
|
||||
cJSON_AddStringToObject(root, "type", "trace");
|
||||
if (trace_id != nullptr && trace_id[0] != '\0') {
|
||||
cJSON_AddStringToObject(root, "trace_id", trace_id);
|
||||
}
|
||||
cJSON_AddStringToObject(root, "stage", stage);
|
||||
cJSON_AddNumberToObject(
|
||||
root, "seq", static_cast<double>(sequence));
|
||||
cJSON_AddNumberToObject(
|
||||
root, "frames", static_cast<double>(frames));
|
||||
cJSON_AddNumberToObject(
|
||||
root, "bytes", static_cast<double>(bytes));
|
||||
cJSON_AddNumberToObject(
|
||||
root,
|
||||
"client_send_ms",
|
||||
static_cast<double>(client_send_ms));
|
||||
cJSON_AddNumberToObject(
|
||||
root,
|
||||
"client_epoch_ms",
|
||||
static_cast<double>(client_epoch_ms));
|
||||
return Print(root, output, capacity, output_size);
|
||||
}
|
||||
|
||||
bool ProtocolMessageBuilder::BuildGoodbye(
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size) const
|
||||
{
|
||||
cJSON* root = cJSON_CreateObject();
|
||||
if (root == nullptr) {
|
||||
return false;
|
||||
}
|
||||
cJSON_AddStringToObject(root, "type", "goodbye");
|
||||
return Print(root, output, capacity, output_size);
|
||||
}
|
||||
|
||||
bool ProtocolMessageBuilder::BuildPong(
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size) const
|
||||
{
|
||||
cJSON* root = cJSON_CreateObject();
|
||||
if (root == nullptr) {
|
||||
return false;
|
||||
}
|
||||
cJSON_AddStringToObject(root, "type", "pong");
|
||||
return Print(root, output, capacity, output_size);
|
||||
}
|
||||
|
||||
bool ProtocolMessageBuilder::BuildButton(
|
||||
uint8_t click_count,
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size) const
|
||||
{
|
||||
if (click_count != 3 && click_count != 4) {
|
||||
return false;
|
||||
}
|
||||
cJSON* root = cJSON_CreateObject();
|
||||
if (root == nullptr) {
|
||||
return false;
|
||||
}
|
||||
cJSON_AddStringToObject(root, "type", "button");
|
||||
cJSON_AddNumberToObject(root, "count", click_count);
|
||||
return Print(root, output, capacity, output_size);
|
||||
}
|
||||
|
||||
bool ProtocolMessageBuilder::BuildLocalPlaybackState(
|
||||
const char* group,
|
||||
bool started,
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size) const
|
||||
{
|
||||
if (group == nullptr || group[0] == '\0') {
|
||||
return false;
|
||||
}
|
||||
cJSON* root = cJSON_CreateObject();
|
||||
if (root == nullptr) {
|
||||
return false;
|
||||
}
|
||||
cJSON_AddStringToObject(root, "type", "play_local");
|
||||
cJSON_AddStringToObject(
|
||||
root, "state", started ? "start" : "done");
|
||||
cJSON_AddStringToObject(root, "group", group);
|
||||
return Print(root, output, capacity, output_size);
|
||||
}
|
||||
|
||||
bool ProtocolMessageBuilder::BuildStatus(
|
||||
uint8_t battery_percent,
|
||||
uint16_t battery_voltage_mv,
|
||||
bool charging,
|
||||
const char* version,
|
||||
int16_t volume_percent,
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size) const
|
||||
{
|
||||
cJSON* root = cJSON_CreateObject();
|
||||
if (root == nullptr || version == nullptr) {
|
||||
cJSON_Delete(root);
|
||||
return false;
|
||||
}
|
||||
cJSON_AddStringToObject(root, "type", "status");
|
||||
cJSON_AddNumberToObject(root, "battery", battery_percent);
|
||||
cJSON_AddNumberToObject(
|
||||
root, "battery_voltage_mv", battery_voltage_mv);
|
||||
cJSON_AddBoolToObject(root, "charging", charging);
|
||||
cJSON_AddStringToObject(root, "version", version);
|
||||
if (volume_percent >= 0) {
|
||||
cJSON_AddNumberToObject(root, "volume", volume_percent);
|
||||
}
|
||||
return Print(root, output, capacity, output_size);
|
||||
}
|
||||
|
||||
bool ProtocolMessageBuilder::BuildAlarmFired(
|
||||
int32_t alarm_id,
|
||||
int64_t fired_at_epoch,
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size) const
|
||||
{
|
||||
cJSON* root = cJSON_CreateObject();
|
||||
if (root == nullptr) {
|
||||
return false;
|
||||
}
|
||||
cJSON_AddStringToObject(root, "type", "alarm_fired");
|
||||
cJSON_AddNumberToObject(root, "id", alarm_id);
|
||||
cJSON_AddNumberToObject(
|
||||
root, "fired_at", static_cast<double>(fired_at_epoch));
|
||||
return Print(root, output, capacity, output_size);
|
||||
}
|
||||
|
||||
bool ProtocolMessageBuilder::BuildCallAction(
|
||||
const char* state,
|
||||
const char* call_id,
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size) const
|
||||
{
|
||||
cJSON* root = cJSON_CreateObject();
|
||||
if (root == nullptr || state == nullptr || call_id == nullptr ||
|
||||
call_id[0] == '\0') {
|
||||
cJSON_Delete(root);
|
||||
return false;
|
||||
}
|
||||
cJSON_AddStringToObject(root, "type", "call");
|
||||
cJSON_AddStringToObject(root, "state", state);
|
||||
cJSON_AddStringToObject(root, "call_id", call_id);
|
||||
return Print(root, output, capacity, output_size);
|
||||
}
|
||||
|
||||
bool ProtocolMessageBuilder::BuildOtaNotify(
|
||||
const char* text,
|
||||
bool optional,
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size) const
|
||||
{
|
||||
cJSON* root = cJSON_CreateObject();
|
||||
if (root == nullptr || text == nullptr || text[0] == '\0') {
|
||||
cJSON_Delete(root);
|
||||
return false;
|
||||
}
|
||||
cJSON_AddStringToObject(root, "type", "ota_notify");
|
||||
cJSON_AddStringToObject(root, "text", text);
|
||||
if (optional) {
|
||||
// Only emitted for advisory notices so the existing server contract
|
||||
// (absent field == mandatory upgrade) is preserved byte for byte.
|
||||
cJSON_AddBoolToObject(root, "optional", true);
|
||||
}
|
||||
return Print(root, output, capacity, output_size);
|
||||
}
|
||||
|
||||
bool ProtocolMessageBuilder::BuildFriendAdd(
|
||||
const char* local_mac,
|
||||
const char* local_name,
|
||||
const char* remote_mac,
|
||||
const char* remote_name,
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size) const
|
||||
{
|
||||
cJSON* root = cJSON_CreateObject();
|
||||
if (root == nullptr || local_mac == nullptr ||
|
||||
local_name == nullptr || remote_mac == nullptr ||
|
||||
remote_name == nullptr || local_mac[0] == '\0' ||
|
||||
remote_mac[0] == '\0') {
|
||||
cJSON_Delete(root);
|
||||
return false;
|
||||
}
|
||||
cJSON_AddStringToObject(root, "type", "friend_add");
|
||||
cJSON_AddStringToObject(root, "local_mac", local_mac);
|
||||
cJSON_AddStringToObject(root, "local_name", local_name);
|
||||
cJSON_AddStringToObject(root, "remote_mac", remote_mac);
|
||||
cJSON_AddStringToObject(root, "remote_name", remote_name);
|
||||
return Print(root, output, capacity, output_size);
|
||||
}
|
||||
|
||||
bool ProtocolMessageBuilder::Print(
|
||||
void* opaque_root,
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size) const
|
||||
{
|
||||
auto* root = static_cast<cJSON*>(opaque_root);
|
||||
if (root == nullptr || output == nullptr ||
|
||||
capacity == 0 || output_size == nullptr) {
|
||||
cJSON_Delete(root);
|
||||
return false;
|
||||
}
|
||||
|
||||
char* rendered = cJSON_PrintUnformatted(root);
|
||||
cJSON_Delete(root);
|
||||
if (rendered == nullptr) {
|
||||
return false;
|
||||
}
|
||||
const size_t size = std::strlen(rendered);
|
||||
if (size >= capacity) {
|
||||
cJSON_free(rendered);
|
||||
return false;
|
||||
}
|
||||
std::memcpy(output, rendered, size + 1);
|
||||
*output_size = size;
|
||||
cJSON_free(rendered);
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace borla
|
||||
136
main/protocol/protocol_message_builder.h
Normal file
136
main/protocol/protocol_message_builder.h
Normal file
@@ -0,0 +1,136 @@
|
||||
#pragma once
|
||||
|
||||
#include "core/runtime_state.h"
|
||||
#include "memory/memory_types.h"
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
namespace borla {
|
||||
|
||||
class ProtocolMessageBuilder final {
|
||||
public:
|
||||
bool BuildHello(
|
||||
uint8_t protocol_version,
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size) const;
|
||||
bool BuildHello(
|
||||
uint8_t protocol_version,
|
||||
const MemorySnapshot* memory,
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size) const;
|
||||
bool BuildStartListening(
|
||||
const char* session_id,
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size) const;
|
||||
bool BuildStopListening(
|
||||
const char* session_id,
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size) const;
|
||||
// playback_text is the sentence the speaker was in the middle of when the
|
||||
// turn was interrupted, or nullptr/"" when nothing was playing. The server
|
||||
// needs it to know how much of its reply the child actually heard, so the
|
||||
// next turn continues from there instead of from the full untruncated
|
||||
// reply. Capped at kPlaybackTextBytes on a UTF-8 character boundary.
|
||||
static constexpr size_t kPlaybackTextBytes = 100;
|
||||
|
||||
bool BuildAbort(
|
||||
const char* session_id,
|
||||
ConversationInterruptSource source,
|
||||
const char* playback_text,
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size) const;
|
||||
// Latency/clock-skew marker for one uplink audio batch. The server reads
|
||||
// client_send_ms and client_epoch_ms out of this message
|
||||
// (connection.py _update_trace_from_payload) and derives the device-to-
|
||||
// server clock delta from them. client_epoch_ms is 0 when the wall clock
|
||||
// has not been synced yet, which the server treats as "unknown" rather
|
||||
// than as a bogus 1970 timestamp.
|
||||
bool BuildTraceMarker(
|
||||
const char* trace_id,
|
||||
const char* stage,
|
||||
uint64_t sequence,
|
||||
size_t frames,
|
||||
size_t bytes,
|
||||
uint64_t client_send_ms,
|
||||
int64_t client_epoch_ms,
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size) const;
|
||||
|
||||
bool BuildGoodbye(
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size) const;
|
||||
bool BuildPing(
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size) const;
|
||||
bool BuildPong(
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size) const;
|
||||
bool BuildButton(
|
||||
uint8_t click_count,
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size) const;
|
||||
bool BuildLocalPlaybackState(
|
||||
const char* group,
|
||||
bool started,
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size) const;
|
||||
// volume_percent is emitted only when >= 0 so the ServerHello status frame
|
||||
// (sent before the audio engine is queried) keeps its original shape.
|
||||
bool BuildStatus(
|
||||
uint8_t battery_percent,
|
||||
uint16_t battery_voltage_mv,
|
||||
bool charging,
|
||||
const char* version,
|
||||
int16_t volume_percent,
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size) const;
|
||||
bool BuildAlarmFired(
|
||||
int32_t alarm_id,
|
||||
int64_t fired_at_epoch,
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size) const;
|
||||
bool BuildCallAction(
|
||||
const char* state,
|
||||
const char* call_id,
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size) const;
|
||||
bool BuildOtaNotify(
|
||||
const char* text,
|
||||
bool optional,
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size) const;
|
||||
|
||||
bool BuildFriendAdd(
|
||||
const char* local_mac,
|
||||
const char* local_name,
|
||||
const char* remote_mac,
|
||||
const char* remote_name,
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size) const;
|
||||
|
||||
private:
|
||||
bool Print(
|
||||
void* root,
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size) const;
|
||||
};
|
||||
|
||||
} // namespace borla
|
||||
17
main/protocol/realtime_binary_sink.h
Normal file
17
main/protocol/realtime_binary_sink.h
Normal file
@@ -0,0 +1,17 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
namespace borla {
|
||||
|
||||
class IRealtimeBinarySink {
|
||||
public:
|
||||
virtual ~IRealtimeBinarySink() = default;
|
||||
virtual void OnRealtimeBinary(
|
||||
const uint8_t* data,
|
||||
size_t size,
|
||||
uint32_t playback_session_id) = 0;
|
||||
};
|
||||
|
||||
} // namespace borla
|
||||
129
main/protocol/realtime_config.cc
Normal file
129
main/protocol/realtime_config.cc
Normal file
@@ -0,0 +1,129 @@
|
||||
#include "protocol/realtime_config.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
|
||||
#include <esp_err.h>
|
||||
#include <esp_log.h>
|
||||
#include <nvs.h>
|
||||
|
||||
namespace borla {
|
||||
namespace {
|
||||
|
||||
constexpr const char* kTag = "RealtimeConfig2";
|
||||
constexpr const char* kNamespace = "websocket";
|
||||
constexpr const char* kFallbackUrl = kDefaultRealtimeUrl;
|
||||
|
||||
template <size_t N>
|
||||
void CopyLiteral(std::array<char, N>* output, const char* value)
|
||||
{
|
||||
output->fill('\0');
|
||||
if (value != nullptr) {
|
||||
std::strncpy(output->data(), value, output->size() - 1);
|
||||
}
|
||||
}
|
||||
|
||||
template <size_t N>
|
||||
bool ReadString(
|
||||
nvs_handle_t handle,
|
||||
const char* key,
|
||||
std::array<char, N>* output)
|
||||
{
|
||||
size_t size = output->size();
|
||||
output->fill('\0');
|
||||
return nvs_get_str(handle, key, output->data(), &size) == ESP_OK;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool NvsRealtimeConfigStore::SaveEndpoint(
|
||||
const char* url,
|
||||
const char* token)
|
||||
{
|
||||
if ((url == nullptr || url[0] == '\0') &&
|
||||
(token == nullptr || token[0] == '\0')) {
|
||||
return true;
|
||||
}
|
||||
nvs_handle_t handle = 0;
|
||||
esp_err_t result =
|
||||
nvs_open(kNamespace, NVS_READWRITE, &handle);
|
||||
if (result != ESP_OK) {
|
||||
ESP_LOGE(kTag, "open writable namespace failed: %s",
|
||||
esp_err_to_name(result));
|
||||
return false;
|
||||
}
|
||||
if (url != nullptr && url[0] != '\0') {
|
||||
result = nvs_set_str(handle, "url", url);
|
||||
}
|
||||
if (result == ESP_OK && token != nullptr && token[0] != '\0') {
|
||||
result = nvs_set_str(handle, "token", token);
|
||||
}
|
||||
if (result == ESP_OK) {
|
||||
result = nvs_set_i32(handle, "version", 3);
|
||||
}
|
||||
if (result == ESP_OK) {
|
||||
result = nvs_commit(handle);
|
||||
}
|
||||
nvs_close(handle);
|
||||
if (result != ESP_OK) {
|
||||
ESP_LOGE(kTag, "endpoint save failed: %s",
|
||||
esp_err_to_name(result));
|
||||
return false;
|
||||
}
|
||||
ESP_LOGI(kTag, "endpoint persisted url=%s token=%s",
|
||||
url != nullptr && url[0] != '\0' ? url : "(unchanged)",
|
||||
token != nullptr && token[0] != '\0'
|
||||
? "present"
|
||||
: "(unchanged)");
|
||||
return true;
|
||||
}
|
||||
|
||||
bool NvsRealtimeConfigStore::Load(RealtimeConfig* output) const
|
||||
{
|
||||
if (output == nullptr) {
|
||||
return false;
|
||||
}
|
||||
|
||||
RealtimeConfig config;
|
||||
CopyLiteral(&config.transport.url, kFallbackUrl);
|
||||
|
||||
nvs_handle_t handle = 0;
|
||||
const esp_err_t open_result =
|
||||
nvs_open(kNamespace, NVS_READONLY, &handle);
|
||||
if (open_result == ESP_OK) {
|
||||
std::array<char, kWebsocketUrlCapacity> saved_url{};
|
||||
if (ReadString(handle, "url", &saved_url) &&
|
||||
saved_url[0] != '\0') {
|
||||
config.transport.url = saved_url;
|
||||
}
|
||||
ReadString(handle, "token", &config.transport.token);
|
||||
|
||||
int32_t version = 0;
|
||||
if (nvs_get_i32(handle, "version", &version) == ESP_OK &&
|
||||
version > 0 && version <= UINT8_MAX) {
|
||||
config.transport.protocol_version =
|
||||
static_cast<uint8_t>(version);
|
||||
}
|
||||
nvs_close(handle);
|
||||
} else if (open_result != ESP_ERR_NVS_NOT_FOUND) {
|
||||
ESP_LOGE(kTag, "open namespace failed: %s",
|
||||
esp_err_to_name(open_result));
|
||||
return false;
|
||||
}
|
||||
|
||||
if (config.transport.protocol_version != 3) {
|
||||
ESP_LOGW(kTag, "forcing protocol version 3 instead of %u",
|
||||
static_cast<unsigned>(
|
||||
config.transport.protocol_version));
|
||||
config.transport.protocol_version = 3;
|
||||
}
|
||||
*output = config;
|
||||
ESP_LOGI(kTag, "loaded endpoint url=%s protocol=%u token=%s",
|
||||
output->transport.url.data(),
|
||||
static_cast<unsigned>(
|
||||
output->transport.protocol_version),
|
||||
output->transport.token[0] == '\0' ? "absent" : "present");
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace borla
|
||||
41
main/protocol/realtime_config.h
Normal file
41
main/protocol/realtime_config.h
Normal file
@@ -0,0 +1,41 @@
|
||||
#pragma once
|
||||
|
||||
#include "protocol/websocket_transport.h"
|
||||
|
||||
namespace borla {
|
||||
|
||||
// Build default used when NVS holds nothing, and the replacement applied when
|
||||
// a stored/pushed endpoint turns out to be a retired staging host.
|
||||
inline constexpr const char* kDefaultRealtimeUrl =
|
||||
"wss://borlaws.lkall.com/v1/ws";
|
||||
|
||||
struct RealtimeConfig {
|
||||
WebsocketTransportConfig transport;
|
||||
uint32_t hello_timeout_ms = 15000;
|
||||
uint32_t heartbeat_interval_ms = 30000;
|
||||
uint32_t heartbeat_timeout_ms = 90000;
|
||||
};
|
||||
|
||||
class IRealtimeConfigStore {
|
||||
public:
|
||||
virtual ~IRealtimeConfigStore() = default;
|
||||
virtual bool Load(RealtimeConfig* output) const = 0;
|
||||
|
||||
// Persist an endpoint handed down by the OTA check response. `token` may
|
||||
// be null to leave the stored token untouched. Returns false only on a
|
||||
// real NVS failure; the caller treats that as non-fatal because the
|
||||
// in-memory endpoint is still usable for this boot.
|
||||
virtual bool SaveEndpoint(
|
||||
const char* url,
|
||||
const char* token) = 0;
|
||||
};
|
||||
|
||||
class NvsRealtimeConfigStore final : public IRealtimeConfigStore {
|
||||
public:
|
||||
bool Load(RealtimeConfig* output) const override;
|
||||
bool SaveEndpoint(
|
||||
const char* url,
|
||||
const char* token) override;
|
||||
};
|
||||
|
||||
} // namespace borla
|
||||
1546
main/protocol/realtime_protocol.cc
Normal file
1546
main/protocol/realtime_protocol.cc
Normal file
File diff suppressed because it is too large
Load Diff
253
main/protocol/realtime_protocol.h
Normal file
253
main/protocol/realtime_protocol.h
Normal file
@@ -0,0 +1,253 @@
|
||||
#pragma once
|
||||
|
||||
#include "connectivity/reconnect_backoff.h"
|
||||
#include "audio/encoded_audio_sink.h"
|
||||
#include "ports/battery_status_provider.h"
|
||||
#include "ports/device_platform.h"
|
||||
#include "ports/device_profile_sink.h"
|
||||
#include "ports/event_publisher.h"
|
||||
#include "ports/local_sequence_handler.h"
|
||||
#include "ports/memory_cache.h"
|
||||
#include "ports/remote_behavior_config.h"
|
||||
#include "ports/realtime_protocol.h"
|
||||
#include "ports/sensor_message_sink.h"
|
||||
#include "ports/volume_status_provider.h"
|
||||
#include "protocol/protocol_message_builder.h"
|
||||
#include "protocol/binary_audio_protocol.h"
|
||||
#include "protocol/realtime_config.h"
|
||||
#include "protocol/server_message_dispatcher.h"
|
||||
#include "protocol/realtime_binary_sink.h"
|
||||
#include "protocol/websocket_transport.h"
|
||||
#include "schedule/schedule_types.h"
|
||||
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
#include <esp_timer.h>
|
||||
#include <freertos/FreeRTOS.h>
|
||||
#include <freertos/semphr.h>
|
||||
|
||||
namespace borla {
|
||||
|
||||
enum class RealtimeConnectionPhase : uint8_t {
|
||||
kClosed,
|
||||
kConnecting,
|
||||
kAwaitingHello,
|
||||
kOpen,
|
||||
kClosingAfterError,
|
||||
};
|
||||
|
||||
struct RealtimeDiagnostics {
|
||||
RealtimeConnectionPhase phase = RealtimeConnectionPhase::kClosed;
|
||||
uint32_t reconnect_attempt_count = 0;
|
||||
uint32_t invalid_message_count = 0;
|
||||
uint32_t unsupported_message_count = 0;
|
||||
uint32_t received_text_count = 0;
|
||||
uint32_t received_binary_count = 0;
|
||||
uint32_t sent_text_count = 0;
|
||||
uint32_t transport_error_count = 0;
|
||||
uint32_t active_tts_session = 0;
|
||||
uint32_t active_call_session = 0;
|
||||
uint64_t last_incoming_ms = 0;
|
||||
std::array<char, kRealtimeSessionIdCapacity> session_id{};
|
||||
};
|
||||
|
||||
class RealtimeProtocol final
|
||||
: public IRealtimeProtocol,
|
||||
public IEncodedAudioSink,
|
||||
public ISensorMessageSink,
|
||||
public IScheduleEventSink,
|
||||
public IWebsocketTransportObserver {
|
||||
public:
|
||||
RealtimeProtocol(
|
||||
IWebsocketTransport& transport,
|
||||
IRealtimeConfigStore& config_store);
|
||||
~RealtimeProtocol();
|
||||
|
||||
bool Initialize(const DeviceIdentity& identity);
|
||||
void SetEventPublisher(IEventPublisher* publisher)
|
||||
{
|
||||
publisher_ = publisher;
|
||||
}
|
||||
void SetBinarySink(IRealtimeBinarySink* sink) { binary_sink_ = sink; }
|
||||
void SetScheduleCommandHandler(IScheduleCommandHandler* handler)
|
||||
{
|
||||
schedule_handler_ = handler;
|
||||
}
|
||||
void SetBatteryStatusProvider(IBatteryStatusProvider* provider)
|
||||
{
|
||||
battery_ = provider;
|
||||
}
|
||||
void SetVolumeStatusProvider(IVolumeStatusProvider* provider)
|
||||
{
|
||||
volume_ = provider;
|
||||
}
|
||||
void SetDeviceProfileSink(IDeviceProfileSink* sink)
|
||||
{
|
||||
device_profile_sink_ = sink;
|
||||
}
|
||||
void SetLocalSequenceHandler(ILocalSequenceHandler* handler)
|
||||
{
|
||||
local_sequence_handler_ = handler;
|
||||
}
|
||||
void SetMemoryCache(IMemoryCache* cache)
|
||||
{
|
||||
memory_cache_ = cache;
|
||||
}
|
||||
void SetRemoteBehaviorConfig(IRemoteBehaviorConfig* config)
|
||||
{
|
||||
remote_behavior_config_ = config;
|
||||
}
|
||||
|
||||
void Open() override;
|
||||
void Close() override;
|
||||
void SendStartListening() override;
|
||||
void SendStopListening() override;
|
||||
void SendAbortSpeaking(
|
||||
ConversationInterruptSource source) override;
|
||||
void SendGoodbye() override;
|
||||
void SendAcceptCall() override;
|
||||
void SendHangupCall() override;
|
||||
void SendButtonClick(uint8_t click_count) override;
|
||||
void SendLocalPlaybackState(
|
||||
LocalPrompt prompt,
|
||||
bool started) override;
|
||||
bool SendFriendAdd(
|
||||
const char* local_mac,
|
||||
const char* local_name,
|
||||
const char* remote_mac,
|
||||
const char* remote_name) override;
|
||||
bool SendOtaNotify(
|
||||
const char* text,
|
||||
bool optional) override;
|
||||
void RequestConnectionErrorPrompt() override;
|
||||
bool SubmitEncodedAudio(
|
||||
const uint8_t* data,
|
||||
size_t size) override;
|
||||
void FlushEncodedAudio() override;
|
||||
bool SendSensorMessage(
|
||||
const char* data,
|
||||
size_t size) override;
|
||||
bool SendAlarmFired(
|
||||
int32_t alarm_id,
|
||||
int64_t fired_at_epoch) override;
|
||||
|
||||
RealtimeDiagnostics GetDiagnostics() const;
|
||||
uint32_t ActiveTtsSession() const;
|
||||
|
||||
void OnWebsocketConnected() override;
|
||||
void OnWebsocketDisconnected(int error_code) override;
|
||||
void OnWebsocketText(const char* data, size_t size) override;
|
||||
void OnWebsocketBinary(
|
||||
const uint8_t* data,
|
||||
size_t size) override;
|
||||
|
||||
private:
|
||||
static constexpr size_t kMessageCapacity =
|
||||
kBinaryAudioMaximumPacketBytes;
|
||||
static constexpr size_t kHeartbeatMessageCapacity = 128;
|
||||
// Status is built on the esp_timer task, whose stack is a few KB. Size the
|
||||
// buffer for the message (~150 bytes) instead of reusing the 2.5 KB
|
||||
// audio-packet capacity the other builders share.
|
||||
static constexpr size_t kStatusMessageCapacity = 256;
|
||||
static constexpr uint32_t kProtocolRetryMaximumMs = 30000;
|
||||
static constexpr uint32_t kStatusIntervalMs = 60000;
|
||||
static constexpr size_t kTraceMarkerCapacity = 256;
|
||||
static constexpr uint64_t kAudioTraceHeartbeatMs = 5000;
|
||||
static constexpr float kAudioTraceRelativeChange = 0.20F;
|
||||
static constexpr size_t kAudioTraceMinimumByteDelta = 160;
|
||||
|
||||
static void TimerCallback(void* context);
|
||||
void OnTimer();
|
||||
void HandleCommand(const ServerCommand& command);
|
||||
void HandleHello(const ServerCommand& command);
|
||||
void RequestErrorClose(uint32_t error_id);
|
||||
void ScheduleReconnectLocked(uint64_t now_ms);
|
||||
void Publish(const AppEvent& event);
|
||||
bool SendBuiltMessage(const char* data, size_t size);
|
||||
bool TakeAudioBatchLocked(size_t* packet_size);
|
||||
// One uplink batch leaves every 300 ms, and a marker per batch would be
|
||||
// pure noise. Emit one when the batch shape actually changes — first batch,
|
||||
// a different frame count, or a byte size that moved by both an absolute
|
||||
// and a relative margin — plus a slow heartbeat so a steady stream still
|
||||
// reports a clock sample. Same policy as the previous firmware.
|
||||
bool ShouldTraceAudioBatchLocked(
|
||||
uint64_t sequence,
|
||||
size_t frames,
|
||||
size_t bytes,
|
||||
uint64_t now_ms);
|
||||
void SendAudioBatchTrace(
|
||||
uint64_t sequence,
|
||||
size_t frames,
|
||||
size_t bytes,
|
||||
uint64_t client_send_ms);
|
||||
static int64_t EpochMs();
|
||||
bool UplinkEnabledLocked() const;
|
||||
uint32_t AllocateTtsSessionLocked();
|
||||
uint32_t AllocateCallSessionLocked();
|
||||
void ClearCallLocked();
|
||||
void SyncClock(const ServerCommand& command);
|
||||
void SendStatusSnapshot();
|
||||
uint64_t NowMs() const;
|
||||
|
||||
IWebsocketTransport& transport_;
|
||||
IRealtimeConfigStore& config_store_;
|
||||
IEventPublisher* publisher_ = nullptr;
|
||||
IRealtimeBinarySink* binary_sink_ = nullptr;
|
||||
IScheduleCommandHandler* schedule_handler_ = nullptr;
|
||||
IBatteryStatusProvider* battery_ = nullptr;
|
||||
IVolumeStatusProvider* volume_ = nullptr;
|
||||
IDeviceProfileSink* device_profile_sink_ = nullptr;
|
||||
ILocalSequenceHandler* local_sequence_handler_ = nullptr;
|
||||
IMemoryCache* memory_cache_ = nullptr;
|
||||
IRemoteBehaviorConfig* remote_behavior_config_ = nullptr;
|
||||
RealtimeConfig config_{};
|
||||
ServerMessageDispatcher dispatcher_;
|
||||
ServerCommand* incoming_command_ = nullptr;
|
||||
ProtocolMessageBuilder builder_;
|
||||
ReconnectBackoff reconnect_backoff_;
|
||||
|
||||
mutable StaticSemaphore_t mutex_storage_{};
|
||||
SemaphoreHandle_t mutex_ = nullptr;
|
||||
esp_timer_handle_t timer_ = nullptr;
|
||||
bool initialized_ = false;
|
||||
bool intentional_close_ = true;
|
||||
bool pending_open_ = false;
|
||||
bool disconnect_reported_ = false;
|
||||
RealtimeConnectionPhase phase_ = RealtimeConnectionPhase::kClosed;
|
||||
uint64_t hello_deadline_ms_ = 0;
|
||||
uint64_t reconnect_at_ms_ = 0;
|
||||
uint64_t last_incoming_ms_ = 0;
|
||||
uint64_t last_ping_ms_ = 0;
|
||||
uint64_t last_status_ms_ = 0;
|
||||
uint32_t next_tts_session_ = 1;
|
||||
uint32_t active_tts_session_ = 0;
|
||||
uint32_t next_call_session_ = 0x80000001U;
|
||||
uint32_t active_call_session_ = 0;
|
||||
std::array<char, kCallIdCapacity> active_call_id_{};
|
||||
// The sentence currently coming out of the speaker, reported to the server
|
||||
// on abort so it knows how much of its reply the child actually heard.
|
||||
// Only the leading bytes are kept — the abort builder caps the field anyway,
|
||||
// and holding a full sentence per connection is not worth the RAM.
|
||||
std::array<
|
||||
char,
|
||||
ProtocolMessageBuilder::kPlaybackTextBytes + 1>
|
||||
playback_text_{};
|
||||
uint64_t trace_audio_batch_sequence_ = 0;
|
||||
uint64_t last_trace_audio_batch_ms_ = 0;
|
||||
size_t last_trace_audio_batch_frames_ = 0;
|
||||
size_t last_trace_audio_batch_bytes_ = 0;
|
||||
bool listening_uplink_enabled_ = false;
|
||||
bool barge_in_enabled_ = false;
|
||||
bool tts_tail_uplink_enabled_ = false;
|
||||
bool call_uplink_enabled_ = false;
|
||||
BinaryAudioBatchBuilder audio_batch_;
|
||||
std::array<
|
||||
uint8_t,
|
||||
kBinaryAudioMaximumPacketBytes>
|
||||
audio_packet_{};
|
||||
RealtimeDiagnostics diagnostics_{};
|
||||
};
|
||||
|
||||
} // namespace borla
|
||||
944
main/protocol/server_message_dispatcher.cc
Normal file
944
main/protocol/server_message_dispatcher.cc
Normal file
@@ -0,0 +1,944 @@
|
||||
#include "protocol/server_message_dispatcher.h"
|
||||
|
||||
#include "connectivity/wifi_types.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <climits>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <new>
|
||||
|
||||
#include <cJSON.h>
|
||||
|
||||
namespace borla {
|
||||
namespace {
|
||||
|
||||
constexpr uint32_t kMalformedJsonError = 3101;
|
||||
constexpr uint32_t kInvalidMessageError = 3102;
|
||||
constexpr uint32_t kInvalidHelloError = 3103;
|
||||
constexpr uint32_t kServerReportedError = 3104;
|
||||
|
||||
void ResetCommand(
|
||||
ServerCommand* output,
|
||||
ServerCommandType type)
|
||||
{
|
||||
output->~ServerCommand();
|
||||
new (output) ServerCommand();
|
||||
output->type = type;
|
||||
}
|
||||
|
||||
void SetInvalid(ServerCommand* output, uint32_t error_id)
|
||||
{
|
||||
ResetCommand(output, ServerCommandType::kInvalid);
|
||||
output->error_id = error_id;
|
||||
}
|
||||
|
||||
const char* StringField(const cJSON* root, const char* name)
|
||||
{
|
||||
const cJSON* item =
|
||||
cJSON_GetObjectItemCaseSensitive(root, name);
|
||||
return cJSON_IsString(item) ? item->valuestring : nullptr;
|
||||
}
|
||||
|
||||
bool IntegerField(
|
||||
const cJSON* root,
|
||||
const char* name,
|
||||
int64_t minimum,
|
||||
int64_t maximum,
|
||||
int64_t* value)
|
||||
{
|
||||
const cJSON* item =
|
||||
cJSON_GetObjectItemCaseSensitive(root, name);
|
||||
if (!cJSON_IsNumber(item) || !std::isfinite(item->valuedouble) ||
|
||||
std::floor(item->valuedouble) != item->valuedouble ||
|
||||
item->valuedouble < static_cast<double>(minimum) ||
|
||||
item->valuedouble > static_cast<double>(maximum)) {
|
||||
return false;
|
||||
}
|
||||
*value = static_cast<int64_t>(item->valuedouble);
|
||||
return true;
|
||||
}
|
||||
|
||||
template <size_t Capacity>
|
||||
bool CopyOptionalString(
|
||||
const cJSON* root,
|
||||
const char* name,
|
||||
std::array<char, Capacity>* output)
|
||||
{
|
||||
if (output == nullptr) {
|
||||
return false;
|
||||
}
|
||||
const char* value = StringField(root, name);
|
||||
if (value == nullptr) {
|
||||
output->fill('\0');
|
||||
return true;
|
||||
}
|
||||
const size_t size = BoundedStringLength(value, Capacity);
|
||||
if (size >= Capacity) {
|
||||
return false;
|
||||
}
|
||||
output->fill('\0');
|
||||
std::memcpy(output->data(), value, size);
|
||||
return true;
|
||||
}
|
||||
|
||||
template <size_t Capacity>
|
||||
bool CopyRequiredString(
|
||||
const cJSON* root,
|
||||
const char* name,
|
||||
std::array<char, Capacity>* output)
|
||||
{
|
||||
if (output == nullptr) {
|
||||
return false;
|
||||
}
|
||||
const char* value = StringField(root, name);
|
||||
const size_t size = BoundedStringLength(value, Capacity);
|
||||
if (size == 0 || size >= Capacity) {
|
||||
return false;
|
||||
}
|
||||
output->fill('\0');
|
||||
std::memcpy(output->data(), value, size);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ParseAlarmObject(const cJSON* object, AlarmEntry* alarm)
|
||||
{
|
||||
if (!cJSON_IsObject(object) || alarm == nullptr) {
|
||||
return false;
|
||||
}
|
||||
int64_t id = 0;
|
||||
int64_t hour = 0;
|
||||
int64_t minute = 0;
|
||||
int64_t repeat_mask = 0;
|
||||
if (!IntegerField(object, "id", INT32_MIN, INT32_MAX, &id) ||
|
||||
id == 0 || id == kBuiltInFirstDayAlarmId ||
|
||||
!IntegerField(object, "hour", 0, 23, &hour) ||
|
||||
!IntegerField(object, "minute", 0, 59, &minute) ||
|
||||
!IntegerField(object, "repeat_mask", 0, 0x7F, &repeat_mask)) {
|
||||
return false;
|
||||
}
|
||||
int64_t fire_epoch = 0;
|
||||
const cJSON* fire =
|
||||
cJSON_GetObjectItemCaseSensitive(object, "fire_epoch");
|
||||
if (fire != nullptr &&
|
||||
!IntegerField(object, "fire_epoch", 0, INT64_MAX, &fire_epoch)) {
|
||||
return false;
|
||||
}
|
||||
const cJSON* enabled =
|
||||
cJSON_GetObjectItemCaseSensitive(object, "enabled");
|
||||
if (enabled != nullptr && !cJSON_IsBool(enabled)) {
|
||||
return false;
|
||||
}
|
||||
const char* label = StringField(object, "label");
|
||||
if (label != nullptr &&
|
||||
std::strlen(label) >= kAlarmLabelCapacity) {
|
||||
return false;
|
||||
}
|
||||
AlarmEntry parsed;
|
||||
parsed.id = static_cast<int32_t>(id);
|
||||
parsed.hour = static_cast<uint8_t>(hour);
|
||||
parsed.minute = static_cast<uint8_t>(minute);
|
||||
parsed.repeat_mask = static_cast<uint8_t>(repeat_mask);
|
||||
parsed.fire_epoch = fire_epoch;
|
||||
parsed.enabled = enabled == nullptr || cJSON_IsTrue(enabled);
|
||||
if (label != nullptr) {
|
||||
std::memcpy(parsed.label.data(), label, std::strlen(label));
|
||||
}
|
||||
*alarm = parsed;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool LookupPrompt(
|
||||
const char* group,
|
||||
LocalPrompt* prompt,
|
||||
PlaybackPriority* priority)
|
||||
{
|
||||
if (group == nullptr || prompt == nullptr || priority == nullptr) {
|
||||
return false;
|
||||
}
|
||||
|
||||
struct PromptMapping {
|
||||
const char* group;
|
||||
LocalPrompt prompt;
|
||||
PlaybackPriority priority;
|
||||
};
|
||||
static constexpr PromptMapping kMappings[] = {
|
||||
{"activation_device", LocalPrompt::kActivationDevice,
|
||||
PlaybackPriority::kLocalPrompt},
|
||||
{"activation_prompt", LocalPrompt::kActivationDevice,
|
||||
PlaybackPriority::kLocalPrompt},
|
||||
{"device_already_bound", LocalPrompt::kDeviceAlreadyBound,
|
||||
PlaybackPriority::kLocalPrompt},
|
||||
{"server_error", LocalPrompt::kServerError,
|
||||
PlaybackPriority::kSystem},
|
||||
{"alarm_wake", LocalPrompt::kAlarmWake,
|
||||
PlaybackPriority::kAlarm},
|
||||
{"alarm_set", LocalPrompt::kAlarmSet,
|
||||
PlaybackPriority::kSystem},
|
||||
{"no_network", LocalPrompt::kNoNetwork,
|
||||
PlaybackPriority::kSystem},
|
||||
{"wifi_config", LocalPrompt::kProvisioning,
|
||||
PlaybackPriority::kSystem},
|
||||
{"wake_response", LocalPrompt::kWakeResponse,
|
||||
PlaybackPriority::kLocalPrompt},
|
||||
{"story_expired", LocalPrompt::kStoryExpired,
|
||||
PlaybackPriority::kLocalPrompt},
|
||||
{"idle_check", LocalPrompt::kIdleCheck,
|
||||
PlaybackPriority::kLocalPrompt},
|
||||
{"idle_goodbye", LocalPrompt::kIdleGoodbye,
|
||||
PlaybackPriority::kLocalPrompt},
|
||||
{"snore_light", LocalPrompt::kSnoreLight,
|
||||
PlaybackPriority::kLocalPrompt},
|
||||
{"wifi_success", LocalPrompt::kWifiSuccess,
|
||||
PlaybackPriority::kSystem},
|
||||
{"welcome", LocalPrompt::kWelcome,
|
||||
PlaybackPriority::kLocalPrompt},
|
||||
{"shutdown", LocalPrompt::kShutdown,
|
||||
PlaybackPriority::kSystem},
|
||||
{"boot", LocalPrompt::kBoot,
|
||||
PlaybackPriority::kSystem},
|
||||
{"error", LocalPrompt::kError,
|
||||
PlaybackPriority::kSystem},
|
||||
{"low_battery_20", LocalPrompt::kLowBattery20,
|
||||
PlaybackPriority::kSystem},
|
||||
{"low_battery_10", LocalPrompt::kLowBattery10,
|
||||
PlaybackPriority::kSystem},
|
||||
{"net4g_boot_on", LocalPrompt::kNet4gBootOn,
|
||||
PlaybackPriority::kSystem},
|
||||
{"net4g_off", LocalPrompt::kNet4gOff,
|
||||
PlaybackPriority::kSystem},
|
||||
{"net4g_on", LocalPrompt::kNet4gOn,
|
||||
PlaybackPriority::kSystem},
|
||||
{"net4g_no_wifi", LocalPrompt::kNet4gNoWifi,
|
||||
PlaybackPriority::kSystem},
|
||||
{"digit_0", LocalPrompt::kDigit0,
|
||||
PlaybackPriority::kLocalPrompt},
|
||||
{"digit_1", LocalPrompt::kDigit1,
|
||||
PlaybackPriority::kLocalPrompt},
|
||||
{"digit_2", LocalPrompt::kDigit2,
|
||||
PlaybackPriority::kLocalPrompt},
|
||||
{"digit_3", LocalPrompt::kDigit3,
|
||||
PlaybackPriority::kLocalPrompt},
|
||||
{"digit_4", LocalPrompt::kDigit4,
|
||||
PlaybackPriority::kLocalPrompt},
|
||||
{"digit_5", LocalPrompt::kDigit5,
|
||||
PlaybackPriority::kLocalPrompt},
|
||||
{"digit_6", LocalPrompt::kDigit6,
|
||||
PlaybackPriority::kLocalPrompt},
|
||||
{"digit_7", LocalPrompt::kDigit7,
|
||||
PlaybackPriority::kLocalPrompt},
|
||||
{"digit_8", LocalPrompt::kDigit8,
|
||||
PlaybackPriority::kLocalPrompt},
|
||||
{"digit_9", LocalPrompt::kDigit9,
|
||||
PlaybackPriority::kLocalPrompt},
|
||||
};
|
||||
|
||||
for (const PromptMapping& mapping : kMappings) {
|
||||
if (std::strcmp(group, mapping.group) == 0) {
|
||||
*prompt = mapping.prompt;
|
||||
*priority = mapping.priority;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool ServerMessageDispatcher::ParseInto(
|
||||
const char* json,
|
||||
size_t size,
|
||||
ServerCommand* output) const
|
||||
{
|
||||
if (output == nullptr) {
|
||||
return false;
|
||||
}
|
||||
if (json == nullptr || size == 0) {
|
||||
SetInvalid(output, kMalformedJsonError);
|
||||
return true;
|
||||
}
|
||||
cJSON* root = cJSON_ParseWithLength(json, size);
|
||||
if (!cJSON_IsObject(root)) {
|
||||
cJSON_Delete(root);
|
||||
SetInvalid(output, kMalformedJsonError);
|
||||
return true;
|
||||
}
|
||||
|
||||
const char* type = StringField(root, "type");
|
||||
if (type == nullptr) {
|
||||
SetInvalid(output, kInvalidMessageError);
|
||||
} else if (std::strcmp(type, "hello") == 0) {
|
||||
ParseHello(root, output);
|
||||
} else if (std::strcmp(type, "ping") == 0) {
|
||||
ResetCommand(output, ServerCommandType::kPing);
|
||||
} else if (std::strcmp(type, "pong") == 0) {
|
||||
ResetCommand(output, ServerCommandType::kPong);
|
||||
} else if (std::strcmp(type, "stt") == 0) {
|
||||
ParseStt(root, output);
|
||||
} else if (std::strcmp(type, "llm") == 0) {
|
||||
ParseLlm(root, output);
|
||||
} else if (std::strcmp(type, "tts") == 0) {
|
||||
ParseTts(root, output);
|
||||
} else if (std::strcmp(type, "barge_in") == 0) {
|
||||
ParseBargeIn(root, output);
|
||||
} else if (std::strcmp(type, "control") == 0) {
|
||||
ParseControl(root, output);
|
||||
} else if (std::strcmp(type, "play_local") == 0) {
|
||||
ParsePlayLocal(root, output);
|
||||
} else if (std::strcmp(type, "play_local_sequence") == 0) {
|
||||
ParsePlayLocalSequence(root, output);
|
||||
} else if (std::strcmp(type, "memory_sync") == 0) {
|
||||
ParseMemorySync(root, output);
|
||||
} else if (std::strcmp(type, "set_timer") == 0) {
|
||||
ParseSetTimer(root, output);
|
||||
} else if (std::strcmp(type, "cancel_timer") == 0) {
|
||||
ParseCancelTimer(root, output);
|
||||
} else if (std::strcmp(type, "set_alarm") == 0) {
|
||||
ParseSetAlarm(root, output);
|
||||
} else if (std::strcmp(type, "delete_alarm") == 0) {
|
||||
ParseDeleteAlarm(root, output);
|
||||
} else if (std::strcmp(type, "sync_alarms") == 0) {
|
||||
ParseSyncAlarms(root, output);
|
||||
} else if (std::strcmp(type, "alarm_config") == 0) {
|
||||
ParseAlarmConfig(root, output);
|
||||
} else if (std::strcmp(type, "call") == 0) {
|
||||
ParseCall(root, output);
|
||||
} else if (std::strcmp(type, "wifi_config") == 0) {
|
||||
ResetCommand(output, ServerCommandType::kEnterProvisioning);
|
||||
} else if (std::strcmp(type, "error") == 0) {
|
||||
ResetCommand(output, ServerCommandType::kError);
|
||||
output->error_id = kServerReportedError;
|
||||
const cJSON* code =
|
||||
cJSON_GetObjectItemCaseSensitive(root, "code");
|
||||
if (cJSON_IsNumber(code) && code->valuedouble > 0) {
|
||||
output->error_id =
|
||||
static_cast<uint32_t>(code->valuedouble);
|
||||
}
|
||||
} else {
|
||||
ResetCommand(output, ServerCommandType::kUnsupported);
|
||||
}
|
||||
|
||||
cJSON_Delete(root);
|
||||
return true;
|
||||
}
|
||||
|
||||
void ServerMessageDispatcher::ParseBargeIn(
|
||||
const void* opaque_root,
|
||||
ServerCommand* output) const
|
||||
{
|
||||
const auto* root = static_cast<const cJSON*>(opaque_root);
|
||||
const char* state = StringField(root, "state");
|
||||
if (state == nullptr) {
|
||||
SetInvalid(output, kInvalidMessageError);
|
||||
return;
|
||||
}
|
||||
ResetCommand(output, ServerCommandType::kBargeIn);
|
||||
if (std::strcmp(state, "candidate") == 0) {
|
||||
output->barge_in_state = BargeInDecisionState::kCandidate;
|
||||
} else if (std::strcmp(state, "rejected") == 0) {
|
||||
output->barge_in_state = BargeInDecisionState::kRejected;
|
||||
} else if (std::strcmp(state, "confirmed") == 0) {
|
||||
output->barge_in_state = BargeInDecisionState::kConfirmed;
|
||||
} else {
|
||||
SetInvalid(output, kInvalidMessageError);
|
||||
}
|
||||
}
|
||||
|
||||
void ServerMessageDispatcher::ParseControl(
|
||||
const void* opaque_root,
|
||||
ServerCommand* output) const
|
||||
{
|
||||
const auto* root = static_cast<const cJSON*>(opaque_root);
|
||||
const char* action = StringField(root, "action");
|
||||
if (action == nullptr) {
|
||||
SetInvalid(output, kInvalidMessageError);
|
||||
return;
|
||||
}
|
||||
ResetCommand(output, ServerCommandType::kControl);
|
||||
ServerCommand& command = *output;
|
||||
if (std::strcmp(action, "volume") == 0) {
|
||||
int64_t volume = 0;
|
||||
if (!IntegerField(root, "volume", INT_MIN, INT_MAX, &volume)) {
|
||||
SetInvalid(output, kInvalidMessageError);
|
||||
return;
|
||||
}
|
||||
command.control_action = RemoteControlAction::kVolume;
|
||||
command.control_value = static_cast<int32_t>(
|
||||
std::clamp<int64_t>(volume, 0, 100));
|
||||
return;
|
||||
}
|
||||
if (std::strcmp(action, "wake_word") == 0 ||
|
||||
std::strcmp(action, "barge_in") == 0) {
|
||||
const cJSON* enabled =
|
||||
cJSON_GetObjectItemCaseSensitive(root, "enabled");
|
||||
if (!cJSON_IsBool(enabled)) {
|
||||
SetInvalid(output, kInvalidMessageError);
|
||||
return;
|
||||
}
|
||||
command.control_action =
|
||||
std::strcmp(action, "wake_word") == 0
|
||||
? RemoteControlAction::kWakeWord
|
||||
: RemoteControlAction::kBargeIn;
|
||||
command.control_value = cJSON_IsTrue(enabled) ? 1 : 0;
|
||||
return;
|
||||
}
|
||||
if (std::strcmp(action, "light_sleep") == 0) {
|
||||
const char* mode = StringField(root, "mode");
|
||||
if (mode != nullptr && std::strcmp(mode, "idle_sleep") != 0) {
|
||||
SetInvalid(output, kInvalidMessageError);
|
||||
return;
|
||||
}
|
||||
command.control_action = RemoteControlAction::kLightSleep;
|
||||
return;
|
||||
}
|
||||
if (std::strcmp(action, "led") == 0) {
|
||||
const char* state = StringField(root, "state");
|
||||
const char* color = StringField(root, "color");
|
||||
int64_t duration_ms = 0;
|
||||
if (state == nullptr || color == nullptr ||
|
||||
std::strcmp(state, "alert") != 0 ||
|
||||
std::strcmp(color, "red") != 0 ||
|
||||
!IntegerField(
|
||||
root,
|
||||
"duration_ms",
|
||||
INT_MIN,
|
||||
INT_MAX,
|
||||
&duration_ms)) {
|
||||
SetInvalid(output, kInvalidMessageError);
|
||||
return;
|
||||
}
|
||||
command.control_action = RemoteControlAction::kLedAlert;
|
||||
command.control_value = static_cast<int32_t>(
|
||||
std::clamp<int64_t>(duration_ms, 100, 60000));
|
||||
return;
|
||||
}
|
||||
ResetCommand(output, ServerCommandType::kUnsupported);
|
||||
}
|
||||
|
||||
void ServerMessageDispatcher::ParseCall(
|
||||
const void* opaque_root,
|
||||
ServerCommand* output) const
|
||||
{
|
||||
const auto* root = static_cast<const cJSON*>(opaque_root);
|
||||
const char* state = StringField(root, "state");
|
||||
const char* call_id = StringField(root, "call_id");
|
||||
const size_t call_id_size =
|
||||
BoundedStringLength(call_id, kCallIdCapacity);
|
||||
if (state == nullptr || call_id_size == 0 ||
|
||||
call_id_size >= kCallIdCapacity) {
|
||||
SetInvalid(output, kInvalidMessageError);
|
||||
return;
|
||||
}
|
||||
|
||||
ResetCommand(output, ServerCommandType::kCall);
|
||||
ServerCommand& command = *output;
|
||||
if (std::strcmp(state, "ring") == 0) {
|
||||
command.call_state = CallSignalState::kRing;
|
||||
} else if (std::strcmp(state, "invite") == 0) {
|
||||
command.call_state = CallSignalState::kInvite;
|
||||
} else if (std::strcmp(state, "connected") == 0) {
|
||||
command.call_state = CallSignalState::kConnected;
|
||||
} else if (std::strcmp(state, "ended") == 0) {
|
||||
command.call_state = CallSignalState::kEnded;
|
||||
} else if (std::strcmp(state, "missed") == 0) {
|
||||
command.call_state = CallSignalState::kMissed;
|
||||
} else {
|
||||
SetInvalid(output, kInvalidMessageError);
|
||||
return;
|
||||
}
|
||||
|
||||
std::memcpy(command.call_id.data(), call_id, call_id_size);
|
||||
const char* peer_field = "peer_name";
|
||||
if (command.call_state == CallSignalState::kRing) {
|
||||
peer_field = "target_name";
|
||||
} else if (command.call_state == CallSignalState::kInvite) {
|
||||
peer_field = "caller_name";
|
||||
}
|
||||
if (!CopyOptionalString(root, peer_field, &command.peer_name)) {
|
||||
SetInvalid(output, kInvalidMessageError);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
void ServerMessageDispatcher::ParseSetTimer(
|
||||
const void* opaque_root,
|
||||
ServerCommand* output) const
|
||||
{
|
||||
const auto* root = static_cast<const cJSON*>(opaque_root);
|
||||
int64_t duration = 0;
|
||||
if (!IntegerField(root, "duration", 1, 604800, &duration)) {
|
||||
SetInvalid(output, kInvalidMessageError);
|
||||
return;
|
||||
}
|
||||
ResetCommand(output, ServerCommandType::kSetTimer);
|
||||
output->duration_seconds = static_cast<uint32_t>(duration);
|
||||
}
|
||||
|
||||
void ServerMessageDispatcher::ParseCancelTimer(
|
||||
const void* opaque_root,
|
||||
ServerCommand* output) const
|
||||
{
|
||||
const auto* root = static_cast<const cJSON*>(opaque_root);
|
||||
const char* scope = StringField(root, "scope");
|
||||
ResetCommand(output, ServerCommandType::kCancelTimer);
|
||||
if (scope == nullptr || std::strcmp(scope, "recent") == 0) {
|
||||
output->timer_cancel_scope = TimerCancelScope::kNext;
|
||||
} else if (std::strcmp(scope, "all") == 0) {
|
||||
output->timer_cancel_scope = TimerCancelScope::kAll;
|
||||
} else {
|
||||
SetInvalid(output, kInvalidMessageError);
|
||||
}
|
||||
}
|
||||
|
||||
void ServerMessageDispatcher::ParseSetAlarm(
|
||||
const void* opaque_root,
|
||||
ServerCommand* output) const
|
||||
{
|
||||
const auto* root = static_cast<const cJSON*>(opaque_root);
|
||||
const cJSON* item =
|
||||
cJSON_GetObjectItemCaseSensitive(root, "alarm");
|
||||
ResetCommand(output, ServerCommandType::kSetAlarm);
|
||||
if (!ParseAlarmObject(item, &output->alarm)) {
|
||||
SetInvalid(output, kInvalidMessageError);
|
||||
}
|
||||
}
|
||||
|
||||
void ServerMessageDispatcher::ParseDeleteAlarm(
|
||||
const void* opaque_root,
|
||||
ServerCommand* output) const
|
||||
{
|
||||
const auto* root = static_cast<const cJSON*>(opaque_root);
|
||||
int64_t id = 0;
|
||||
if (!IntegerField(root, "id", INT32_MIN, INT32_MAX, &id) ||
|
||||
(id <= 0 && id != kBuiltInFirstDayAlarmId)) {
|
||||
SetInvalid(output, kInvalidMessageError);
|
||||
return;
|
||||
}
|
||||
ResetCommand(output, ServerCommandType::kDeleteAlarm);
|
||||
output->alarm_id = static_cast<int32_t>(id);
|
||||
}
|
||||
|
||||
void ServerMessageDispatcher::ParseSyncAlarms(
|
||||
const void* opaque_root,
|
||||
ServerCommand* output) const
|
||||
{
|
||||
const auto* root = static_cast<const cJSON*>(opaque_root);
|
||||
const cJSON* alarms =
|
||||
cJSON_GetObjectItemCaseSensitive(root, "alarms");
|
||||
if (!cJSON_IsArray(alarms) ||
|
||||
cJSON_GetArraySize(alarms) >
|
||||
static_cast<int>(kMaximumAlarmCount)) {
|
||||
SetInvalid(output, kInvalidMessageError);
|
||||
return;
|
||||
}
|
||||
ResetCommand(output, ServerCommandType::kSyncAlarms);
|
||||
cJSON* item = nullptr;
|
||||
cJSON_ArrayForEach(item, alarms) {
|
||||
if (!ParseAlarmObject(
|
||||
item,
|
||||
&output->alarms.entries[output->alarms.count])) {
|
||||
SetInvalid(output, kInvalidMessageError);
|
||||
return;
|
||||
}
|
||||
output->alarms.count++;
|
||||
}
|
||||
}
|
||||
|
||||
void ServerMessageDispatcher::ParseAlarmConfig(
|
||||
const void* opaque_root,
|
||||
ServerCommand* output) const
|
||||
{
|
||||
const auto* root = static_cast<const cJSON*>(opaque_root);
|
||||
int64_t set_index = 0;
|
||||
int64_t wake_index = 0;
|
||||
if (!IntegerField(root, "set_tone_index", -1, 15, &set_index) ||
|
||||
!IntegerField(root, "wake_tone_index", -1, 15, &wake_index)) {
|
||||
SetInvalid(output, kInvalidMessageError);
|
||||
return;
|
||||
}
|
||||
ResetCommand(output, ServerCommandType::kAlarmConfig);
|
||||
output->set_tone_index = static_cast<int8_t>(set_index);
|
||||
output->wake_tone_index = static_cast<int8_t>(wake_index);
|
||||
}
|
||||
|
||||
void ServerMessageDispatcher::ParseHello(
|
||||
const void* opaque_root,
|
||||
ServerCommand* output) const
|
||||
{
|
||||
const auto* root = static_cast<const cJSON*>(opaque_root);
|
||||
const char* session_id = StringField(root, "session_id");
|
||||
const char* transport = StringField(root, "transport");
|
||||
const cJSON* version =
|
||||
cJSON_GetObjectItemCaseSensitive(root, "version");
|
||||
const cJSON* audio =
|
||||
cJSON_GetObjectItemCaseSensitive(root, "audio_params");
|
||||
const cJSON* sample_rate =
|
||||
cJSON_GetObjectItemCaseSensitive(audio, "sample_rate");
|
||||
const cJSON* channels =
|
||||
cJSON_GetObjectItemCaseSensitive(audio, "channels");
|
||||
const cJSON* frame_duration =
|
||||
cJSON_GetObjectItemCaseSensitive(audio, "frame_duration");
|
||||
const char* format = StringField(audio, "format");
|
||||
|
||||
const size_t session_length =
|
||||
BoundedStringLength(session_id, kRealtimeSessionIdCapacity);
|
||||
const bool valid_version =
|
||||
!cJSON_IsNumber(version) || version->valueint == 3;
|
||||
const bool valid_transport =
|
||||
transport == nullptr || std::strcmp(transport, "websocket") == 0;
|
||||
const bool valid_audio =
|
||||
cJSON_IsObject(audio) &&
|
||||
cJSON_IsNumber(sample_rate) &&
|
||||
sample_rate->valueint == 24000 &&
|
||||
(!cJSON_IsNumber(channels) || channels->valueint == 1) &&
|
||||
cJSON_IsNumber(frame_duration) &&
|
||||
frame_duration->valueint == 60 &&
|
||||
(format == nullptr || std::strcmp(format, "opus") == 0);
|
||||
|
||||
if (session_length == 0 ||
|
||||
session_length >= kRealtimeSessionIdCapacity ||
|
||||
!valid_version || !valid_transport || !valid_audio) {
|
||||
SetInvalid(output, kInvalidHelloError);
|
||||
return;
|
||||
}
|
||||
|
||||
ResetCommand(output, ServerCommandType::kHello);
|
||||
ServerCommand& command = *output;
|
||||
std::memcpy(
|
||||
command.session_id.data(), session_id, session_length);
|
||||
command.output_sample_rate =
|
||||
static_cast<uint32_t>(sample_rate->valueint);
|
||||
command.frame_duration_ms =
|
||||
static_cast<uint16_t>(frame_duration->valueint);
|
||||
|
||||
const cJSON* server_time =
|
||||
cJSON_GetObjectItemCaseSensitive(root, "server_time");
|
||||
const cJSON* timezone =
|
||||
cJSON_GetObjectItemCaseSensitive(root, "tz_offset");
|
||||
if (cJSON_IsNumber(server_time)) {
|
||||
command.server_time_seconds =
|
||||
static_cast<int64_t>(server_time->valuedouble);
|
||||
}
|
||||
if (cJSON_IsNumber(timezone)) {
|
||||
command.timezone_offset_seconds = timezone->valueint;
|
||||
}
|
||||
if (!CopyOptionalString(root, "device_name", &command.device_name)) {
|
||||
SetInvalid(output, kInvalidHelloError);
|
||||
return;
|
||||
}
|
||||
|
||||
const cJSON* button_map =
|
||||
cJSON_GetObjectItemCaseSensitive(root, "button_map");
|
||||
if (cJSON_IsObject(button_map)) {
|
||||
const cJSON* triple =
|
||||
cJSON_GetObjectItemCaseSensitive(button_map, "3");
|
||||
const cJSON* quadruple =
|
||||
cJSON_GetObjectItemCaseSensitive(button_map, "4");
|
||||
if (cJSON_IsString(triple)) {
|
||||
ParseButtonAction(
|
||||
triple->valuestring,
|
||||
&command.triple_click_action);
|
||||
}
|
||||
if (cJSON_IsString(quadruple)) {
|
||||
ParseButtonAction(
|
||||
quadruple->valuestring,
|
||||
&command.quadruple_click_action);
|
||||
}
|
||||
}
|
||||
|
||||
const cJSON* prompts = cJSON_GetObjectItemCaseSensitive(
|
||||
root, "connection_error_prompts");
|
||||
if (cJSON_IsObject(prompts)) {
|
||||
const cJSON* server = cJSON_GetObjectItemCaseSensitive(
|
||||
prompts, "server_unreachable");
|
||||
const cJSON* network = cJSON_GetObjectItemCaseSensitive(
|
||||
prompts, "no_network");
|
||||
if (cJSON_IsString(server)) {
|
||||
command.has_server_unreachable_prompt =
|
||||
ParseConnectionPrompt(
|
||||
server->valuestring,
|
||||
&command.server_unreachable_prompt);
|
||||
}
|
||||
if (cJSON_IsString(network)) {
|
||||
command.has_no_network_prompt =
|
||||
ParseConnectionPrompt(
|
||||
network->valuestring,
|
||||
&command.no_network_prompt);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ServerMessageDispatcher::ParseTts(
|
||||
const void* opaque_root,
|
||||
ServerCommand* output) const
|
||||
{
|
||||
const auto* root = static_cast<const cJSON*>(opaque_root);
|
||||
const char* state = StringField(root, "state");
|
||||
if (state == nullptr) {
|
||||
SetInvalid(output, kInvalidMessageError);
|
||||
return;
|
||||
}
|
||||
if (std::strcmp(state, "start") == 0) {
|
||||
ResetCommand(output, ServerCommandType::kTtsStart);
|
||||
return;
|
||||
}
|
||||
if (std::strcmp(state, "stop") == 0) {
|
||||
ResetCommand(output, ServerCommandType::kTtsStop);
|
||||
return;
|
||||
}
|
||||
if (std::strcmp(state, "sentence_start") == 0) {
|
||||
ResetCommand(output, ServerCommandType::kTtsSentenceStart);
|
||||
if (!CopyRequiredString(
|
||||
root,
|
||||
"text",
|
||||
&output->conversation_text)) {
|
||||
SetInvalid(output, kInvalidMessageError);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (std::strcmp(state, "sentence_end") == 0) {
|
||||
ResetCommand(output, ServerCommandType::kTtsSentenceEnd);
|
||||
return;
|
||||
}
|
||||
ResetCommand(output, ServerCommandType::kUnsupported);
|
||||
}
|
||||
|
||||
void ServerMessageDispatcher::ParseStt(
|
||||
const void* opaque_root,
|
||||
ServerCommand* output) const
|
||||
{
|
||||
const auto* root = static_cast<const cJSON*>(opaque_root);
|
||||
ResetCommand(output, ServerCommandType::kSttText);
|
||||
if (!CopyRequiredString(
|
||||
root,
|
||||
"text",
|
||||
&output->conversation_text)) {
|
||||
SetInvalid(output, kInvalidMessageError);
|
||||
}
|
||||
}
|
||||
|
||||
void ServerMessageDispatcher::ParseLlm(
|
||||
const void* opaque_root,
|
||||
ServerCommand* output) const
|
||||
{
|
||||
const auto* root = static_cast<const cJSON*>(opaque_root);
|
||||
ResetCommand(output, ServerCommandType::kLlmEmotion);
|
||||
// The emotion string is advisory only: firmware logs it so the device-side
|
||||
// trace lines up with the server dialogue log. An llm frame without a
|
||||
// usable emotion is still a well-formed frame, not an error.
|
||||
if (!CopyOptionalString(
|
||||
root, "emotion", &output->conversation_text)) {
|
||||
output->conversation_text.fill('\0');
|
||||
}
|
||||
}
|
||||
|
||||
void ServerMessageDispatcher::ParsePlayLocal(
|
||||
const void* opaque_root,
|
||||
ServerCommand* output) const
|
||||
{
|
||||
const auto* root = static_cast<const cJSON*>(opaque_root);
|
||||
const char* group = StringField(root, "group");
|
||||
ResetCommand(output, ServerCommandType::kPlayLocal);
|
||||
ServerCommand& command = *output;
|
||||
if (!LookupPrompt(
|
||||
group,
|
||||
&command.local_prompt,
|
||||
&command.playback_priority)) {
|
||||
ResetCommand(output, ServerCommandType::kUnsupported);
|
||||
return;
|
||||
}
|
||||
|
||||
const cJSON* index =
|
||||
cJSON_GetObjectItemCaseSensitive(root, "index");
|
||||
if (cJSON_IsNumber(index) &&
|
||||
index->valueint >= 0 &&
|
||||
index->valueint <= INT16_MAX) {
|
||||
command.prompt_index =
|
||||
static_cast<int16_t>(index->valueint);
|
||||
}
|
||||
|
||||
const char* post_action = StringField(root, "post_action");
|
||||
const cJSON* block_reconnect =
|
||||
cJSON_GetObjectItemCaseSensitive(root, "block_reconnect");
|
||||
const bool has_new_fields =
|
||||
post_action != nullptr || cJSON_IsBool(block_reconnect);
|
||||
command.soft_off_after_playback =
|
||||
(post_action != nullptr &&
|
||||
std::strcmp(post_action, "enter_soft_off") == 0) ||
|
||||
(!has_new_fields &&
|
||||
command.local_prompt == LocalPrompt::kShutdown) ||
|
||||
(command.local_prompt == LocalPrompt::kShutdown &&
|
||||
cJSON_IsTrue(block_reconnect));
|
||||
}
|
||||
|
||||
void ServerMessageDispatcher::ParsePlayLocalSequence(
|
||||
const void* opaque_root,
|
||||
ServerCommand* output) const
|
||||
{
|
||||
const auto* root = static_cast<const cJSON*>(opaque_root);
|
||||
const cJSON* sequence =
|
||||
cJSON_GetObjectItemCaseSensitive(root, "sequence");
|
||||
if (!cJSON_IsArray(sequence) ||
|
||||
cJSON_GetArraySize(sequence) >
|
||||
static_cast<int>(kMaxLocalPromptSequenceItems)) {
|
||||
SetInvalid(output, kInvalidMessageError);
|
||||
return;
|
||||
}
|
||||
|
||||
ResetCommand(output, ServerCommandType::kPlayLocalSequence);
|
||||
ServerCommand& command = *output;
|
||||
const cJSON* item = nullptr;
|
||||
cJSON_ArrayForEach(item, sequence) {
|
||||
if (!cJSON_IsObject(item)) {
|
||||
continue;
|
||||
}
|
||||
LocalPrompt prompt = LocalPrompt::kError;
|
||||
PlaybackPriority priority = PlaybackPriority::kLocalPrompt;
|
||||
if (!LookupPrompt(
|
||||
StringField(item, "group"),
|
||||
&prompt,
|
||||
&priority)) {
|
||||
continue;
|
||||
}
|
||||
int16_t selector = -1;
|
||||
const cJSON* index =
|
||||
cJSON_GetObjectItemCaseSensitive(item, "index");
|
||||
if (index != nullptr) {
|
||||
int64_t parsed_index = 0;
|
||||
if (!IntegerField(
|
||||
item,
|
||||
"index",
|
||||
0,
|
||||
INT16_MAX,
|
||||
&parsed_index)) {
|
||||
continue;
|
||||
}
|
||||
selector = static_cast<int16_t>(parsed_index);
|
||||
}
|
||||
command.local_sequence.items[
|
||||
command.local_sequence.count++] = {
|
||||
prompt,
|
||||
selector,
|
||||
};
|
||||
}
|
||||
if (command.local_sequence.Empty()) {
|
||||
ResetCommand(output, ServerCommandType::kUnsupported);
|
||||
}
|
||||
}
|
||||
|
||||
void ServerMessageDispatcher::ParseMemorySync(
|
||||
const void* opaque_root,
|
||||
ServerCommand* output) const
|
||||
{
|
||||
const auto* root = static_cast<const cJSON*>(opaque_root);
|
||||
ResetCommand(output, ServerCommandType::kMemorySync);
|
||||
ServerCommand& command = *output;
|
||||
const cJSON* name =
|
||||
cJSON_GetObjectItemCaseSensitive(root, "child_name");
|
||||
const cJSON* brain =
|
||||
cJSON_GetObjectItemCaseSensitive(root, "brain_text");
|
||||
const cJSON* count =
|
||||
cJSON_GetObjectItemCaseSensitive(root, "interaction_count");
|
||||
if ((name != nullptr && !cJSON_IsString(name)) ||
|
||||
(brain != nullptr && !cJSON_IsString(brain)) ||
|
||||
(count != nullptr && !cJSON_IsNumber(count)) ||
|
||||
!CopyOptionalString(
|
||||
root, "child_name", &command.memory.child_name) ||
|
||||
!CopyOptionalString(
|
||||
root, "brain_text", &command.memory.brain_text)) {
|
||||
SetInvalid(output, kInvalidMessageError);
|
||||
return;
|
||||
}
|
||||
if (count != nullptr) {
|
||||
int64_t parsed_count = 0;
|
||||
if (!IntegerField(
|
||||
root,
|
||||
"interaction_count",
|
||||
0,
|
||||
INT32_MAX,
|
||||
&parsed_count)) {
|
||||
SetInvalid(output, kInvalidMessageError);
|
||||
return;
|
||||
}
|
||||
command.memory.interaction_count =
|
||||
static_cast<int32_t>(parsed_count);
|
||||
}
|
||||
}
|
||||
|
||||
const char* ToString(ServerCommandType type)
|
||||
{
|
||||
switch (type) {
|
||||
case ServerCommandType::kInvalid:
|
||||
return "invalid";
|
||||
case ServerCommandType::kUnsupported:
|
||||
return "unsupported";
|
||||
case ServerCommandType::kHello:
|
||||
return "hello";
|
||||
case ServerCommandType::kPing:
|
||||
return "ping";
|
||||
case ServerCommandType::kPong:
|
||||
return "pong";
|
||||
case ServerCommandType::kSttText:
|
||||
return "stt_text";
|
||||
case ServerCommandType::kLlmEmotion:
|
||||
return "llm_emotion";
|
||||
case ServerCommandType::kTtsStart:
|
||||
return "tts_start";
|
||||
case ServerCommandType::kTtsStop:
|
||||
return "tts_stop";
|
||||
case ServerCommandType::kTtsSentenceStart:
|
||||
return "tts_sentence_start";
|
||||
case ServerCommandType::kTtsSentenceEnd:
|
||||
return "tts_sentence_end";
|
||||
case ServerCommandType::kBargeIn:
|
||||
return "barge_in";
|
||||
case ServerCommandType::kControl:
|
||||
return "control";
|
||||
case ServerCommandType::kPlayLocal:
|
||||
return "play_local";
|
||||
case ServerCommandType::kPlayLocalSequence:
|
||||
return "play_local_sequence";
|
||||
case ServerCommandType::kMemorySync:
|
||||
return "memory_sync";
|
||||
case ServerCommandType::kSetTimer:
|
||||
return "set_timer";
|
||||
case ServerCommandType::kCancelTimer:
|
||||
return "cancel_timer";
|
||||
case ServerCommandType::kSetAlarm:
|
||||
return "set_alarm";
|
||||
case ServerCommandType::kDeleteAlarm:
|
||||
return "delete_alarm";
|
||||
case ServerCommandType::kSyncAlarms:
|
||||
return "sync_alarms";
|
||||
case ServerCommandType::kAlarmConfig:
|
||||
return "alarm_config";
|
||||
case ServerCommandType::kCall:
|
||||
return "call";
|
||||
case ServerCommandType::kEnterProvisioning:
|
||||
return "enter_provisioning";
|
||||
case ServerCommandType::kError:
|
||||
return "error";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
const char* ToString(CallSignalState state)
|
||||
{
|
||||
switch (state) {
|
||||
case CallSignalState::kNone:
|
||||
return "none";
|
||||
case CallSignalState::kRing:
|
||||
return "ring";
|
||||
case CallSignalState::kInvite:
|
||||
return "invite";
|
||||
case CallSignalState::kConnected:
|
||||
return "connected";
|
||||
case CallSignalState::kEnded:
|
||||
return "ended";
|
||||
case CallSignalState::kMissed:
|
||||
return "missed";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
} // namespace borla
|
||||
153
main/protocol/server_message_dispatcher.h
Normal file
153
main/protocol/server_message_dispatcher.h
Normal file
@@ -0,0 +1,153 @@
|
||||
#pragma once
|
||||
|
||||
#include "core/playback_types.h"
|
||||
#include "core/remote_behavior.h"
|
||||
#include "memory/memory_types.h"
|
||||
#include "schedule/schedule_types.h"
|
||||
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
namespace borla {
|
||||
|
||||
inline constexpr size_t kRealtimeSessionIdCapacity = 64;
|
||||
inline constexpr size_t kCallIdCapacity = 96;
|
||||
inline constexpr size_t kPeerNameCapacity = 64;
|
||||
inline constexpr size_t kDeviceNameCapacity = 64;
|
||||
inline constexpr size_t kConversationTextCapacity = 1024;
|
||||
|
||||
enum class CallSignalState : uint8_t {
|
||||
kNone,
|
||||
kRing,
|
||||
kInvite,
|
||||
kConnected,
|
||||
kEnded,
|
||||
kMissed,
|
||||
};
|
||||
|
||||
enum class RemoteControlAction : uint8_t {
|
||||
kNone,
|
||||
kVolume,
|
||||
kWakeWord,
|
||||
kBargeIn,
|
||||
kLightSleep,
|
||||
kLedAlert,
|
||||
};
|
||||
|
||||
enum class BargeInDecisionState : uint8_t {
|
||||
kNone,
|
||||
kCandidate,
|
||||
kRejected,
|
||||
kConfirmed,
|
||||
};
|
||||
|
||||
enum class ServerCommandType : uint8_t {
|
||||
kInvalid,
|
||||
kUnsupported,
|
||||
kHello,
|
||||
kPing,
|
||||
kPong,
|
||||
kSttText,
|
||||
kLlmEmotion,
|
||||
kTtsStart,
|
||||
kTtsStop,
|
||||
kTtsSentenceStart,
|
||||
kTtsSentenceEnd,
|
||||
kBargeIn,
|
||||
kControl,
|
||||
kPlayLocal,
|
||||
kPlayLocalSequence,
|
||||
kMemorySync,
|
||||
kSetTimer,
|
||||
kCancelTimer,
|
||||
kSetAlarm,
|
||||
kDeleteAlarm,
|
||||
kSyncAlarms,
|
||||
kAlarmConfig,
|
||||
kCall,
|
||||
kEnterProvisioning,
|
||||
kError,
|
||||
};
|
||||
|
||||
struct ServerCommand {
|
||||
ServerCommandType type = ServerCommandType::kInvalid;
|
||||
uint32_t error_id = 0;
|
||||
std::array<char, kRealtimeSessionIdCapacity> session_id{};
|
||||
std::array<char, kDeviceNameCapacity> device_name{};
|
||||
std::array<char, kCallIdCapacity> call_id{};
|
||||
std::array<char, kPeerNameCapacity> peer_name{};
|
||||
std::array<char, kConversationTextCapacity> conversation_text{};
|
||||
ButtonAction triple_click_action = ButtonAction::kUnspecified;
|
||||
ButtonAction quadruple_click_action = ButtonAction::kUnspecified;
|
||||
LocalPrompt server_unreachable_prompt = LocalPrompt::kServerError;
|
||||
LocalPrompt no_network_prompt = LocalPrompt::kNoNetwork;
|
||||
bool has_server_unreachable_prompt = false;
|
||||
bool has_no_network_prompt = false;
|
||||
CallSignalState call_state = CallSignalState::kNone;
|
||||
RemoteControlAction control_action = RemoteControlAction::kNone;
|
||||
BargeInDecisionState barge_in_state = BargeInDecisionState::kNone;
|
||||
int32_t control_value = 0;
|
||||
uint32_t output_sample_rate = 0;
|
||||
uint16_t frame_duration_ms = 0;
|
||||
int64_t server_time_seconds = 0;
|
||||
int32_t timezone_offset_seconds = 0;
|
||||
LocalPrompt local_prompt = LocalPrompt::kError;
|
||||
PlaybackPriority playback_priority = PlaybackPriority::kLocalPrompt;
|
||||
int16_t prompt_index = -1;
|
||||
bool soft_off_after_playback = false;
|
||||
LocalPromptSequence local_sequence{};
|
||||
MemorySnapshot memory{};
|
||||
uint32_t duration_seconds = 0;
|
||||
TimerCancelScope timer_cancel_scope = TimerCancelScope::kNext;
|
||||
AlarmEntry alarm{};
|
||||
AlarmList alarms{};
|
||||
int32_t alarm_id = 0;
|
||||
int8_t set_tone_index = -1;
|
||||
int8_t wake_tone_index = -1;
|
||||
};
|
||||
|
||||
class ServerMessageDispatcher final {
|
||||
public:
|
||||
bool ParseInto(
|
||||
const char* json,
|
||||
size_t size,
|
||||
ServerCommand* output) const;
|
||||
|
||||
private:
|
||||
void ParseHello(const void* root, ServerCommand* output) const;
|
||||
void ParseStt(const void* root, ServerCommand* output) const;
|
||||
void ParseLlm(const void* root, ServerCommand* output) const;
|
||||
void ParseTts(const void* root, ServerCommand* output) const;
|
||||
void ParseBargeIn(const void* root, ServerCommand* output) const;
|
||||
void ParseControl(const void* root, ServerCommand* output) const;
|
||||
void ParsePlayLocal(
|
||||
const void* root,
|
||||
ServerCommand* output) const;
|
||||
void ParsePlayLocalSequence(
|
||||
const void* root,
|
||||
ServerCommand* output) const;
|
||||
void ParseMemorySync(
|
||||
const void* root,
|
||||
ServerCommand* output) const;
|
||||
void ParseSetTimer(const void* root, ServerCommand* output) const;
|
||||
void ParseCancelTimer(
|
||||
const void* root,
|
||||
ServerCommand* output) const;
|
||||
void ParseSetAlarm(const void* root, ServerCommand* output) const;
|
||||
void ParseDeleteAlarm(
|
||||
const void* root,
|
||||
ServerCommand* output) const;
|
||||
void ParseSyncAlarms(
|
||||
const void* root,
|
||||
ServerCommand* output) const;
|
||||
void ParseAlarmConfig(
|
||||
const void* root,
|
||||
ServerCommand* output) const;
|
||||
void ParseCall(const void* root, ServerCommand* output) const;
|
||||
};
|
||||
|
||||
const char* ToString(ServerCommandType type);
|
||||
const char* ToString(CallSignalState state);
|
||||
|
||||
} // namespace borla
|
||||
48
main/protocol/utf8_text.h
Normal file
48
main/protocol/utf8_text.h
Normal file
@@ -0,0 +1,48 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
|
||||
namespace borla {
|
||||
namespace utf8_text {
|
||||
|
||||
// Continuation bytes are 0b10xxxxxx — every byte of a multi-byte sequence
|
||||
// except the first.
|
||||
inline bool IsContinuationByte(char value)
|
||||
{
|
||||
return (static_cast<unsigned char>(value) & 0xC0) == 0x80;
|
||||
}
|
||||
|
||||
// Longest prefix of `text` that is at most `max_bytes` long AND ends on a UTF-8
|
||||
// character boundary. Returns the length in bytes; the caller copies that many.
|
||||
//
|
||||
// Truncating on a raw byte boundary is not a cosmetic problem. The previous
|
||||
// firmware capped the same field with substr(0, 100), which splits a 3-byte
|
||||
// Chinese character straddling byte 100 into an incomplete sequence. The
|
||||
// server's websockets library validates text frames as UTF-8 and force-closes
|
||||
// with code 1007 (invalid frame payload data) — seen in production as "invalid
|
||||
// continuation byte at position 214", killing the session mid-story. JSON
|
||||
// escaping does not help: half a character is still invalid UTF-8, and cJSON
|
||||
// escapes control characters without validating encoding.
|
||||
inline size_t SafeTruncatedLength(
|
||||
const char* text,
|
||||
size_t length,
|
||||
size_t max_bytes)
|
||||
{
|
||||
if (text == nullptr) {
|
||||
return 0;
|
||||
}
|
||||
if (length <= max_bytes) {
|
||||
return length;
|
||||
}
|
||||
// Walk left from the cap until the byte at the cut is a lead byte, i.e.
|
||||
// the start of the character that is being dropped. Everything before it
|
||||
// is then a run of complete characters.
|
||||
size_t end = max_bytes;
|
||||
while (end > 0 && IsContinuationByte(text[end])) {
|
||||
--end;
|
||||
}
|
||||
return end;
|
||||
}
|
||||
|
||||
} // namespace utf8_text
|
||||
} // namespace borla
|
||||
53
main/protocol/websocket_transport.h
Normal file
53
main/protocol/websocket_transport.h
Normal file
@@ -0,0 +1,53 @@
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
namespace borla {
|
||||
|
||||
inline constexpr size_t kWebsocketUrlCapacity = 512;
|
||||
inline constexpr size_t kWebsocketTokenCapacity = 320;
|
||||
inline constexpr size_t kWebsocketDeviceIdCapacity = 24;
|
||||
inline constexpr size_t kWebsocketFirmwareVersionCapacity = 48;
|
||||
|
||||
struct WebsocketTransportConfig {
|
||||
std::array<char, kWebsocketUrlCapacity> url{};
|
||||
std::array<char, kWebsocketTokenCapacity> token{};
|
||||
std::array<char, kWebsocketDeviceIdCapacity> device_id{};
|
||||
std::array<char, kWebsocketFirmwareVersionCapacity> firmware_version{};
|
||||
uint8_t protocol_version = 3;
|
||||
uint32_t connect_timeout_ms = 15000;
|
||||
};
|
||||
|
||||
class IWebsocketTransportObserver {
|
||||
public:
|
||||
virtual ~IWebsocketTransportObserver() = default;
|
||||
virtual void OnWebsocketConnected() = 0;
|
||||
virtual void OnWebsocketDisconnected(int error_code) = 0;
|
||||
virtual void OnWebsocketText(const char* data, size_t size) = 0;
|
||||
virtual void OnWebsocketBinary(
|
||||
const uint8_t* data,
|
||||
size_t size) = 0;
|
||||
};
|
||||
|
||||
class IWebsocketTransport {
|
||||
public:
|
||||
virtual ~IWebsocketTransport() = default;
|
||||
|
||||
virtual bool Initialize() = 0;
|
||||
virtual bool Open(
|
||||
const WebsocketTransportConfig& config,
|
||||
IWebsocketTransportObserver& observer) = 0;
|
||||
virtual void Close() = 0;
|
||||
virtual bool SendText(const char* data, size_t size) = 0;
|
||||
virtual bool SendTelemetryText(const char* data, size_t size)
|
||||
{
|
||||
return SendText(data, size);
|
||||
}
|
||||
virtual bool SendBinary(const uint8_t* data, size_t size) = 0;
|
||||
virtual bool IsConnected() const = 0;
|
||||
};
|
||||
|
||||
} // namespace borla
|
||||
143
main/protocol/websocket_uri.cc
Normal file
143
main/protocol/websocket_uri.cc
Normal file
@@ -0,0 +1,143 @@
|
||||
#include "protocol/websocket_uri.h"
|
||||
|
||||
#include "connectivity/wifi_types.h"
|
||||
|
||||
#include <cctype>
|
||||
#include <cstring>
|
||||
|
||||
namespace borla {
|
||||
namespace {
|
||||
|
||||
bool CopyRange(
|
||||
const char* begin,
|
||||
const char* end,
|
||||
char* output,
|
||||
size_t capacity)
|
||||
{
|
||||
if (begin == nullptr || end == nullptr || output == nullptr ||
|
||||
end <= begin || static_cast<size_t>(end - begin) >= capacity) {
|
||||
return false;
|
||||
}
|
||||
const size_t size = static_cast<size_t>(end - begin);
|
||||
std::memcpy(output, begin, size);
|
||||
output[size] = '\0';
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ParsePort(const char* begin, const char* end, uint16_t* output)
|
||||
{
|
||||
if (begin == nullptr || end == nullptr || output == nullptr ||
|
||||
begin >= end) {
|
||||
return false;
|
||||
}
|
||||
uint32_t value = 0;
|
||||
for (const char* cursor = begin; cursor < end; ++cursor) {
|
||||
if (!std::isdigit(static_cast<unsigned char>(*cursor))) {
|
||||
return false;
|
||||
}
|
||||
value = value * 10U +
|
||||
static_cast<uint32_t>(*cursor - '0');
|
||||
if (value > 65535U) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (value == 0) {
|
||||
return false;
|
||||
}
|
||||
*output = static_cast<uint16_t>(value);
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool ParseWebsocketUri(const char* uri, WebsocketUri* output)
|
||||
{
|
||||
if (uri == nullptr || output == nullptr) {
|
||||
return false;
|
||||
}
|
||||
const size_t uri_size = BoundedStringLength(uri, 1024);
|
||||
if (uri_size == 0 || uri_size >= 1024) {
|
||||
return false;
|
||||
}
|
||||
|
||||
WebsocketUri parsed;
|
||||
const char* authority = nullptr;
|
||||
if (std::strncmp(uri, "ws://", 5) == 0) {
|
||||
parsed.secure = false;
|
||||
parsed.port = 80;
|
||||
authority = uri + 5;
|
||||
} else if (std::strncmp(uri, "wss://", 6) == 0) {
|
||||
parsed.secure = true;
|
||||
parsed.port = 443;
|
||||
authority = uri + 6;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
|
||||
const char* const uri_end = uri + uri_size;
|
||||
const char* path = std::strchr(authority, '/');
|
||||
const char* authority_end = path == nullptr ? uri_end : path;
|
||||
if (authority >= authority_end) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const char* port_separator = nullptr;
|
||||
if (*authority == '[') {
|
||||
const char* bracket = std::strchr(authority, ']');
|
||||
if (bracket == nullptr || bracket >= authority_end ||
|
||||
!CopyRange(
|
||||
authority + 1,
|
||||
bracket,
|
||||
parsed.host.data(),
|
||||
parsed.host.size())) {
|
||||
return false;
|
||||
}
|
||||
if (bracket + 1 < authority_end) {
|
||||
if (*(bracket + 1) != ':') {
|
||||
return false;
|
||||
}
|
||||
port_separator = bracket + 1;
|
||||
}
|
||||
} else {
|
||||
for (const char* cursor = authority;
|
||||
cursor < authority_end;
|
||||
++cursor) {
|
||||
if (*cursor == ':') {
|
||||
if (port_separator != nullptr) {
|
||||
return false;
|
||||
}
|
||||
port_separator = cursor;
|
||||
}
|
||||
}
|
||||
const char* host_end =
|
||||
port_separator == nullptr ? authority_end : port_separator;
|
||||
if (!CopyRange(
|
||||
authority,
|
||||
host_end,
|
||||
parsed.host.data(),
|
||||
parsed.host.size())) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (port_separator != nullptr &&
|
||||
!ParsePort(port_separator + 1, authority_end, &parsed.port)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (path == nullptr) {
|
||||
parsed.path[0] = '/';
|
||||
parsed.path[1] = '\0';
|
||||
} else if (!CopyRange(
|
||||
path,
|
||||
uri_end,
|
||||
parsed.path.data(),
|
||||
parsed.path.size())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
*output = parsed;
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace borla
|
||||
21
main/protocol/websocket_uri.h
Normal file
21
main/protocol/websocket_uri.h
Normal file
@@ -0,0 +1,21 @@
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
namespace borla {
|
||||
|
||||
inline constexpr size_t kWebsocketHostCapacity = 128;
|
||||
inline constexpr size_t kWebsocketPathCapacity = 384;
|
||||
|
||||
struct WebsocketUri {
|
||||
bool secure = false;
|
||||
uint16_t port = 0;
|
||||
std::array<char, kWebsocketHostCapacity> host{};
|
||||
std::array<char, kWebsocketPathCapacity> path{};
|
||||
};
|
||||
|
||||
bool ParseWebsocketUri(const char* uri, WebsocketUri* output);
|
||||
|
||||
} // namespace borla
|
||||
Reference in New Issue
Block a user