bolar_1 date 2026-7-1 d:/proc

This commit is contained in:
2026-11-27 17:44:38 +08:00
commit 0dbdfa57bc
890 changed files with 325428 additions and 0 deletions

56
main/CMakeLists.txt Normal file
View File

@@ -0,0 +1,56 @@
set(SRCS
"main.cc"
"trace_ctx.cc"
"application.cc"
"settings.cc"
"system_info.cc"
"ota.cc"
"audio/audio_codec.cc"
"audio/audio_service.cc"
"audio/voice_processor.cc"
"audio/wake_word.cc"
"audio/codecs/es8311_audio_codec.cc"
"protocols/protocol.cc"
"protocols/websocket_protocol.cc"
"boards/wifi_board.cc"
"boards/ml307_board.cc"
"boards/dual_network_board.cc"
"boards/borla_s3/borla_s3_board.cc"
"boards/common/bmi270.c"
"boards/common/bmi270_context.c"
"boards/common/button.cc"
"led/single_led.cc"
"audio/audio_prompt.cc"
"memory_cache.cc"
"conn_error_config.cc"
"button_config.cc"
"ble/friend_exchange.cc"
)
idf_component_register(
SRCS ${SRCS}
INCLUDE_DIRS "."
REQUIRES
nvs_flash spi_flash
esp_wifi
esp_http_client
esp_timer
driver
esp_app_format
app_update
json
pthread
esp-opus
esp-opus-encoder
esp-ml307
esp-wifi-connect
freertos
esp_driver_i2s
esp_driver_i2c
esp_driver_ledc
esp_driver_gpio
esp-sr
led_strip
button
bt
)

10
main/Kconfig.projbuild Normal file
View File

@@ -0,0 +1,10 @@
menu "Borla Firmware"
config OTA_URL
string "OTA endpoint URL"
default "https://borla-ota-dev.lkall.com/xiaozhi/ota/"
help
Default OTA endpoint used when the device has no saved OTA URL or when
a stale environment URL is detected in NVS.
endmenu

3282
main/application.cc Normal file

File diff suppressed because it is too large Load Diff

296
main/application.h Normal file
View File

@@ -0,0 +1,296 @@
#pragma once
#include "protocols/protocol.h"
#include "audio/audio_service.h"
#include "audio/audio_prompt.h"
#include "ota.h"
#include <freertos/FreeRTOS.h>
#include <freertos/event_groups.h>
#include <esp_timer.h>
#include <string>
#include <memory>
#include <functional>
#include <vector>
#include <deque>
#include <mutex>
#include <atomic>
enum DeviceState {
kDeviceStateUnknown,
kDeviceStateStarting,
kDeviceStateWifiConfiguring,
kDeviceStateIdle,
kDeviceStateConnecting,
kDeviceStateListening,
kDeviceStateSpeaking,
kDeviceStateRinging, // Incoming call, playing ringtone + mic on for accept detection
kDeviceStateCalling, // Active call, full-duplex audio
kDeviceStateUpgrading,
};
#define MAIN_EVENT_SCHEDULE BIT0
#define MAIN_EVENT_SEND_AUDIO BIT1
#define MAIN_EVENT_ERROR BIT2
#define MAIN_EVENT_CLOCK_TICK BIT3
#define MAIN_EVENT_STATUS_TICK BIT4
#define MAIN_EVENT_WAKE_WORD BIT5
class Board;
class Application {
public:
static Application& GetInstance();
void Start();
DeviceState device_state() const { return device_state_; }
// 对话控制
void ToggleChatState();
void StartListening();
void StopListening();
// 音量
bool SetSpeakerVolume(int volume);
// Schedule 异步任务到主循环
void Schedule(std::function<void()> callback);
// Send text message to server via protocol (thread-safe, scheduled on main loop)
void SendTextMessage(const std::string& text);
// Called by Board when the underlying network (WiFi / 4G modem) goes
// down or comes back up. On down we actively tear down the zombie WS
// so the next send won't stall waiting for a 10s TCP timeout; on the
// up edge (only after a prior down) we eagerly reopen so the device
// is ready before the user talks again.
void NotifyNetworkStateChanged(bool ready);
Protocol* GetProtocol() { return protocol_.get(); }
AudioService audio_service_;
AudioPrompt audio_prompt_;
private:
Application();
~Application();
void MainEventLoop();
void SetDeviceState(DeviceState state);
void SendStatusUpdate();
void AbortSpeaking(AbortReason reason);
void SetListeningMode(ListeningMode mode);
void SetDeviceStateForIdleWatchdog(DeviceState state);
void CheckNewVersion(class Ota& ota);
EventGroupHandle_t event_group_ = nullptr;
esp_timer_handle_t clock_timer_handle_ = nullptr;
esp_timer_handle_t status_timer_handle_ = nullptr;
TaskHandle_t main_event_loop_task_ = nullptr;
std::unique_ptr<Protocol> protocol_;
DeviceState device_state_ = kDeviceStateUnknown;
ListeningMode listening_mode_ = kListeningModeAutoStop;
//2026-6-24 ckkj debug 防止人声未结束马上应答
int64_t listening_start_ms_ = 0; // Timestamp when entering listening state
static constexpr int64_t kMinListeningDurationMs = 5000; // Minimum 5s listening before speaking
std::mutex mutex_;
std::deque<std::function<void()>> main_tasks_;
std::string last_error_message_;
std::atomic<bool> tts_audio_active_{false};
std::string tts_current_text_; // Accumulated sentence_start texts, logged full on tts.stop
std::atomic<bool> local_prompt_playing_{false}; // 2026-6-27 ckkj debug 正在播放本地提示音
// 2026-6-24 ckkj debug 超时保护防止网络不好服务器断开导致卡住
static constexpr int64_t kTtsTimeoutMs = 60000; // 60s timeout
esp_timer_handle_t tts_timeout_timer_ = nullptr;
void StartTtsTimeoutTimer();
void CancelTtsTimeoutTimer();
void OnTtsTimeout();//超时回调,强制切换到 listening 状态
// 2026-6-30 ckkj debug 管理 listening->speaking 的延迟切换 timer,
// 避免状态已变后延迟 timer 仍错误触发
esp_timer_handle_t speaking_delay_timer_ = nullptr;
void CancelSpeakingDelayTimer();
// 2026-6-30 ckkj debug 添加 TTS 流沉寂超时:超过该时间未收到任何 TTS
// 数据/文本则认为服务器流已中断,主动切回 listening,避免无 stop 时卡死
static constexpr int64_t kTtsStreamIdleTimeoutMs = 10000; // 10s idle timeout
esp_timer_handle_t tts_stream_idle_timer_ = nullptr;
void StartTtsStreamIdleTimer();
void CancelTtsStreamIdleTimer();
void OnTtsStreamIdleTimeout();
//debug end
// One-shot guard: set when welcome prompt starts; consumed (cleared without
// audible playback) by the next wake-word-in-idle so the device doesn't say
// "我在" right after the boot greeting which already addressed the child.
std::atomic<bool> suppress_next_wake_response_{false};
// Tracks the last network edge seen via NotifyNetworkStateChanged.
// Only flips to true when we actually observe a down event, so the
// initial "network ready" emitted at boot does NOT trigger a reconnect
// (Application::Start already owns the first OpenAudioChannel).
std::atomic<bool> network_was_down_{false};
// === Low-battery monitoring ===
// See docs/features/low-battery-monitor.md (TODO) — runs every 10 minutes
// via the clock tick. Skipped entirely when board.IsCharging() is true.
// Two thresholds:
// ≤20% → play "我快没电了,请及时充电哦!" every 10 min (idle/listening only)
// <10% → play "我快没电了,帮我连接电源充电哦!我先退下了。" then EnterSoftOff
void CheckLowBatteryPeriodic();
void TriggerLowBatteryShutdown(); // 10% path — waits for current playback, then off
void TriggerLowBatteryWarning20(); // 20% path — skipped if speaking
// Pending 20% warning at boot: when boot battery ≤20%, set so the first
// periodic tick after entering idle plays the warning (rather than
// interrupting boot prompt / welcome).
bool pending_low_battery_warning_at_boot_ = false;
public:
std::atomic<bool> shutting_down_{false}; // Soft power off in progress
// 传感器重构 ADR-006 / 决策 #8 #43:删除 upright_axis_ / upright_threshold_。
// 姿态识别能力保留在 server 侧,未来从 IMU 向量流自行计算。
// Alarm tone selection (index into alarm_set/alarm_wake prompt arrays, -1 = random)
std::atomic<int> alarm_set_tone_index_{-1};
std::atomic<int> alarm_wake_tone_index_{-1};
// Reminder timers (multi, one-shot, set via "set_timer" message from server)
// Stored as a sorted ascending list of esp_timer_get_time() targets.
// Protected by reminder_mutex_ since it is read by both the main loop and the
// soft-off polling loop on a separate task.
mutable std::mutex reminder_mutex_;
std::vector<int64_t> reminder_targets_us_;
void AddReminderTimer(int seconds);
void CancelAllReminderTimers();
void CancelMostRecentReminderTimer(); // removes the next-to-fire timer
bool IsReminderDue() const;
void PlayReminderSound();
int GetReminderCount() const;
// Alarm clock (absolute time, persisted in NVS, set via "set_alarm" from server)
// Completely independent of reminder timers — separate mutex, storage, and play function.
struct AlarmEntry {
int32_t id; // Server-assigned unique ID
uint8_t hour; // 0-23
uint8_t minute; // 0-59
uint8_t repeat_mask; // bit0=Sun..bit6=Sat, 0=one-shot
bool enabled;
int64_t fire_epoch; // One-shot: Unix seconds, 0 = not used
char label[32];
};
static constexpr int kMaxAlarms = 16;
mutable std::mutex alarm_mutex_;
std::vector<AlarmEntry> alarms_;
int alarm_last_fired_minute_{-1}; // Dedup: don't re-fire within same minute
// Shared across PlayReminderSound (timer) and PlayAlarmSound (clock alarm)
// to prevent two reminders/alarms overlapping when they fire close in time.
// The second fire in the same window is merged: its fired IDs are still
// reported to server, but its audio is suppressed until the first finishes.
std::atomic<bool> alarm_reminder_playing_{false};
void LoadAlarmsFromNvs();
void SaveAlarmsToNvs();
void AddOrUpdateAlarm(const AlarmEntry& entry);
void DeleteAlarm(int32_t id);
void SyncAlarms(const std::vector<AlarmEntry>& entries);
void ClearAllAlarms();
void EnsureBuiltInFirstDayPromptAlarm();
void DisableBuiltInFirstDayPromptAlarm();
bool IsWakeOnlyAlarm(const AlarmEntry& entry) const;
bool IsAlarmDue() const;
void PlayAlarmSound();
int GetAlarmCount() const;
// Loop a local prompt (with ~1s gap between rings) until either
// loop_duration_ms elapses or wake-word triggers ResetDecoder. Used by
// PlayReminderSound + PlayAlarmSound so the ringing keeps going for ~1
// minute instead of single-shot. NotifyLocalDone is called internally
// at exit; caller still owns SetDeviceState / tts_audio_active_ etc.
void PlayAlarmLoop(PromptGroup pg, int wake_idx, const char* group_name,
int loop_duration_ms);
// FreeRTOS entry that runs PlayAlarmLoop in its own task so the main
// event loop stays responsive (wake word, button, network, sensor) for
// the 60-second alarm. Without this, PlayAlarmLoop runs synchronously
// inside a Schedule() lambda that blocks MainEventLoop, which means
// the WAKE_WORD bit gets set but never consumed → alarm uninterruptible.
// Receives a heap-allocated AlarmPlaybackParams (defined in .cc), runs,
// posts teardown back via Schedule() (avoids cross-task SetDeviceState
// race), deletes params, vTaskDelete(self).
static void AlarmPlaybackTask(void* arg);
// === IdleWatchdog (firmware-side idle sleep strategy) ===
// See docs/features/idle-sleep-strategy.md for full specification.
public:
// Activity events (button, touch, etc.) call this to keep watchdog from
// firing. Safe to call from any task — Schedule()s its work to the main loop.
void IdleWatchdogResetExternal();
const char* IdleWatchdogHelloConnectReason() const;
bool IdleWatchdogShouldSkipChannelOpenReset() const;
private:
// Two-phase timeout from last activity:
// T+180s: play idle_check ("你还在吗?小朋友") + 15s listening window
// → no response → enter idle sleeping (LED off + WS closed,
// wake-word/button/touch still live)
// T+600s: play idle_goodbye ("那我先退下来…") + 15s VAD window
// → no response → EnterSoftOff (light sleep, button-wake only)
// Reset by any activity: SetDeviceState(Listening/Speaking/Ringing/Calling),
// button click, touch event, energy-VAD voice detection, OnAudioChannelOpened.
enum class IdleWatchdogPhase : uint8_t {
kInactive, // WS not connected / watchdog disabled
kRunning, // Plain idle, master timer counting down to 60s
kPromptingCheck, // Playing idle_check prompt
kAwaitCheckResponse, // Prompt done, 15s listen/VAD/button/touch window
kIdleSleeping, // WS closed, LED off, wake-word/button/touch live
kPromptingGoodbye, // Playing idle_goodbye prompt
kAwaitGoodbyeResponse, // Prompt done, 15s VAD/button/touch window
};
void IdleWatchdogReset(); // Called by any activity
void IdleWatchdogStop(); // Called when leaving idle entirely
void IdleWatchdogOnMasterFire(); // Master timer expired
void IdleWatchdogOnWindowFire(); // 15s window expired
void IdleWatchdogEnterCheckListeningWindow(); // Prompt done → normal listening window
void IdleWatchdogEnterIdleSleeping(); // T+76s no response → low-power idle
void IdleWatchdogWakeFromIdleSleeping(); // Wake word explicitly exits IdleSleeping
static const char* IdleWatchdogPhaseName(IdleWatchdogPhase p);
esp_timer_handle_t idle_master_timer_ = nullptr; // 60s or remaining-to-180s
esp_timer_handle_t idle_window_timer_ = nullptr; // 15s post-prompt window
// === Activation code periodic replay (firmware-side) ===
// Server pushes the activation-code sequence once per hello. To let the user
// hear the code multiple times without relying on WS reconnect, we cache the
// last sequence locally and replay it every kActivationReplayMs until
// (a) the device gets activated (server pushes welcome/tts/play_local for
// anything other than activation_device → StopActivationReplay), or
// (b) idle watchdog enters IdleSleeping (StopActivationReplay).
// Gap between the END of one playback and the START of the next.
// Total cycle ≈ ~14s playback + this gap. Set to 6000ms → ~20s cycle.
static constexpr int kActivationReplayMs = 6000;
std::mutex activation_replay_mutex_;
std::atomic<bool> activation_replay_active_{false};
std::vector<std::pair<PromptGroup, int>> activation_replay_seq_;
esp_timer_handle_t activation_replay_timer_ = nullptr;
void StartActivationReplay(std::vector<std::pair<PromptGroup, int>> seq);
void StopActivationReplay(const char* reason);
void RunActivationSequence(const std::vector<std::pair<PromptGroup, int>>& items);
void OnActivationReplayTimer();
int64_t idle_start_ts_ms_ = 0; // T0 anchor (esp_timer_get_time/1000)
std::atomic<IdleWatchdogPhase> idle_phase_{IdleWatchdogPhase::kInactive};
std::atomic<bool> idle_watchdog_opening_check_channel_{false};
std::atomic<bool> idle_watchdog_internal_state_change_{false};
private:
std::atomic<bool> call_active_{false}; // Phone call in progress
std::string pending_call_id_; // Current call ID from server
// Pending OTA upgrade (decided at startup, executed after WS connect)
std::unique_ptr<Ota> pending_ota_;
std::string pending_ota_reason_; // "auto" or "force"
};

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

BIN
main/assets/common/boot.ogg Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,195 @@
"""Generate C header from Opus files — extracts Opus frames from OGG container.
Usage: python gen_audio_prompts.py <opus_dir> <output.h>
"""
import os
import sys
import struct
import random
def parse_ogg_opus(filepath):
"""Extract raw Opus frames from OGG/Opus file.
Validates that page 0 carries OpusHead — refuses OGG/FLAC, OGG/Vorbis
or any other non-Opus container that would otherwise be silently
misinterpreted as Opus packets and break the firmware decoder.
"""
frames = []
with open(filepath, "rb") as f:
data = f.read()
pos = 0
page_num = 0
while pos < len(data):
# OGG page header
if data[pos:pos+4] != b"OggS":
break
num_segments = data[pos+26]
segment_table = data[pos+27:pos+27+num_segments]
data_start = pos + 27 + num_segments
# Reconstruct packets from segments
packet_data = bytearray()
data_offset = data_start
for seg_size in segment_table:
packet_data.extend(data[data_offset:data_offset+seg_size])
data_offset += seg_size
if seg_size < 255:
# Packet complete
if page_num == 0:
# First packet must be OpusHead — reject anything else
# (FLAC marker is "fLaC", Vorbis is b"\x01vorbis", etc.)
if not bytes(packet_data).startswith(b"OpusHead"):
actual = bytes(packet_data[:8]).decode("ascii", errors="replace")
raise ValueError(
f"{filepath}: not OGG/Opus (page-0 packet starts "
f"with {actual!r}). Re-encode the source to Opus "
f"with: ffmpeg -i <src> -c:a libopus -ar 24000 -b:a 24k <out>.opus"
)
if page_num >= 2 and len(packet_data) > 0:
# Skip pages 0 (OpusHead) and 1 (OpusTags)
frames.append(bytes(packet_data))
packet_data = bytearray()
# If packet spans pages (all segments = 255)
if len(packet_data) > 0 and page_num >= 2:
frames.append(bytes(packet_data))
packet_data = bytearray()
pos = data_offset
page_num += 1
return frames
GROUPS = [
"activation_device",
"device_already_bound",
"server_error",
"alarm_wake",
"alarm_set",
"no_network",
"wifi_config",
"wake_response",
"story_expired",
"idle_check",
"idle_goodbye",
"wifi_success",
"welcome",
"shutdown",
"boot",
"error",
"low_battery_20",
"low_battery_10",
] + [f"digit_{d}" for d in range(10)]
def classify_file(filename):
"""Map filename → group.
File naming rule: <group>.ogg or <group>_<n>.ogg, lowercase, ASCII only.
Single-file groups (e.g. boot, shutdown) match by exact stem; multi-file
groups (e.g. welcome_1, error_3) match by `<group>_` prefix.
Match priority follows GROUPS order (longer-prefix groups first to avoid
`server_error_1` falsely matching `server`-style entries; current GROUPS
list has no prefix overlap, but the order is preserved as a safety rail).
"""
stem = os.path.splitext(filename)[0]
for g in GROUPS:
if stem == g or stem.startswith(g + "_"):
return g
return None
def frames_to_c_array(frames, var_name):
"""Convert Opus frames to C byte array with simple format:
[num_frames:u16][frame_size:u16, frame_data:bytes]...
"""
buf = bytearray()
buf.extend(struct.pack("<H", len(frames)))
for frame in frames:
buf.extend(struct.pack("<H", len(frame)))
buf.extend(frame)
lines = [f"static const uint8_t {var_name}[] = {{"]
for i in range(0, len(buf), 16):
chunk = buf[i:i+16]
hex_str = ", ".join(f"0x{b:02x}" for b in chunk)
lines.append(f" {hex_str},")
lines.append("};")
return "\n".join(lines), len(buf)
def main():
if len(sys.argv) < 3:
print(f"Usage: {sys.argv[0]} <opus_dir> <output.h>")
sys.exit(1)
opus_dir = sys.argv[1]
output_h = sys.argv[2]
groups = {g: [] for g in GROUPS}
total_size = 0
# Scan directory
files = []
for f in sorted(os.listdir(opus_dir)):
if f.lower().endswith((".opus", ".ogg")):
filepath = os.path.join(opus_dir, f)
group = classify_file(f)
if group:
files.append((f, filepath, group))
print(f"Found {len(files)} audio files")
# Generate header
header_lines = [
"#pragma once",
"",
"// Auto-generated by gen_audio_prompts.py — DO NOT EDIT",
"",
"#include <cstdint>",
"#include <cstddef>",
"",
]
array_names = {g: [] for g in GROUPS}
for idx, (filename, filepath, group) in enumerate(files):
frames = parse_ogg_opus(filepath)
var_name = f"audio_{group}_{idx}"
c_array, size = frames_to_c_array(frames, var_name)
header_lines.append(f"// {filename} ({len(frames)} frames, {size} bytes)")
header_lines.append(c_array)
header_lines.append("")
array_names[group].append(var_name)
total_size += size
sys.stdout.buffer.write(f" [{group}] {filename}: {len(frames)} frames, {size} bytes\n".encode("utf-8", errors="replace"))
# Generate group index tables. Always emit the symbols even for empty
# groups so audio_prompt.cc's static references compile — count=0 makes
# HasPrompts() return false and the caller falls back gracefully.
for group, names in array_names.items():
if names:
ptrs = ", ".join(names)
header_lines.append(f"static const uint8_t* audio_{group}_files[] = {{ {ptrs} }};")
header_lines.append(f"static const size_t audio_{group}_sizes[] = {{ {', '.join(f'sizeof({n})' for n in names)} }};")
header_lines.append(f"static const int audio_{group}_count = {len(names)};")
else:
header_lines.append(f"static const uint8_t* audio_{group}_files[] = {{ nullptr }};")
header_lines.append(f"static const size_t audio_{group}_sizes[] = {{ 0 }};")
header_lines.append(f"static const int audio_{group}_count = 0;")
header_lines.append("")
# Write header file
os.makedirs(os.path.dirname(output_h), exist_ok=True)
with open(output_h, "w", encoding="utf-8") as f:
f.write("\n".join(header_lines))
print(f"\nGenerated {output_h}: {total_size} bytes total ({total_size/1024:.1f} KB)")
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,62 @@
#!/bin/bash
# Generate low-battery prompt OGG files via IndexTTS HTTP API.
# Outputs to firmware/main/assets/common/{low_battery_20,low_battery_10}.ogg
#
# Requires: curl, ffmpeg, jq (optional for error msg parsing)
# Run from anywhere; paths resolved relative to script location.
set -euo pipefail
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
OUT_DIR="$SCRIPT_DIR/common"
# IndexTTS HTTP endpoint (matches server/config.yaml TTS_BASE_URL)
TTS_URL="${TTS_BASE_URL:-http://192.168.1.150:10140}/audio/speech/stream"
TTS_VOICE="${TTS_VOICE:-my_voice}" # matches server/config.yaml default
TTS_MODEL="${TTS_MODEL:-indextts}"
declare -a TEXTS=(
"low_battery_20|我快没电了,请及时充电哦!"
"low_battery_10|我快没电了,帮我连接电源充电哦!我先退下了。"
)
mkdir -p "$OUT_DIR"
for entry in "${TEXTS[@]}"; do
name="${entry%%|*}"
text="${entry#*|}"
wav_path="$OUT_DIR/${name}.wav"
ogg_path="$OUT_DIR/${name}.ogg"
echo "==> Generating: $name"
echo " Text: $text"
echo " URL: $TTS_URL"
# Call IndexTTS — response is WAV binary
http_code=$(curl -sS -o "$wav_path" -w "%{http_code}" \
-X POST "$TTS_URL" \
-H "Content-Type: application/json" \
-d "$(printf '{"model":"%s","voice":"%s","input":"%s"}' "$TTS_MODEL" "$TTS_VOICE" "$text")")
if [ "$http_code" != "200" ]; then
echo " ERROR: HTTP $http_code"
cat "$wav_path"
echo
rm -f "$wav_path"
exit 1
fi
echo " WAV: $(stat -f%z "$wav_path" 2>/dev/null || stat -c%s "$wav_path") bytes"
# Convert WAV → Opus OGG (24kHz mono, matches firmware decoder expectations)
ffmpeg -y -i "$wav_path" -c:a libopus -ar 24000 -ac 1 -b:a 24k \
-frame_duration 60 "$ogg_path" 2>&1 | tail -3
rm -f "$wav_path"
echo " OGG: $ogg_path ($(stat -f%z "$ogg_path" 2>/dev/null || stat -c%s "$ogg_path") bytes)"
echo
done
echo "Done. Two OGG files generated in $OUT_DIR/"
echo "Next: regenerate audio_prompts_data.h:"
echo " cd $SCRIPT_DIR && python gen_audio_prompts.py common ../audio/audio_prompts_data.h"

79
main/audio/audio_codec.cc Normal file
View File

@@ -0,0 +1,79 @@
#include "audio_codec.h"
#include "settings.h"
#include <esp_log.h>
#include <cstring>
#include <driver/i2s_common.h>
#define TAG "AudioCodec"
AudioCodec::AudioCodec() {}
AudioCodec::~AudioCodec() {}
void AudioCodec::OutputData(std::vector<int16_t>& data)
{
Write(data.data(), data.size());
}
bool AudioCodec::InputData(std::vector<int16_t>& data)
{
int samples = Read(data.data(), data.size());
return samples > 0;
}
void AudioCodec::Start()
{
Settings settings("audio", false);
output_volume_ = settings.GetInt("output_volume", output_volume_);
if (output_volume_ < AUDIO_CODEC_MIN_OUTPUT_VOLUME) {
ESP_LOGW(TAG, "Output volume (%d) too small, setting to %d",
output_volume_, AUDIO_CODEC_MIN_OUTPUT_VOLUME);
output_volume_ = AUDIO_CODEC_MIN_OUTPUT_VOLUME;
} else if (output_volume_ > AUDIO_CODEC_MAX_OUTPUT_VOLUME) {
output_volume_ = AUDIO_CODEC_MAX_OUTPUT_VOLUME;
}
if (tx_handle_) {
ESP_ERROR_CHECK(i2s_channel_enable(tx_handle_));
}
if (rx_handle_) {
ESP_ERROR_CHECK(i2s_channel_enable(rx_handle_));
}
EnableInput(true);
EnableOutput(true);
ESP_LOGI(TAG, "Audio codec started");
}
void AudioCodec::SetOutputVolume(int volume)
{
if (volume < AUDIO_CODEC_MIN_OUTPUT_VOLUME) {
volume = AUDIO_CODEC_MIN_OUTPUT_VOLUME;
} else if (volume > AUDIO_CODEC_MAX_OUTPUT_VOLUME) {
volume = AUDIO_CODEC_MAX_OUTPUT_VOLUME;
}
output_volume_ = volume;
ESP_LOGI(TAG, "Set output volume to %d", output_volume_);
Settings settings("audio", true);
settings.SetInt("output_volume", output_volume_);
}
void AudioCodec::SetInputGain(float gain)
{
input_gain_ = gain;
ESP_LOGI(TAG, "Set input gain to %.1f", input_gain_);
}
void AudioCodec::EnableInput(bool enable)
{
if (enable == input_enabled_) return;
input_enabled_ = enable;
ESP_LOGI(TAG, "Set input enable to %s", enable ? "true" : "false");
}
void AudioCodec::EnableOutput(bool enable)
{
if (enable == output_enabled_) return;
output_enabled_ = enable;
ESP_LOGI(TAG, "Set output enable to %s", enable ? "true" : "false");
}

61
main/audio/audio_codec.h Normal file
View File

@@ -0,0 +1,61 @@
#ifndef _AUDIO_CODEC_H
#define _AUDIO_CODEC_H
#include <freertos/FreeRTOS.h>
#include <freertos/event_groups.h>
#include <driver/i2s_std.h>
#include <vector>
#include <string>
#include <functional>
#define AUDIO_CODEC_DMA_DESC_NUM 6
#define AUDIO_CODEC_DMA_FRAME_NUM 240
#define AUDIO_CODEC_MIN_OUTPUT_VOLUME 15
#define AUDIO_CODEC_MAX_OUTPUT_VOLUME 100
class AudioCodec {
public:
AudioCodec();
virtual ~AudioCodec();
virtual void SetOutputVolume(int volume);
virtual void SetInputGain(float gain);
virtual void EnableInput(bool enable);
virtual void EnableOutput(bool enable);
virtual void OutputData(std::vector<int16_t>& data);
virtual bool InputData(std::vector<int16_t>& data);
virtual void Start();
inline bool duplex() const { return duplex_; }
inline bool input_reference() const { return input_reference_; }
inline int input_sample_rate() const { return input_sample_rate_; }
inline int output_sample_rate() const { return output_sample_rate_; }
inline int input_channels() const { return input_channels_; }
inline int output_channels() const { return output_channels_; }
inline int output_volume() const { return output_volume_; }
inline float input_gain() const { return input_gain_; }
inline bool input_enabled() const { return input_enabled_; }
inline bool output_enabled() const { return output_enabled_; }
protected:
i2s_chan_handle_t tx_handle_ = nullptr;
i2s_chan_handle_t rx_handle_ = nullptr;
bool duplex_ = false;
bool input_reference_ = false;
bool input_enabled_ = false;
bool output_enabled_ = false;
int input_sample_rate_ = 0;
int output_sample_rate_ = 0;
int input_channels_ = 1;
int output_channels_ = 1;
int output_volume_ = 70;
float input_gain_ = 0.0;
virtual int Read(int16_t* dest, int samples) = 0;
virtual int Write(const int16_t* data, int samples) = 0;
};
#endif // _AUDIO_CODEC_H

341
main/audio/audio_prompt.cc Normal file
View File

@@ -0,0 +1,341 @@
#include "audio_prompt.h"
#include "audio_prompts_data.h"
#include "protocols/protocol.h"
#include <esp_log.h>
#include <esp_random.h>
#include <cstring>
#define TAG "AudioPrompt"
struct PromptGroupInfo {
const uint8_t** files;
const size_t* sizes;
int count;
};
static PromptGroupInfo GetGroupInfo(PromptGroup group)
{
PromptGroupInfo info = {nullptr, nullptr, 0};
switch (group) {
case kPromptWelcome:
info.files = audio_welcome_files;
info.sizes = audio_welcome_sizes;
info.count = audio_welcome_count;
break;
case kPromptShutdown:
info.files = audio_shutdown_files;
info.sizes = audio_shutdown_sizes;
info.count = audio_shutdown_count;
break;
case kPromptNoNetwork:
info.files = audio_no_network_files;
info.sizes = audio_no_network_sizes;
info.count = audio_no_network_count;
break;
case kPromptError:
info.files = audio_error_files;
info.sizes = audio_error_sizes;
info.count = audio_error_count;
break;
case kPromptWifiConfig:
info.files = audio_wifi_config_files;
info.sizes = audio_wifi_config_sizes;
info.count = audio_wifi_config_count;
break;
case kPromptAlarmSet:
info.files = audio_alarm_set_files;
info.sizes = audio_alarm_set_sizes;
info.count = audio_alarm_set_count;
break;
case kPromptAlarmWake:
info.files = audio_alarm_wake_files;
info.sizes = audio_alarm_wake_sizes;
info.count = audio_alarm_wake_count;
break;
case kPromptDeviceAlreadyBound:
info.files = audio_device_already_bound_files;
info.sizes = audio_device_already_bound_sizes;
info.count = audio_device_already_bound_count;
break;
case kPromptBoot:
info.files = audio_boot_files;
info.sizes = audio_boot_sizes;
info.count = audio_boot_count;
break;
case kPromptServerError:
info.files = audio_server_error_files;
info.sizes = audio_server_error_sizes;
info.count = audio_server_error_count;
break;
case kPromptStoryExpired:
info.files = audio_story_expired_files;
info.sizes = audio_story_expired_sizes;
info.count = audio_story_expired_count;
break;
case kPromptWakeResponse:
info.files = audio_wake_response_files;
info.sizes = audio_wake_response_sizes;
info.count = audio_wake_response_count;
break;
case kPromptIdleCheck:
info.files = audio_idle_check_files;
info.sizes = audio_idle_check_sizes;
info.count = audio_idle_check_count;
break;
case kPromptIdleGoodbye:
info.files = audio_idle_goodbye_files;
info.sizes = audio_idle_goodbye_sizes;
info.count = audio_idle_goodbye_count;
break;
case kPromptWifiSuccess:
info.files = audio_wifi_success_files;
info.sizes = audio_wifi_success_sizes;
info.count = audio_wifi_success_count;
break;
case kPromptLowBattery20:
info.files = audio_low_battery_20_files;
info.sizes = audio_low_battery_20_sizes;
info.count = audio_low_battery_20_count;
break;
case kPromptLowBattery10:
info.files = audio_low_battery_10_files;
info.sizes = audio_low_battery_10_sizes;
info.count = audio_low_battery_10_count;
break;
case kPromptActivationDevice:
info.files = audio_activation_device_files;
info.sizes = audio_activation_device_sizes;
info.count = audio_activation_device_count;
break;
case kPromptDigit0:
info.files = audio_digit_0_files;
info.sizes = audio_digit_0_sizes;
info.count = audio_digit_0_count;
break;
case kPromptDigit1:
info.files = audio_digit_1_files;
info.sizes = audio_digit_1_sizes;
info.count = audio_digit_1_count;
break;
case kPromptDigit2:
info.files = audio_digit_2_files;
info.sizes = audio_digit_2_sizes;
info.count = audio_digit_2_count;
break;
case kPromptDigit3:
info.files = audio_digit_3_files;
info.sizes = audio_digit_3_sizes;
info.count = audio_digit_3_count;
break;
case kPromptDigit4:
info.files = audio_digit_4_files;
info.sizes = audio_digit_4_sizes;
info.count = audio_digit_4_count;
break;
case kPromptDigit5:
info.files = audio_digit_5_files;
info.sizes = audio_digit_5_sizes;
info.count = audio_digit_5_count;
break;
case kPromptDigit6:
info.files = audio_digit_6_files;
info.sizes = audio_digit_6_sizes;
info.count = audio_digit_6_count;
break;
case kPromptDigit7:
info.files = audio_digit_7_files;
info.sizes = audio_digit_7_sizes;
info.count = audio_digit_7_count;
break;
case kPromptDigit8:
info.files = audio_digit_8_files;
info.sizes = audio_digit_8_sizes;
info.count = audio_digit_8_count;
break;
case kPromptDigit9:
info.files = audio_digit_9_files;
info.sizes = audio_digit_9_sizes;
info.count = audio_digit_9_count;
break;
}
return info;
}
bool AudioPrompt::HasPrompts(PromptGroup group) const
{
auto info = GetGroupInfo(group);
return info.count > 0;
}
int AudioPrompt::GetFrameCount(PromptGroup group, int index) const
{
auto info = GetGroupInfo(group);
if (info.count <= 0 || index < 0 || index >= info.count) return 0;
const uint8_t* data = info.files[index];
if (!data) return 0;
// Header layout produced by gen_audio_prompts.py:
// [num_frames:u16 LE][frame_size:u16 LE, frame_data:bytes]...
return data[0] | (data[1] << 8);
}
struct PlayTaskParams {
AudioPrompt* self;
const uint8_t* data;
size_t size;
AudioService* audio;
int generation; // captured at xTaskCreate time
};
static void PlayTask(void* arg)
{
auto* params = static_cast<PlayTaskParams*>(arg);
// NOTE: BeginNewPlayback is now called *synchronously* by the caller
// (PlayByIndex / PlayRandom) before xTaskCreate. Doing it here used to
// race with wake-word-triggered ResetDecoder: a wake word fired after
// PlayLocal scheduled this task would set cancelled=true, then this
// BeginNewPlayback would clear it, swallowing the abort.
params->self->PlayEmbeddedOpus(params->data, params->size, *params->audio,
params->generation);
delete params;
vTaskDelete(nullptr);
}
bool AudioPrompt::PlayByIndex(PromptGroup group, int index, AudioService& audio)
{
auto info = GetGroupInfo(group);
if (info.count <= 0) return false;
if (index < 0 || index >= info.count) {
return PlayRandom(group, audio);
}
ESP_LOGI(TAG, "Playing prompt group=%d, index=%d/%d (by index)", group, index, info.count);
// Clear any stale cancel flag from a previous prompt that was aborted.
// Must happen synchronously, before scheduling PlayTask, otherwise a
// wake-word interrupt landing between here and the task starting would
// be undone by the old in-task BeginNewPlayback.
audio.BeginNewPlayback();
int gen = audio.CurrentPlaybackGeneration();
auto* params = new PlayTaskParams{this, info.files[index], info.sizes[index], &audio, gen};
xTaskCreate(PlayTask, "audio_prompt", 4096, params, 3, nullptr);
return true;
}
bool AudioPrompt::PlayRandom(PromptGroup group, AudioService& audio)
{
auto info = GetGroupInfo(group);
if (info.count <= 0) return false;
int idx = esp_random() % info.count;
ESP_LOGI(TAG, "Playing prompt group=%d, index=%d/%d", group, idx, info.count);
// See PlayByIndex comment — BeginNewPlayback must be synchronous so a
// subsequent ResetDecoder (e.g. from wake word) survives until consumed.
audio.BeginNewPlayback();
int gen = audio.CurrentPlaybackGeneration();
// Run in a separate task to avoid blocking the main event loop
auto* params = new PlayTaskParams{this, info.files[idx], info.sizes[idx], &audio, gen};
xTaskCreate(PlayTask, "audio_prompt", 4096, params, 3, nullptr);
return true;
}
namespace {
void SendPlayLocalSignal(Protocol* protocol, const char* state, const std::string& group) {
// 验证假设:暂时禁用 play_local start/done 消息上报。
// 日志显示本地音频播完后发 "done" 60 字节小消息会正好落在 ML307 radio
// 刚进 idle 的窗口,MIPSEND 连续失败触发 WS 断连 + 4G 反注册。
// 原版 xiaozhi 没有 play_local 机制,所以没这个断连触发器。
// 如果禁用后 4G 能稳定 2 分钟以上,说明根因确认。
ESP_LOGI("PlayLocal", "[DISABLED] skip sending play_local state=%s group=%s",
state, group.c_str());
(void)protocol;
}
}
bool AudioPrompt::PlayLocal(PromptGroup group, AudioService& audio,
Protocol* protocol, const std::string& group_name)
{
// 1. Tell server first so it stops pushing TTS/music frames ASAP.
SendPlayLocalSignal(protocol, "start", group_name);
// 2. Clear any residual frames from a previous stream (e.g. stale TTS
// during reconnect). PlayTask will re-arm the cancel flag on startup.
audio.ResetDecoder();
// 3. Launch the local playback (async PlayTask internally).
bool ok = PlayRandom(group, audio);
if (!ok) {
// Playback failed to start — emit done immediately so server doesn't
// hang in "speaking" state forever.
SendPlayLocalSignal(protocol, "done", group_name);
}
// Caller must call NotifyLocalDone() after WaitForPlaybackComplete.
return ok;
}
bool AudioPrompt::PlayLocalByIndex(PromptGroup group, int index, AudioService& audio,
Protocol* protocol, const std::string& group_name)
{
SendPlayLocalSignal(protocol, "start", group_name);
audio.ResetDecoder();
bool ok = PlayByIndex(group, index, audio);
if (!ok) {
SendPlayLocalSignal(protocol, "done", group_name);
}
return ok;
}
void AudioPrompt::NotifyLocalDone(Protocol* protocol, const std::string& group_name)
{
SendPlayLocalSignal(protocol, "done", group_name);
}
bool AudioPrompt::PlayEmbeddedOpus(const uint8_t* data, size_t size, AudioService& audio,
int my_generation)
{
if (!data || size < 2) return false;
// Parse format: [num_frames:u16][frame_size:u16, frame_data:bytes]...
size_t pos = 0;
uint16_t num_frames = data[pos] | (data[pos+1] << 8);
pos += 2;
ESP_LOGI(TAG, "Playing %d Opus frames (%zu bytes), gen=%d",
num_frames, size, my_generation);
for (uint16_t i = 0; i < num_frames && pos + 2 <= size; i++) {
// Abort if caller signalled cancel (e.g. wake word interrupt, or
// a new playback preempted via ResetDecoder). Without this check the
// task keeps pushing frames even after the queue was cleared.
if (audio.IsPlaybackCancelled()) {
ESP_LOGI(TAG, "Playback cancelled at frame %u/%u (gen=%d)",
i, num_frames, my_generation);
return false;
}
// Generation guard — a newer Reset+BeginNewPlayback cycle started.
// Cancel flag may already have been re-cleared to false by the new
// BeginNewPlayback, so cancel-only check would let us keep pushing
// and corrupt the new playback. Generation never decreases.
if (audio.CurrentPlaybackGeneration() != my_generation) {
ESP_LOGI(TAG, "Generation changed (mine=%d cur=%d) at frame %u/%u — exit",
my_generation, audio.CurrentPlaybackGeneration(), i, num_frames);
return false;
}
uint16_t frame_size = data[pos] | (data[pos+1] << 8);
pos += 2;
if (pos + frame_size > size) break;
auto pkt = std::make_unique<AudioStreamPacket>();
pkt->sample_rate = 24000;
pkt->frame_duration = 20;
pkt->timestamp = i * 20;
pkt->payload.assign(data + pos, data + pos + frame_size);
audio.PushPacketToDecodeQueue(std::move(pkt));
pos += frame_size;
// Feed at playback rate: each frame is ~20ms, delay every frame
vTaskDelay(pdMS_TO_TICKS(18));
}
return true;
}

92
main/audio/audio_prompt.h Normal file
View File

@@ -0,0 +1,92 @@
#pragma once
#include "audio_service.h"
#include <cstdint>
#include <string>
class Protocol; // fwd-decl to avoid pulling protocol.h
enum PromptGroup {
kPromptWelcome,
kPromptShutdown,
kPromptNoNetwork,
kPromptError,
kPromptWifiConfig,
kPromptAlarmSet,
kPromptAlarmWake,
kPromptDeviceAlreadyBound,
kPromptBoot, // 长按开机 - 立即播放,不等 WebSocket
kPromptServerError, // 服务器连接失败(404 / 超时)
kPromptStoryExpired, // 故事断点过期提示
kPromptWakeResponse, // 唤醒应答 - 每次 wake word 触发后播放("我在。")
kPromptIdleCheck, // 空闲提醒 - T+3min 无活动时播放("你还在吗?小朋友")
kPromptIdleGoodbye, // 空闲告别 - T+10min 无活动时播放("那我先退下来…"),播完进 light sleep
kPromptWifiSuccess, // 配网成功 - BLE 配网联通 WiFi 瞬间播放("配网成功啦。")
kPromptLowBattery20, // 低电量提醒 - 电量降到 20% 时播放(每 10 分钟提醒一次)
kPromptLowBattery10, // 低电量关机 - 电量降到 10% 时播放后关机
// Activation-code sequence playback: spoken prompt + per-digit OGGs
kPromptActivationDevice,
kPromptDigit0,
kPromptDigit1,
kPromptDigit2,
kPromptDigit3,
kPromptDigit4,
kPromptDigit5,
kPromptDigit6,
kPromptDigit7,
kPromptDigit8,
kPromptDigit9,
};
class AudioPrompt {
public:
// Check if local prompts are available
bool HasPrompts(PromptGroup group) const;
// Play a random prompt from the group through the audio pipeline
bool PlayRandom(PromptGroup group, AudioService& audio);
// Play a specific prompt by index (0-based). Falls back to PlayRandom if index invalid.
bool PlayByIndex(PromptGroup group, int index, AudioService& audio);
// Parse num_frames from the embedded-opus header so callers can derive
// playback duration (each frame = 20ms audio). Returns 0 on invalid
// group/index — caller must skip that item.
int GetFrameCount(PromptGroup group, int index) const;
// Parse embedded Opus frames and push to decode queue. `my_generation` is
// captured at task launch (right after BeginNewPlayback bumped it) and
// checked each frame; mismatch with AudioService::CurrentPlaybackGeneration
// means a newer playback cycle started and this task must self-exit.
bool PlayEmbeddedOpus(const uint8_t* data, size_t size, AudioService& audio,
int my_generation);
// === ADR-004 anti-mixing: unified local playback with server signalling ===
//
// PlayLocal wraps PlayRandom/PlayByIndex and sends
// {"type":"play_local","state":"start","group":"<name>"}
// to the server so the server can stop any in-flight TTS / music stream,
// preventing overlap with the local OGG. Caller must call NotifyDone()
// after WaitForPlaybackComplete (PlayTask is async, so "done" must be
// emitted on completion, not here).
//
// If protocol is null or WS not open, falls back silently to PlayRandom —
// the local prompt still plays, just without the server hand-shake. This
// covers boot prompt / connection-failure prompts where WS doesn't exist
// yet (no server in flight = no mixing risk anyway).
//
// group_name: the string server would see (e.g. "welcome", "alarm_wake").
// Must match the PromptGroup argument semantically — used only for the
// server message body.
bool PlayLocal(PromptGroup group, AudioService& audio,
Protocol* protocol, const std::string& group_name);
// Variant that picks a specific index inside the group.
bool PlayLocalByIndex(PromptGroup group, int index, AudioService& audio,
Protocol* protocol, const std::string& group_name);
// Send the "done" notification. Must be called by the caller after
// WaitForPlaybackComplete or equivalent, so server unlocks TTS lane.
// Safe to call with null/closed protocol (no-op).
void NotifyLocalDone(Protocol* protocol, const std::string& group_name);
};

File diff suppressed because it is too large Load Diff

1184
main/audio/audio_service.cc Normal file

File diff suppressed because it is too large Load Diff

210
main/audio/audio_service.h Normal file
View File

@@ -0,0 +1,210 @@
#pragma once
#include "audio_codec.h"
#include "wake_word.h"
#include "voice_processor.h"
#include <opus_encoder.h>
#include <opus_decoder.h>
#include <opus_resampler.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <functional>
#include <memory>
#include <deque>
#include <mutex>
#include <condition_variable>
#include <vector>
#include <atomic>
#define OPUS_FRAME_DURATION_MS 60
// 音频任务项
struct AudioTask {
enum Type { kEncode, kPlayback };
Type type;
std::vector<int16_t> pcm;
};
// 音频流包(与 Protocol 层交互)
struct AudioStreamPacket {
int sample_rate = 0;
int frame_duration = 0;
uint32_t timestamp = 0;
std::vector<uint8_t> payload;
};
struct AudioServiceCallbacks {
std::function<void()> on_send_queue_available;
// Fired by energy-threshold VAD (rough RMS detector) when sustained voice
// energy is observed. One-shot: VAD auto-disables after firing. Used by
// IdleWatchdog to detect "child responded" inside the post-prompt window.
std::function<void()> on_voice_detected;
};
// 音频服务:管理 3 个 FreeRTOS 任务实现音频采集 → Opus 编码 → 发送
// 接收 → Opus 解码 → 播放
class AudioService {
public:
void Initialize(AudioCodec* codec);
void Start();
void Stop();
void SetCallbacks(const AudioServiceCallbacks& callbacks);
// Play a generated tone through the speaker
// freq_hz: frequency, duration_ms: length, volume: 0.0-1.0
void PlayTone(int freq_hz, int duration_ms, float volume = 0.3f);
// Play predefined sound effects
void PlayBootSound();
void PlayShutdownSound();
void PlayConfigSound();
void PlayErrorSound();
// 上行:编码后的 Opus 包从发送队列弹出
std::unique_ptr<AudioStreamPacket> PopPacketFromSendQueue();
// 下行:收到 server Opus 音频包,入解码队列
void PushPacketToDecodeQueue(std::unique_ptr<AudioStreamPacket> packet);
// 播放控制
void SetPlaybackHint(bool playing);
void ResetDecoder();
// 2026-6-29 ckkj debug 获取解码、播放队列是否为空
void GetQueueEmptyStatus(bool& decode_empty, bool& play_empty);
// Clear the cancel flag and bump the generation counter before starting a
// new local prompt. Generation lets in-flight PlayTask from the previous
// iteration self-exit even if its cancel-flag check is racing against this
// BeginNewPlayback() (cancel may have been re-cleared to false before the
// old task wakes from vTaskDelay). Must be called right before
// xTaskCreate(PlayTask, ...).
void BeginNewPlayback() {
playback_cancelled_.store(false);
playback_generation_.fetch_add(1, std::memory_order_relaxed);
}
bool IsPlaybackCancelled() const { return playback_cancelled_.load(); }
int CurrentPlaybackGeneration() const {
return playback_generation_.load(std::memory_order_relaxed);
}
// 录音控制(语音处理开关)
void EnableVoiceProcessing(bool enable);
// Phone-call mode: enable AEC+NS+AGC on MIC path, with downlink PCM as
// the speaker reference signal. On enable the VoiceProcessor is lazy-
// initialized; on disable the processor is torn down and the reference
// queue cleared.
void EnableCallMode(bool enable);
bool IsCallModeEnabled() const { return call_mode_enabled_.load(); }
// TTS barge-in mode: keep MIC upload active during Speaking and reuse the
// VoiceProcessor/AEC reference path so the server can hear the child
// without treating the speaker's own TTS as speech.
void EnableBargeInMode(bool enable);
bool IsBargeInModeEnabled() const { return barge_in_mode_enabled_.load(); }
// 能量阈值粗 VAD(用于 IdleWatchdog 检测 15s 等待窗口内是否有声音)
// 一次性触发:on_voice_detected 回调后自动 disable,需重新 enable。
// 仅在 wake_word 或 voice_processing 已启用(MIC 在采集)时生效。
void EnableEnergyVad(bool enable);
bool IsEnergyVadEnabled() const { return energy_vad_enabled_.load(); }
// 唤醒词检测
bool InitWakeWord();
void EnableWakeWordDetection(bool enable);
bool IsWakeWordDetectionEnabled() const { return wake_word_enabled_.load(); }
WakeWordDetector& wake_word_detector() { return wake_word_detector_; }
bool IsIdle() const;
// Wait until decode and playback queues are empty (audio finished playing)
void WaitForPlaybackComplete(int timeout_ms);
private:
static void AudioInputTask(void* arg);
static void AudioOutputTask(void* arg);
static void OpusCodecTask(void* arg);
AudioCodec* codec_ = nullptr;
AudioServiceCallbacks callbacks_;
// Opus 编解码器
std::unique_ptr<OpusEncoderWrapper> opus_encoder_;
std::unique_ptr<OpusDecoderWrapper> opus_decoder_;
std::unique_ptr<OpusResampler> input_resampler_;
std::unique_ptr<OpusResampler> output_resampler_;
// Downsamples decoded downlink PCM (at decoder rate, typically 24k)
// to 16kHz for the AEC reference path. Only used in call mode.
std::unique_ptr<OpusResampler> aec_ref_resampler_;
// 队列(用 deque + mutex + cv 替代 FreeRTOS Queue,与 xiaozhi 对齐)
std::deque<std::unique_ptr<AudioTask>> encode_queue_;
std::mutex encode_mutex_;
std::condition_variable encode_cv_;
std::deque<std::unique_ptr<AudioStreamPacket>> decode_queue_;
std::mutex decode_mutex_;
std::condition_variable decode_cv_;
std::deque<std::unique_ptr<AudioStreamPacket>> send_queue_;
std::mutex send_mutex_;
std::deque<std::unique_ptr<AudioTask>> playback_queue_;
std::mutex playback_mutex_;
std::condition_variable playback_cv_;
// FreeRTOS 任务
TaskHandle_t input_task_ = nullptr;
TaskHandle_t output_task_ = nullptr;
TaskHandle_t codec_task_ = nullptr;
std::atomic<bool> running_{false};
std::atomic<bool> voice_processing_enabled_{false};
std::atomic<bool> wake_word_enabled_{false};
std::atomic<bool> playback_hint_{false};
std::atomic<bool> call_mode_enabled_{false}; // AEC+NS+AGC active when true
std::atomic<bool> barge_in_mode_enabled_{false};
std::atomic<bool> energy_vad_enabled_{false}; // Rough RMS-based VAD for IdleWatchdog
int vad_consecutive_frames_ = 0;
// Voice processing pipeline for phone-call mode. Lazy-inited on first
// EnableCallMode(true); torn down on EnableCallMode(false).
std::mutex voice_processor_mutex_;
std::unique_ptr<VoiceProcessor> voice_processor_;
// Reference PCM queue — 16kHz mono int16 frames written by AudioOutputTask
// when downlink audio is actually sent to the speaker, then consumed by
// AudioInputTask paired with freshly-captured MIC PCM for AEC.
// Keeping this tied to real playback timing avoids feeding the canceller
// an early reference while frames are still buffered in playback_queue_.
std::deque<std::vector<int16_t>> aec_ref_queue_;
std::mutex aec_ref_mutex_;
static constexpr size_t kMaxAecRefFrames = 10; // ~600ms buffer
// Encoder accumulator for call mode. VoiceProcessor emits chunks whose
// size depends on AEC/NS alignment (not 60ms). This buffer collects
// clean PCM and hands it to OpusEncoder in fixed 960-sample (60ms@16k)
// frames. Only used in call mode — the non-call path sends raw 60ms
// frames directly.
std::vector<int16_t> vp_encoder_acc_;
// Set true by ResetDecoder; PlayEmbeddedOpus (audio_prompt) checks it each
// frame and breaks early so the local-prompt task stops re-filling the
// queue after an abort (e.g. wake-word interrupt during alarm ringing).
std::atomic<bool> playback_cancelled_{false};
// Bumped by BeginNewPlayback. Each PlayTask captures the value at start
// and self-exits when CurrentPlaybackGeneration() != captured value —
// immune to the cancel-flag race in tight Reset→BeginNew sequences.
std::atomic<int> playback_generation_{0};
WakeWordDetector wake_word_detector_;
std::vector<int16_t> wake_word_buffer_;
static constexpr int kInputSampleRate = 16000;
static constexpr int kMaxEncodeQueueSize = 2;
static constexpr int kMaxDecodeQueueSize = 40; // 2400ms / 60ms
static constexpr int kMaxSendQueueSize = 40;
static constexpr int kMaxPlaybackQueueSize = 8;
};

View File

@@ -0,0 +1,301 @@
#include "es8311_audio_codec.h"
#include <vector>
#include <esp_log.h>
#define TAG "Es8311AudioCodec"
Es8311AudioCodec::Es8311AudioCodec(void* i2c_master_handle, i2c_port_t i2c_port, int input_sample_rate, int output_sample_rate,
gpio_num_t mclk, gpio_num_t bclk, gpio_num_t ws, gpio_num_t dout, gpio_num_t din,
gpio_num_t pa_pin, uint8_t es8311_addr, bool use_mclk, bool pa_inverted) {
duplex_ = true; // 是否双工
input_reference_ = false; // 是否使用参考输入,实现回声消除
input_channels_ = 1; // 输入通道数
input_sample_rate_ = input_sample_rate;
output_sample_rate_ = output_sample_rate;
pa_pin_ = pa_pin;
pa_inverted_ = pa_inverted;
input_gain_ = 30;
assert(input_sample_rate_ == output_sample_rate_);
CreateDuplexChannels(mclk, bclk, ws, dout, din);
// Do initialize of related interface: data_if, ctrl_if and gpio_if
audio_codec_i2s_cfg_t i2s_cfg = {
.port = I2S_NUM_0,
.rx_handle = rx_handle_,
.tx_handle = tx_handle_,
};
data_if_ = audio_codec_new_i2s_data(&i2s_cfg);
assert(data_if_ != NULL);
// Output
audio_codec_i2c_cfg_t i2c_cfg = {
.port = i2c_port,
.addr = es8311_addr,
.bus_handle = i2c_master_handle,
};
ctrl_if_ = audio_codec_new_i2c_ctrl(&i2c_cfg);
assert(ctrl_if_ != NULL);
gpio_if_ = audio_codec_new_gpio();
assert(gpio_if_ != NULL);
es8311_codec_cfg_t es8311_cfg = {};
es8311_cfg.ctrl_if = ctrl_if_;
es8311_cfg.gpio_if = gpio_if_;
es8311_cfg.codec_mode = ESP_CODEC_DEV_WORK_MODE_BOTH;
es8311_cfg.pa_pin = pa_pin;
es8311_cfg.use_mclk = use_mclk;
es8311_cfg.hw_gain.pa_voltage = 5.0;
es8311_cfg.hw_gain.codec_dac_voltage = 3.3;
es8311_cfg.pa_reverted = pa_inverted_;
codec_if_ = es8311_codec_new(&es8311_cfg);
if (codec_if_ == nullptr) {
ESP_LOGE(TAG, "Failed to create Es8311AudioCodec");
} else {
ESP_LOGI(TAG, "Es8311AudioCodec initialized");
}
}
Es8311AudioCodec::~Es8311AudioCodec() {
esp_codec_dev_delete(dev_);
audio_codec_delete_codec_if(codec_if_);
audio_codec_delete_ctrl_if(ctrl_if_);
audio_codec_delete_gpio_if(gpio_if_);
audio_codec_delete_data_if(data_if_);
}
void Es8311AudioCodec::UpdateDeviceState() {
if ((input_enabled_ || output_enabled_) && dev_ == nullptr) {
esp_codec_dev_cfg_t dev_cfg = {
.dev_type = ESP_CODEC_DEV_TYPE_IN_OUT,
.codec_if = codec_if_,
.data_if = data_if_,
};
dev_ = esp_codec_dev_new(&dev_cfg);
assert(dev_ != NULL);
esp_codec_dev_sample_info_t fs = {
.bits_per_sample = 16,
.channel = 1,
.channel_mask = 0,
.sample_rate = (uint32_t)input_sample_rate_,
.mclk_multiple = 0,
};
esp_err_t err = esp_codec_dev_open(dev_, &fs);
if (err != ESP_OK) {
if (!device_open_error_reported_) {
ESP_LOGE(TAG, "Failed to open ES8311 codec device: %s", esp_err_to_name(err));
device_open_error_reported_ = true;
}
esp_codec_dev_delete(dev_);
dev_ = nullptr;
return;
}
err = esp_codec_dev_set_in_gain(dev_, input_gain_);
if (err != ESP_OK) {
if (!device_open_error_reported_) {
ESP_LOGE(TAG, "Failed to set ES8311 input gain: %s", esp_err_to_name(err));
device_open_error_reported_ = true;
}
esp_codec_dev_close(dev_);
esp_codec_dev_delete(dev_);
dev_ = nullptr;
return;
}
// Always pin the hardware DAC at 100% so software gain in Write()
// gets the full output headroom. SetOutputVolume() never re-touches
// the hardware DAC — it only updates output_volume_ used by the
// software gain. If we wrote NVS-cached value here, vol later set to
// 100 would max software gain but hit a hardware ceiling, sounding
// identical to vol=70.
err = esp_codec_dev_set_out_vol(dev_, 100);
if (err != ESP_OK) {
if (!device_open_error_reported_) {
ESP_LOGE(TAG, "Failed to set ES8311 output volume: %s", esp_err_to_name(err));
device_open_error_reported_ = true;
}
esp_codec_dev_close(dev_);
esp_codec_dev_delete(dev_);
dev_ = nullptr;
return;
}
} else if (!input_enabled_ && !output_enabled_ && dev_ != nullptr) {
esp_codec_dev_close(dev_);
dev_ = nullptr;
}
if (pa_pin_ != GPIO_NUM_NC) {
int level = output_enabled_ ? 1 : 0;
gpio_set_level(pa_pin_, pa_inverted_ ? !level : level);
}
if (dev_ != nullptr && device_open_error_reported_) {
device_open_error_reported_ = false;
}
}
void Es8311AudioCodec::CreateDuplexChannels(gpio_num_t mclk, gpio_num_t bclk, gpio_num_t ws, gpio_num_t dout, gpio_num_t din) {
assert(input_sample_rate_ == output_sample_rate_);
i2s_chan_config_t chan_cfg = {
.id = I2S_NUM_0,
.role = I2S_ROLE_MASTER,
.dma_desc_num = AUDIO_CODEC_DMA_DESC_NUM,
.dma_frame_num = AUDIO_CODEC_DMA_FRAME_NUM,
.auto_clear_after_cb = true,
.auto_clear_before_cb = false,
.intr_priority = 0,
};
ESP_ERROR_CHECK(i2s_new_channel(&chan_cfg, &tx_handle_, &rx_handle_));
i2s_std_config_t std_cfg = {
.clk_cfg = {
.sample_rate_hz = (uint32_t)output_sample_rate_,
.clk_src = I2S_CLK_SRC_DEFAULT,
.mclk_multiple = I2S_MCLK_MULTIPLE_256,
#ifdef I2S_HW_VERSION_2
.ext_clk_freq_hz = 0,
#endif
},
.slot_cfg = {
.data_bit_width = I2S_DATA_BIT_WIDTH_16BIT,
.slot_bit_width = I2S_SLOT_BIT_WIDTH_AUTO,
.slot_mode = I2S_SLOT_MODE_MONO,
.slot_mask = I2S_STD_SLOT_LEFT,
.ws_width = I2S_DATA_BIT_WIDTH_16BIT,
.ws_pol = false,
.bit_shift = true,
#ifdef I2S_HW_VERSION_2
.left_align = true,
.big_endian = false,
.bit_order_lsb = false
#endif
},
.gpio_cfg = {
.mclk = mclk,
.bclk = bclk,
.ws = ws,
.dout = dout,
.din = din,
.invert_flags = {
.mclk_inv = false,
.bclk_inv = false,
.ws_inv = false
}
}
};
ESP_ERROR_CHECK(i2s_channel_init_std_mode(tx_handle_, &std_cfg));
ESP_ERROR_CHECK(i2s_channel_init_std_mode(rx_handle_, &std_cfg));
ESP_LOGI(TAG, "Duplex channels created");
}
void Es8311AudioCodec::SetOutputVolume(int volume) {
if (volume == output_volume_) return;
// Software volume scaling happens in Write(); just update member + NVS.
AudioCodec::SetOutputVolume(volume);
ESP_LOGI(TAG, "Output volume set to %d (software scaling)", volume);
}
//ALEX 重写
void Es8311AudioCodec::SetInputGain(float gain) {
std::lock_guard<std::mutex> lock(data_if_mutex_);
if (codec_if_ == nullptr) return;
if (gain == input_gain_) return;
AudioCodec::SetInputGain(gain); // 调用基类设置变量
UpdateDeviceState(); // 关键:更新硬件寄存器
ESP_LOGI(TAG, "ES8311 hardware gain set to %.1f", gain);
}
void Es8311AudioCodec::EnableInput(bool enable) {
std::lock_guard<std::mutex> lock(data_if_mutex_);
if (codec_if_ == nullptr) {
return;
}
if (enable == input_enabled_) {
return;
}
AudioCodec::EnableInput(enable);
UpdateDeviceState();
}
void Es8311AudioCodec::EnableOutput(bool enable) {
std::lock_guard<std::mutex> lock(data_if_mutex_);
if (codec_if_ == nullptr) {
return;
}
if (enable == output_enabled_) {
return;
}
AudioCodec::EnableOutput(enable);
UpdateDeviceState();
}
int Es8311AudioCodec::Read(int16_t* dest, int samples) {
if (input_enabled_) {
//2026-6-19 ckkj debug
if (dev_ == nullptr) {
ESP_LOGW(TAG, "Read called before codec device is ready; retrying");
UpdateDeviceState();
if (dev_ == nullptr) {
ESP_LOGW(TAG, "ES8311 input unavailable, dropping %d samples", samples);
return samples;
}
}
//end debug
ESP_ERROR_CHECK_WITHOUT_ABORT(esp_codec_dev_read(dev_, (void*)dest, samples * sizeof(int16_t)));
}
return samples;
}
int Es8311AudioCodec::Write(const int16_t* data, int samples) {
//if (!output_enabled_) return samples;
//2026-6-19 ckkj debug
if (!output_enabled_) {
ESP_LOGD(TAG, "Codec output disabled, skip write");
return samples;
}
if (dev_ == nullptr) {
ESP_LOGW(TAG, "Write called before codec device is ready; retrying");
UpdateDeviceState();
if (dev_ == nullptr) {
ESP_LOGW(TAG, "ES8311 output unavailable, dropping %d samples", samples);
return samples;
}
}
//end debug
if (data == nullptr || samples <= 0) {
return 0;
}
// Volume curve: linear software gain on top of a hardware DAC pinned at 100%.
// gain = output_volume_ / 100 (0..1.0)
// Hardware ceiling is the true 100% acoustic output; we never amplify
// beyond it, so vol=100 is the genuine maximum (no clipping/distortion).
if (output_volume_ <= 0) {
std::vector<int16_t> silence(samples, 0);
ESP_ERROR_CHECK_WITHOUT_ABORT(esp_codec_dev_write(dev_, silence.data(), samples * sizeof(int16_t)));
return samples;
}
int vol = output_volume_;
if (vol > 100) vol = 100;
float gain = static_cast<float>(vol) / 100.0f;
// Fixed-point: gain × 256 (range 0..256)
int32_t gain_fp = static_cast<int32_t>(gain * 256.0f);
std::vector<int16_t> scaled(samples);
for (int i = 0; i < samples; i++) {
int32_t s = (static_cast<int32_t>(data[i]) * gain_fp) >> 8;
// Clamp to int16 range
if (s > 32767) s = 32767;
if (s < -32768) s = -32768;
scaled[i] = static_cast<int16_t>(s);
}
ESP_ERROR_CHECK_WITHOUT_ABORT(esp_codec_dev_write(dev_, scaled.data(), samples * sizeof(int16_t)));
return samples;
}

View File

@@ -0,0 +1,44 @@
#ifndef _ES8311_AUDIO_CODEC_H
#define _ES8311_AUDIO_CODEC_H
#include "audio/audio_codec.h"
#include <driver/i2c_master.h>
#include <driver/gpio.h>
#include <esp_codec_dev.h>
#include <esp_codec_dev_defaults.h>
#include <mutex>
class Es8311AudioCodec : public AudioCodec {
private:
const audio_codec_data_if_t* data_if_ = nullptr;
const audio_codec_ctrl_if_t* ctrl_if_ = nullptr;
const audio_codec_if_t* codec_if_ = nullptr;
const audio_codec_gpio_if_t* gpio_if_ = nullptr;
esp_codec_dev_handle_t dev_ = nullptr;
gpio_num_t pa_pin_ = GPIO_NUM_NC;
bool pa_inverted_ = false;
bool device_open_error_reported_ = false;
std::mutex data_if_mutex_;
void CreateDuplexChannels(gpio_num_t mclk, gpio_num_t bclk, gpio_num_t ws, gpio_num_t dout, gpio_num_t din);
void UpdateDeviceState();
virtual int Read(int16_t* dest, int samples) override;
virtual int Write(const int16_t* data, int samples) override;
public:
Es8311AudioCodec(void* i2c_master_handle, i2c_port_t i2c_port, int input_sample_rate, int output_sample_rate,
gpio_num_t mclk, gpio_num_t bclk, gpio_num_t ws, gpio_num_t dout, gpio_num_t din,
gpio_num_t pa_pin, uint8_t es8311_addr, bool use_mclk = true, bool pa_inverted = false);
virtual ~Es8311AudioCodec();
//ALEX 重写
void SetInputGain(float gain) override;
virtual void SetOutputVolume(int volume) override;
virtual void EnableInput(bool enable) override;
virtual void EnableOutput(bool enable) override;
};
#endif // _ES8311_AUDIO_CODEC_H

View File

@@ -0,0 +1,254 @@
#include "voice_processor.h"
#include <esp_log.h>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#define TAG "VoiceProc"
// AEC filter length — recommended 4 for ESP32-S3 (see esp_afe_aec.h).
// Higher filter = better echo tail but more CPU.
static constexpr int AEC_FILTER_LENGTH_CALL = 4;
//static constexpr int AEC_FILTER_LENGTH_BARGE_IN = 4;
static constexpr int AEC_FILTER_LENGTH_BARGE_IN = 8;//(~128ms)能覆盖更长的回声路径
// NS pro frame length in ms. pro_create supports only 10ms.
// Renamed from kNsFrameLengthMs — esp_ns.h already uses that as a macro.
static constexpr int kNsFrameLengthMs = 10;
// AGC target envelope (normalized 0..1) and smoothing constants.
// Call audio should land near normal TTS loudness without boosting the room
// floor into a hiss. Track both peak and RMS: peak protects from clipping, RMS
// gates very low-level residual echo/noise.
static constexpr float AGC_TARGET_PEAK = 0.42f; // near -7.5 dBFS peak
static constexpr float AGC_MAX_GAIN = 6.0f; // enough for quiet child speech
//static constexpr float AGC_MAX_GAIN_BARGE_IN = 2.2f; // avoid boosting residual TTS echo
static constexpr float AGC_MIN_GAIN = 0.8f;
static constexpr float AGC_ENV_ATTACK = 0.45f; // fast reduction on loud peaks
static constexpr float AGC_ENV_RELEASE = 0.12f; // recover within ~1s, not 7s+
static constexpr float AGC_GAIN_SMOOTH = 0.18f; // responsive but not pumping
//static constexpr float NOISE_GATE_RMS = 0.006f; // -44 dBFS
//static constexpr float NOISE_GATE_PEAK = 0.018f; // -35 dBFS
static constexpr float NOISE_GATE_ATTENUATION = 0.20f;
//static constexpr float NOISE_GATE_ATTENUATION_BARGE_IN = 0.08f;
// 修改后,更激进地抑制低音量环境噪音
static constexpr float AGC_MAX_GAIN_BARGE_IN = 1.8f; // reduced to avoid boosting residual TTS echo
static constexpr float NOISE_GATE_RMS = 0.004f; // -48 dBFS,更激进的噪音门控
static constexpr float NOISE_GATE_PEAK = 0.015f; // -38 dBFS
static constexpr float NOISE_GATE_ATTENUATION_BARGE_IN = 0.05f; // barge-in模式更激
VoiceProcessor::VoiceProcessor() = default;
VoiceProcessor::~VoiceProcessor() { Deinit(); }
bool VoiceProcessor::Init(bool low_cost) {
if (aec_handle_) {
if (low_cost_mode_ == low_cost) return true; // already inited
Deinit();
}
low_cost_mode_ = low_cost;
const int filter_length = low_cost ? AEC_FILTER_LENGTH_BARGE_IN : AEC_FILTER_LENGTH_CALL;
// Barge-in is full-duplex human-device speech while TTS is playing.
// FD_LOW_COST is a better fit than VOIP_LOW_COST for this scenario and keeps
// CPU/memory lower than FD_HIGH_PERF.
const aec_mode_t mode = low_cost ? AEC_MODE_FD_LOW_COST : AEC_MODE_VOIP_HIGH_PERF;
// Single mic + single reference, 16kHz.
aec_handle_ = aec_create(16000, filter_length, 1, mode);
if (!aec_handle_) {
ESP_LOGE(TAG, "aec_create failed");
return false;
}
chunk_samples_ = aec_get_chunksize(aec_handle_);
if (chunk_samples_ <= 0) {
ESP_LOGE(TAG, "aec_get_chunksize returned %d", chunk_samples_);
aec_destroy(aec_handle_);
aec_handle_ = nullptr;
return false;
}
ns_frame_samples_ = 16 * kNsFrameLengthMs; // 160 samples @ 16kHz
if (!low_cost_mode_) {
ns_handle_ = ns_pro_create(kNsFrameLengthMs, /*mode=aggressive*/ 2, 16000);
if (!ns_handle_) {
ESP_LOGW(TAG, "ns_pro_create failed, continuing without NS");
}
} else {
// Barge-in runs inside the real-time audio input task while TTS is
// playing. WebRTC NS FFT processing has shown watchdog pressure on
// ESP32-S3 here, so keep the interrupt path to AEC + conservative
// AGC/gate only.
ns_handle_ = nullptr;
}
aec_out_chunk_.resize(chunk_samples_);
ns_out_chunk_.resize(ns_frame_samples_);
mic_acc_.reserve(chunk_samples_ * 2);
ref_acc_.reserve(chunk_samples_ * 2);
ns_in_acc_.reserve(ns_frame_samples_ * 2);
ESP_LOGI(TAG, "VoiceProcessor initialized: mode=%s, AEC chunk=%d, NS=%s frame=%d samples",
aec_get_mode_string(mode), chunk_samples_, ns_handle_ ? "on" : "off",
ns_frame_samples_);
return true;
}
void VoiceProcessor::Deinit() {
if (aec_handle_) {
aec_destroy(aec_handle_);
aec_handle_ = nullptr;
}
if (ns_handle_) {
ns_destroy(ns_handle_);
ns_handle_ = nullptr;
}
chunk_samples_ = 0;
ns_frame_samples_ = 0;
mic_acc_.clear();
ref_acc_.clear();
ns_in_acc_.clear();
mic_acc_pos_ = 0;
ref_acc_pos_ = 0;
ns_in_acc_pos_ = 0;
low_cost_mode_ = false;
envelope_ = 0.08f;
gain_ = 1.0f;
}
void VoiceProcessor::Reset() {
mic_acc_.clear();
ref_acc_.clear();
ns_in_acc_.clear();
mic_acc_pos_ = 0;
ref_acc_pos_ = 0;
ns_in_acc_pos_ = 0;
envelope_ = 0.08f;
gain_ = 1.0f;
}
bool VoiceProcessor::Process(const int16_t* mic, const int16_t* ref,
size_t samples, std::vector<int16_t>& out) {
if (!aec_handle_ || !mic || !ref) return false;
// Append this batch onto accumulators.
mic_acc_.insert(mic_acc_.end(), mic, mic + samples);
ref_acc_.insert(ref_acc_.end(), ref, ref + samples);
// Process AEC chunks while both accumulators hold enough. Use cursor
// offsets instead of vector.erase(begin...), which was moving most of the
// buffer several times per 60ms frame and could starve the idle task.
while (mic_acc_.size() - mic_acc_pos_ >= static_cast<size_t>(chunk_samples_) &&
ref_acc_.size() - ref_acc_pos_ >= static_cast<size_t>(chunk_samples_)) {
aec_process(aec_handle_,
mic_acc_.data() + mic_acc_pos_,
ref_acc_.data() + ref_acc_pos_,
aec_out_chunk_.data());
mic_acc_pos_ += chunk_samples_;
ref_acc_pos_ += chunk_samples_;
if (ns_handle_) {
// Hand AEC output to NS accumulator only when NS is active. In
// low-cost TTS barge-in mode NS is intentionally off; feeding this
// buffer there would grow it forever and eventually abort on OOM.
ns_in_acc_.insert(ns_in_acc_.end(),
aec_out_chunk_.begin(), aec_out_chunk_.end());
// NS processes 160-sample frames. AEC chunks are typically 256 so
// we'll usually run 1-2 NS frames per AEC chunk.
while (ns_in_acc_.size() - ns_in_acc_pos_ >= static_cast<size_t>(ns_frame_samples_)) {
ns_process(ns_handle_, ns_in_acc_.data() + ns_in_acc_pos_, ns_out_chunk_.data());
ApplyAgc(ns_out_chunk_.data(), ns_out_chunk_.size());
out.insert(out.end(),
ns_out_chunk_.begin(), ns_out_chunk_.end());
ns_in_acc_pos_ += ns_frame_samples_;
}
} else {
// Fallback: no NS available: push AEC output directly after AGC.
ApplyAgc(aec_out_chunk_.data(), aec_out_chunk_.size());
out.insert(out.end(),
aec_out_chunk_.begin(), aec_out_chunk_.end());
}
CompactAccumulatorsIfNeeded();
//2026-6-23 ckkj debug
vTaskDelay(1); // 让出 CPU 给 IDLE 任务,防止 Task Watchdog 触发
}
return true;
}
void VoiceProcessor::CompactAccumulatorsIfNeeded() {
const size_t compact_threshold =
static_cast<size_t>(chunk_samples_ > 0 ? chunk_samples_ * 4 : 1024);
if (mic_acc_pos_ > 0 &&
(mic_acc_pos_ >= compact_threshold || mic_acc_pos_ * 2 >= mic_acc_.size())) {
mic_acc_.erase(mic_acc_.begin(), mic_acc_.begin() + mic_acc_pos_);
mic_acc_pos_ = 0;
}
if (ref_acc_pos_ > 0 &&
(ref_acc_pos_ >= compact_threshold || ref_acc_pos_ * 2 >= ref_acc_.size())) {
ref_acc_.erase(ref_acc_.begin(), ref_acc_.begin() + ref_acc_pos_);
ref_acc_pos_ = 0;
}
const size_t ns_threshold =
static_cast<size_t>(ns_frame_samples_ > 0 ? ns_frame_samples_ * 8 : 1024);
if (ns_in_acc_pos_ > 0 &&
(ns_in_acc_pos_ >= ns_threshold || ns_in_acc_pos_ * 2 >= ns_in_acc_.size())) {
ns_in_acc_.erase(ns_in_acc_.begin(), ns_in_acc_.begin() + ns_in_acc_pos_);
ns_in_acc_pos_ = 0;
}
}
void VoiceProcessor::ApplyAgc(int16_t* samples, size_t n) {
// Update envelope from peak of this block and compute RMS for a very
// conservative residual-noise gate.
int16_t peak = 0;
int64_t sum_sq = 0;
for (size_t i = 0; i < n; ++i) {
int32_t v = samples[i];
int32_t a32 = v < 0 ? -v : v;
int16_t a = a32 > 32767 ? 32767 : static_cast<int16_t>(a32);
if (a > peak) peak = a;
sum_sq += v * v;
}
float peak_norm = peak / 32768.0f;
float rms_norm = 0.0f;
if (n > 0) {
rms_norm = sqrtf(static_cast<float>(sum_sq) / static_cast<float>(n)) / 32768.0f;
}
// If AEC/NS leaves only very low-level residue, attenuate it and avoid
// letting AGC turn it into audible hiss when two devices are close.
if (rms_norm < NOISE_GATE_RMS && peak_norm < NOISE_GATE_PEAK) {
float attenuation = low_cost_mode_ ? NOISE_GATE_ATTENUATION_BARGE_IN : NOISE_GATE_ATTENUATION;
for (size_t i = 0; i < n; ++i) {
samples[i] = static_cast<int16_t>(samples[i] * attenuation);
}
return;
}
// Asymmetric envelope tracker: fast attack, slow release
float alpha = (peak_norm > envelope_) ? AGC_ENV_ATTACK : AGC_ENV_RELEASE;
envelope_ += alpha * (peak_norm - envelope_);
if (envelope_ < 0.01f) envelope_ = 0.01f; // avoid div-by-zero + noise boost
// Target gain so envelope reaches AGC_TARGET_PEAK
float target_gain = AGC_TARGET_PEAK / envelope_;
float max_gain = low_cost_mode_ ? AGC_MAX_GAIN_BARGE_IN : AGC_MAX_GAIN;
if (target_gain > max_gain) target_gain = max_gain;
if (target_gain < AGC_MIN_GAIN) target_gain = AGC_MIN_GAIN;
// Smooth gain changes (prevent pumping / breathing artefacts)
gain_ += AGC_GAIN_SMOOTH * (target_gain - gain_);
// Apply with hard limiter clip
for (size_t i = 0; i < n; ++i) {
float v = samples[i] * gain_;
if (v > 32767.0f) v = 32767.0f;
if (v < -32768.0f) v = -32768.0f;
samples[i] = static_cast<int16_t>(v);
}
}

View File

@@ -0,0 +1,92 @@
#pragma once
/**
* Voice processing front-end for phone-call mode.
*
* Chain (16kHz mono int16):
* MIC ─┐
* ├─→ AEC (VOIP_HIGH_PERF, filter_length=4) ─→ NS (pro, aggressive) ─→ AGC (soft) ─→ clean PCM
* REF ─┘
*
* AEC_MODE_VOIP_HIGH_PERF already includes nonlinear residual echo
* suppression — the explicit NS step on top is mainly for ambient noise
* (kid-voice / room hum), not echo. AGC is a simple envelope normalizer in
* software (ESP-SR's AGC API is coarse; children voice amplitude swing is
* better handled by a gentle limiter).
*
* Chunk handling: AEC has a fixed internal chunk size (typically 256 samples
* @ 16kHz). The input and reference buffers for one Process() call can be of
* any length; unprocessed tail samples are held in internal accumulators and
* processed on the next call.
*/
#include <cstddef>
#include <cstdint>
#include <memory>
#include <vector>
#include "esp_aec.h"
#include "esp_ns.h"
class VoiceProcessor {
public:
VoiceProcessor();
~VoiceProcessor();
// Initialize AEC and AGC. Call mode also enables NS; barge-in keeps NS off
// to reduce CPU on the audio input path.
// Safe to call multiple times; second call is a no-op if already inited.
bool Init(bool low_cost = false);
// Free all allocated resources. Safe to call repeatedly.
void Deinit();
bool IsReady() const { return aec_handle_ != nullptr; }
bool IsLowCostMode() const { return low_cost_mode_; }
// AEC's fixed chunk size in samples (at 16kHz). 0 if not inited.
int ChunkSamples() const { return chunk_samples_; }
// Process one batch of mic + reference PCM (both 16kHz mono int16, equal
// length required). Clean output is appended to `out` (length depends on
// chunk alignment — unprocessed tail is buffered for next call).
//
// Returns false if not initialized or sizes mismatch.
bool Process(const int16_t* mic, const int16_t* ref, size_t samples,
std::vector<int16_t>& out);
// Clear internal accumulators. Call when entering/leaving call mode.
void Reset();
private:
aec_handle_t* aec_handle_ = nullptr;
ns_handle_t ns_handle_ = nullptr;
bool low_cost_mode_ = false;
int chunk_samples_ = 0; // AEC chunk size in samples (e.g. 256)
int ns_frame_samples_ = 0; // NS pro requires 10ms = 160 samples @ 16kHz
// Accumulators for chunk alignment. AEC reads N=chunk_samples_ at a time;
// any leftover from a partial Process() stays here until next call.
std::vector<int16_t> mic_acc_;
std::vector<int16_t> ref_acc_;
size_t mic_acc_pos_ = 0;
size_t ref_acc_pos_ = 0;
// NS operates on a different chunk (160 samples). Second-stage accumulator
// sits between AEC output and NS input.
std::vector<int16_t> ns_in_acc_;
size_t ns_in_acc_pos_ = 0;
// Pre-allocated scratch buffers for one chunk — avoid per-call alloc.
std::vector<int16_t> aec_out_chunk_;
std::vector<int16_t> ns_out_chunk_;
// Soft AGC state: simple envelope tracker + gain smoother.
float envelope_ = 1.0f; // EMA of recent sample peak
float gain_ = 1.0f; // current applied gain
// Apply soft AGC in-place on `samples`. Gain moves slowly toward a target
// that keeps peak envelope near ~0.3 * full-scale (10kRMS).
void ApplyAgc(int16_t* samples, size_t n);
void CompactAccumulatorsIfNeeded();
};

71
main/audio/wake_word.cc Normal file
View File

@@ -0,0 +1,71 @@
#include "wake_word.h"
#include <esp_log.h>
#include <esp_wn_iface.h>
#include <esp_wn_models.h>
#include <model_path.h>
#include <cstring>
#define TAG "WakeWord"
bool WakeWordDetector::Initialize()
{
srmodel_list_t* models = esp_srmodel_init("model");
if (!models) {
ESP_LOGE(TAG, "Failed to init SR models");
return false;
}
// Find the custom wake word model (你好播乐 = ni3hao3bo1le4)
char* model_name = esp_srmodel_filter(models, ESP_WN_PREFIX, "ni3hao3bo1le4");
if (!model_name) {
// Fallback: use any available wake word model
model_name = esp_srmodel_filter(models, ESP_WN_PREFIX, NULL);
}
if (!model_name) {
ESP_LOGE(TAG, "No wake word model found");
return false;
}
ESP_LOGI(TAG, "Using wake word model: %s", model_name);
const esp_wn_iface_t* iface = esp_wn_handle_from_name(model_name);
if (!iface) {
ESP_LOGE(TAG, "Failed to get WakeNet interface");
return false;
}
wakenet_iface_ = iface;
wakenet_handle_ = iface->create(model_name, DET_MODE_90);
if (!wakenet_handle_) {
ESP_LOGE(TAG, "Failed to create WakeNet instance");
return false;
}
chunk_size_ = iface->get_samp_chunksize(static_cast<model_iface_data_t*>(wakenet_handle_));
int sample_rate = iface->get_samp_rate(static_cast<model_iface_data_t*>(wakenet_handle_));
ESP_LOGI(TAG, "WakeNet ready: chunk_size=%d, sample_rate=%d", chunk_size_, sample_rate);
initialized_ = true;
return true;
}
void WakeWordDetector::SetCallback(DetectedCallback callback)
{
callback_ = callback;
}
void WakeWordDetector::Feed(const int16_t* samples, int count)
{
if (!initialized_ || !wakenet_iface_ || !wakenet_handle_) return;
auto* iface = static_cast<const esp_wn_iface_t*>(wakenet_iface_);
int result = iface->detect(static_cast<model_iface_data_t*>(wakenet_handle_), const_cast<int16_t*>(samples));
if (result > 0) {
ESP_LOGI(TAG, "Wake word detected!");
if (callback_) {
callback_();
}
}
}

30
main/audio/wake_word.h Normal file
View File

@@ -0,0 +1,30 @@
#pragma once
#include <functional>
#include <atomic>
#include <cstdint>
/**
* WakeNet-based wake word detector.
* Feeds 16kHz PCM audio to ESP-SR WakeNet and triggers callback on detection.
*/
class WakeWordDetector {
public:
using DetectedCallback = std::function<void()>;
bool Initialize();
void SetCallback(DetectedCallback callback);
// Feed 16kHz 16-bit mono PCM samples. Caller must provide chunk_size() samples.
void Feed(const int16_t* samples, int count);
int chunk_size() const { return chunk_size_; }
bool is_initialized() const { return initialized_; }
private:
void* wakenet_handle_ = nullptr;
const void* wakenet_iface_ = nullptr;
DetectedCallback callback_;
int chunk_size_ = 0;
bool initialized_ = false;
};

586
main/ble/friend_exchange.cc Normal file
View File

@@ -0,0 +1,586 @@
/**
* BLE Friend Exchange — alternating advertise/scan for "BorlaF-*" devices.
*
* NimBLE cannot advertise and scan simultaneously (non-extended).
* Solution: use timed adv (2s) → on completion callback → timed scan (2s) → loop.
* NimBLE cleans up internally when duration expires, avoiding EBUSY race.
*/
#include "friend_exchange.h"
#include "system_info.h"
#include <esp_log.h>
#include <esp_timer.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <nimble/nimble_port.h>
#include <nimble/nimble_port_freertos.h>
#include <host/ble_hs.h>
#include <host/ble_gap.h>
#include <host/util/util.h>
#include <services/gap/ble_svc_gap.h>
// NimBLE os.h defines min/max macros that conflict with C++ <limits>
#undef min
#undef max
#include <atomic>
#include <map>
#include <mutex>
#include <string>
#include <cstring>
#include <algorithm>
#define TAG "FriendExch"
static constexpr int FRIEND_MODE_TIMEOUT_S = 30;
static constexpr int SCAN_LOG_INTERVAL_MS = 1000;
// Duration for each phase in milliseconds
static constexpr int ADV_DURATION_MS = 2000; // Advertise for 2 seconds
static constexpr int SCAN_DURATION_MS = 2000; // Scan for 2 seconds
static constexpr int MATCH_ADV_GRACE_MS = 4000;
static constexpr int MATCH_STOP_FALLBACK_MS = 9000;
static constexpr int FRIEND_STRONG_RSSI_THRESHOLD = -60;
static constexpr int FRIEND_WEAK_RSSI_THRESHOLD = -85;
static constexpr int FRIEND_WEAK_MIN_SEEN = 2;
static constexpr const char* FRIEND_PREFIX = "BorlaF-";
// --- State ---
static std::atomic<bool> s_active{false};
static std::atomic<bool> s_nimble_ready{false};
static std::atomic<bool> s_nimble_task_started{false};
static std::atomic<bool> s_is_advertising{false};
static std::atomic<bool> s_match_reported{false};
static std::atomic<bool> s_match_grace_requested{false};
static std::atomic<bool> s_match_grace_advertising{false};
struct DiscoveredDevice {
std::string name;
int rssi = -127;
int best_rssi = -127;
int seen_count = 0;
int64_t last_seen_ms = 0;
ble_addr_t addr = {};
};
static std::mutex s_devices_mutex;
static std::map<std::string, DiscoveredDevice> s_discovered;
static FriendInfo s_local_info;
static FriendExchangeCallback s_on_complete;
static FriendExchangeOnStopped s_on_stopped;
static std::atomic<bool> s_paired{false}; // 区分 timeout vs successful exit
static esp_timer_handle_t s_timeout_timer = nullptr;
static esp_timer_handle_t s_log_timer = nullptr;
static esp_timer_handle_t s_sync_watchdog_timer = nullptr;
static esp_timer_handle_t s_release_timer = nullptr;
static esp_timer_handle_t s_match_stop_timer = nullptr;
static bool s_adv_fields_set = false;
static constexpr int NIMBLE_SYNC_TIMEOUT_MS = 5000; // 5s 没 sync 就直接 stop friend mode(不重试)
static constexpr int NIMBLE_RELEASE_DELAY_MS = 200; // GAP stop 稍等 200ms 后释放 BLE,再恢复 WS
// Forward declarations
static void StartAdvertisePhase(int duration_ms = ADV_DURATION_MS);
static void StartScanPhase();
static int OnGapEvent(struct ble_gap_event* event, void* arg);
static std::string AddrToString(const ble_addr_t& addr);
// --- NimBLE host ---
static void NimbleHostTask(void* arg)
{
ESP_LOGI(TAG, "NimBLE host task started");
nimble_port_run();
nimble_port_freertos_deinit();
}
static void OnNimbleSync()
{
s_nimble_ready.store(true);
ESP_LOGI(TAG, "NimBLE synced, starting scan phase");
// Sync 来了,watchdog 不再需要触发
if (s_sync_watchdog_timer) esp_timer_stop(s_sync_watchdog_timer);
if (s_active.load()) {
// Start with scan to find already-advertising peers
StartScanPhase();
}
}
// Sync watchdog: 5s 内 sync_cb 没回调就强制重启 NimBLE。
// 解决 ble_prov 配网过后 NimBLE 残留导致的"task spawn 了但 controller 不发 sync"症状。
static void OnNimbleSyncWatchdog(void* arg);
static void OnMatchStopFallback(void* arg);
static void NotifyStopped()
{
if (s_on_stopped) {
auto cb = s_on_stopped;
s_on_stopped = nullptr;
cb(s_paired.load());
}
}
static bool StartNimbleStack()
{
ESP_LOGI(TAG, "nimble_port_init() begin");
esp_err_t ret = nimble_port_init();
ESP_LOGI(TAG, "nimble_port_init() returned 0x%x (%s)",
ret, ret == ESP_OK ? "OK" : esp_err_to_name(ret));
if (ret != ESP_OK) {
ESP_LOGE(TAG, "NimBLE port init failed: 0x%x", ret);
s_nimble_task_started.store(false);
return false;
}
ble_hs_cfg.sync_cb = OnNimbleSync;
ESP_LOGI(TAG, "Spawning NimBLE host task via nimble_port_freertos_init");
nimble_port_freertos_init(NimbleHostTask);
// Set after spawn so a failure to spawn doesn't poison the flag.
s_nimble_task_started.store(true);
ESP_LOGI(TAG, "nimble_port_freertos_init returned (task should now be scheduled)");
// Arm sync watchdog: if controller never delivers sync within 5s, full reset.
if (!s_sync_watchdog_timer) {
esp_timer_create_args_t args = {
.callback = OnNimbleSyncWatchdog, .arg = nullptr,
.dispatch_method = ESP_TIMER_TASK, .name = "friend_sync_wd",
.skip_unhandled_events = true,
};
esp_timer_create(&args, &s_sync_watchdog_timer);
}
esp_timer_stop(s_sync_watchdog_timer);
esp_timer_start_once(s_sync_watchdog_timer,
(uint64_t)NIMBLE_SYNC_TIMEOUT_MS * 1000);
return true;
}
static void HardResetNimble(const char* reason)
{
ESP_LOGW(TAG, "Hard-resetting NimBLE: %s", reason ? reason : "");
// These no-op safely if not running.
if (s_nimble_task_started.load() || s_nimble_ready.load()) {
ble_gap_disc_cancel();
ble_gap_adv_stop();
}
nimble_port_stop();
nimble_port_deinit();
s_nimble_task_started.store(false);
s_nimble_ready.store(false);
s_adv_fields_set = false;
}
static void EnsureNimbleStarted()
{
// 如果刚退出 friend mode 但 release_timer 还没执行,用户又立刻重试,
// 复用已同步的 NimBLE host,避免一边释放一边重新初始化。
if (s_release_timer) esp_timer_stop(s_release_timer);
if (s_nimble_task_started.load() && s_nimble_ready.load()) {
// 健康复用 — 直接进 scan
ESP_LOGI(TAG, "NimBLE already running, reusing for new friend mode session");
StartScanPhase();
return;
}
if (s_nimble_task_started.load() && !s_nimble_ready.load()) {
// 上次 init 卡住了(sync_cb 一直没来),用户主动重试 → 强制清理重来。
// 这种场景才 deinit;正常 stop 路径不动 NimBLE。
ESP_LOGW(TAG, "NimBLE stuck (init OK but no sync) — hard reset before re-init");
HardResetNimble("user retry after stuck state");
}
if (!StartNimbleStack()) {
FriendExchange::StopFriendMode();
}
}
static void OnNimbleSyncWatchdog(void* arg)
{
if (!s_active.load()) return;
if (s_nimble_ready.load()) return; // sync 来过了,watchdog 不需要做事
// sync_cb 没回调 → controller 起不来 / coex 卡死。直接结束 friend mode
// 让用户重试(不再原地 hard-reset 重试 — 每次 reinit 都新占 4-6 个 task
// slot,累积起来 web_socket.cc:387 std::thread create 会 abort)。
// StopFriendMode 会调 on_stopped(false) 让 button_config 恢复 WS。
ESP_LOGW(TAG, "NimBLE sync_cb never fired within %dms — exiting friend mode (user retry)",
NIMBLE_SYNC_TIMEOUT_MS);
FriendExchange::StopFriendMode();
}
static void OnMatchStopFallback(void* arg)
{
if (!s_active.load() || !s_match_reported.load()) return;
ESP_LOGW(TAG, "Matched but grace ADV did not complete within %dms — stopping friend mode",
MATCH_STOP_FALLBACK_MS);
FriendExchange::StopFriendMode();
}
// stop 后异步释放 NimBLE。释放完成后再通知上层重开 WS,避免 WS 握手
// 和 nimble_port_stop/deinit 同时争抢 task slot / WiFi-BLE coex 资源。
static void OnReleaseNimble(void* arg)
{
if (s_active.load()) {
// 又有人开了 friend mode(用户连按按钮),跳过释放,让它继续工作
ESP_LOGI(TAG, "Release skipped: friend mode reactivated");
return;
}
if (!s_nimble_task_started.load()) {
NotifyStopped();
return;
}
HardResetNimble("post-stop full release (async)");
NotifyStopped();
}
// --- Advertising phase (timed, auto-expires) ---
static void StartAdvertisePhase(int duration_ms)
{
if (!s_active.load()) return;
std::string adv_name = s_local_info.name;
if (adv_name.empty()) adv_name = "BorlaF-0000";
// Set adv fields once
if (!s_adv_fields_set) {
ble_svc_gap_device_name_set(adv_name.c_str());
struct ble_hs_adv_fields adv_fields = {};
adv_fields.flags = BLE_HS_ADV_F_DISC_GEN | BLE_HS_ADV_F_BREDR_UNSUP;
adv_fields.name = (uint8_t*)adv_name.c_str();
adv_fields.name_len = adv_name.size();
adv_fields.name_is_complete = 1;
int rc = ble_gap_adv_set_fields(&adv_fields);
if (rc != 0) {
ESP_LOGE(TAG, "Set adv fields failed: %d", rc);
return;
}
s_adv_fields_set = true;
}
struct ble_gap_adv_params adv_params = {};
adv_params.conn_mode = BLE_GAP_CONN_MODE_NON;
adv_params.disc_mode = BLE_GAP_DISC_MODE_GEN;
adv_params.itvl_min = 48; // 30ms
adv_params.itvl_max = 96; // 60ms
// Timed advertising: auto-stops after ADV_DURATION_MSms
// OnGapEvent will receive BLE_GAP_EVENT_ADV_COMPLETE → start scan phase
int rc = ble_gap_adv_start(BLE_OWN_ADDR_PUBLIC, nullptr,
duration_ms,
&adv_params, OnGapEvent, nullptr);
if (rc == 0) {
s_is_advertising.store(true);
ESP_LOGI(TAG, "[Phase] ADV \"%s\" for %dms", adv_name.c_str(), duration_ms);
} else {
ESP_LOGW(TAG, "[Phase] ADV failed: rc=%d, retrying scan", rc);
// Fallback: try scan instead
StartScanPhase();
}
}
// --- Scanning phase (timed, auto-expires) ---
static void StartScanPhase()
{
if (!s_active.load()) return;
struct ble_gap_disc_params scan_params = {};
scan_params.passive = 1;
scan_params.itvl = 80; // 50ms
scan_params.window = 60; // 37.5ms
scan_params.filter_duplicates = 0;
scan_params.limited = 0;
// Timed scan: auto-stops after SCAN_DURATION_MS
// OnGapEvent will receive BLE_GAP_EVENT_DISC_COMPLETE → start adv phase
int rc = ble_gap_disc(BLE_OWN_ADDR_PUBLIC,
SCAN_DURATION_MS, // duration in ms
&scan_params, OnGapEvent, nullptr);
if (rc == 0) {
s_is_advertising.store(false);
ESP_LOGI(TAG, "[Phase] SCAN for %dms", SCAN_DURATION_MS);
} else {
ESP_LOGW(TAG, "[Phase] SCAN failed: rc=%d, retrying adv", rc);
// Fallback: try adv instead
StartAdvertisePhase();
}
}
// --- GAP event handler ---
static std::string AddrToString(const ble_addr_t& addr)
{
char buf[18];
snprintf(buf, sizeof(buf), "%02X:%02X:%02X:%02X:%02X:%02X",
addr.val[5], addr.val[4], addr.val[3],
addr.val[2], addr.val[1], addr.val[0]);
return std::string(buf);
}
static int OnGapEvent(struct ble_gap_event* event, void* arg)
{
switch (event->type) {
case BLE_GAP_EVENT_DISC: {
// Scan result
if (!s_active.load()) break;
const struct ble_gap_disc_desc* disc = &event->disc;
struct ble_hs_adv_fields fields = {};
if (ble_hs_adv_parse_fields(&fields, disc->data, disc->length_data) != 0) break;
std::string name;
if (fields.name_len > 0 && fields.name != nullptr) {
name.assign((const char*)fields.name, fields.name_len);
}
if (name.find(FRIEND_PREFIX) != 0) break;
std::string mac = AddrToString(disc->addr);
int64_t now_ms = esp_timer_get_time() / 1000;
{
std::lock_guard<std::mutex> lock(s_devices_mutex);
auto& dev = s_discovered[mac];
int rssi = static_cast<int>(disc->rssi);
dev.name = name;
dev.rssi = rssi;
dev.best_rssi = std::max(dev.best_rssi, rssi);
dev.seen_count++;
dev.last_seen_ms = now_ms;
dev.addr = disc->addr;
}
break;
}
case BLE_GAP_EVENT_DISC_COMPLETE:
// Scan phase finished → start advertise phase
ESP_LOGD(TAG, "Scan complete, switching to ADV");
if (s_active.load()) {
if (s_match_grace_requested.exchange(false)) {
s_match_grace_advertising.store(true);
StartAdvertisePhase(MATCH_ADV_GRACE_MS);
} else {
StartAdvertisePhase();
}
}
break;
case BLE_GAP_EVENT_ADV_COMPLETE:
// Advertise phase finished → start scan phase
ESP_LOGD(TAG, "Adv complete, switching to SCAN");
s_is_advertising.store(false);
if (s_active.load()) {
if (s_match_grace_advertising.load()) {
FriendExchange::StopFriendMode();
} else if (s_match_grace_requested.exchange(false)) {
s_match_grace_advertising.store(true);
StartAdvertisePhase(MATCH_ADV_GRACE_MS);
} else {
StartScanPhase();
}
}
break;
default:
break;
}
return 0;
}
// --- Periodic log (every 1s) ---
static void OnLogTimer(void* arg)
{
if (!s_active.load()) return;
int64_t now_ms = esp_timer_get_time() / 1000;
std::unique_lock<std::mutex> lock(s_devices_mutex);
// Remove stale (not seen in 6s)
for (auto it = s_discovered.begin(); it != s_discovered.end();) {
if (now_ms - it->second.last_seen_ms > 6000) {
it = s_discovered.erase(it);
} else {
++it;
}
}
const char* phase = s_is_advertising.load() ? "ADV" : "SCAN";
if (s_discovered.empty()) {
ESP_LOGI(TAG, "[%s] No BorlaF-* devices nearby", phase);
return;
}
ESP_LOGI(TAG, "[%s] %zu device(s):", phase, s_discovered.size());
FriendInfo remote;
FriendExchangeCallback cb = nullptr;
for (auto& [mac, dev] : s_discovered) {
bool strong = dev.best_rssi >= FRIEND_STRONG_RSSI_THRESHOLD;
bool weak_confirmed = dev.best_rssi >= FRIEND_WEAK_RSSI_THRESHOLD &&
dev.seen_count >= FRIEND_WEAK_MIN_SEEN;
bool close = strong || weak_confirmed;
ESP_LOGI(TAG, " %s %-16s RSSI: %d dBm best=%d seen=%d%s",
mac.c_str(), dev.name.c_str(), dev.rssi,
dev.best_rssi, dev.seen_count,
close ? " *** CLOSE ***" : "");
if (close && !s_match_reported.load() && s_on_complete && !cb) {
remote.mac = SystemInfo::BleMacToBaseMac(mac);
remote.name = dev.name;
ESP_LOGI(TAG, ">>> FRIEND MATCHED: %s BLE=%s BASE=%s RSSI=%d <<<",
dev.name.c_str(), mac.c_str(), remote.mac.c_str(), dev.rssi);
cb = s_on_complete;
}
}
// Release the mutex before calling StopFriendMode/cb — StopFriendMode
// acquires s_devices_mutex to clear s_discovered, and std::mutex is not
// recursive. Doing it inside the lock deadlocks the esp_timer task, after
// which neither the callback nor subsequent button presses work.
if (cb) {
lock.unlock();
s_paired.store(true);
s_match_reported.store(true);
s_match_grace_requested.store(true);
if (s_timeout_timer) esp_timer_stop(s_timeout_timer);
if (!s_match_stop_timer) {
esp_timer_create_args_t args = {
.callback = OnMatchStopFallback, .arg = nullptr,
.dispatch_method = ESP_TIMER_TASK, .name = "friend_match_to",
.skip_unhandled_events = true,
};
esp_timer_create(&args, &s_match_stop_timer);
}
esp_timer_stop(s_match_stop_timer);
esp_timer_start_once(s_match_stop_timer,
(uint64_t)MATCH_STOP_FALLBACK_MS * 1000);
cb(s_local_info, remote);
ESP_LOGI(TAG, "Friend matched; waiting for current GAP phase to finish before grace ADV");
}
}
// --- Timeout ---
static void OnScanTimeout(void* arg)
{
ESP_LOGI(TAG, "Friend mode timeout (%ds)", FRIEND_MODE_TIMEOUT_S);
FriendExchange::StopFriendMode();
}
// === Public API ===
void FriendExchange::StartFriendMode(const FriendInfo& local_info,
FriendExchangeCallback on_complete,
FriendExchangeOnStopped on_stopped)
{
if (s_active.load()) {
ESP_LOGW(TAG, "Friend mode already active");
return;
}
s_active.store(true);
s_paired.store(false);
s_match_reported.store(false);
s_match_grace_requested.store(false);
s_match_grace_advertising.store(false);
s_local_info = local_info;
s_on_complete = on_complete;
s_on_stopped = on_stopped;
s_adv_fields_set = false;
ESP_LOGI(TAG, "========================================");
ESP_LOGI(TAG, " FRIEND MODE START");
ESP_LOGI(TAG, " Local: %s (%s)", local_info.name.c_str(), local_info.mac.c_str());
ESP_LOGI(TAG, " ADV %dms ↔ SCAN %dms Timeout: %ds",
ADV_DURATION_MS, SCAN_DURATION_MS, FRIEND_MODE_TIMEOUT_S);
ESP_LOGI(TAG, " RSSI threshold: strong=%d dBm, weak=%d dBm x%d",
FRIEND_STRONG_RSSI_THRESHOLD, FRIEND_WEAK_RSSI_THRESHOLD,
FRIEND_WEAK_MIN_SEEN);
ESP_LOGI(TAG, "========================================");
{
std::lock_guard<std::mutex> lock(s_devices_mutex);
s_discovered.clear();
}
// Timeout timer (30s)
if (!s_timeout_timer) {
esp_timer_create_args_t args = {
.callback = OnScanTimeout, .arg = nullptr,
.dispatch_method = ESP_TIMER_TASK, .name = "friend_to",
.skip_unhandled_events = true,
};
esp_timer_create(&args, &s_timeout_timer);
}
esp_timer_start_once(s_timeout_timer, (uint64_t)FRIEND_MODE_TIMEOUT_S * 1000000);
// Log timer (1s)
if (!s_log_timer) {
esp_timer_create_args_t args = {
.callback = OnLogTimer, .arg = nullptr,
.dispatch_method = ESP_TIMER_TASK, .name = "friend_log",
.skip_unhandled_events = true,
};
esp_timer_create(&args, &s_log_timer);
}
esp_timer_start_periodic(s_log_timer, (uint64_t)SCAN_LOG_INTERVAL_MS * 1000);
// Start NimBLE (OnNimbleSync → StartScanPhase)
EnsureNimbleStarted();
}
void FriendExchange::StopFriendMode()
{
if (!s_active.load()) return;
s_active.store(false);
if (s_timeout_timer) esp_timer_stop(s_timeout_timer);
if (s_log_timer) esp_timer_stop(s_log_timer);
if (s_sync_watchdog_timer) esp_timer_stop(s_sync_watchdog_timer);
if (s_match_stop_timer) esp_timer_stop(s_match_stop_timer);
// 同步停 GAP,让 host task 退出 adv/scan 状态。NimBLE host 本身稍后
// 由 release_timer 异步释放(见下面注释)。
if (s_nimble_task_started.load() || s_nimble_ready.load()) {
ble_gap_disc_cancel();
ble_gap_adv_stop();
}
{
std::lock_guard<std::mutex> lock(s_devices_mutex);
s_discovered.clear();
}
s_on_complete = nullptr;
s_adv_fields_set = false;
s_match_grace_requested.store(false);
s_match_grace_advertising.store(false);
ESP_LOGI(TAG, "=== FRIEND MODE STOP ===");
// 先释放 NimBLE host(还给 WS 握手需要的 task slot),释放完成后再通知
// button_config 重开 WS。不能反过来,否则会出现日志里的 WS handshake timeout。
if (!s_nimble_task_started.load()) {
NotifyStopped();
return;
}
if (!s_release_timer) {
esp_timer_create_args_t args = {
.callback = OnReleaseNimble, .arg = nullptr,
.dispatch_method = ESP_TIMER_TASK, .name = "friend_rel",
.skip_unhandled_events = true,
};
esp_timer_create(&args, &s_release_timer);
}
esp_timer_stop(s_release_timer);
esp_timer_start_once(s_release_timer, (uint64_t)NIMBLE_RELEASE_DELAY_MS * 1000);
}
bool FriendExchange::IsActive()
{
return s_active.load();
}

View File

@@ -0,0 +1,56 @@
#pragma once
#include <string>
#include <functional>
/**
* BLE Friend Exchange module.
*
* Handles BLE advertise/scan based device-to-device friend pairing.
* Flow:
* 1. Triple-click → StartFriendMode()
* 2. Advertise as "BorlaF-XXXX" + scan for "BorlaF-*"
* 3. On discovery: derive peer identity from BorlaF-* advertisement
* 4. Report to server via WebSocket friend_add message
* 5. Auto-close BLE after timeout (30s)
*
* This module intentionally does not register the BLE provisioning GATT
* service. Double-click provisioning owns that service in BleProv.
*/
struct FriendInfo {
std::string mac;
std::string name;
};
// Callback when friend exchange completes successfully
using FriendExchangeCallback = std::function<void(const FriendInfo& local, const FriendInfo& remote)>;
// Callback fired when friend mode exits — either after a successful pairing
// (right after FriendExchangeCallback) or after a 30s timeout. Always called
// exactly once per StartFriendMode invocation, on the esp_timer task.
// Caller uses this to restore resources it disabled at start time (e.g. WS).
using FriendExchangeOnStopped = std::function<void(bool paired)>;
class FriendExchange {
public:
/**
* Start BLE friend discovery mode.
* Advertises and scans simultaneously for 30 seconds.
* Calls on_complete when a friend is successfully exchanged.
* Calls on_stopped at the end (paired or timeout) — always once.
*/
static void StartFriendMode(const FriendInfo& local_info,
FriendExchangeCallback on_complete,
FriendExchangeOnStopped on_stopped = nullptr);
/**
* Stop friend mode early (e.g., button press to cancel).
*/
static void StopFriendMode();
/**
* Check if friend mode is currently active.
*/
static bool IsActive();
};

39
main/boards/board.h Normal file
View File

@@ -0,0 +1,39 @@
#ifndef _BOARD_H_
#define _BOARD_H_
#include <string>
#include "audio/audio_codec.h"
#include "led/led.h"
#include <network_interface.h>
class Board {
public:
virtual ~Board() = default;
static Board& GetInstance();
virtual std::string GetBoardType() const = 0;
virtual AudioCodec* GetAudioCodec() = 0;
virtual Led* GetLed() = 0;
virtual NetworkInterface* GetNetwork() = 0;
virtual void StartNetwork() = 0;
virtual bool IsNetworkConnected() const = 0;
//2026-6-24 ckkj debug (关闭射频)
virtual void StopNetwork() {}
virtual int GetBatteryLevel() const { return -1; }
// Whether USB is currently charging the battery. Default false for boards
// without charge detection. Used by Application to skip low-battery
// warnings when the device is plugged in.
virtual bool IsCharging() const { return false; }
virtual void SetPowerSaveMode(bool enabled) {}
// Light-sleep shutdown equivalent to long-press power off. Default no-op
// for boards that don't implement low-power shutdown. BorlaS3Board
// overrides to drive the EXT1-wakeup light-sleep loop. Called by
// IdleWatchdog after the 10-minute idle goodbye prompt finishes.
virtual void EnterSoftOff() {}
};
#endif // _BOARD_H_

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,67 @@
#ifndef _BOARD_CONFIG_H_
#define _BOARD_CONFIG_H_
// Borla S3 (esp-spot-s3) Board Configuration
// Source: xiaozhi-esp32/main/boards/esp-spot-s3/config.h
#include <driver/gpio.h>
// Audio sample rates
#define AUDIO_INPUT_SAMPLE_RATE 16000
#define AUDIO_OUTPUT_SAMPLE_RATE 16000
#define AUDIO_INPUT_REFERENCE false
// I2S GPIO — 注意: 不使用 MCLK
#define AUDIO_I2S_GPIO_MCLK GPIO_NUM_NC
#define AUDIO_I2S_GPIO_WS GPIO_NUM_17
#define AUDIO_I2S_GPIO_BCLK GPIO_NUM_16
#define AUDIO_I2S_GPIO_DIN GPIO_NUM_15
#define AUDIO_I2S_GPIO_DOUT GPIO_NUM_18
// ES8311 Codec I2C
#define AUDIO_CODEC_I2C_SDA_PIN GPIO_NUM_2
#define AUDIO_CODEC_I2C_SCL_PIN GPIO_NUM_1
#define AUDIO_CODEC_ES8311_ADDR ES8311_CODEC_DEFAULT_ADDR
// NS4150B PA enable
#define AUDIO_CODEC_PA_PIN GPIO_NUM_40
// #define AUDIO_CODEC_PA_PIN GPIO_NUM_NC
// 4G ML307 UART
// Note: Despite the confusing naming in xiaozhi reference,
// ML307_TX_PIN = ESP32's TX pin (sends AT commands to ML307)
// ML307_RX_PIN = ESP32's RX pin (receives responses from ML307)
#define ML307_TX_PIN GPIO_NUM_43
#define ML307_RX_PIN GPIO_NUM_44
#define ML307_DTR_PIN GPIO_NUM_NC
// Buttons
#define BOOT_BUTTON_GPIO GPIO_NUM_0
#define KEY_BUTTON_GPIO GPIO_NUM_12
#define POWER_BUTTON_GPIO KEY_BUTTON_GPIO
// WS2812E RGB LED
#define LED_PIN GPIO_NUM_11
// Touch buttons — logical touch_1..touch_5 must match server semantics:
// touch_1=head, touch_2=back, touch_3=right hand, touch_4=left hand, touch_5=belly.
// GPIO order below follows the actual doll harness.
#define TOUCH_BUTTON_1 GPIO_NUM_3
#define TOUCH_BUTTON_2 GPIO_NUM_9
#define TOUCH_BUTTON_3 GPIO_NUM_13
#define TOUCH_BUTTON_4 GPIO_NUM_7
#define TOUCH_BUTTON_5 GPIO_NUM_8
// Battery ADC — 1S Li-ion cell, 3.7V nominal / 1000mAh / 3.7Wh
#define VBAT_ADC_CHANNEL ADC_CHANNEL_9 // GPIO10
#define FULL_BATTERY_VOLTAGE 4200 // CV cutoff (fully charged)
#define EMPTY_BATTERY_VOLTAGE 3000 // discharge cutoff (protect cell)
// Power control
#define MCU_VCC_CTL GPIO_NUM_4
#define PERP_VCC_CTL GPIO_NUM_6
// Board name
#define BOARD_NAME "borla-s3"
#endif // _BOARD_CONFIG_H_

308
main/boards/common/bmi270.c Normal file
View File

@@ -0,0 +1,308 @@
/*
* BMI270 IMU 驱动实现
* 整合自原始代码的硬件操作部分
*/
#include "bmi270.h"
#include "driver/i2c_master.h"
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include <string.h> // 添加这行
static const char *TAG = "BMI270";
// 静态变量
static i2c_master_bus_handle_t i2c_bus_handle = NULL;
static i2c_master_dev_handle_t bmi270_handle = NULL;
static bmi270_config_t current_config;
// BMI270 配置数据(来自 bmi270_context.c)
extern const uint8_t bmi270_context_config_file[];
extern const int bmi270_context_config_file_size;
// I2C 缓冲区
static uint8_t i2c_write_buffer[32];
static uint8_t i2c_read_buffer[32];
// 私有函数声明
static esp_err_t write_bmi270_reg(uint8_t addr, uint8_t data);
static uint8_t read_bmi270_reg(uint8_t addr, esp_err_t* err);
static esp_err_t write_bmi270_data(uint8_t addr, uint8_t* data, int length);
static esp_err_t read_bmi270_data(uint8_t addr, uint8_t* data, int length);
static esp_err_t read_bmm150_data(uint8_t addr, uint8_t* data, int length);
static esp_err_t write_bmm150_data(uint8_t addr, uint8_t* data, int length);
// ==================== 公共API实现 ====================
esp_err_t bmi270_init(bmi270_config_t* config) {
esp_err_t err = ESP_OK;
if (config == NULL) {
ESP_LOGE(TAG, "配置参数不能为NULL");
return ESP_ERR_INVALID_ARG;
}
// 保存配置
memcpy(&current_config, config, sizeof(bmi270_config_t));
// 1. 获取I2C总线
err = i2c_master_get_bus_handle(I2C_NUM_0, &i2c_bus_handle);
if (err != ESP_OK) {
ESP_LOGE(TAG, "获取I2C总线失败: 0x%x", err);
return err;
}
// 2. 配置BMI270设备
const i2c_device_config_t bmi270_dev_config = {
.dev_addr_length = I2C_ADDR_BIT_LEN_7,
.device_address = config->i2c_addr,
.scl_speed_hz = config->i2c_speed_hz,
};
err = i2c_master_bus_add_device(i2c_bus_handle, &bmi270_dev_config, &bmi270_handle);
if (err != ESP_OK) {
ESP_LOGE(TAG, "添加BMI270设备失败: 0x%x", err);
return err;
}
vTaskDelay(pdMS_TO_TICKS(10));
// 3. 检查芯片ID
i2c_write_buffer[0] = BMI270_CHIP_ID;
err = i2c_master_transmit_receive(bmi270_handle,
i2c_write_buffer, 1,
i2c_read_buffer, 1,
1000);
ESP_LOGI(TAG, "BMI270 芯片ID: 0x%02x (预期: 0x24)", i2c_read_buffer[0]);
if (i2c_read_buffer[0] != 0x24) {
ESP_LOGE(TAG, "芯片ID不匹配");
return ESP_ERR_NOT_FOUND;
}
// 4. 配置辅助I2C接口(用于BMM150磁力计)
err = write_bmi270_reg(BMI270_IF_CONF, 0x20);
if (err != ESP_OK) return err;
err = write_bmi270_reg(BMI270_PWR_CTRL, 0x0F); // 启用所有传感器
if (err != ESP_OK) return err;
err = write_bmi270_reg(BMI270_AUX_IF_CONFIG, 0x80); // 启用辅助接口
if (err != ESP_OK) return err;
vTaskDelay(pdMS_TO_TICKS(1));
// 5. 初始化BMM150磁力计
// 上电
i2c_read_buffer[0] = 0x01;
err = write_bmm150_data(BMM150_REG_POWER_CONTROL, i2c_read_buffer, 1);
if (err != ESP_OK) return err;
vTaskDelay(pdMS_TO_TICKS(1));
// 检查BMM150芯片ID
err = read_bmm150_data(BMM150_SHIP_ID, i2c_read_buffer, 1);
ESP_LOGI(TAG, "BMM150 芯片ID: 0x%02x (预期: 0x32)", i2c_read_buffer[0]);
// 配置磁力计
i2c_read_buffer[0] = 0x18; // 输出数据速率和操作模式
err = write_bmm150_data(0x4C, i2c_read_buffer, 1);
if (err != ESP_OK) return err;
vTaskDelay(pdMS_TO_TICKS(1));
// 6. 加载BMI270配置数据
err = write_bmi270_reg(BMI270_PWR_CONF, 0x00);
if (err != ESP_OK) return err;
vTaskDelay(pdMS_TO_TICKS(10));
err = write_bmi270_reg(BMI270_INIT_CTRL, 0x00);
if (err != ESP_OK) return err;
err = write_bmi270_data(BMI270_INIT_DATA,
(uint8_t*)bmi270_context_config_file,
bmi270_context_config_file_size);
if (err != ESP_OK) return err;
err = write_bmi270_reg(BMI270_INIT_CTRL, 0x01);
if (err != ESP_OK) return err;
// 7. 配置传感器参数
err = write_bmi270_reg(BMI270_PWR_CTRL, 0x0F); // 启用传感器
err = write_bmi270_reg(BMI270_ACC_CONF, 0xA6); // 加速度计配置
err = write_bmi270_reg(BMI270_GYR_CONF, 0xA6); // 陀螺仪配置
err = write_bmi270_reg(BMI270_PWR_CONF, 0x02); // 电源配置
err = write_bmi270_reg(BMI270_AUX_CONF, 0x07); // 辅助传感器配置
// 设置量程
err = write_bmi270_reg(BMI270_ACC_RANGE, config->acc_range);
err = write_bmi270_reg(BMI270_GYR_RANGE, config->gyro_range);
// 8. 最终配置
err = write_bmi270_reg(BMI270_IF_CONF, 0x00);
err = write_bmi270_reg(BMI270_AUX_IF_CONFIG, 0x03);
ESP_LOGI(TAG, "BMI270 初始化完成");
return ESP_OK;
}
esp_err_t bmi270_read_sensor_data(bmi270_data_t* data) {
if (data == NULL || bmi270_handle == NULL) {
return ESP_ERR_INVALID_ARG;
}
esp_err_t err;
int16_t raw_data[10]; // 足够存储所有传感器数据
// 读取传感器数据(20字节:3磁力计 + 1保留 + 3加速度计 + 3陀螺仪)
err = read_bmi270_data(BMI270_AUX_DATA0, (uint8_t*)raw_data, 20);
if (err != ESP_OK) {
ESP_LOGE(TAG, "读取传感器数据失败: 0x%x", err);
return err;
}
// 解析数据(注意:原始代码中有些轴需要取反)
// 磁力计数据
data->magn[0] = raw_data[0];
data->magn[1] = -raw_data[1]; // Y轴取反
data->magn[2] = -raw_data[2]; // Z轴取反
// 加速度计数据(跳过第3个磁力计数据后的保留字节)
data->accel[0] = raw_data[4];
data->accel[1] = -raw_data[5]; // Y轴取反
data->accel[2] = -raw_data[6]; // Z轴取反
// 陀螺仪数据
data->gyro[0] = raw_data[7];
data->gyro[1] = -raw_data[8]; // Y轴取反
data->gyro[2] = -raw_data[9]; // Z轴取反
return ESP_OK;
}
// ==================== 私有函数实现 ====================
static esp_err_t write_bmi270_reg(uint8_t addr, uint8_t data) {
i2c_write_buffer[0] = addr;
i2c_write_buffer[1] = data;
return i2c_master_transmit(bmi270_handle, i2c_write_buffer, 2, 1000);
}
static uint8_t read_bmi270_reg(uint8_t addr, esp_err_t* err) {
i2c_write_buffer[0] = addr;
*err = i2c_master_transmit_receive(bmi270_handle,
i2c_write_buffer, 1,
&i2c_write_buffer[16], 1,
1000);
return i2c_write_buffer[16];
}
static esp_err_t write_bmi270_data(uint8_t addr, uint8_t* data, int length) {
if (length < 32) {
i2c_write_buffer[0] = addr;
memcpy(&i2c_write_buffer[1], data, length);
return i2c_master_transmit(bmi270_handle, i2c_write_buffer, 1 + length, 1000);
}
uint8_t* temp_data = malloc(length + 1);
if (temp_data == NULL) {
return ESP_ERR_NO_MEM;
}
temp_data[0] = addr;
memcpy(&temp_data[1], data, length);
esp_err_t err = i2c_master_transmit(bmi270_handle, temp_data, 1 + length, 1000);
free(temp_data);
return err;
}
static esp_err_t read_bmi270_data(uint8_t addr, uint8_t* data, int length) {
i2c_write_buffer[0] = addr;
return i2c_master_transmit_receive(bmi270_handle,
i2c_write_buffer, 1,
data, length,
1000);
}
static esp_err_t read_bmm150_data(uint8_t addr, uint8_t* data, int length) {
esp_err_t err;
// 设置读取地址
i2c_write_buffer[0] = BMI270_AUX_READ_ADDR;
i2c_write_buffer[1] = addr;
err = i2c_master_transmit(bmi270_handle, i2c_write_buffer, 2, 1000);
if (err != ESP_OK) return err;
// 读取状态
i2c_write_buffer[0] = BMI270_AUX_STATUS;
err = i2c_master_transmit_receive(bmi270_handle,
i2c_write_buffer, 1,
data, length,
1000);
if (err != ESP_OK) return err;
// 读取数据
i2c_write_buffer[0] = BMI270_AUX_DATA0;
err = i2c_master_transmit_receive(bmi270_handle,
i2c_write_buffer, 1,
data, length,
1000);
return err;
}
static esp_err_t write_bmm150_data(uint8_t addr, uint8_t* data, int length) {
esp_err_t err;
// 写入数据
i2c_write_buffer[0] = BMI270_AUX_WRITE_DATA;
i2c_write_buffer[1] = data[0];
err = i2c_master_transmit(bmi270_handle, i2c_write_buffer, 2, 1000);
if (err != ESP_OK) return err;
// 设置写入地址
i2c_write_buffer[0] = BMI270_AUX_WRITE_ADDR;
i2c_write_buffer[1] = addr;
err = i2c_master_transmit(bmi270_handle, i2c_write_buffer, 2, 1000);
return err;
}
// ==================== 其他公共函数 ====================
esp_err_t bmi270_deinit(void) {
if (bmi270_handle != NULL) {
esp_err_t err = i2c_master_bus_rm_device(bmi270_handle);
bmi270_handle = NULL;
return err;
}
return ESP_OK;
}
esp_err_t bmi270_set_accel_range(uint8_t range) {
if (range > 3) return ESP_ERR_INVALID_ARG;
current_config.acc_range = range;
return write_bmi270_reg(BMI270_ACC_RANGE, range);
}
esp_err_t bmi270_set_gyro_range(uint8_t range) {
if (range > 4) return ESP_ERR_INVALID_ARG;
current_config.gyro_range = range;
return write_bmi270_reg(BMI270_GYR_RANGE, range);
}
uint8_t bmi270_get_chip_id(void) {
esp_err_t err;
return read_bmi270_reg(BMI270_CHIP_ID, &err);
}

View File

@@ -0,0 +1,87 @@
/*
* BMI270 IMU Driver for ESP32
* 整合自 3d_kalman_demo.cpp 和 bmi270_context.c
*/
#ifndef BMI270_H
#define BMI270_H
#include <stdint.h>
#include "esp_err.h"
#ifdef __cplusplus
extern "C" {
#endif
// BMI270 寄存器定义
#define BMI270_CHIP_ID 0x00
#define BMI270_IF_CONF 0x6B
#define BMI270_AUX_DEV_ID 0x4B
#define BMI270_PWR_CONF 0x7C
#define BMI270_PWR_CTRL 0x7D
#define BMI270_CMD 0x7E
#define BMI270_AUX_IF_CONFIG 0x4C
#define BMI270_AUX_READ_ADDR 0x4D
#define BMI270_AUX_WRITE_ADDR 0x4E
#define BMI270_AUX_WRITE_DATA 0x4F
#define BMI270_AUX_STATUS 0x03
#define BMI270_AUX_DATA0 0x04
#define BMI270_ACC_DATA0 0x0C
#define BMI270_GYR_DATA0 0x12
#define BMI270_ACC_CONF 0x40
#define BMI270_ACC_RANGE 0x41
#define BMI270_GYR_CONF 0x42
#define BMI270_GYR_RANGE 0x43
#define BMI270_AUX_CONF 0x44
#define BMI270_INIT_CTRL 0x59
#define BMI270_INIT_DATA 0x5E
#define BMI270_INTERNAL_STATUS 0x21
// BMM150 寄存器定义
#define BMM150_REG_POWER_CONTROL 0x4B
#define BMM150_SHIP_ID 0x40
#define BMM150_DATA0 0x42
// 传感器数据结构
typedef struct {
int16_t accel[3]; // 加速度计数据 (x, y, z)
int16_t gyro[3]; // 陀螺仪数据 (x, y, z)
int16_t magn[3]; // 磁力计数据 (x, y, z)
float temperature; // 温度(如有)
} bmi270_data_t;
// 配置结构
typedef struct {
uint8_t i2c_addr; // I2C 地址 (默认 0x69)
uint8_t acc_range; // 加速度计量程
uint8_t gyro_range; // 陀螺仪量程
uint32_t i2c_speed_hz; // I2C 速度
uint8_t aux_i2c_addr; // 辅助I2C地址 (BMM150磁力计)
} bmi270_config_t;
// BMI270 设备句柄类型(前向声明)
typedef struct bmi270_dev_t* bmi270_handle_t;
// 初始化函数
esp_err_t bmi270_init(bmi270_config_t* config);
esp_err_t bmi270_read_sensor_data(bmi270_data_t* data);
// 配置函数
esp_err_t bmi270_set_accel_range(uint8_t range);
esp_err_t bmi270_set_gyro_range(uint8_t range);
esp_err_t bmi270_set_power_mode(uint8_t mode);
// 工具函数
esp_err_t bmi270_self_test(void);
uint8_t bmi270_get_chip_id(void);
esp_err_t bmi270_soft_reset(void);
// 原始数据访问
esp_err_t bmi270_read_raw_accel(int16_t* x, int16_t* y, int16_t* z);
esp_err_t bmi270_read_raw_gyro(int16_t* x, int16_t* y, int16_t* z);
esp_err_t bmi270_read_raw_magn(int16_t* x, int16_t* y, int16_t* z);
#ifdef __cplusplus
}
#endif
#endif // BMI270_H

View File

@@ -0,0 +1,444 @@
/*
* SPDX-FileCopyrightText: 2025 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <stdint.h>
const uint8_t bmi270_context_config_file[] = {
0xc8, 0x2e, 0x00, 0x2e, 0x80, 0x2e, 0x00, 0xb0, 0xc8, 0x2e, 0x00, 0x2e, 0xc8, 0x2e, 0x00, 0x2e, 0x80, 0x2e, 0xc9,
0x01, 0x80, 0x2e, 0xe2, 0x00, 0xc8, 0x2e, 0x00, 0x2e, 0x80, 0x2e, 0x77, 0xb0, 0x50, 0x30, 0x21, 0x2e, 0x59, 0xf5,
0x10, 0x30, 0x21, 0x2e, 0x6a, 0xf5, 0x80, 0x2e, 0xaf, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x09, 0x01, 0x00, 0x22,
0x00, 0x76, 0x00, 0x00, 0x10, 0x00, 0x10, 0xd1, 0x00, 0xcb, 0xa7, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1,
0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00,
0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e,
0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80,
0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1,
0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00,
0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e,
0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80,
0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1,
0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0xfd, 0x2d, 0x2c, 0x56, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x02, 0x08, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x04, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1a, 0x24, 0x22, 0x00, 0x80, 0x2e, 0x48, 0x02, 0x01, 0x2e, 0x49,
0xf1, 0x0b, 0xbc, 0x10, 0x50, 0x0f, 0xb8, 0x00, 0x90, 0xfb, 0x7f, 0x07, 0x2f, 0x03, 0x2e, 0x21, 0xf2, 0x02, 0x31,
0x4a, 0x0a, 0x23, 0x2e, 0x21, 0xf2, 0x09, 0x2c, 0x00, 0x30, 0x98, 0x2e, 0x0e, 0xc7, 0x03, 0x2e, 0x21, 0xf2, 0xf2,
0x3e, 0x4a, 0x08, 0x23, 0x2e, 0x21, 0xf2, 0xfb, 0x6f, 0xf0, 0x5f, 0xb8, 0x2e, 0x13, 0x52, 0x00, 0x2e, 0x60, 0x40,
0x41, 0x40, 0x0d, 0xbc, 0x98, 0xbc, 0xc0, 0x2e, 0x01, 0x0a, 0x0f, 0xb8, 0x43, 0x86, 0x25, 0x40, 0x04, 0x40, 0xd8,
0xbe, 0x2c, 0x0b, 0x22, 0x11, 0x54, 0x42, 0x03, 0x80, 0x4b, 0x0e, 0xf6, 0x2f, 0xb8, 0x2e, 0x20, 0x50, 0xe7, 0x7f,
0xf6, 0x7f, 0x46, 0x30, 0x0f, 0x2e, 0xa4, 0xf1, 0xbe, 0x09, 0x80, 0xb3, 0x06, 0x2f, 0x0d, 0x2e, 0x84, 0x00, 0x84,
0xaf, 0x02, 0x2f, 0x16, 0x30, 0x2d, 0x2e, 0x7b, 0x00, 0x86, 0x30, 0x2d, 0x2e, 0x60, 0xf5, 0xf6, 0x6f, 0xe7, 0x6f,
0xe0, 0x5f, 0xc8, 0x2e, 0x80, 0x2e, 0xfb, 0x00, 0x00, 0x30, 0xc0, 0x2e, 0x21, 0x2e, 0x8d, 0x00, 0x44, 0x47, 0x99,
0x00, 0xff, 0x3f, 0x00, 0x0c, 0xff, 0x0f, 0x00, 0x04, 0xc0, 0x00, 0x5b, 0xf5, 0x90, 0x00, 0x1e, 0xf2, 0xfd, 0xf5,
0x8e, 0x00, 0x96, 0x00, 0x96, 0x00, 0xe0, 0x00, 0x19, 0xf4, 0x66, 0xf5, 0x00, 0x18, 0x64, 0xf5, 0x9d, 0x00, 0x7f,
0x00, 0x81, 0x00, 0xae, 0x00, 0xff, 0xfb, 0x21, 0x02, 0x00, 0x10, 0x00, 0x40, 0xff, 0x00, 0x00, 0x80, 0xff, 0x7f,
0x54, 0x0f, 0xeb, 0x00, 0x7f, 0xff, 0xc2, 0xf5, 0x68, 0xf7, 0xb3, 0xf1, 0x4e, 0x0f, 0x42, 0x0f, 0x48, 0x0f, 0x80,
0x00, 0x67, 0x0f, 0x58, 0xf7, 0x5b, 0xf7, 0x6a, 0x0f, 0x86, 0x00, 0x59, 0x0f, 0x6c, 0x0f, 0xc6, 0xf1, 0x66, 0x0f,
0x6c, 0xf7, 0x00, 0xe0, 0x00, 0xff, 0xd1, 0xf5, 0x6e, 0x0f, 0x71, 0x0f, 0xff, 0x03, 0x00, 0xfc, 0xf0, 0x3f, 0xb9,
0x00, 0x2d, 0xf5, 0xca, 0xf5, 0x8a, 0x00, 0x00, 0x08, 0x71, 0x7d, 0xfe, 0xc0, 0x03, 0x3f, 0x05, 0x3e, 0x49, 0x01,
0x92, 0x02, 0xf5, 0xd6, 0xe8, 0x63, 0xd3, 0xf8, 0x2e, 0x07, 0x5c, 0xce, 0xa5, 0x67, 0x28, 0x02, 0x4e, 0x01, 0x00,
0xf0, 0x33, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x15, 0x50, 0x10,
0x50, 0x17, 0x52, 0x05, 0x2e, 0x7d, 0x00, 0xfb, 0x7f, 0x00, 0x2e, 0x13, 0x40, 0x93, 0x42, 0x41, 0x0e, 0xfb, 0x2f,
0x98, 0x2e, 0x91, 0x03, 0x98, 0x2e, 0x87, 0xcf, 0x01, 0x2e, 0x89, 0x00, 0x00, 0xb2, 0x08, 0x2f, 0x01, 0x2e, 0x69,
0xf7, 0xb1, 0x3f, 0x01, 0x08, 0x01, 0x30, 0x23, 0x2e, 0x89, 0x00, 0x21, 0x2e, 0x69, 0xf7, 0xfb, 0x6f, 0xf0, 0x5f,
0xb8, 0x2e, 0xa0, 0x50, 0x80, 0x7f, 0xe7, 0x7f, 0xd5, 0x7f, 0xc4, 0x7f, 0xb3, 0x7f, 0xa2, 0x7f, 0x91, 0x7f, 0xf6,
0x7f, 0x7b, 0x7f, 0x00, 0x2e, 0x01, 0x2e, 0x60, 0xf5, 0x60, 0x7f, 0x98, 0x2e, 0xce, 0x00, 0x62, 0x6f, 0x01, 0x32,
0x91, 0x08, 0x80, 0xb2, 0x11, 0x2f, 0x00, 0xb2, 0x03, 0x2f, 0x05, 0x2e, 0x18, 0x00, 0x80, 0x90, 0x09, 0x2f, 0x60,
0x7f, 0x98, 0x2e, 0xf9, 0x00, 0x23, 0x50, 0x01, 0x32, 0x01, 0x42, 0x02, 0x86, 0x60, 0x6f, 0x02, 0x30, 0xc2, 0x42,
0x23, 0x2e, 0x60, 0xf5, 0x00, 0x90, 0x00, 0x30, 0x01, 0x2f, 0x21, 0x2e, 0x7a, 0x00, 0xf6, 0x6f, 0x91, 0x6f, 0xa2,
0x6f, 0xb3, 0x6f, 0xc4, 0x6f, 0xd5, 0x6f, 0xe7, 0x6f, 0x7b, 0x6f, 0x80, 0x6f, 0x60, 0x5f, 0xc8, 0x2e, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2d, 0x01, 0xd4, 0x7b, 0x3b,
0x01, 0xdb, 0x7a, 0x04, 0x00, 0x3f, 0x7b, 0xcd, 0x6c, 0xc3, 0x04, 0x85, 0x09, 0xc3, 0x04, 0xec, 0xe6, 0x0c, 0x46,
0x01, 0x00, 0x27, 0x00, 0x19, 0x00, 0x96, 0x00, 0xa0, 0x00, 0x01, 0x00, 0x0c, 0x00, 0xf0, 0x3c, 0x00, 0x01, 0x01,
0x00, 0x03, 0x00, 0x01, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x01, 0x00, 0x07, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x01, 0x00, 0xe1, 0x06, 0x66, 0x0a, 0x0a, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x50, 0x98, 0x2e, 0xd7, 0x0e, 0x50, 0x32, 0x98, 0x2e,
0x48, 0x03, 0x10, 0x30, 0x21, 0x2e, 0x21, 0xf2, 0x00, 0x30, 0x00, 0x2e, 0x00, 0x2e, 0xd0, 0x2e, 0x00, 0x2e, 0x01,
0x80, 0x06, 0xa2, 0xfb, 0x2f, 0x01, 0x2e, 0x9c, 0x00, 0x00, 0xb2, 0x10, 0x2f, 0x01, 0x2e, 0x18, 0x00, 0x00, 0xb2,
0x0c, 0x2f, 0x01, 0x54, 0x03, 0x52, 0x01, 0x50, 0x98, 0x2e, 0xc2, 0xc0, 0x98, 0x2e, 0xf5, 0xb0, 0x01, 0x50, 0x98,
0x2e, 0xd5, 0xb6, 0x10, 0x30, 0x21, 0x2e, 0x19, 0x00, 0x01, 0x2e, 0x84, 0x00, 0x04, 0xae, 0x0b, 0x2f, 0x01, 0x2e,
0x9c, 0x00, 0x00, 0xb2, 0x07, 0x2f, 0x01, 0x52, 0x98, 0x2e, 0x8e, 0x0e, 0x00, 0xb2, 0x02, 0x2f, 0x10, 0x30, 0x21,
0x2e, 0x79, 0x00, 0x01, 0x2e, 0x79, 0x00, 0x00, 0x90, 0x90, 0x2e, 0x14, 0x03, 0x01, 0x2e, 0x87, 0x00, 0x00, 0xb2,
0x04, 0x2f, 0x98, 0x2e, 0x2f, 0x0e, 0x00, 0x30, 0x21, 0x2e, 0x7b, 0x00, 0x01, 0x2e, 0x7b, 0x00, 0x00, 0xb2, 0x12,
0x2f, 0x01, 0x2e, 0x84, 0x00, 0x00, 0x90, 0x02, 0x2f, 0x98, 0x2e, 0x1f, 0x0e, 0x09, 0x2d, 0x98, 0x2e, 0x81, 0x0d,
0x01, 0x2e, 0x84, 0x00, 0x04, 0x90, 0x02, 0x2f, 0x50, 0x32, 0x98, 0x2e, 0x48, 0x03, 0x00, 0x30, 0x21, 0x2e, 0x7b,
0x00, 0x01, 0x2e, 0x78, 0x00, 0x00, 0xb2, 0x90, 0x2e, 0x2c, 0x03, 0x01, 0x2e, 0x78, 0x00, 0x81, 0x30, 0x01, 0x08,
0x00, 0xb2, 0x61, 0x2f, 0x03, 0x2e, 0x24, 0x02, 0x01, 0x2e, 0x84, 0x00, 0x98, 0xbc, 0x98, 0xb8, 0x05, 0xb2, 0x0d,
0x58, 0x23, 0x2f, 0x07, 0x90, 0x07, 0x54, 0x00, 0x30, 0x37, 0x2f, 0x15, 0x41, 0x04, 0x41, 0xdc, 0xbe, 0x44, 0xbe,
0xdc, 0xba, 0x2c, 0x01, 0x61, 0x00, 0x0d, 0x56, 0x4a, 0x0f, 0x0c, 0x2f, 0xd1, 0x42, 0x94, 0xb8, 0xc1, 0x42, 0x11,
0x30, 0x05, 0x2e, 0x6a, 0xf7, 0x2c, 0xbd, 0x2f, 0xb9, 0x80, 0xb2, 0x08, 0x22, 0x98, 0x2e, 0xaf, 0x03, 0x21, 0x2d,
0x61, 0x30, 0x23, 0x2e, 0x84, 0x00, 0x98, 0x2e, 0xaf, 0x03, 0x00, 0x30, 0x21, 0x2e, 0x5a, 0xf5, 0x18, 0x2d, 0xf1,
0x7f, 0x50, 0x30, 0x98, 0x2e, 0x48, 0x03, 0x0d, 0x52, 0x05, 0x50, 0x50, 0x42, 0x70, 0x30, 0x0b, 0x54, 0x42, 0x42,
0x7e, 0x82, 0xf2, 0x6f, 0x80, 0xb2, 0x42, 0x42, 0x05, 0x2f, 0x21, 0x2e, 0x84, 0x00, 0x10, 0x30, 0x98, 0x2e, 0xaf,
0x03, 0x03, 0x2d, 0x60, 0x30, 0x21, 0x2e, 0x84, 0x00, 0x01, 0x2e, 0x84, 0x00, 0x06, 0x90, 0x18, 0x2f, 0x01, 0x2e,
0x77, 0x00, 0x09, 0x54, 0x05, 0x52, 0xf0, 0x7f, 0x98, 0x2e, 0x7a, 0xc1, 0xf1, 0x6f, 0x08, 0x1a, 0x40, 0x30, 0x08,
0x2f, 0x21, 0x2e, 0x84, 0x00, 0x20, 0x30, 0x98, 0x2e, 0x9b, 0x03, 0x50, 0x32, 0x98, 0x2e, 0x48, 0x03, 0x05, 0x2d,
0x98, 0x2e, 0x38, 0x0e, 0x00, 0x30, 0x21, 0x2e, 0x84, 0x00, 0x00, 0x30, 0x21, 0x2e, 0x78, 0x00, 0x18, 0x2d, 0x01,
0x2e, 0x84, 0x00, 0x03, 0xaa, 0x01, 0x2f, 0x98, 0x2e, 0x45, 0x0e, 0x01, 0x2e, 0x84, 0x00, 0x3f, 0x80, 0x03, 0xa2,
0x01, 0x2f, 0x00, 0x2e, 0x02, 0x2d, 0x98, 0x2e, 0x5b, 0x0e, 0x30, 0x30, 0x98, 0x2e, 0xba, 0x03, 0x00, 0x30, 0x21,
0x2e, 0x79, 0x00, 0x50, 0x32, 0x98, 0x2e, 0x48, 0x03, 0x01, 0x2e, 0x19, 0x00, 0x00, 0xb2, 0x10, 0x2f, 0x01, 0x2e,
0x85, 0x00, 0x21, 0x2e, 0x90, 0x00, 0x0f, 0x52, 0x7e, 0x82, 0x11, 0x50, 0x41, 0x40, 0x18, 0xb9, 0x11, 0x42, 0x02,
0x42, 0x02, 0x80, 0x00, 0x2e, 0x01, 0x40, 0x01, 0x42, 0x98, 0x2e, 0xaa, 0x01, 0x00, 0x30, 0x21, 0x2e, 0x19, 0x00,
0x21, 0x2e, 0x9c, 0x00, 0x80, 0x2e, 0x52, 0x02, 0x21, 0x2e, 0x59, 0xf5, 0x10, 0x30, 0xc0, 0x2e, 0x21, 0x2e, 0x4a,
0xf1, 0x80, 0x2e, 0x00, 0xc1, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x9a, 0x01,
0x34, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x03, 0x2e, 0x7d, 0x00, 0x16, 0xb8, 0x02, 0x34, 0x4a, 0x0c, 0x21, 0x2e, 0x2d, 0xf5, 0xc0, 0x2e, 0x23,
0x2e, 0x7d, 0x00, 0x03, 0xbc, 0x21, 0x2e, 0x85, 0x00, 0x03, 0x2e, 0x85, 0x00, 0x40, 0xb2, 0x10, 0x30, 0x21, 0x2e,
0x19, 0x00, 0x01, 0x30, 0x05, 0x2f, 0x05, 0x2e, 0x88, 0x00, 0x80, 0x90, 0x01, 0x2f, 0x23, 0x2e, 0x6f, 0xf5, 0xc0,
0x2e, 0x21, 0x2e, 0x89, 0x00, 0x11, 0x30, 0x81, 0x08, 0x01, 0x2e, 0x6a, 0xf7, 0x71, 0x3f, 0x23, 0xbd, 0x01, 0x08,
0x02, 0x0a, 0xc0, 0x2e, 0x21, 0x2e, 0x6a, 0xf7, 0x30, 0x25, 0x00, 0x30, 0x21, 0x2e, 0x5a, 0xf5, 0x10, 0x50, 0x21,
0x2e, 0x7b, 0x00, 0x21, 0x2e, 0x78, 0x00, 0xfb, 0x7f, 0x98, 0x2e, 0xaf, 0x03, 0x40, 0x30, 0x21, 0x2e, 0x84, 0x00,
0xfb, 0x6f, 0xf0, 0x5f, 0x03, 0x25, 0x80, 0x2e, 0x9b, 0x03, 0x0b, 0x00, 0x94, 0x02, 0x14, 0x24, 0x80, 0x00, 0x04,
0x00, 0x04, 0x30, 0x08, 0xb8, 0x94, 0x02, 0xc0, 0x2e, 0x28, 0xbd, 0x02, 0x0a, 0x0d, 0x82, 0x02, 0x30, 0x12, 0x42,
0x41, 0x0e, 0xfc, 0x2f, 0xb8, 0x2e, 0x95, 0x50, 0xc0, 0x2e, 0x21, 0x2e, 0xa9, 0x01, 0x02, 0x30, 0x02, 0x2c, 0x41,
0x00, 0x12, 0x42, 0x41, 0x0e, 0xfc, 0x2f, 0xb8, 0x2e, 0x13, 0x82, 0x02, 0x30, 0x12, 0x42, 0x41, 0x0e, 0xfc, 0x2f,
0x3f, 0x80, 0xa1, 0x30, 0xc0, 0x2e, 0x01, 0x42, 0x00, 0x2e, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80,
0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0xc0, 0x50, 0xe7, 0x7f,
0xf6, 0x7f, 0x26, 0x30, 0x0f, 0x2e, 0x61, 0xf5, 0x2f, 0x2e, 0x78, 0x00, 0x0f, 0x2e, 0x78, 0x00, 0xbe, 0x09, 0xa2,
0x7f, 0x80, 0x7f, 0x80, 0xb3, 0xd5, 0x7f, 0xc4, 0x7f, 0xb3, 0x7f, 0x91, 0x7f, 0x7b, 0x7f, 0x0b, 0x2f, 0x19, 0x50,
0x1a, 0x25, 0x12, 0x40, 0x42, 0x7f, 0x74, 0x82, 0x12, 0x40, 0x52, 0x7f, 0x00, 0x2e, 0x00, 0x40, 0x60, 0x7f, 0x98,
0x2e, 0x6a, 0xd6, 0x81, 0x30, 0x01, 0x2e, 0x78, 0x00, 0x01, 0x08, 0x00, 0xb2, 0x42, 0x2f, 0x03, 0x2e, 0x24, 0x02,
0x01, 0x2e, 0x24, 0x02, 0x97, 0xbc, 0x06, 0xbc, 0x9f, 0xb8, 0x0f, 0xb8, 0x00, 0x90, 0x23, 0x2e, 0x88, 0x00, 0x10,
0x30, 0x01, 0x30, 0x2a, 0x2f, 0x03, 0x2e, 0x84, 0x00, 0x44, 0xb2, 0x05, 0x2f, 0x47, 0xb2, 0x00, 0x30, 0x2d, 0x2f,
0x21, 0x2e, 0x78, 0x00, 0x2b, 0x2d, 0x03, 0x2e, 0xfd, 0xf5, 0x9e, 0xbc, 0x9f, 0xb8, 0x40, 0x90, 0x14, 0x2f, 0x03,
0x2e, 0xfc, 0xf5, 0x99, 0xbc, 0x9f, 0xb8, 0x40, 0x90, 0x0e, 0x2f, 0x03, 0x2e, 0x49, 0xf1, 0x1b, 0x54, 0x4a, 0x08,
0x40, 0x90, 0x08, 0x2f, 0x98, 0x2e, 0xce, 0x00, 0x00, 0xb2, 0x10, 0x30, 0x03, 0x2f, 0x50, 0x30, 0x21, 0x2e, 0x84,
0x00, 0x10, 0x2d, 0x98, 0x2e, 0x9b, 0x03, 0x00, 0x30, 0x21, 0x2e, 0x78, 0x00, 0x0a, 0x2d, 0x05, 0x2e, 0x69, 0xf7,
0x2d, 0xbd, 0x2f, 0xb9, 0x80, 0xb2, 0x01, 0x2f, 0x21, 0x2e, 0x79, 0x00, 0x23, 0x2e, 0x78, 0x00, 0xe0, 0x31, 0x21,
0x2e, 0x61, 0xf5, 0xf6, 0x6f, 0xe7, 0x6f, 0x80, 0x6f, 0xa2, 0x6f, 0xb3, 0x6f, 0xc4, 0x6f, 0xd5, 0x6f, 0x7b, 0x6f,
0x91, 0x6f, 0x40, 0x5f, 0xc8, 0x2e, 0x90, 0x50, 0xf7, 0x7f, 0xe6, 0x7f, 0xd5, 0x7f, 0xc4, 0x7f, 0xb3, 0x7f, 0xa1,
0x7f, 0x90, 0x7f, 0x82, 0x7f, 0x7b, 0x7f, 0x98, 0x2e, 0xce, 0x00, 0x00, 0xb2, 0x10, 0x30, 0x49, 0x2f, 0x05, 0x2e,
0x21, 0x02, 0x03, 0x2e, 0x2d, 0x02, 0x21, 0x56, 0x08, 0x08, 0x93, 0x08, 0x90, 0x0a, 0x25, 0x2e, 0x18, 0x00, 0x05,
0x2e, 0xc1, 0xf5, 0x2e, 0xbc, 0x05, 0x2e, 0x84, 0x00, 0x84, 0xa2, 0x0e, 0xb8, 0x31, 0x30, 0x88, 0x04, 0x03, 0x2f,
0x01, 0x2e, 0x18, 0x00, 0x00, 0xb2, 0x0c, 0x2f, 0x1d, 0x50, 0x01, 0x52, 0x98, 0x2e, 0xd7, 0x00, 0x05, 0x2e, 0x7a,
0x00, 0x80, 0x90, 0x02, 0x2f, 0x10, 0x30, 0x21, 0x2e, 0x7a, 0x00, 0x25, 0x2e, 0x9c, 0x00, 0x05, 0x2e, 0x18, 0x00,
0x80, 0xb2, 0x20, 0x2f, 0x01, 0x2e, 0xc0, 0xf5, 0xf2, 0x30, 0x02, 0x08, 0x07, 0xaa, 0x73, 0x30, 0x03, 0x2e, 0x7c,
0x00, 0x18, 0x22, 0x41, 0x1a, 0x05, 0x2f, 0x03, 0x2e, 0x66, 0xf5, 0x9f, 0xbc, 0x9f, 0xb8, 0x40, 0x90, 0x0c, 0x2f,
0x1f, 0x52, 0x03, 0x30, 0x53, 0x42, 0x2b, 0x30, 0x90, 0x04, 0x5b, 0x42, 0x21, 0x2e, 0x7c, 0x00, 0x24, 0xbd, 0x7e,
0x80, 0x81, 0x84, 0x43, 0x42, 0x02, 0x42, 0x02, 0x32, 0x25, 0x2e, 0x62, 0xf5, 0x05, 0x2e, 0x86, 0x00, 0x81, 0x84,
0x25, 0x2e, 0x86, 0x00, 0x02, 0x31, 0x25, 0x2e, 0x60, 0xf5, 0x05, 0x2e, 0x25, 0x02, 0x10, 0x30, 0x90, 0x08, 0x80,
0xb2, 0x0b, 0x2f, 0x05, 0x2e, 0xca, 0xf5, 0xf0, 0x3e, 0x90, 0x08, 0x25, 0x2e, 0xca, 0xf5, 0x05, 0x2e, 0x59, 0xf5,
0xe0, 0x3f, 0x90, 0x08, 0x25, 0x2e, 0x59, 0xf5, 0x90, 0x6f, 0xa1, 0x6f, 0xb3, 0x6f, 0xc4, 0x6f, 0xd5, 0x6f, 0xe6,
0x6f, 0xf7, 0x6f, 0x7b, 0x6f, 0x82, 0x6f, 0x70, 0x5f, 0xc8, 0x2e, 0x2f, 0x52, 0x90, 0x50, 0x53, 0x40, 0x4a, 0x25,
0x40, 0x40, 0x39, 0x8b, 0xfb, 0x7f, 0x0c, 0xbc, 0x21, 0x52, 0x37, 0x89, 0x0b, 0x30, 0x59, 0x08, 0x0c, 0xb8, 0xe0,
0x7f, 0x8b, 0x7f, 0x4b, 0x43, 0x0b, 0x43, 0x40, 0xb2, 0xd1, 0x7f, 0x6e, 0x2f, 0x01, 0x2e, 0x83, 0x00, 0x00, 0xb2,
0x0e, 0x2f, 0x25, 0x52, 0x01, 0x2e, 0x7e, 0x00, 0xc3, 0x7f, 0xb4, 0x7f, 0xa5, 0x7f, 0x98, 0x2e, 0xbb, 0xcc, 0x05,
0x30, 0x2b, 0x2e, 0x83, 0x00, 0xc3, 0x6f, 0xd1, 0x6f, 0xb4, 0x6f, 0xa5, 0x6f, 0x36, 0xbc, 0x06, 0xb9, 0x35, 0xbc,
0x0f, 0xb8, 0x94, 0xb0, 0xc6, 0x7f, 0x00, 0xb2, 0x0c, 0x2f, 0x27, 0x50, 0x29, 0x56, 0x0b, 0x30, 0x05, 0x2e, 0x21,
0x02, 0x2d, 0x5c, 0x1b, 0x42, 0xdb, 0x42, 0x96, 0x08, 0x25, 0x2e, 0x21, 0x02, 0x0b, 0x42, 0xcb, 0x42, 0x00, 0x2e,
0x31, 0x56, 0xcb, 0x08, 0x25, 0x52, 0x01, 0x2e, 0x7e, 0x00, 0x01, 0x54, 0x2b, 0x5c, 0x98, 0x2e, 0x06, 0xcd, 0xd2,
0x6f, 0x27, 0x5a, 0x94, 0x6f, 0xa4, 0xbc, 0x53, 0x41, 0x00, 0xb3, 0x1f, 0xb8, 0x44, 0x41, 0x01, 0x30, 0xd5, 0x7f,
0x05, 0x2f, 0x00, 0xb2, 0x03, 0x2f, 0x29, 0x5c, 0x11, 0x30, 0x93, 0x43, 0x84, 0x43, 0x23, 0xbd, 0x2f, 0xb9, 0x80,
0xb2, 0x1c, 0x2f, 0x72, 0x6f, 0xda, 0x00, 0x82, 0x6f, 0x22, 0x03, 0x44, 0x43, 0x00, 0x90, 0x27, 0x2e, 0x7f, 0x00,
0x29, 0x5a, 0x12, 0x2f, 0x29, 0x54, 0x00, 0x2e, 0x90, 0x40, 0x82, 0x40, 0x18, 0x04, 0xa2, 0x06, 0x80, 0xaa, 0x04,
0x2f, 0x80, 0x90, 0x08, 0x2f, 0xc2, 0x6f, 0x50, 0x0f, 0x05, 0x2f, 0xc0, 0x6f, 0x00, 0xb2, 0x02, 0x2f, 0x53, 0x43,
0x44, 0x43, 0x11, 0x30, 0xe0, 0x6f, 0x98, 0x2e, 0x95, 0xcf, 0xd1, 0x6f, 0x15, 0x5a, 0x09, 0x2e, 0x7f, 0x00, 0x41,
0x40, 0x54, 0x43, 0x08, 0x2c, 0x41, 0x43, 0x15, 0x30, 0x2b, 0x2e, 0x83, 0x00, 0x01, 0x30, 0xe0, 0x6f, 0x98, 0x2e,
0x95, 0xcf, 0x00, 0x2e, 0xfb, 0x6f, 0x70, 0x5f, 0xb8, 0x2e, 0x50, 0x86, 0xcd, 0x88, 0x34, 0x85, 0xc5, 0x40, 0x91,
0x40, 0x8c, 0x80, 0x06, 0x41, 0x13, 0x40, 0x50, 0x50, 0x6e, 0x01, 0x82, 0x40, 0x04, 0x40, 0x34, 0x8c, 0xfb, 0x7f,
0x98, 0x2e, 0xce, 0x03, 0xe0, 0x7f, 0x00, 0x2e, 0x91, 0x41, 0x8c, 0x81, 0x82, 0x41, 0x13, 0x40, 0x04, 0x40, 0x34,
0x8e, 0x98, 0x2e, 0xce, 0x03, 0xc0, 0x7f, 0xd5, 0x7f, 0x13, 0x24, 0xff, 0x00, 0xd6, 0x41, 0xcc, 0x83, 0xc2, 0x41,
0x57, 0x40, 0x74, 0x80, 0x44, 0x40, 0x11, 0x40, 0x0c, 0x8a, 0xf7, 0x01, 0x94, 0x03, 0x12, 0x24, 0x80, 0x00, 0x3a,
0x01, 0x02, 0x30, 0xb2, 0x03, 0xce, 0x17, 0xfb, 0x08, 0x23, 0x01, 0xb2, 0x02, 0x48, 0xbb, 0x28, 0xbd, 0xf2, 0x0b,
0x53, 0x41, 0x02, 0x40, 0x44, 0x41, 0x74, 0x8d, 0xb7, 0x7f, 0x98, 0x2e, 0xce, 0x03, 0x50, 0x25, 0x91, 0x41, 0x8c,
0x81, 0x82, 0x41, 0x13, 0x40, 0x04, 0x40, 0x34, 0x8e, 0x98, 0x2e, 0xce, 0x03, 0x60, 0x25, 0xd1, 0x41, 0xcc, 0x81,
0xc2, 0x41, 0x13, 0x40, 0x04, 0x40, 0x98, 0x2e, 0xce, 0x03, 0x11, 0x24, 0xb3, 0x00, 0x71, 0x0e, 0xd3, 0x6f, 0xe1,
0x6f, 0x33, 0x2f, 0x12, 0x24, 0xdd, 0x00, 0xda, 0x0f, 0x2b, 0x2f, 0x12, 0x24, 0x8c, 0x00, 0x5a, 0x0e, 0x09, 0x2f,
0x10, 0x24, 0x83, 0x05, 0x48, 0x0e, 0x11, 0x24, 0x7f, 0x22, 0x10, 0x24, 0x18, 0x32, 0x08, 0x22, 0x80, 0x2e, 0xd7,
0xb4, 0x13, 0x24, 0xf4, 0x00, 0x73, 0x0e, 0x0f, 0x2f, 0x10, 0x24, 0x11, 0x10, 0x68, 0x0e, 0x10, 0x24, 0xa2, 0x30,
0x13, 0x24, 0x97, 0x23, 0x03, 0x22, 0x13, 0x24, 0x3b, 0x04, 0x4b, 0x0e, 0x11, 0x24, 0x0f, 0x30, 0x01, 0x22, 0x80,
0x2e, 0xd7, 0xb4, 0x11, 0x24, 0x53, 0x02, 0x41, 0x0e, 0x11, 0x24, 0xe7, 0x31, 0x10, 0x24, 0xfc, 0x25, 0x08, 0x22,
0x80, 0x2e, 0xd7, 0xb4, 0x10, 0x24, 0xe8, 0x40, 0x80, 0x2e, 0xd7, 0xb4, 0xf2, 0x37, 0x5a, 0x0e, 0x90, 0x2e, 0x50,
0xb3, 0x12, 0x24, 0xea, 0x00, 0x4a, 0x0e, 0x90, 0x2e, 0xc7, 0xb2, 0xc2, 0x6f, 0x14, 0x24, 0x4c, 0x0b, 0x54, 0x0e,
0x90, 0x2e, 0xab, 0xb2, 0x14, 0x24, 0x9b, 0x00, 0x5c, 0x0e, 0x90, 0x2e, 0xa1, 0xb2, 0x14, 0x24, 0x22, 0x01, 0x4c,
0x0e, 0x70, 0x2f, 0x82, 0xa3, 0x5e, 0x2f, 0x11, 0x24, 0xba, 0x0b, 0x51, 0x0e, 0x35, 0x2f, 0x11, 0x24, 0x03, 0x08,
0x69, 0x0e, 0x2d, 0x2f, 0xb1, 0x6f, 0x14, 0x24, 0x90, 0x00, 0x0c, 0x0e, 0x24, 0x2f, 0x11, 0x24, 0x31, 0x08, 0x69,
0x0e, 0x16, 0x2f, 0x11, 0x24, 0x7d, 0x01, 0x59, 0x0e, 0x0e, 0x2f, 0x11, 0x24, 0xd7, 0x0c, 0x51, 0x0e, 0x11, 0x24,
0x9f, 0x44, 0x13, 0x24, 0x41, 0x57, 0x4b, 0x22, 0x93, 0x35, 0x43, 0x0e, 0x10, 0x24, 0xbd, 0x42, 0x08, 0x22, 0x80,
0x2e, 0xd7, 0xb4, 0x10, 0x24, 0x1c, 0x42, 0x80, 0x2e, 0xd7, 0xb4, 0x11, 0x24, 0x47, 0x01, 0x59, 0x0e, 0x11, 0x24,
0xa2, 0x45, 0x10, 0x24, 0x31, 0x51, 0x08, 0x22, 0x80, 0x2e, 0xd7, 0xb4, 0x10, 0x24, 0x80, 0x41, 0x80, 0x2e, 0xd7,
0xb4, 0x10, 0x24, 0x67, 0x54, 0x80, 0x2e, 0xd7, 0xb4, 0x11, 0x24, 0x8c, 0x08, 0xe9, 0x0f, 0x10, 0x24, 0x0a, 0x48,
0x90, 0x2e, 0xd7, 0xb4, 0xb1, 0x6f, 0x13, 0x24, 0xe8, 0x03, 0x8b, 0x0f, 0x10, 0x24, 0xcd, 0x57, 0x90, 0x2e, 0xd7,
0xb4, 0x73, 0x35, 0x8b, 0x0f, 0x10, 0x24, 0x6f, 0x42, 0x90, 0x2e, 0xd7, 0xb4, 0x10, 0x24, 0xa0, 0xfe, 0x08, 0x0e,
0x10, 0x24, 0x38, 0x54, 0x13, 0x24, 0xa3, 0x46, 0x03, 0x22, 0x13, 0x24, 0x45, 0xfd, 0x0b, 0x0e, 0x11, 0x24, 0x04,
0x43, 0x08, 0x22, 0x80, 0x2e, 0xd7, 0xb4, 0xb1, 0x6f, 0x00, 0x3a, 0x08, 0x0e, 0x11, 0x24, 0x3d, 0x45, 0x10, 0x24,
0x52, 0x54, 0x48, 0x22, 0x10, 0x24, 0x8f, 0x01, 0x58, 0x0e, 0x10, 0x24, 0x48, 0x44, 0x01, 0x22, 0x80, 0x2e, 0xd7,
0xb4, 0xb1, 0x6f, 0x13, 0x24, 0xfa, 0x03, 0x0b, 0x0e, 0x11, 0x24, 0x85, 0x43, 0x13, 0x24, 0x35, 0x55, 0x4b, 0x22,
0x11, 0xa2, 0x10, 0x24, 0xf6, 0x57, 0x08, 0x22, 0x80, 0x2e, 0xd7, 0xb4, 0x11, 0x24, 0xa4, 0x0a, 0x69, 0x0e, 0x11,
0x24, 0x7b, 0x5a, 0x10, 0x24, 0x5e, 0x20, 0x08, 0x22, 0x80, 0x2e, 0xd7, 0xb4, 0x11, 0x24, 0x0f, 0x01, 0x59, 0x0e,
0x0d, 0x2f, 0x18, 0xa2, 0x11, 0x24, 0x2b, 0x47, 0x10, 0x24, 0xf4, 0x55, 0x48, 0x22, 0x10, 0x24, 0x16, 0x0b, 0x50,
0x0e, 0x10, 0x24, 0xc7, 0x51, 0x01, 0x22, 0x80, 0x2e, 0xd7, 0xb4, 0x11, 0x24, 0x72, 0x0a, 0x51, 0x0e, 0x11, 0x24,
0x85, 0x55, 0x10, 0x24, 0xb2, 0x47, 0x08, 0x22, 0x80, 0x2e, 0xd7, 0xb4, 0x10, 0x24, 0x83, 0x00, 0x48, 0x0e, 0x53,
0x2f, 0x11, 0x24, 0xe1, 0x07, 0x69, 0x0e, 0x2d, 0x2f, 0x95, 0xaf, 0x27, 0x2f, 0x82, 0xaf, 0x21, 0x2f, 0x11, 0x24,
0xd7, 0x00, 0x59, 0x0e, 0x19, 0x2f, 0xb1, 0x6f, 0x10, 0x24, 0xcc, 0x03, 0x88, 0x0f, 0x10, 0x2f, 0x10, 0x24, 0xe8,
0xfe, 0x08, 0x0e, 0x11, 0x24, 0x7e, 0x56, 0x10, 0x24, 0x94, 0x45, 0x48, 0x22, 0xc0, 0x6f, 0x13, 0x24, 0x06, 0x0b,
0x43, 0x0e, 0x10, 0x24, 0x2f, 0x51, 0x01, 0x22, 0x80, 0x2e, 0xd7, 0xb4, 0x10, 0x24, 0xde, 0x51, 0x80, 0x2e, 0xd7,
0xb4, 0x10, 0x24, 0xe8, 0x54, 0x80, 0x2e, 0xd7, 0xb4, 0x10, 0x24, 0xa4, 0x52, 0x80, 0x2e, 0xd7, 0xb4, 0x10, 0x24,
0xd0, 0x44, 0x80, 0x2e, 0xd7, 0xb4, 0x11, 0x24, 0xb8, 0x00, 0xd9, 0x0f, 0x19, 0x2f, 0xc1, 0x6f, 0x10, 0x24, 0xe7,
0x0c, 0xc8, 0x0f, 0x10, 0x2f, 0x11, 0x24, 0xc7, 0x07, 0x69, 0x0e, 0x11, 0x24, 0xf6, 0x52, 0x10, 0x24, 0x7a, 0x12,
0x48, 0x22, 0xb0, 0x6f, 0x13, 0x24, 0x5d, 0x02, 0x03, 0x0e, 0x10, 0x24, 0x7c, 0x54, 0x01, 0x22, 0x80, 0x2e, 0xd7,
0xb4, 0x10, 0x24, 0x8d, 0x51, 0x80, 0x2e, 0xd7, 0xb4, 0x10, 0x24, 0x28, 0x52, 0x80, 0x2e, 0xd7, 0xb4, 0x10, 0x24,
0xd2, 0x07, 0xe8, 0x0f, 0x28, 0x2f, 0x10, 0x24, 0xb0, 0x00, 0xd8, 0x0f, 0x20, 0x2f, 0x10, 0x24, 0xc6, 0x07, 0x68,
0x0e, 0x18, 0x2f, 0x50, 0x35, 0x48, 0x0e, 0x11, 0x2f, 0xb1, 0x6f, 0x10, 0x24, 0xf4, 0x01, 0x08, 0x0e, 0x11, 0x24,
0x35, 0x51, 0x10, 0x24, 0x22, 0x12, 0x48, 0x22, 0xc0, 0x6f, 0x13, 0x24, 0xe0, 0x0c, 0x43, 0x0e, 0x10, 0x24, 0x7b,
0x50, 0x08, 0x22, 0x80, 0x2e, 0xd7, 0xb4, 0x10, 0x24, 0x81, 0x52, 0x80, 0x2e, 0xd7, 0xb4, 0x10, 0x24, 0x3b, 0x53,
0x80, 0x2e, 0xd7, 0xb4, 0x10, 0x24, 0x63, 0x51, 0x80, 0x2e, 0xd7, 0xb4, 0x10, 0x24, 0x27, 0x51, 0x80, 0x2e, 0xd7,
0xb4, 0x18, 0xa2, 0x90, 0x2e, 0xdb, 0xb3, 0x12, 0x24, 0x08, 0x02, 0x4a, 0x0e, 0x37, 0x2f, 0x12, 0x24, 0x2a, 0x09,
0x6a, 0x0e, 0x1d, 0x2f, 0x13, 0x24, 0x8e, 0x00, 0x73, 0x0e, 0x09, 0x2f, 0x11, 0x24, 0xa5, 0x01, 0x41, 0x0e, 0x11,
0x24, 0x76, 0x32, 0x10, 0x24, 0x12, 0x25, 0x08, 0x22, 0x80, 0x2e, 0xd7, 0xb4, 0x10, 0x24, 0xa9, 0x0d, 0x68, 0x0e,
0x10, 0x24, 0x04, 0x27, 0x13, 0x24, 0x73, 0x20, 0x03, 0x22, 0x13, 0x24, 0x14, 0x04, 0x4b, 0x0e, 0x11, 0x24, 0x15,
0x2c, 0x01, 0x22, 0x80, 0x2e, 0xd7, 0xb4, 0x11, 0x24, 0xae, 0x08, 0x69, 0x0e, 0x08, 0x2f, 0xa1, 0x35, 0x71, 0x0e,
0x11, 0x24, 0x8b, 0x2b, 0x10, 0x24, 0x07, 0x35, 0x08, 0x22, 0x80, 0x2e, 0xd7, 0xb4, 0x91, 0x34, 0x59, 0x0e, 0x11,
0x24, 0x7b, 0x19, 0x10, 0x24, 0x50, 0x59, 0x08, 0x22, 0x80, 0x2e, 0xd7, 0xb4, 0x62, 0x32, 0x42, 0x0e, 0x22, 0x2f,
0xa2, 0x32, 0x5a, 0x0e, 0x1b, 0x2f, 0x12, 0x24, 0x0b, 0x08, 0x6a, 0x0e, 0x0e, 0x2f, 0xa3, 0x34, 0x43, 0x0e, 0x10,
0x24, 0x28, 0x2b, 0x13, 0x24, 0x20, 0x23, 0x03, 0x22, 0x13, 0x24, 0x8d, 0x01, 0x4b, 0x0e, 0x11, 0x24, 0x5c, 0x21,
0x08, 0x22, 0x80, 0x2e, 0xd7, 0xb4, 0x31, 0x36, 0x59, 0x0e, 0x11, 0x24, 0x43, 0x25, 0x10, 0x24, 0xfa, 0x49, 0x08,
0x22, 0x80, 0x2e, 0xd7, 0xb4, 0x10, 0x24, 0xc7, 0x2a, 0x80, 0x2e, 0xd7, 0xb4, 0x40, 0x36, 0x58, 0x0e, 0x09, 0x2f,
0x11, 0x24, 0x9e, 0x08, 0x69, 0x0e, 0x11, 0x24, 0xe3, 0x54, 0x10, 0x24, 0x73, 0x22, 0x08, 0x22, 0x80, 0x2e, 0xd7,
0xb4, 0x10, 0x24, 0x38, 0x01, 0xc8, 0x0f, 0x10, 0x2f, 0x11, 0x24, 0x11, 0x08, 0x69, 0x0e, 0x11, 0x24, 0x6e, 0x48,
0x10, 0x24, 0x2b, 0x28, 0x48, 0x22, 0xc0, 0x6f, 0x13, 0x24, 0xc1, 0x0a, 0x43, 0x0e, 0x10, 0x24, 0x0f, 0x23, 0x08,
0x22, 0x80, 0x2e, 0xd7, 0xb4, 0x10, 0x24, 0xd0, 0x1a, 0x80, 0x2e, 0xd7, 0xb4, 0xe2, 0x33, 0x5a, 0x0e, 0x77, 0x2f,
0x12, 0x24, 0x0c, 0x08, 0x6a, 0x0e, 0x2a, 0x2f, 0x12, 0x24, 0xc5, 0x00, 0x4a, 0x0e, 0x08, 0x2f, 0x11, 0x36, 0x59,
0x0e, 0x11, 0x24, 0xfd, 0x18, 0x10, 0x24, 0x75, 0x58, 0x08, 0x22, 0x80, 0x2e, 0xd7, 0xb4, 0xc2, 0x34, 0x5a, 0x0e,
0x0d, 0x2f, 0x11, 0x24, 0x36, 0x08, 0x69, 0x0e, 0x11, 0x24, 0x08, 0x58, 0x13, 0x24, 0x3b, 0x54, 0x4b, 0x22, 0x01,
0xa2, 0x10, 0x24, 0xc6, 0x52, 0x08, 0x22, 0x80, 0x2e, 0xd7, 0xb4, 0xb3, 0x36, 0x4b, 0x0e, 0x11, 0x24, 0x0e, 0x24,
0x13, 0x24, 0x7b, 0x50, 0x59, 0x22, 0x0e, 0xa2, 0x10, 0x24, 0xf7, 0x56, 0x01, 0x22, 0x80, 0x2e, 0xd7, 0xb4, 0xc2,
0x35, 0x5a, 0x0e, 0x12, 0x2f, 0x01, 0xa2, 0x0c, 0x2f, 0x84, 0xa3, 0x10, 0x24, 0xd4, 0x58, 0x13, 0x24, 0x76, 0x56,
0x03, 0x22, 0x73, 0x36, 0x4b, 0x0e, 0x11, 0x24, 0xeb, 0x52, 0x08, 0x22, 0x80, 0x2e, 0xd7, 0xb4, 0x10, 0x24, 0x87,
0x16, 0x80, 0x2e, 0xd7, 0xb4, 0xb0, 0x6f, 0x13, 0x24, 0x02, 0xfd, 0x03, 0x0e, 0x29, 0x2f, 0x84, 0xa3, 0xc0, 0x6f,
0x09, 0x2f, 0x11, 0x24, 0xe4, 0x0a, 0x41, 0x0e, 0x11, 0x24, 0x5d, 0x44, 0x10, 0x24, 0x2f, 0x5a, 0x08, 0x22, 0x80,
0x2e, 0xd7, 0xb4, 0x13, 0x24, 0x96, 0x0c, 0x43, 0x0e, 0x0e, 0x2f, 0x40, 0x33, 0x48, 0x0e, 0x10, 0x24, 0xf2, 0x18,
0x13, 0x24, 0x31, 0x49, 0x03, 0x22, 0x13, 0x24, 0x99, 0x00, 0x4b, 0x0e, 0x11, 0x24, 0xab, 0x18, 0x01, 0x22, 0x80,
0x2e, 0xd7, 0xb4, 0x11, 0x24, 0xc6, 0x07, 0x69, 0x0e, 0x11, 0x24, 0xb0, 0x49, 0x10, 0x24, 0xbf, 0x17, 0x08, 0x22,
0x80, 0x2e, 0xd7, 0xb4, 0x10, 0x24, 0x03, 0x15, 0x80, 0x2e, 0xd7, 0xb4, 0xb0, 0x32, 0x48, 0x0e, 0x57, 0x2f, 0xa0,
0x37, 0x48, 0x0e, 0x13, 0x2f, 0x83, 0xa3, 0x08, 0x2f, 0x10, 0x24, 0xe0, 0x00, 0x48, 0x0e, 0x11, 0x24, 0xf6, 0x25,
0x10, 0x24, 0x75, 0x17, 0x71, 0x2c, 0x08, 0x22, 0x10, 0x24, 0xa0, 0x00, 0x48, 0x0e, 0x11, 0x24, 0x7f, 0x18, 0x10,
0x24, 0xa6, 0x13, 0x68, 0x2c, 0x08, 0x22, 0x11, 0x24, 0xf9, 0x07, 0x69, 0x0e, 0x0d, 0x2f, 0x11, 0x24, 0x10, 0x08,
0x69, 0x0e, 0x11, 0x24, 0xb1, 0x14, 0x10, 0x24, 0x8e, 0x58, 0x48, 0x22, 0x90, 0x32, 0x58, 0x0e, 0x10, 0x24, 0x6d,
0x14, 0x56, 0x2c, 0x01, 0x22, 0xc1, 0x6f, 0x10, 0x24, 0x68, 0x0c, 0x48, 0x0e, 0xb1, 0x6f, 0x0c, 0x2f, 0xcd, 0xa2,
0x10, 0x24, 0x23, 0x14, 0x13, 0x24, 0x8d, 0x42, 0x03, 0x22, 0x13, 0x24, 0x2a, 0xfd, 0x0b, 0x0e, 0x11, 0x24, 0x53,
0x12, 0x43, 0x2c, 0x08, 0x22, 0x10, 0x24, 0xcc, 0x07, 0x68, 0x0e, 0x0e, 0x2f, 0x10, 0x24, 0x08, 0xfd, 0x08, 0x0e,
0x10, 0x24, 0x08, 0x16, 0x13, 0x24, 0x83, 0x45, 0x03, 0x22, 0x13, 0x24, 0xa1, 0xfd, 0x0b, 0x0e, 0x11, 0x24, 0xa6,
0x14, 0x30, 0x2c, 0x01, 0x22, 0x10, 0x24, 0x5b, 0x01, 0x08, 0x0e, 0x11, 0x24, 0x2f, 0x12, 0x10, 0x24, 0xdd, 0x44,
0x27, 0x2c, 0x08, 0x22, 0xdb, 0xa2, 0x0f, 0x2f, 0xc1, 0x6f, 0x10, 0x24, 0xb2, 0x0b, 0x48, 0x0e, 0x11, 0x24, 0x21,
0x55, 0x10, 0x24, 0xc8, 0x14, 0x48, 0x22, 0x10, 0x24, 0x4c, 0x08, 0x68, 0x0e, 0x10, 0x24, 0xe4, 0x57, 0x15, 0x2c,
0x01, 0x22, 0x44, 0xa2, 0x0f, 0x2f, 0xc1, 0x6f, 0x10, 0x24, 0xcb, 0x0b, 0x48, 0x0e, 0x11, 0x24, 0x09, 0x58, 0x10,
0x24, 0xe4, 0x10, 0x48, 0x22, 0x10, 0x24, 0x4d, 0x08, 0x68, 0x0e, 0x10, 0x24, 0x1a, 0x12, 0x03, 0x2c, 0x01, 0x22,
0x10, 0x24, 0x0c, 0x10, 0xfb, 0x6f, 0xb0, 0x5f, 0xb8, 0x2e, 0xa3, 0x32, 0xc3, 0x00, 0x60, 0x51, 0xc2, 0x40, 0x81,
0x84, 0xd3, 0x7f, 0xd2, 0x42, 0xe0, 0x7f, 0x00, 0x30, 0xc4, 0x40, 0x20, 0x02, 0xc3, 0x7f, 0xd0, 0x42, 0x42, 0x3d,
0xc0, 0x40, 0x01, 0x80, 0xc0, 0x42, 0xda, 0x00, 0x93, 0x7f, 0xb1, 0x7f, 0xab, 0x7f, 0x98, 0x2e, 0xb3, 0xc0, 0x91,
0x6f, 0xf3, 0x32, 0x40, 0x42, 0x00, 0xac, 0x8b, 0x00, 0x02, 0x2f, 0xe1, 0x6f, 0x39, 0x56, 0x43, 0x42, 0xa1, 0x82,
0x91, 0x7f, 0x33, 0x33, 0x4b, 0x00, 0x81, 0x7f, 0x13, 0x3c, 0x4b, 0x00, 0x80, 0x40, 0x53, 0x34, 0xb5, 0x6f, 0x8b,
0x00, 0x0d, 0xb0, 0x43, 0x87, 0x76, 0x7f, 0xb2, 0x7f, 0x63, 0x7f, 0x65, 0x25, 0xb5, 0x6f, 0x92, 0x41, 0x63, 0x41,
0x64, 0x41, 0x44, 0x81, 0x56, 0x7f, 0x41, 0x7f, 0x00, 0x2e, 0x26, 0x40, 0x27, 0x40, 0x45, 0x41, 0xf7, 0x7f, 0xb0,
0x7f, 0x98, 0x2e, 0x67, 0xcc, 0x81, 0x6f, 0x0f, 0xa4, 0x43, 0x40, 0x72, 0x6f, 0x94, 0x6f, 0x05, 0x30, 0x01, 0x2f,
0xc0, 0xa0, 0x03, 0x2f, 0x31, 0xac, 0x07, 0x2f, 0xc0, 0xa4, 0x05, 0x2f, 0xa2, 0x00, 0xeb, 0x04, 0x80, 0x40, 0x01,
0x80, 0x43, 0x42, 0x80, 0x42, 0x41, 0x86, 0x56, 0x6f, 0x62, 0x6f, 0x41, 0x6f, 0x42, 0x82, 0x72, 0x0e, 0x83, 0x7f,
0xd5, 0x2f, 0x53, 0x32, 0x8b, 0x00, 0xa1, 0x86, 0x56, 0x25, 0xf0, 0x82, 0x82, 0x40, 0x8d, 0xb0, 0x52, 0x40, 0xde,
0x00, 0x91, 0x7f, 0xb3, 0x7f, 0x85, 0x7f, 0xb3, 0x30, 0x7b, 0x52, 0x98, 0x2e, 0x5a, 0xca, 0x1a, 0x25, 0x83, 0x6f,
0x6d, 0x82, 0xfd, 0x88, 0x50, 0x7f, 0x71, 0x7f, 0x81, 0x7f, 0x05, 0x30, 0x83, 0x30, 0x00, 0x30, 0x11, 0x41, 0x52,
0x6f, 0x25, 0x7f, 0x30, 0x7f, 0x44, 0x7f, 0x98, 0x2e, 0x0f, 0xca, 0x73, 0x6f, 0x20, 0x25, 0x90, 0x6f, 0x7d, 0x52,
0xd2, 0x42, 0x73, 0x7f, 0x12, 0x7f, 0x98, 0x2e, 0x86, 0xb7, 0x93, 0x6f, 0x11, 0x6f, 0xd2, 0x40, 0x0a, 0x18, 0x31,
0x6f, 0x0e, 0x00, 0x93, 0x7f, 0x83, 0x30, 0x44, 0x6f, 0x21, 0x6f, 0x62, 0x6f, 0x62, 0x0e, 0x4f, 0x03, 0xe1, 0x2f,
0x33, 0x52, 0x01, 0x00, 0x01, 0x30, 0x69, 0x03, 0x3a, 0x25, 0xea, 0x82, 0x92, 0x6f, 0xf0, 0x86, 0xd1, 0xbe, 0x0f,
0xb8, 0xbd, 0x84, 0x94, 0x7f, 0x05, 0x0a, 0x23, 0x7f, 0x52, 0x7f, 0x40, 0x7f, 0x31, 0x7f, 0x71, 0x7f, 0xd3, 0x30,
0x84, 0x6f, 0x55, 0x6f, 0x10, 0x41, 0x52, 0x41, 0x41, 0x6f, 0x55, 0x7f, 0x10, 0x7f, 0x04, 0x7f, 0x98, 0x2e, 0x0f,
0xca, 0x11, 0x6f, 0x20, 0x25, 0x98, 0x2e, 0xfe, 0xc9, 0x31, 0x6f, 0x04, 0x6f, 0x50, 0x42, 0x31, 0x7f, 0xd3, 0x30,
0x21, 0x6f, 0x61, 0x0e, 0xea, 0x2f, 0xb1, 0x6f, 0x41, 0x84, 0x32, 0x25, 0x90, 0x40, 0x84, 0x40, 0x71, 0x6f, 0xb4,
0x7f, 0x72, 0x7f, 0x40, 0x7f, 0x33, 0x7f, 0x98, 0x2e, 0xb3, 0xc0, 0x53, 0x6f, 0xb1, 0x32, 0x99, 0x00, 0x83, 0xb9,
0x41, 0x6f, 0x4b, 0x00, 0xb0, 0x6f, 0x03, 0x30, 0xc3, 0x02, 0x84, 0x40, 0xb2, 0x7f, 0xa1, 0x84, 0x0d, 0xb1, 0x52,
0x7f, 0x56, 0x01, 0x74, 0x6f, 0x30, 0x6f, 0x92, 0x6f, 0x43, 0x8b, 0x03, 0x43, 0x01, 0x42, 0x95, 0x7f, 0xbd, 0x86,
0x51, 0x41, 0x41, 0x7f, 0x75, 0x7f, 0x00, 0x2e, 0xd1, 0x40, 0x42, 0x41, 0x32, 0x7f, 0x23, 0x7f, 0x98, 0x2e, 0x74,
0xc0, 0x41, 0x6f, 0xc8, 0x00, 0x90, 0x6f, 0x01, 0x30, 0x75, 0x6f, 0x32, 0x6f, 0x03, 0x42, 0x91, 0x02, 0x23, 0x6f,
0x61, 0x6f, 0x59, 0x0e, 0x62, 0x43, 0x95, 0x7f, 0xe7, 0x2f, 0xb2, 0x6f, 0x51, 0x6f, 0x82, 0x40, 0x8d, 0xb0, 0x8e,
0x00, 0xfd, 0x8a, 0xb2, 0x7f, 0x02, 0x30, 0x79, 0x52, 0x05, 0x25, 0x03, 0x30, 0x54, 0x40, 0xec, 0x01, 0x16, 0x40,
0x43, 0x89, 0xc7, 0x41, 0x37, 0x18, 0x3d, 0x8b, 0x96, 0x00, 0x44, 0x0e, 0xdf, 0x02, 0xf4, 0x2f, 0x09, 0x52, 0x51,
0x00, 0x02, 0x30, 0x9a, 0x02, 0xb5, 0x6f, 0x45, 0x87, 0x1b, 0xba, 0x25, 0xbc, 0x51, 0x6f, 0x4d, 0x8b, 0x7a, 0x82,
0xc6, 0x40, 0x20, 0x0a, 0x30, 0x00, 0xd0, 0x42, 0x2b, 0xb5, 0xc0, 0x40, 0x82, 0x02, 0x40, 0x34, 0x08, 0x00, 0xd2,
0x42, 0xb0, 0x7f, 0x75, 0x7f, 0x93, 0x7f, 0x00, 0x2e, 0xb5, 0x6f, 0xe2, 0x6f, 0x63, 0x41, 0x64, 0x41, 0x44, 0x8f,
0x82, 0x40, 0xe6, 0x41, 0xc0, 0x41, 0xc4, 0x8f, 0x45, 0x41, 0xf0, 0x7f, 0xb7, 0x7f, 0x61, 0x7f, 0x98, 0x2e, 0x67,
0xcc, 0x00, 0x18, 0x09, 0x52, 0x71, 0x00, 0x03, 0x30, 0xbb, 0x02, 0x1b, 0xba, 0x93, 0x6f, 0x25, 0xbc, 0x61, 0x6f,
0xc5, 0x40, 0x42, 0x82, 0x20, 0x0a, 0x28, 0x00, 0xd0, 0x42, 0x2b, 0xb9, 0xc0, 0x40, 0x82, 0x02, 0xd2, 0x42, 0x93,
0x7f, 0x00, 0x2e, 0x72, 0x6f, 0x5a, 0x0e, 0xd9, 0x2f, 0xb1, 0x6f, 0xf3, 0x3c, 0xcb, 0x00, 0xda, 0x82, 0xc3, 0x40,
0x41, 0x40, 0x59, 0x0e, 0x50, 0x2f, 0xe1, 0x6f, 0xe3, 0x32, 0xcb, 0x00, 0xb3, 0x7f, 0x22, 0x30, 0xc0, 0x40, 0x01,
0x80, 0xc0, 0x42, 0x02, 0xa2, 0x30, 0x2f, 0xc2, 0x42, 0x98, 0x2e, 0x83, 0xb1, 0xe1, 0x6f, 0xb3, 0x35, 0xcb, 0x00,
0x24, 0x3d, 0xc2, 0x40, 0xdc, 0x00, 0x84, 0x40, 0x00, 0x91, 0x93, 0x7f, 0x02, 0x2f, 0x00, 0x2e, 0x06, 0x2c, 0x0c,
0xb8, 0x30, 0x25, 0x00, 0x33, 0x48, 0x00, 0x98, 0x2e, 0xf6, 0xb6, 0x91, 0x6f, 0x90, 0x7f, 0x00, 0x2e, 0x44, 0x40,
0x20, 0x1a, 0x15, 0x2f, 0xd3, 0x6f, 0xc1, 0x6f, 0xc3, 0x40, 0x35, 0x5a, 0x42, 0x40, 0xd3, 0x7e, 0x08, 0xbc, 0x25,
0x09, 0xe2, 0x7e, 0xc4, 0x0a, 0x42, 0x82, 0xf3, 0x7e, 0xd1, 0x7f, 0x34, 0x30, 0x83, 0x6f, 0x82, 0x30, 0x31, 0x30,
0x98, 0x2e, 0xb3, 0x00, 0xd1, 0x6f, 0x93, 0x6f, 0x43, 0x42, 0xf0, 0x32, 0xb1, 0x6f, 0x41, 0x82, 0xe2, 0x6f, 0x43,
0x40, 0xc1, 0x86, 0xc2, 0xa2, 0x43, 0x42, 0x03, 0x30, 0x02, 0x2f, 0x90, 0x00, 0x00, 0x2e, 0x83, 0x42, 0x61, 0x88,
0x42, 0x40, 0x8d, 0xb0, 0x26, 0x00, 0x98, 0x2e, 0xd9, 0x03, 0x1c, 0x83, 0x00, 0x2e, 0x43, 0x42, 0x00, 0x2e, 0xab,
0x6f, 0xa0, 0x5e, 0xb8, 0x2e, 0xb1, 0x35, 0x40, 0x51, 0x41, 0x01, 0x02, 0x30, 0x1a, 0x25, 0x13, 0x30, 0x40, 0x25,
0x12, 0x42, 0x45, 0x0e, 0xfc, 0x2f, 0x65, 0x34, 0x28, 0x80, 0x25, 0x01, 0x13, 0x42, 0x44, 0x0e, 0xfc, 0x2f, 0x27,
0x80, 0x65, 0x56, 0x03, 0x42, 0x15, 0x80, 0xa3, 0x30, 0x03, 0x42, 0x04, 0x80, 0x4d, 0x56, 0x7f, 0x58, 0x13, 0x42,
0xd4, 0x7e, 0xc2, 0x7e, 0xf2, 0x7e, 0x6c, 0x8c, 0x81, 0x56, 0x83, 0x58, 0xe3, 0x7e, 0x04, 0x7f, 0x71, 0x8a, 0x97,
0x41, 0x17, 0x42, 0x75, 0x0e, 0xfb, 0x2f, 0x85, 0x5c, 0x87, 0x5e, 0x16, 0x7f, 0x36, 0x7f, 0x27, 0x7f, 0x00, 0x2e,
0x89, 0x5c, 0x8b, 0x5e, 0x46, 0x7f, 0x57, 0x7f, 0x76, 0x8c, 0x57, 0x41, 0x17, 0x42, 0x6e, 0x0e, 0xfb, 0x2f, 0x8d,
0x5a, 0x8f, 0x5e, 0x65, 0x7f, 0x87, 0x7f, 0x72, 0x7f, 0x00, 0x2e, 0x91, 0x5a, 0x93, 0x5e, 0x95, 0x7f, 0xa7, 0x7f,
0x7b, 0x8a, 0x97, 0x41, 0x17, 0x42, 0x75, 0x0e, 0xfb, 0x2f, 0x7f, 0x5c, 0xb2, 0x7f, 0xc6, 0x7f, 0xd3, 0x7f, 0xe2,
0x7f, 0xf4, 0x7f, 0x40, 0x82, 0x52, 0x41, 0x12, 0x42, 0x69, 0x0e, 0xfb, 0x2f, 0xc0, 0x5e, 0xb8, 0x2e, 0x03, 0x2e,
0x2d, 0x02, 0x9f, 0xbc, 0x9f, 0xb8, 0x20, 0x50, 0x40, 0xb2, 0x14, 0x2f, 0x10, 0x25, 0x01, 0x2e, 0x8d, 0x00, 0x00,
0x90, 0x0b, 0x2f, 0x97, 0x50, 0xf1, 0x7f, 0xeb, 0x7f, 0x98, 0x2e, 0x83, 0xb6, 0x01, 0x2e, 0x8d, 0x00, 0x01, 0x80,
0x21, 0x2e, 0x8d, 0x00, 0xf1, 0x6f, 0xeb, 0x6f, 0xe0, 0x5f, 0x97, 0x50, 0x80, 0x2e, 0xda, 0xb4, 0x00, 0x30, 0x21,
0x2e, 0x8d, 0x00, 0xe0, 0x5f, 0xb8, 0x2e, 0x41, 0x25, 0x42, 0x8a, 0x50, 0x50, 0x99, 0x52, 0x81, 0x80, 0x99, 0x09,
0xf5, 0x7f, 0x52, 0x25, 0x07, 0x52, 0x03, 0x8e, 0xd9, 0x08, 0x02, 0x40, 0x03, 0x81, 0x44, 0x83, 0x6c, 0xbb, 0xda,
0x0e, 0xe7, 0x7f, 0xdb, 0x7f, 0x20, 0x2f, 0x02, 0x41, 0x32, 0x1a, 0x1d, 0x2f, 0x42, 0x85, 0x00, 0x2e, 0x82, 0x40,
0xda, 0x0e, 0x03, 0x30, 0x05, 0x2f, 0xf1, 0x6f, 0x06, 0x30, 0x42, 0x40, 0x81, 0x84, 0x18, 0x2c, 0x42, 0x42, 0xbf,
0x85, 0x82, 0x00, 0x41, 0x40, 0x86, 0x40, 0x81, 0x8d, 0x86, 0x42, 0x20, 0x25, 0x13, 0x30, 0x06, 0x30, 0x97, 0x40,
0x81, 0x8d, 0xf9, 0x0f, 0x09, 0x2f, 0x85, 0xa3, 0xf9, 0x2f, 0x03, 0x30, 0x06, 0x2c, 0x06, 0x30, 0x9b, 0x52, 0xd9,
0x0e, 0x13, 0x30, 0x01, 0x30, 0xd9, 0x22, 0xc0, 0xb2, 0x12, 0x83, 0xc1, 0x7f, 0x03, 0x30, 0xb4, 0x7f, 0x06, 0x2f,
0x51, 0x30, 0x70, 0x25, 0x98, 0x2e, 0xe3, 0x03, 0xff, 0x81, 0x00, 0x2e, 0x03, 0x42, 0x43, 0x8b, 0xe0, 0x6f, 0xf1,
0x6f, 0x00, 0x40, 0x41, 0x40, 0xc8, 0x0f, 0x37, 0x2f, 0x00, 0x41, 0x80, 0xa7, 0x3c, 0x2f, 0x01, 0x83, 0x47, 0x8e,
0x42, 0x40, 0xfa, 0x01, 0x81, 0x84, 0x08, 0x89, 0x45, 0x41, 0x55, 0x0e, 0xc6, 0x43, 0x42, 0x42, 0xf4, 0x7f, 0x00,
0x2f, 0x43, 0x42, 0x51, 0x82, 0x70, 0x1a, 0x41, 0x40, 0x06, 0x2f, 0xc3, 0x6f, 0x41, 0x82, 0xc1, 0x42, 0xcd, 0x0e,
0x26, 0x2f, 0xc5, 0x42, 0x25, 0x2d, 0x7f, 0x82, 0x51, 0xbb, 0xa5, 0x00, 0xce, 0x0f, 0x12, 0x2f, 0x14, 0x30, 0x05,
0x30, 0xf7, 0x6f, 0x06, 0x30, 0x05, 0x2c, 0xe0, 0x7f, 0xd0, 0x41, 0x05, 0x1a, 0x23, 0x22, 0xb0, 0x01, 0x7a, 0x0e,
0xf9, 0x2f, 0x71, 0x0f, 0xe0, 0x6f, 0x28, 0x22, 0x41, 0x8b, 0x71, 0x22, 0x45, 0xa7, 0xee, 0x2f, 0xb3, 0x6f, 0xc2,
0x6f, 0xc0, 0x42, 0x81, 0x42, 0x08, 0x2d, 0x04, 0x25, 0xc4, 0x6f, 0x98, 0x2e, 0xea, 0x03, 0x00, 0x2e, 0x40, 0x41,
0x00, 0x43, 0x00, 0x30, 0xdb, 0x6f, 0xb0, 0x5f, 0xb8, 0x2e, 0x10, 0x50, 0x03, 0x40, 0x19, 0x18, 0x37, 0x56, 0x19,
0x05, 0x36, 0x25, 0xf7, 0x7f, 0x4a, 0x17, 0x54, 0x18, 0xec, 0x18, 0x09, 0x17, 0x01, 0x30, 0x0c, 0x07, 0xe2, 0x18,
0xde, 0x00, 0xf2, 0x6f, 0x97, 0x02, 0x33, 0x58, 0xdc, 0x00, 0x91, 0x02, 0xbf, 0xb8, 0x21, 0xbd, 0x8a, 0x0a, 0xc0,
0x2e, 0x02, 0x42, 0xf0, 0x5f, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e,
0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80,
0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1,
0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00,
0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e,
0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80,
0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1,
0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00,
0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e,
0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80,
0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x01, 0x2e, 0x5d, 0xf7, 0x08, 0xbc, 0x80, 0xac, 0x0e, 0xbb, 0x02, 0x2f,
0x00, 0x30, 0x41, 0x04, 0x82, 0x06, 0xc0, 0xa4, 0x00, 0x30, 0x11, 0x2f, 0x40, 0xa9, 0x03, 0x2f, 0x40, 0x91, 0x0d,
0x2f, 0x00, 0xa7, 0x0b, 0x2f, 0x80, 0xb3, 0x33, 0x58, 0x02, 0x2f, 0x90, 0xa1, 0x26, 0x13, 0x20, 0x23, 0x80, 0x90,
0x10, 0x30, 0x01, 0x2f, 0xcc, 0x0e, 0x00, 0x2f, 0x00, 0x30, 0xb8, 0x2e, 0x35, 0x50, 0x18, 0x08, 0x08, 0xbc, 0x88,
0xb6, 0x0d, 0x17, 0xc6, 0xbd, 0x56, 0xbc, 0x37, 0x58, 0xda, 0xba, 0x04, 0x01, 0x1d, 0x0a, 0x10, 0x50, 0x05, 0x30,
0x32, 0x25, 0x45, 0x03, 0xfb, 0x7f, 0xf6, 0x30, 0x21, 0x25, 0x98, 0x2e, 0x37, 0xca, 0x16, 0xb5, 0x9a, 0xbc, 0x06,
0xb8, 0x80, 0xa8, 0x41, 0x0a, 0x0e, 0x2f, 0x80, 0x90, 0x02, 0x2f, 0x39, 0x50, 0x48, 0x0f, 0x09, 0x2f, 0xbf, 0xa0,
0x04, 0x2f, 0xbf, 0x90, 0x06, 0x2f, 0x37, 0x54, 0xca, 0x0f, 0x03, 0x2f, 0x00, 0x2e, 0x02, 0x2c, 0x37, 0x52, 0x39,
0x52, 0xf2, 0x33, 0x98, 0x2e, 0xd9, 0xc0, 0xfb, 0x6f, 0xf1, 0x37, 0xc0, 0x2e, 0x01, 0x08, 0xf0, 0x5f, 0x41, 0x56,
0x3b, 0x54, 0xd0, 0x40, 0xc4, 0x40, 0x0b, 0x2e, 0xfd, 0xf3, 0x41, 0x52, 0x90, 0x42, 0x94, 0x42, 0x95, 0x42, 0x05,
0x30, 0x43, 0x50, 0x0f, 0x88, 0x06, 0x40, 0x04, 0x41, 0x96, 0x42, 0xc5, 0x42, 0x48, 0xbe, 0x73, 0x30, 0x0d, 0x2e,
0x88, 0x00, 0x4f, 0xba, 0x84, 0x42, 0x03, 0x42, 0x81, 0xb3, 0x02, 0x2f, 0x2b, 0x2e, 0x6f, 0xf5, 0x06, 0x2d, 0x05,
0x2e, 0x77, 0xf7, 0x3f, 0x56, 0x93, 0x08, 0x25, 0x2e, 0x77, 0xf7, 0x3d, 0x54, 0x25, 0x2e, 0xc2, 0xf5, 0x07, 0x2e,
0xfd, 0xf3, 0x42, 0x30, 0xb4, 0x33, 0xda, 0x0a, 0x4c, 0x00, 0x27, 0x2e, 0xfd, 0xf3, 0x43, 0x40, 0xd4, 0x3f, 0xdc,
0x08, 0x43, 0x42, 0x00, 0x2e, 0x00, 0x2e, 0x43, 0x40, 0x24, 0x30, 0xdc, 0x0a, 0x43, 0x42, 0x04, 0x80, 0x03, 0x2e,
0xfd, 0xf3, 0x4a, 0x0a, 0x23, 0x2e, 0xfd, 0xf3, 0x61, 0x34, 0xc0, 0x2e, 0x01, 0x42, 0x00, 0x2e, 0x60, 0x50, 0x1a,
0x25, 0x7a, 0x86, 0xe0, 0x7f, 0xf3, 0x7f, 0x03, 0x25, 0x45, 0x52, 0x41, 0x84, 0xdb, 0x7f, 0x33, 0x30, 0x98, 0x2e,
0x16, 0xc2, 0x1a, 0x25, 0x7d, 0x82, 0xf0, 0x6f, 0xe2, 0x6f, 0x32, 0x25, 0x16, 0x40, 0x94, 0x40, 0x26, 0x01, 0x85,
0x40, 0x8e, 0x17, 0xc4, 0x42, 0x6e, 0x03, 0x95, 0x42, 0x41, 0x0e, 0xf4, 0x2f, 0xdb, 0x6f, 0xa0, 0x5f, 0xb8, 0x2e,
0xb0, 0x51, 0xfb, 0x7f, 0x98, 0x2e, 0xe8, 0x0d, 0x5a, 0x25, 0x98, 0x2e, 0x0f, 0x0e, 0x4f, 0x58, 0x32, 0x87, 0xc4,
0x7f, 0x65, 0x89, 0x6b, 0x8d, 0x47, 0x5a, 0x65, 0x7f, 0xe1, 0x7f, 0x83, 0x7f, 0xa6, 0x7f, 0x74, 0x7f, 0xd0, 0x7f,
0xb6, 0x7f, 0x94, 0x7f, 0x17, 0x30, 0x49, 0x52, 0x4b, 0x54, 0x51, 0x7f, 0x00, 0x2e, 0x85, 0x6f, 0x42, 0x7f, 0x00,
0x2e, 0x51, 0x41, 0x45, 0x81, 0x42, 0x41, 0x13, 0x40, 0x3b, 0x8a, 0x00, 0x40, 0x4b, 0x04, 0xd0, 0x06, 0xc0, 0xac,
0x85, 0x7f, 0x02, 0x2f, 0x02, 0x30, 0x51, 0x04, 0xd3, 0x06, 0x41, 0x84, 0x05, 0x30, 0x5d, 0x02, 0xc9, 0x16, 0xdf,
0x08, 0xd3, 0x00, 0x8d, 0x02, 0xaf, 0xbc, 0xb1, 0xb9, 0x59, 0x0a, 0x65, 0x6f, 0x11, 0x43, 0xa1, 0xb4, 0x52, 0x41,
0x53, 0x41, 0x01, 0x43, 0x34, 0x7f, 0x65, 0x7f, 0x26, 0x31, 0xe5, 0x6f, 0xd4, 0x6f, 0x98, 0x2e, 0x37, 0xca, 0x32,
0x6f, 0x75, 0x6f, 0x83, 0x40, 0x42, 0x41, 0x23, 0x7f, 0x12, 0x7f, 0xf6, 0x30, 0x40, 0x25, 0x51, 0x25, 0x98, 0x2e,
0x37, 0xca, 0x14, 0x6f, 0x20, 0x05, 0x70, 0x6f, 0x25, 0x6f, 0x69, 0x07, 0xa2, 0x6f, 0x31, 0x6f, 0x0b, 0x30, 0x04,
0x42, 0x9b, 0x42, 0x8b, 0x42, 0x55, 0x42, 0x32, 0x7f, 0x40, 0xa9, 0xc3, 0x6f, 0x71, 0x7f, 0x02, 0x30, 0xd0, 0x40,
0xc3, 0x7f, 0x03, 0x2f, 0x40, 0x91, 0x15, 0x2f, 0x00, 0xa7, 0x13, 0x2f, 0x00, 0xa4, 0x11, 0x2f, 0x84, 0xbd, 0x98,
0x2e, 0x79, 0xca, 0x55, 0x6f, 0x37, 0x54, 0x54, 0x41, 0x82, 0x00, 0xf3, 0x3f, 0x45, 0x41, 0xcb, 0x02, 0xf6, 0x30,
0x98, 0x2e, 0x37, 0xca, 0x35, 0x6f, 0xa4, 0x6f, 0x41, 0x43, 0x03, 0x2c, 0x00, 0x43, 0xa4, 0x6f, 0x35, 0x6f, 0x17,
0x30, 0x42, 0x6f, 0x51, 0x6f, 0x93, 0x40, 0x42, 0x82, 0x00, 0x41, 0xc3, 0x00, 0x03, 0x43, 0x51, 0x7f, 0x00, 0x2e,
0x94, 0x40, 0x41, 0x41, 0x4c, 0x02, 0xc4, 0x6f, 0x55, 0x56, 0x63, 0x0e, 0x74, 0x6f, 0x51, 0x43, 0xa5, 0x7f, 0x8a,
0x2f, 0x09, 0x2e, 0x88, 0x00, 0x01, 0xb3, 0x21, 0x2f, 0x4f, 0x58, 0x90, 0x6f, 0x13, 0x41, 0xb6, 0x6f, 0xe4, 0x7f,
0x00, 0x2e, 0x91, 0x41, 0x14, 0x40, 0x92, 0x41, 0x15, 0x40, 0x17, 0x2e, 0x6f, 0xf5, 0xb6, 0x7f, 0xd0, 0x7f, 0xcb,
0x7f, 0x98, 0x2e, 0x00, 0x0c, 0x07, 0x15, 0xc2, 0x6f, 0x14, 0x0b, 0x29, 0x2e, 0x6f, 0xf5, 0xc3, 0xa3, 0xc1, 0x8f,
0xe4, 0x6f, 0xd0, 0x6f, 0xe6, 0x2f, 0x14, 0x30, 0x05, 0x2e, 0x6f, 0xf5, 0x14, 0x0b, 0x29, 0x2e, 0x6f, 0xf5, 0x18,
0x2d, 0x51, 0x56, 0x04, 0x32, 0xb5, 0x6f, 0x1c, 0x01, 0x51, 0x41, 0x52, 0x41, 0xc3, 0x40, 0xb5, 0x7f, 0xe4, 0x7f,
0x98, 0x2e, 0x1f, 0x0c, 0xe4, 0x6f, 0x21, 0x87, 0x00, 0x43, 0x04, 0x32, 0x53, 0x54, 0x5a, 0x0e, 0xef, 0x2f, 0x4d,
0x54, 0x09, 0x2e, 0x77, 0xf7, 0x22, 0x0b, 0x29, 0x2e, 0x77, 0xf7, 0xfb, 0x6f, 0x50, 0x5e, 0xb8, 0x2e, 0x10, 0x50,
0x01, 0x2e, 0x84, 0x00, 0x00, 0xb2, 0xfb, 0x7f, 0x51, 0x2f, 0x01, 0xb2, 0x48, 0x2f, 0x02, 0xb2, 0x42, 0x2f, 0x03,
0x90, 0x56, 0x2f, 0x5b, 0x52, 0x79, 0x80, 0x42, 0x40, 0x81, 0x84, 0x00, 0x40, 0x42, 0x42, 0x98, 0x2e, 0x93, 0x0c,
0x5d, 0x54, 0x5b, 0x50, 0xa1, 0x40, 0x98, 0xbd, 0x82, 0x40, 0x3e, 0x82, 0xda, 0x0a, 0x44, 0x40, 0x8b, 0x16, 0xe3,
0x00, 0x53, 0x42, 0x00, 0x2e, 0x43, 0x40, 0x9a, 0x02, 0x52, 0x42, 0x00, 0x2e, 0x41, 0x40, 0x4d, 0x54, 0x4a, 0x0e,
0x3a, 0x2f, 0x3a, 0x82, 0x00, 0x30, 0x41, 0x40, 0x21, 0x2e, 0x6c, 0x0f, 0x40, 0xb2, 0x0a, 0x2f, 0x98, 0x2e, 0xb1,
0x0c, 0x98, 0x2e, 0x45, 0x0e, 0x98, 0x2e, 0x5b, 0x0e, 0xfb, 0x6f, 0xf0, 0x5f, 0x00, 0x30, 0x80, 0x2e, 0xba, 0x03,
0x61, 0x52, 0x57, 0x54, 0x42, 0x42, 0x4f, 0x84, 0x73, 0x30, 0x5f, 0x52, 0x83, 0x42, 0x1b, 0x30, 0x6b, 0x42, 0x23,
0x30, 0x27, 0x2e, 0x87, 0x00, 0x37, 0x2e, 0x84, 0x00, 0x21, 0x2e, 0x86, 0x00, 0x7a, 0x84, 0x17, 0x2c, 0x42, 0x42,
0x30, 0x30, 0x21, 0x2e, 0x84, 0x00, 0x12, 0x2d, 0x21, 0x30, 0x00, 0x30, 0x23, 0x2e, 0x84, 0x00, 0x21, 0x2e, 0x7b,
0xf7, 0x0b, 0x2d, 0x17, 0x30, 0x98, 0x2e, 0x51, 0x0c, 0x59, 0x50, 0x0c, 0x82, 0x72, 0x30, 0x2f, 0x2e, 0x84, 0x00,
0x25, 0x2e, 0x7b, 0xf7, 0x40, 0x42, 0x00, 0x2e, 0xfb, 0x6f, 0xf0, 0x5f, 0xb8, 0x2e, 0x70, 0x50, 0x0a, 0x25, 0x39,
0x86, 0xfb, 0x7f, 0xe1, 0x32, 0x62, 0x30, 0x98, 0x2e, 0xc2, 0xc4, 0x35, 0x56, 0xa5, 0x6f, 0xab, 0x08, 0x91, 0x6f,
0x4b, 0x08, 0x63, 0x56, 0xc4, 0x6f, 0x23, 0x09, 0x4d, 0xba, 0x93, 0xbc, 0x8c, 0x0b, 0xd1, 0x6f, 0x0b, 0x09, 0x4f,
0x52, 0x65, 0x5e, 0x56, 0x42, 0xaf, 0x09, 0x4d, 0xba, 0x23, 0xbd, 0x94, 0x0a, 0xe5, 0x6f, 0x68, 0xbb, 0xeb, 0x08,
0xbd, 0xb9, 0x63, 0xbe, 0xfb, 0x6f, 0x52, 0x42, 0xe3, 0x0a, 0xc0, 0x2e, 0x43, 0x42, 0x90, 0x5f, 0x55, 0x50, 0x03,
0x2e, 0x25, 0xf3, 0x13, 0x40, 0x00, 0x40, 0x9b, 0xbc, 0x9b, 0xb4, 0x08, 0xbd, 0xb8, 0xb9, 0x98, 0xbc, 0xda, 0x0a,
0x08, 0xb6, 0x89, 0x16, 0xc0, 0x2e, 0x19, 0x00, 0x62, 0x02, 0x10, 0x50, 0xfb, 0x7f, 0x98, 0x2e, 0x81, 0x0d, 0x01,
0x2e, 0x84, 0x00, 0x31, 0x30, 0x08, 0x04, 0xfb, 0x6f, 0x01, 0x30, 0xf0, 0x5f, 0x23, 0x2e, 0x86, 0x00, 0x21, 0x2e,
0x87, 0x00, 0xb8, 0x2e, 0x01, 0x2e, 0x87, 0x00, 0x03, 0x2e, 0x86, 0x00, 0x48, 0x0e, 0x01, 0x2f, 0x80, 0x2e, 0x1f,
0x0e, 0xb8, 0x2e, 0x67, 0x50, 0x21, 0x34, 0x01, 0x42, 0x82, 0x30, 0xc1, 0x32, 0x25, 0x2e, 0x62, 0xf5, 0x01, 0x00,
0x22, 0x30, 0x01, 0x40, 0x4a, 0x0a, 0x01, 0x42, 0xb8, 0x2e, 0x67, 0x54, 0xf0, 0x3b, 0x83, 0x40, 0xd8, 0x08, 0x69,
0x52, 0x83, 0x42, 0x00, 0x30, 0x83, 0x30, 0x50, 0x42, 0xc4, 0x32, 0x27, 0x2e, 0x64, 0xf5, 0x94, 0x00, 0x50, 0x42,
0x40, 0x42, 0xd3, 0x3f, 0x84, 0x40, 0x7d, 0x82, 0xe3, 0x08, 0x40, 0x42, 0x83, 0x42, 0xb8, 0x2e, 0x61, 0x52, 0x00,
0x30, 0x40, 0x42, 0x7c, 0x86, 0x3b, 0x52, 0x09, 0x2e, 0x57, 0x0f, 0x41, 0x54, 0xc4, 0x42, 0xd3, 0x86, 0x54, 0x40,
0x55, 0x40, 0x94, 0x42, 0x85, 0x42, 0x21, 0x2e, 0x87, 0x00, 0x42, 0x40, 0x25, 0x2e, 0xfd, 0xf3, 0xc0, 0x42, 0x7e,
0x82, 0x05, 0x2e, 0x79, 0x00, 0x80, 0xb2, 0x14, 0x2f, 0x05, 0x2e, 0x24, 0x02, 0x27, 0xbd, 0x2f, 0xb9, 0x80, 0x90,
0x02, 0x2f, 0x21, 0x2e, 0x6f, 0xf5, 0x0c, 0x2d, 0x07, 0x2e, 0x58, 0x0f, 0x14, 0x30, 0x1c, 0x09, 0x05, 0x2e, 0x77,
0xf7, 0x3f, 0x56, 0x47, 0xbe, 0x93, 0x08, 0x94, 0x0a, 0x25, 0x2e, 0x77, 0xf7, 0x6b, 0x54, 0x50, 0x42, 0x4a, 0x0e,
0xfc, 0x2f, 0xb8, 0x2e, 0x50, 0x50, 0x02, 0x30, 0x43, 0x86, 0x69, 0x50, 0xfb, 0x7f, 0xe3, 0x7f, 0xd2, 0x7f, 0xc0,
0x7f, 0xb1, 0x7f, 0x00, 0x2e, 0x41, 0x40, 0x00, 0x40, 0x48, 0x04, 0x98, 0x2e, 0x74, 0xc0, 0x1e, 0xaa, 0xd3, 0x6f,
0x14, 0x30, 0xb1, 0x6f, 0xe3, 0x22, 0xc0, 0x6f, 0x52, 0x40, 0xe4, 0x6f, 0x4c, 0x0e, 0x12, 0x42, 0xd3, 0x7f, 0xeb,
0x2f, 0x03, 0x2e, 0x6d, 0x0f, 0x40, 0x90, 0x11, 0x30, 0x03, 0x2f, 0x23, 0x2e, 0x6d, 0x0f, 0x02, 0x2c, 0x00, 0x30,
0xd0, 0x6f, 0xfb, 0x6f, 0xb0, 0x5f, 0xb8, 0x2e, 0x40, 0x50, 0xf1, 0x7f, 0x0a, 0x25, 0x3c, 0x86, 0xeb, 0x7f, 0x41,
0x33, 0x22, 0x30, 0x98, 0x2e, 0xc2, 0xc4, 0xd3, 0x6f, 0xf4, 0x30, 0xdc, 0x09, 0x6f, 0x58, 0xc2, 0x6f, 0x94, 0x09,
0x71, 0x58, 0x6a, 0xbb, 0xdc, 0x08, 0xb4, 0xb9, 0xb1, 0xbd, 0x6d, 0x5a, 0x95, 0x08, 0x21, 0xbd, 0xf6, 0xbf, 0x77,
0x0b, 0x51, 0xbe, 0xf1, 0x6f, 0xeb, 0x6f, 0x52, 0x42, 0x54, 0x42, 0xc0, 0x2e, 0x43, 0x42, 0xc0, 0x5f, 0x50, 0x50,
0x75, 0x52, 0x93, 0x30, 0x53, 0x42, 0xfb, 0x7f, 0x7b, 0x30, 0x4b, 0x42, 0x13, 0x30, 0x42, 0x82, 0x20, 0x33, 0x43,
0x42, 0xc8, 0x00, 0x01, 0x2e, 0x80, 0x03, 0x05, 0x2e, 0x7d, 0x00, 0x19, 0x52, 0xe2, 0x7f, 0xd0, 0x7f, 0xc3, 0x7f,
0x98, 0x2e, 0xb6, 0x0e, 0xd1, 0x6f, 0x48, 0x0a, 0xd1, 0x7f, 0x3a, 0x25, 0xfb, 0x86, 0x01, 0x33, 0x12, 0x30, 0x98,
0x2e, 0xc2, 0xc4, 0xd1, 0x6f, 0x48, 0x0a, 0x40, 0xb2, 0x0d, 0x2f, 0xe0, 0x6f, 0x03, 0x2e, 0x80, 0x03, 0x53, 0x30,
0x07, 0x80, 0x27, 0x2e, 0x21, 0xf2, 0x98, 0xbc, 0x01, 0x42, 0x98, 0x2e, 0x91, 0x03, 0x00, 0x2e, 0x00, 0x2e, 0xd0,
0x2e, 0xb1, 0x6f, 0x9b, 0xb8, 0x07, 0x2e, 0x1b, 0x00, 0x19, 0x1a, 0xb1, 0x7f, 0x71, 0x30, 0x04, 0x2f, 0x23, 0x2e,
0x21, 0xf2, 0x00, 0x2e, 0x00, 0x2e, 0xd0, 0x2e, 0x98, 0x2e, 0x6d, 0xc0, 0x98, 0x2e, 0x5d, 0xc0, 0x98, 0x2e, 0xdf,
0x03, 0x20, 0x26, 0xc1, 0x6f, 0x02, 0x31, 0x52, 0x42, 0xab, 0x30, 0x4b, 0x42, 0x20, 0x33, 0x77, 0x56, 0xf1, 0x37,
0xc4, 0x40, 0xa2, 0x0a, 0xc2, 0x42, 0xd8, 0x00, 0x01, 0x2e, 0x5e, 0xf7, 0x41, 0x08, 0x23, 0x2e, 0x94, 0x00, 0xe3,
0x7f, 0x98, 0x2e, 0xaa, 0x01, 0xe1, 0x6f, 0x83, 0x30, 0x43, 0x42, 0x03, 0x30, 0xfb, 0x6f, 0x73, 0x50, 0x02, 0x30,
0x00, 0x2e, 0x00, 0x2e, 0x81, 0x84, 0x50, 0x0e, 0xfa, 0x2f, 0x43, 0x42, 0x11, 0x30, 0xb0, 0x5f, 0x23, 0x2e, 0x21,
0xf2, 0xb8, 0x2e, 0xc1, 0x4a, 0x00, 0x00, 0x6d, 0x57, 0x00, 0x00, 0x77, 0x8e, 0x00, 0x00, 0xe0, 0xff, 0xff, 0xff,
0xd3, 0xff, 0xff, 0xff, 0xe5, 0xff, 0xff, 0xff, 0xee, 0xe1, 0xff, 0xff, 0x7c, 0x13, 0x00, 0x00, 0x46, 0xe6, 0xff,
0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80,
0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1,
0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00,
0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e,
0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80,
0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1,
0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00,
0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e,
0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80,
0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1,
0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00,
0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e,
0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80,
0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1,
0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00, 0xc1, 0x80, 0x2e, 0x00,
0xc1, 0xfd, 0x2d
};
const int bmi270_context_config_file_size = sizeof(bmi270_context_config_file);

View File

@@ -0,0 +1,115 @@
#include "button.h"
#include <button_gpio.h>
#include <esp_log.h>
#define TAG "Button"
Button::Button(button_handle_t button_handle) : button_handle_(button_handle) {
}
Button::Button(gpio_num_t gpio_num, bool active_high, uint16_t long_press_time, uint16_t short_press_time, bool enable_power_save) : gpio_num_(gpio_num) {
if (gpio_num == GPIO_NUM_NC) {
return;
}
button_config_t button_config = {
.long_press_time = long_press_time,
.short_press_time = short_press_time
};
button_gpio_config_t gpio_config = {
.gpio_num = gpio_num,
.active_level = static_cast<uint8_t>(active_high ? 1 : 0),
.enable_power_save = enable_power_save,
.disable_pull = false
};
ESP_ERROR_CHECK(iot_button_new_gpio_device(&button_config, &gpio_config, &button_handle_));
}
Button::~Button() {
if (button_handle_ != NULL) {
iot_button_delete(button_handle_);
}
}
void Button::OnPressDown(std::function<void()> callback) {
if (button_handle_ == nullptr) {
return;
}
on_press_down_ = callback;
iot_button_register_cb(button_handle_, BUTTON_PRESS_DOWN, nullptr, [](void* handle, void* usr_data) {
Button* button = static_cast<Button*>(usr_data);
if (button->on_press_down_) {
button->on_press_down_();
}
}, this);
}
void Button::OnPressUp(std::function<void()> callback) {
if (button_handle_ == nullptr) {
return;
}
on_press_up_ = callback;
iot_button_register_cb(button_handle_, BUTTON_PRESS_UP, nullptr, [](void* handle, void* usr_data) {
Button* button = static_cast<Button*>(usr_data);
if (button->on_press_up_) {
button->on_press_up_();
}
}, this);
}
void Button::OnLongPress(std::function<void()> callback) {
if (button_handle_ == nullptr) {
return;
}
on_long_press_ = callback;
iot_button_register_cb(button_handle_, BUTTON_LONG_PRESS_START, nullptr, [](void* handle, void* usr_data) {
Button* button = static_cast<Button*>(usr_data);
if (button->on_long_press_) {
button->on_long_press_();
}
}, this);
}
void Button::OnClick(std::function<void()> callback) {
if (button_handle_ == nullptr) {
return;
}
on_click_ = callback;
iot_button_register_cb(button_handle_, BUTTON_SINGLE_CLICK, nullptr, [](void* handle, void* usr_data) {
Button* button = static_cast<Button*>(usr_data);
if (button->on_click_) {
button->on_click_();
}
}, this);
}
void Button::OnDoubleClick(std::function<void()> callback) {
if (button_handle_ == nullptr) {
return;
}
on_double_click_ = callback;
iot_button_register_cb(button_handle_, BUTTON_DOUBLE_CLICK, nullptr, [](void* handle, void* usr_data) {
Button* button = static_cast<Button*>(usr_data);
if (button->on_double_click_) {
button->on_double_click_();
}
}, this);
}
void Button::OnMultipleClick(std::function<void()> callback, uint8_t click_count) {
if (button_handle_ == nullptr) {
return;
}
on_multiple_click_ = callback;
button_event_args_t event_args = {
.multiple_clicks = {
.clicks = click_count
}
};
iot_button_register_cb(button_handle_, BUTTON_MULTIPLE_CLICK, &event_args, [](void* handle, void* usr_data) {
Button* button = static_cast<Button*>(usr_data);
if (button->on_multiple_click_) {
button->on_multiple_click_();
}
}, this);
}

View File

@@ -0,0 +1,36 @@
#ifndef BUTTON_H_
#define BUTTON_H_
#include <driver/gpio.h>
#include <iot_button.h>
#include <button_types.h>
#include <button_adc.h>
#include <button_gpio.h>
#include <functional>
class Button {
public:
Button(button_handle_t button_handle);
Button(gpio_num_t gpio_num, bool active_high = false, uint16_t long_press_time = 0, uint16_t short_press_time = 0, bool enable_power_save = false);
~Button();
void OnPressDown(std::function<void()> callback);
void OnPressUp(std::function<void()> callback);
void OnLongPress(std::function<void()> callback);
void OnClick(std::function<void()> callback);
void OnDoubleClick(std::function<void()> callback);
void OnMultipleClick(std::function<void()> callback, uint8_t click_count = 3);
protected:
gpio_num_t gpio_num_;
button_handle_t button_handle_ = nullptr;
std::function<void()> on_press_down_;
std::function<void()> on_press_up_;
std::function<void()> on_long_press_;
std::function<void()> on_click_;
std::function<void()> on_double_click_;
std::function<void()> on_multiple_click_;
};
#endif // BUTTON_H_

View File

@@ -0,0 +1,188 @@
#include "dual_network_board.h"
#include "application.h"
#include <esp_log.h>
#include <esp_system.h>
#include <wifi_station.h>
#include "boards/borla_s3/config.h"
static const char *TAG = "DualNetworkBoard";
DualNetworkBoard::DualNetworkBoard(gpio_num_t ml307_tx_pin, gpio_num_t ml307_rx_pin,
gpio_num_t ml307_dtr_pin)
: ml307_tx_pin_(ml307_tx_pin),
ml307_rx_pin_(ml307_rx_pin),
ml307_dtr_pin_(ml307_dtr_pin)
{
// Check if previous boot flagged us to use 4G
Settings settings("network", true);
int use_4g = settings.GetInt("use_4g", 0);
// use_4g=1;
if (use_4g)
{
network_type_ = NetworkType::ML307;
// Clear flag immediately — next reboot will try WiFi again
settings.SetInt("use_4g", 0);
ESP_LOGI(TAG, "Boot mode: 4G (WiFi failed last boot, will retry WiFi on next reboot)");
current_board_ = std::make_unique<Ml307Board>(ml307_tx_pin_, ml307_rx_pin_, ml307_dtr_pin_);
}
else
{
network_type_ = NetworkType::WIFI;
ESP_LOGI(TAG, "Boot mode: WiFi (default)");
current_board_ = std::make_unique<WifiBoard>();
}
}
bool DualNetworkBoard::IsWifiConfigMode() const
{
if (network_type_ != NetworkType::WIFI || !current_board_)
return false;
auto *wifi_board = static_cast<WifiBoard *>(current_board_.get());
return wifi_board->IsWifiConfigMode();
}
void DualNetworkBoard::SwitchNetworkType()
{
if (network_type_ == NetworkType::WIFI)
{
ESP_LOGW(TAG, "Switching WiFi -> 4G, rebooting...");
Settings("network", true).SetInt("use_4g", 1);
// Keep PERP stable during reboot. Board boot logic handles the
// required ML307 cold boot in 4G mode.
}
else
{
ESP_LOGW(TAG, "Switching 4G -> WiFi, rebooting...");
// use_4g already cleared on boot, just restart
}
vTaskDelay(pdMS_TO_TICKS(500));
esp_restart();
}
std::string DualNetworkBoard::GetBoardType() const
{
return current_board_->GetBoardType();
}
void DualNetworkBoard::StartNetwork()
{
if (network_type_ == NetworkType::WIFI)
{
ESP_LOGI(TAG, "Starting network: WiFi");
auto *wifi_board = static_cast<WifiBoard *>(current_board_.get());
wifi_board->SetSkipBleOnTimeout(true);
current_board_->StartNetwork();
if (current_board_->IsNetworkConnected())
{
ESP_LOGI(TAG, "WiFi connected, starting WiFi monitor");
StartWifiMonitor();
return;
}
// WiFi failed — set one-time flag and reboot into 4G
ESP_LOGW(TAG, "WiFi failed, rebooting into 4G");
Settings("network", true).SetInt("use_4g", 1);
vTaskDelay(pdMS_TO_TICKS(500));
esp_restart();
}
else
{
ESP_LOGI(TAG, "Starting network: 4G");
current_board_->StartNetwork();
}
}
NetworkInterface *DualNetworkBoard::GetNetwork()
{
return current_board_->GetNetwork();
}
bool DualNetworkBoard::IsNetworkConnected() const
{
return current_board_->IsNetworkConnected();
}
void DualNetworkBoard::SetPowerSaveMode(bool enabled)
{
current_board_->SetPowerSaveMode(enabled);
}
// === WiFi monitor: reboot and switch to 4G on persistent WiFi failure ===
void DualNetworkBoard::StartWifiMonitor()
{
xTaskCreate(WifiMonitorTaskFunc, "wifi_mon", 3072, this, 1, &wifi_monitor_task_);
ESP_LOGI(TAG, "WiFi monitor started (failover timeout=%ds, RSSI threshold=%ddBm)",
WIFI_FAILOVER_TIMEOUT_MS / 1000, WIFI_RSSI_THRESHOLD);
}
void DualNetworkBoard::WifiMonitorTaskFunc(void * /*arg*/)
{
auto &station = WifiStation::GetInstance();
int disconnect_elapsed_ms = 0;
int weak_signal_count = 0;
// Wait for initial WiFi connection to stabilize
vTaskDelay(pdMS_TO_TICKS(10000));
while (true)
{
vTaskDelay(pdMS_TO_TICKS(WIFI_CHECK_INTERVAL_MS));
// Don't failover during shutdown
if (Application::GetInstance().shutting_down_.load())
{
continue;
}
bool connected = station.IsConnected();
if (!connected)
{
disconnect_elapsed_ms += WIFI_CHECK_INTERVAL_MS;
weak_signal_count = 0;
ESP_LOGW(TAG, "WiFi disconnected for %ds / %ds",
disconnect_elapsed_ms / 1000, WIFI_FAILOVER_TIMEOUT_MS / 1000);
if (disconnect_elapsed_ms >= WIFI_FAILOVER_TIMEOUT_MS)
{
ESP_LOGE(TAG, "WiFi lost — switching to 4G via reboot");
Settings("network", true).SetInt("use_4g", 1);
vTaskDelay(pdMS_TO_TICKS(500));
esp_restart();
}
}
else
{
disconnect_elapsed_ms = 0;
int8_t rssi = station.GetRssi();
if (rssi < WIFI_RSSI_THRESHOLD && rssi != 0)
{
weak_signal_count++;
ESP_LOGW(TAG, "WiFi signal weak: RSSI=%d dBm (%d/%d)",
rssi, weak_signal_count, WIFI_WEAK_SIGNAL_COUNT);
if (weak_signal_count >= WIFI_WEAK_SIGNAL_COUNT)
{
ESP_LOGE(TAG, "WiFi signal persistently weak — switching to 4G via reboot");
Settings("network", true).SetInt("use_4g", 1);
vTaskDelay(pdMS_TO_TICKS(500));
esp_restart();
}
}
else
{
if (weak_signal_count > 0)
{
ESP_LOGI(TAG, "WiFi signal recovered: RSSI=%d dBm", rssi);
}
weak_signal_count = 0;
}
}
}
}

View File

@@ -0,0 +1,62 @@
#pragma once
#include "board.h"
#include "wifi_board.h"
#include "ml307_board.h"
#include "settings.h"
#include <memory>
#include <esp_system.h>
#include <esp_log.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
enum class NetworkType {
WIFI,
ML307
};
// Dual network board: loads network type from NVS, initializes only one per boot.
// Switch = save new type to NVS + reboot (old project approach).
class DualNetworkBoard : public Board {
public:
DualNetworkBoard(gpio_num_t ml307_tx_pin, gpio_num_t ml307_rx_pin,
gpio_num_t ml307_dtr_pin = GPIO_NUM_NC);
virtual ~DualNetworkBoard() = default;
NetworkType GetNetworkType() const { return network_type_; }
// Save target type to NVS and reboot
void SwitchNetworkType();
// True if booted into WiFi config AP mode
bool IsWifiConfigMode() const;
// Board interface — network methods delegated to current_board_
std::string GetBoardType() const override;
NetworkInterface* GetNetwork() override;
void StartNetwork() override;
bool IsNetworkConnected() const override;
void SetPowerSaveMode(bool enabled) override;
// Hardware methods — return nullptr, subclass must override
AudioCodec* GetAudioCodec() override { return nullptr; }
Led* GetLed() override { return nullptr; }
private:
std::unique_ptr<Board> current_board_;
NetworkType network_type_ = NetworkType::WIFI;
gpio_num_t ml307_tx_pin_;
gpio_num_t ml307_rx_pin_;
gpio_num_t ml307_dtr_pin_;
// WiFi monitor: detect WiFi loss and switch to 4G
static constexpr int WIFI_CHECK_INTERVAL_MS = 5000;
static constexpr int WIFI_FAILOVER_TIMEOUT_MS = 30000;
static constexpr int WIFI_RSSI_THRESHOLD = -80;
static constexpr int WIFI_WEAK_SIGNAL_COUNT = 6;
TaskHandle_t wifi_monitor_task_ = nullptr;
void StartWifiMonitor();
static void WifiMonitorTaskFunc(void* arg);
};

174
main/boards/ml307_board.cc Normal file
View File

@@ -0,0 +1,174 @@
#include "ml307_board.h"
#include "../application.h"
#include <esp_log.h>
#include <esp_timer.h>
static const char *TAG = "Ml307Board";
// CSQ: 0..31 linear RSSI mapping per 3GPP 27.007; 99 = unknown/undetectable.
// <10 weak, 10-14 marginal, 15-19 good, 20-31 excellent.
static const char* CsqQuality(int csq) {
if (csq == 99 || csq < 0) return "unknown";
if (csq < 10) return "very weak";
if (csq < 15) return "weak";
if (csq < 20) return "good";
return "excellent";
}
// CEREG <stat> decoded (3GPP 27.007).
static const char* CeregStatText(int stat) {
switch (stat) {
case 0: return "not_registered_not_searching";
case 1: return "registered_home";
case 2: return "not_registered_searching";
case 3: return "registration_denied";
case 4: return "unknown";
case 5: return "registered_roaming";
default: return "undefined";
}
}
// AcT (Access Technology) from CEREG.
static const char* CeregActText(int act) {
switch (act) {
case 0: return "GSM";
case 2: return "UTRAN";
case 3: return "GSM_EGPRS";
case 4: return "UTRAN_HSDPA";
case 5: return "UTRAN_HSUPA";
case 6: return "UTRAN_HSDPA_HSUPA";
case 7: return "LTE";
case 8: return "EC_GSM_IoT";
case 9: return "E_UTRAN_NB_S1";
default: return "n/a";
}
}
Ml307Board::Ml307Board(gpio_num_t tx_pin, gpio_num_t rx_pin, gpio_num_t dtr_pin)
: tx_pin_(tx_pin), rx_pin_(rx_pin), dtr_pin_(dtr_pin) {
}
void Ml307Board::StartNetwork() {
ESP_LOGI(TAG, "[4G] Detecting module pins tx=%d rx=%d dtr=%d baud=115200",
static_cast<int>(tx_pin_),
static_cast<int>(rx_pin_),
static_cast<int>(dtr_pin_));
int detect_attempt = 0;
while (true) {
detect_attempt++;
modem_ = AtModem::Detect(tx_pin_, rx_pin_, dtr_pin_, 115200);
if (modem_ != nullptr) {
ESP_LOGI(TAG, "[4G] Module detected on attempt #%d", detect_attempt);
break;
}
ESP_LOGW(TAG, "[4G] Detect attempt #%d failed, retry in 1s", detect_attempt);
vTaskDelay(pdMS_TO_TICKS(1000));
}
modem_->OnNetworkStateChanged([this](bool network_ready) {
// Runs in modem UART/URC task context — MUST NOT send AT commands
// here (would deadlock with the very task that parses responses).
int64_t uptime_ms = esp_timer_get_time() / 1000;
if (network_ready) {
ESP_LOGI(TAG, "[4G] >>>>> NETWORK READY <<<<< (uptime=%lldms)", uptime_ms);
} else {
ESP_LOGE(TAG, "[4G] >>>>> NETWORK DOWN <<<<< (uptime=%lldms)", uptime_ms);
}
ESP_LOGI(TAG, "[4G] Forwarding to Application::NotifyNetworkStateChanged(ready=%d)",
network_ready ? 1 : 0);
Application::GetInstance().NotifyNetworkStateChanged(network_ready);
// Defer AT-dependent diagnostics (CSQ / CEREG / carrier) to main loop
// so SendCommand doesn't run from within a URC handler.
Application::GetInstance().Schedule([this, network_ready]() {
if (!modem_) return;
int csq = modem_->GetCsq();
CeregState cereg = modem_->GetRegistrationState();
std::string carrier = modem_->GetCarrierName();
ESP_LOGI(TAG, "[4G] diag edge=%s | CSQ=%d (%s) | CEREG stat=%d (%s) tac=%s ci=%s AcT=%d (%s) | carrier=%s | ip_ready=%d",
network_ready ? "UP" : "DOWN",
csq, CsqQuality(csq),
cereg.stat, CeregStatText(cereg.stat),
cereg.tac.empty() ? "-" : cereg.tac.c_str(),
cereg.ci.empty() ? "-" : cereg.ci.c_str(),
cereg.AcT, CeregActText(cereg.AcT),
carrier.empty() ? "-" : carrier.c_str(),
modem_->network_ready() ? 1 : 0);
});
});
// Wait for network ready (initial registration)
ESP_LOGI(TAG, "[4G] Registering on network (waiting for CEREG stat=1/5 + IP)...");
int reg_attempt = 0;
while (true) {
reg_attempt++;
int64_t t0 = esp_timer_get_time() / 1000;
auto result = modem_->WaitForNetworkReady();
int64_t dt = esp_timer_get_time() / 1000 - t0;
if (result == NetworkStatus::Ready) {
ESP_LOGI(TAG, "[4G] Registration SUCCESS on attempt #%d (took %lldms)",
reg_attempt, dt);
break;
} else if (result == NetworkStatus::ErrorInsertPin) {
ESP_LOGE(TAG, "[4G] Attempt #%d: SIM PIN error (took %lldms), retry in 10s",
reg_attempt, dt);
} else if (result == NetworkStatus::ErrorRegistrationDenied) {
CeregState c = modem_->GetRegistrationState();
ESP_LOGE(TAG, "[4G] Attempt #%d: Registration DENIED (took %lldms) CEREG stat=%d, retry in 10s",
reg_attempt, dt, c.stat);
} else if (result == NetworkStatus::ErrorTimeout) {
int csq = modem_->GetCsq();
CeregState c = modem_->GetRegistrationState();
ESP_LOGW(TAG, "[4G] Attempt #%d: TIMEOUT (took %lldms) CSQ=%d (%s) CEREG stat=%d (%s), retry in 3s",
reg_attempt, dt, csq, CsqQuality(csq),
c.stat, CeregStatText(c.stat));
} else {
ESP_LOGW(TAG, "[4G] Attempt #%d: generic Error (took %lldms), retry in 3s",
reg_attempt, dt);
}
vTaskDelay(pdMS_TO_TICKS((result == NetworkStatus::ErrorInsertPin ||
result == NetworkStatus::ErrorRegistrationDenied)
? 10000
: 3000));
}
// Print the ML307 modem information
int csq = modem_->GetCsq();
CeregState cereg = modem_->GetRegistrationState();
ESP_LOGI(TAG, "[4G] ========================= MODEM INFO =========================");
ESP_LOGI(TAG, "[4G] Revision : %s", modem_->GetModuleRevision().c_str());
ESP_LOGI(TAG, "[4G] IMEI : %s", modem_->GetImei().c_str());
ESP_LOGI(TAG, "[4G] ICCID : %s", modem_->GetIccid().c_str());
ESP_LOGI(TAG, "[4G] Carrier : %s", modem_->GetCarrierName().c_str());
ESP_LOGI(TAG, "[4G] Signal : CSQ=%d (%s)", csq, CsqQuality(csq));
ESP_LOGI(TAG, "[4G] Network : CEREG stat=%d (%s) tac=%s ci=%s AcT=%d (%s)",
cereg.stat, CeregStatText(cereg.stat),
cereg.tac.empty() ? "-" : cereg.tac.c_str(),
cereg.ci.empty() ? "-" : cereg.ci.c_str(),
cereg.AcT, CeregActText(cereg.AcT));
ESP_LOGI(TAG, "[4G] ==============================================================");
}
NetworkInterface* Ml307Board::GetNetwork() {
return modem_.get();
}
bool Ml307Board::IsNetworkConnected() const {
return modem_ != nullptr && modem_->network_ready();
}
void Ml307Board::SetPowerSaveMode(bool enabled) {
// TODO: Implement power save mode for ML307
}
//2026-6-24 ckkj debug
void Ml307Board::StopNetwork() {
ESP_LOGI(TAG, "Stopping 4G network");
if (modem_) {
// Enable flight mode to power down the radio
modem_->SetFlightMode(true);
ESP_LOGI(TAG, "[4G] Flight mode enabled, radio powered down");
}
}

26
main/boards/ml307_board.h Normal file
View File

@@ -0,0 +1,26 @@
#pragma once
#include "board.h"
#include <at_modem.h>
#include <memory>
class Ml307Board : public Board {
public:
Ml307Board(gpio_num_t tx_pin, gpio_num_t rx_pin, gpio_num_t dtr_pin = GPIO_NUM_NC);
std::string GetBoardType() const override { return "ml307"; }
AudioCodec* GetAudioCodec() override { return nullptr; }
Led* GetLed() override { return nullptr; }
NetworkInterface* GetNetwork() override;
void StartNetwork() override;
bool IsNetworkConnected() const override;
//2026-6-24 ckkj debug
void StopNetwork() override;
void SetPowerSaveMode(bool enabled) override;
protected:
std::unique_ptr<AtModem> modem_;
gpio_num_t tx_pin_;
gpio_num_t rx_pin_;
gpio_num_t dtr_pin_;
};

347
main/boards/wifi_board.cc Normal file
View File

@@ -0,0 +1,347 @@
#include "wifi_board.h"
#include "application.h"
#include "audio/audio_prompt.h"
#include "settings.h"
#include "system_info.h"
#include "ble_prov.h"
#include <algorithm>
#include <esp_log.h>
#include <esp_wifi.h>
#include <esp_event.h>
#include <esp_netif.h>
#include <freertos/event_groups.h>
#define TAG "WifiBoard"
WifiBoard::WifiBoard()
{
Settings wifi_settings("wifi", true);
if (wifi_settings.GetInt("force_ap") == 1) {
wifi_config_mode_ = true;
// Clear flag immediately so next boot is normal
wifi_settings.SetInt("force_ap", 0);
}
}
NetworkInterface* WifiBoard::GetNetwork()
{
static EspNetwork network;
return &network;
}
void WifiBoard::StartNetwork()
{
if (wifi_config_mode_) {
EnterBleConfigMode();
return;
}
// 检查是否有保存的 WiFi
auto& ssid_mgr = SsidManager::GetInstance();
const auto& ssid_list = ssid_mgr.GetSsidList();
if (ssid_list.empty()) {
ESP_LOGW(TAG, "No WiFi configured, entering BLE config mode");
EnterBleConfigMode();
return;
}
// 添加所有保存的 WiFi 到 WifiStation
auto& station = WifiStation::GetInstance();
for (const auto& item : ssid_list) {
station.AddAuth(std::string(item.ssid), std::string(item.password));
}
station.OnConnect([](const std::string& ssid) {
ESP_LOGI(TAG, "Connecting to WiFi: %s", ssid.c_str());
});
station.OnConnected([](const std::string& ssid) {
ESP_LOGI(TAG, "Connected to WiFi: %s", ssid.c_str());
});
station.Start();
wifi_initialized_ = true;
// WiFi connection timeout:
// - With 4G fallback (skip_ble_on_timeout_): 15 seconds, then return to try 4G
// - Without fallback: 60 seconds, then enter BLE config mode
int timeout_ms = skip_ble_on_timeout_ ? 15000 : 60000;
if (!station.WaitForConnected(timeout_ms)) {
station.Stop();
if (skip_ble_on_timeout_) {
ESP_LOGW(TAG, "WiFi connection timeout (%ds), returning to caller for 4G fallback", timeout_ms / 1000);
return;
}
ESP_LOGW(TAG, "WiFi connection timeout, entering BLE config mode");
EnterBleConfigMode();
return;
}
ESP_LOGI(TAG, "WiFi connected, IP: %s", station.GetIpAddress().c_str());
}
bool WifiBoard::IsNetworkConnected() const
{
return WifiStation::GetInstance().IsConnected();
}
void WifiBoard::SetPowerSaveMode(bool enabled)
{
WifiStation::GetInstance().SetPowerSaveMode(enabled);
}
void WifiBoard::EnterBleConfigMode()
{
wifi_config_mode_ = true;
ESP_LOGI(TAG, "Entering BLE provisioning mode");
// Play wifi config prompt (OGG, async — don't block BLE startup).
// Use PlayLocal so that if WS is up (rare but possible when server
// sent {"type":"wifi_config"}), the server is told to stop any TTS.
auto& app = Application::GetInstance();
if (app.audio_prompt_.HasPrompts(kPromptWifiConfig)) {
app.audio_prompt_.PlayLocal(kPromptWifiConfig, app.audio_service_,
app.GetProtocol(), "wifi_config");
} else {
app.audio_service_.PlayConfigSound();
}
// Initialize WiFi STA mode (for scanning and connecting)
// Skip if WiFi was already initialized (e.g. timeout path from StartNetwork)
if (!wifi_initialized_) {
esp_netif_init();
esp_event_loop_create_default();
esp_netif_create_default_wifi_sta();
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
esp_wifi_init(&cfg);
wifi_initialized_ = true;
}
esp_wifi_set_mode(WIFI_MODE_STA);
esp_wifi_start();
// Pre-scan WiFi networks BEFORE BLE starts. Once BLE is connected, running
// esp_wifi_scan_start on ESP32-S3 hangs the BLE notification path due to
// 2.4GHz radio coexistence contention — the scan completes but
// ble_gatts_notify_custom never delivers. Scanning while BLE is still off
// is fast and reliable; the cached result is returned on every BLE scan
// request from the miniprogram.
PreScanWifiForBleProv();
// Build BLE device name from MAC last 4 hex chars
std::string mac = SystemInfo::GetMacAddress();
std::string suffix = mac.substr(mac.length() - 5);
// Remove colon: "E:FF" -> "EEFF"
suffix.erase(std::remove(suffix.begin(), suffix.end(), ':'), suffix.end());
auto& ble = BleProv::GetInstance();
ble.SetDeviceName(suffix);
ble.SetDeviceInfo(SystemInfo::GetMacAddress(), SystemInfo::GetAppVersion());
// WiFi config callback: attempt connection when credentials received
// Uses raw ESP WiFi events (not WifiStation) since we init WiFi manually
ble.SetWifiConfigCallback([this](const std::string& ssid, const std::string& password) {
ESP_LOGI(TAG, "BLE: WiFi config received, ssid=%s", ssid.c_str());
// If password is empty, look up saved password from NVS
std::string actual_password = password;
if (actual_password.empty()) {
const auto& saved_list = SsidManager::GetInstance().GetSsidList();
for (const auto& item : saved_list) {
if (item.ssid == ssid) {
actual_password = item.password;
ESP_LOGI(TAG, "Using saved password for SSID: %s", ssid.c_str());
break;
}
}
}
// Create event group for WiFi connection result
static EventGroupHandle_t s_wifi_event_group = xEventGroupCreate();
static const int WIFI_CONNECTED_BIT = BIT0;
static const int WIFI_FAIL_BIT = BIT1;
xEventGroupClearBits(s_wifi_event_group, WIFI_CONNECTED_BIT | WIFI_FAIL_BIT);
// Register temporary event handlers for connection result
esp_event_handler_instance_t ip_handler;
esp_event_handler_instance_t wifi_handler;
esp_event_handler_instance_register(
IP_EVENT, IP_EVENT_STA_GOT_IP,
[](void* arg, esp_event_base_t, int32_t, void*) {
xEventGroupSetBits((EventGroupHandle_t)arg, BIT0);
}, s_wifi_event_group, &ip_handler);
esp_event_handler_instance_register(
WIFI_EVENT, WIFI_EVENT_STA_DISCONNECTED,
[](void* arg, esp_event_base_t, int32_t, void*) {
xEventGroupSetBits((EventGroupHandle_t)arg, BIT1);
}, s_wifi_event_group, &wifi_handler);
// Configure and connect
wifi_config_t wifi_config = {};
strncpy(reinterpret_cast<char*>(wifi_config.sta.ssid), ssid.c_str(),
sizeof(wifi_config.sta.ssid) - 1);
strncpy(reinterpret_cast<char*>(wifi_config.sta.password), actual_password.c_str(),
sizeof(wifi_config.sta.password) - 1);
esp_wifi_set_config(WIFI_IF_STA, &wifi_config);
esp_err_t err = esp_wifi_connect();
if (err != ESP_OK) {
ESP_LOGE(TAG, "WiFi connect call failed: %s", esp_err_to_name(err));
esp_event_handler_instance_unregister(IP_EVENT, IP_EVENT_STA_GOT_IP, ip_handler);
esp_event_handler_instance_unregister(WIFI_EVENT, WIFI_EVENT_STA_DISCONNECTED, wifi_handler);
BleProv::GetInstance().NotifyWifiResult(false, "unknown");
return;
}
// Wait for connection result (10 second timeout)
EventBits_t bits = xEventGroupWaitBits(s_wifi_event_group,
WIFI_CONNECTED_BIT | WIFI_FAIL_BIT, pdTRUE, pdFALSE, pdMS_TO_TICKS(10000));
// Unregister event handlers
esp_event_handler_instance_unregister(IP_EVENT, IP_EVENT_STA_GOT_IP, ip_handler);
esp_event_handler_instance_unregister(WIFI_EVENT, WIFI_EVENT_STA_DISCONNECTED, wifi_handler);
if (bits & WIFI_CONNECTED_BIT) {
ESP_LOGI(TAG, "WiFi connected via BLE provisioning");
SsidManager::GetInstance().AddSsid(ssid, actual_password);
BleProv::GetInstance().NotifyWifiResult(true, "");
// 配网成功提示音(异步入解码队列;WS 还未建立,protocol=nullptr)
auto& app = Application::GetInstance();
if (app.audio_prompt_.HasPrompts(kPromptWifiSuccess)) {
app.audio_prompt_.PlayLocal(kPromptWifiSuccess, app.audio_service_,
/*protocol=*/nullptr, "wifi_success");
}
} else {
ESP_LOGW(TAG, "WiFi connection failed via BLE provisioning");
esp_wifi_disconnect();
std::string error = (bits & WIFI_FAIL_BIT) ? "password_wrong" : "timeout";
BleProv::GetInstance().NotifyWifiResult(false, error);
}
});
// Reboot callback
ble.SetRebootCallback([]() {
ESP_LOGI(TAG, "BLE: Reboot requested, waiting for wifi_success prompt to finish");
auto& app = Application::GetInstance();
// wifi_success.ogg 约 1.2s,刚才 PlayLocal 异步入队,必须等它播完再重启,
// 否则 esp_restart 会把解码队列连同 I2S DMA 一起切掉。3s 兜底超时。
app.audio_service_.WaitForPlaybackComplete(3000);
app.audio_service_.PlayBootSound();
vTaskDelay(pdMS_TO_TICKS(500));
esp_restart();
});
ble.Start();
ESP_LOGI(TAG, "BLE provisioning started, waiting for connection...");
// Block waiting for provisioning (device reboots after success)
while (true) {
vTaskDelay(pdMS_TO_TICKS(1000));
}
}
void WifiBoard::PreScanWifiForBleProv()
{
ESP_LOGI(TAG, "Pre-scanning WiFi (BLE not active yet)...");
// Give the WiFi driver a moment to finish STA start before the scan
vTaskDelay(pdMS_TO_TICKS(300));
wifi_scan_config_t scan_config = {};
scan_config.show_hidden = false;
scan_config.scan_type = WIFI_SCAN_TYPE_ACTIVE;
scan_config.scan_time.active.min = 80;
scan_config.scan_time.active.max = 150;
// Try up to twice — first attempt sometimes returns 0 if WiFi STA is
// still settling.
std::vector<BleProvWifiNetwork> networks;
for (int attempt = 0; attempt < 2 && networks.empty(); attempt++) {
if (attempt > 0) {
ESP_LOGW(TAG, "Pre-scan attempt %d returned 0 networks, retrying", attempt);
vTaskDelay(pdMS_TO_TICKS(500));
}
esp_err_t err = esp_wifi_scan_start(&scan_config, true);
if (err != ESP_OK) {
ESP_LOGW(TAG, "Pre-scan start failed: %s", esp_err_to_name(err));
continue;
}
uint16_t ap_count = 0;
esp_wifi_scan_get_ap_num(&ap_count);
if (ap_count > 20) ap_count = 20;
std::vector<wifi_ap_record_t> ap_records(ap_count);
if (ap_count > 0) {
esp_wifi_scan_get_ap_records(&ap_count, ap_records.data());
}
for (int i = 0; i < ap_count; i++) {
BleProvWifiNetwork net;
net.ssid = std::string(reinterpret_cast<char*>(ap_records[i].ssid));
net.rssi = ap_records[i].rssi;
net.auth = static_cast<int>(ap_records[i].authmode);
if (!net.ssid.empty()) {
networks.push_back(net);
}
}
}
std::sort(networks.begin(), networks.end(),
[](const BleProvWifiNetwork& a, const BleProvWifiNetwork& b) {
return a.rssi > b.rssi;
});
if (networks.size() > 8) {
networks.resize(8);
}
ESP_LOGI(TAG, "Pre-scan complete, %d networks", static_cast<int>(networks.size()));
BleProv::GetInstance().SetCachedNetworks(networks);
}
// Legacy WiFi AP provisioning (kept for fallback)
void WifiBoard::EnterWifiConfigMode()
{
wifi_config_mode_ = true;
ESP_LOGI(TAG, "Entering WiFi configuration mode (AP) [legacy]");
// Play wifi config prompt (OGG, async — don't block AP startup)
auto& app = Application::GetInstance();
if (app.audio_prompt_.HasPrompts(kPromptWifiConfig)) {
app.audio_prompt_.PlayRandom(kPromptWifiConfig, app.audio_service_);
} else {
app.audio_service_.PlayConfigSound();
}
auto& ap = WifiConfigurationAp::GetInstance();
ap.SetSsidPrefix("播乐");
ap.SetLanguage("zh-CN");
ap.SetConfigSuccessCallback([]() {
ESP_LOGI(TAG, "WiFi configured successfully, restarting...");
Application::GetInstance().audio_service_.PlayBootSound();
vTaskDelay(pdMS_TO_TICKS(1000));
esp_restart();
});
ap.Start();
ESP_LOGI(TAG, "AP mode started, SSID: %s, URL: %s",
ap.GetSsid().c_str(), ap.GetWebServerUrl().c_str());
while (true) {
vTaskDelay(pdMS_TO_TICKS(1000));
}
}
//2026-6-24 ckkj debug
void WifiBoard::StopNetwork()
{
ESP_LOGI(TAG, "Stopping WiFi");
esp_wifi_stop();
}

51
main/boards/wifi_board.h Normal file
View File

@@ -0,0 +1,51 @@
#pragma once
#include "board.h"
#include <wifi_station.h>
#include <wifi_configuration_ap.h>
#include <ssid_manager.h>
#include <esp_network.h>
#include <string>
class WifiBoard : public Board {
public:
WifiBoard();
// When true, WiFi timeout returns instead of entering BLE config.
// Used by DualNetworkBoard to fall through to 4G.
void SetSkipBleOnTimeout(bool skip) { skip_ble_on_timeout_ = skip; }
std::string GetBoardType() const override { return "wifi"; }
// True if this boot was triggered by force_ap (e.g. double-click WiFi config).
// Application uses this to skip the boot prompt and avoid overlapping with
// the wifi_config prompt played by EnterBleConfigMode.
bool IsWifiConfigMode() const { return wifi_config_mode_; }
AudioCodec* GetAudioCodec() override { return nullptr; }
Led* GetLed() override { return nullptr; }
NetworkInterface* GetNetwork() override;
void StartNetwork() override;
bool IsNetworkConnected() const override;
//2026-6-24 ckkj debug
void StopNetwork() override;
void SetPowerSaveMode(bool enabled) override;
protected:
// BLE provisioning (replaces WiFi AP mode)
void EnterBleConfigMode();
// Scan WiFi networks BEFORE BLE starts and cache the results into BleProv.
// ESP32-S3 BLE/WiFi coexistence prevents notifications from delivering
// when esp_wifi_scan_start runs during an active BLE connection, so the
// scan must happen while BLE is still inactive.
void PreScanWifiForBleProv();
// Legacy WiFi AP provisioning (kept for fallback, not used by default)
void EnterWifiConfigMode();
bool wifi_config_mode_ = false;
bool wifi_initialized_ = false;
bool skip_ble_on_timeout_ = false;
};

235
main/button_config.cc Normal file
View File

@@ -0,0 +1,235 @@
#include "button_config.h"
#include "application.h"
#include "settings.h"
#include "system_info.h"
#include "ble/friend_exchange.h"
#include "boards/board.h"
#include "boards/wifi_board.h"
#include "boards/dual_network_board.h"
#include <esp_log.h>
#include <esp_system.h>
#include <esp_timer.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <cstdio>
#include <set>
#define TAG "BtnCfg"
namespace {
constexpr const char* kNvsNs = "btn_cfg";
// Whitelist of server-settable actions. Anything outside is rejected.
const std::set<std::string>& AllowedActions() {
static const std::set<std::string> s = {
"friend_mode",
"network_switch",
"nothing",
};
return s;
}
const char* LegacyDefault(int count) {
switch (count) {
case 3: return "friend_mode";
case 4: return "network_switch";
default: return "";
}
}
std::string NvsKey(int count) {
char key[4];
snprintf(key, sizeof(key), "c%d", count);
return std::string(key);
}
void WriteNvs(int count, const char* action) {
Settings s(kNvsNs, true);
s.SetString(NvsKey(count).c_str(), std::string(action));
}
std::string ReadNvs(int count) {
Settings s(kNvsNs, false);
return s.GetString(NvsKey(count).c_str());
}
// ─── Friend mode WS gating ─────────────────────────────────────────────
// 三连击进 friend mode 时立即关闭 WS 通道,避免 BLE 占用 task slot 期间
// server 推流到 web_socket.cc:OnTcpData 创 std::thread 失败 abort。
// friend mode 退出(成功 / 30s 超时)后立即重新打开 WS。
// pending_friend_add_json:成功配对时缓存待发的 friend_add 消息,等 WS 重连
// 后再发出去(因为 cb 触发时 WS 还没连上)。
namespace {
std::string g_pending_friend_add_json;
}
void DoFriendMode() {
auto& app = Application::GetInstance();
// 互斥 1:BLE 配网中不允许进 friend mode(NimBLE 单实例资源)
auto* dual = dynamic_cast<DualNetworkBoard*>(&Board::GetInstance());
auto* wifi_board = dynamic_cast<WifiBoard*>(&Board::GetInstance());
bool in_provisioning = (dual && dual->IsWifiConfigMode()) ||
(wifi_board && wifi_board->IsWifiConfigMode());
if (in_provisioning) {
ESP_LOGW(TAG, "Friend mode rejected: device in BLE provisioning");
return;
}
// 互斥 2:friend mode 已激活则忽略重复触发
if (FriendExchange::IsActive()) {
ESP_LOGW(TAG, "Friend mode already active, ignoring triple-click");
return;
}
app.audio_service_.PlayConfigSound();
// 通知 server 进入 friend 状态。这里不能用 SendTextMessage(),它只是异步
// Schedule;如果随后立刻 CloseAudioChannel,消息会在主循环里被跳过。
if (app.GetProtocol() && app.GetProtocol()->IsAudioChannelOpened()) {
app.GetProtocol()->SendText("{\"type\":\"friend_mode\",\"action\":\"start\"}");
}
// 关闭 WS:BLE 期间 server 不会推流,避免 OnTcpData 创 std::thread 崩
if (app.GetProtocol() && app.GetProtocol()->IsAudioChannelOpened()) {
ESP_LOGI(TAG, "Friend mode: closing WS to free task slots for BLE");
app.GetProtocol()->CloseAudioChannel();
}
g_pending_friend_add_json.clear();
FriendInfo local;
local.mac = SystemInfo::GetMacAddress();
// BLE adv name stays "BorlaF-XXXX" so the scan filter in friend_exchange.cc
// (`name.find("BorlaF-") != 0`) still matches — otherwise two nicknamed
// devices can never see each other.
local.name = std::string("BorlaF-")
+ local.mac.substr(local.mac.size() - 5, 2)
+ local.mac.substr(local.mac.size() - 2, 2);
// User-set nickname (cached in NVS from ServerHello.device_name). Carried
// over the friend_add WS message so backend stores the miniprogram-side
// nickname as friend_name, which is what ASR "给XX打电话" resolves against.
// Server falls back to backend.device.name for the remote side's nickname.
std::string local_friendly = Settings("device", false).GetString("name");
if (local_friendly.empty()) local_friendly = local.name;
FriendExchange::StartFriendMode(
local,
// on_complete:配对成功 — 保存到 NVS,缓存 friend_add 消息(等 WS 重连后发)
[local_friendly](const FriendInfo& me, const FriendInfo& peer) {
ESP_LOGI(TAG, "Friend paired: %s (base MAC: %s)", peer.name.c_str(), peer.mac.c_str());
Settings friends_store("friends", true);
int count = friends_store.GetInt("count", 0);
bool exists = false;
for (int i = 0; i < count; i++) {
std::string key = "f_" + std::to_string(i);
std::string val = friends_store.GetString(key.c_str());
if (val.find(peer.mac) != std::string::npos) {
exists = true;
break;
}
}
if (!exists && count < 20) {
char json[128];
snprintf(json, sizeof(json), "{\"mac\":\"%s\",\"name\":\"%s\"}",
peer.mac.c_str(), peer.name.c_str());
std::string slot_key = "f_" + std::to_string(count);
friends_store.SetString(slot_key.c_str(), json);
friends_store.SetInt("count", count + 1);
ESP_LOGI(TAG, "Friend saved to NVS: slot %d", count);
}
char buf[256];
snprintf(buf, sizeof(buf),
"{\"type\":\"friend_add\",\"local_mac\":\"%s\",\"local_name\":\"%s\","
"\"remote_mac\":\"%s\",\"remote_name\":\"%s\"}",
me.mac.c_str(), local_friendly.c_str(),
peer.mac.c_str(), peer.name.c_str());
// 缓存到全局,等 on_stopped 里 WS 重连后再发
g_pending_friend_add_json = std::string(buf);
Application::GetInstance().audio_service_.PlayConfigSound();
},
// on_stopped:友好或超时退出都触发;恢复 WS,必要时发送 friend_add
[](bool paired) {
ESP_LOGI(TAG, "Friend mode exited (paired=%d), reopening WS", paired ? 1 : 0);
auto& app2 = Application::GetInstance();
// 异步在主事件循环里 reconnect,避免在 esp_timer task 里做 SSL 握手
app2.Schedule([paired]() {
auto& app3 = Application::GetInstance();
if (app3.GetProtocol() && !app3.GetProtocol()->IsAudioChannelOpened()) {
if (!app3.GetProtocol()->OpenAudioChannel()) {
ESP_LOGW(TAG, "WS reopen failed after friend mode (lazy retry will pick up)");
}
}
if (paired && !g_pending_friend_add_json.empty() &&
app3.GetProtocol() && app3.GetProtocol()->IsAudioChannelOpened()) {
app3.GetProtocol()->SendText(g_pending_friend_add_json);
g_pending_friend_add_json.clear();
}
});
}
);
}
void DoNetworkSwitch() {
auto& app = Application::GetInstance();
app.audio_service_.PlayConfigSound();
vTaskDelay(pdMS_TO_TICKS(1000));
//2026-6-14 ckkj debug
// 四击实现网络切换
auto& board = Board::GetInstance();
auto* dual = dynamic_cast<DualNetworkBoard*>(&board);
if (dual) {
dual->SwitchNetworkType(); // 可以4g-->wifi-->4g
}
esp_restart();
}
void DoNothing() {
ESP_LOGI(TAG, "Action 'nothing' — no-op");
}
} // namespace
namespace button_config {
void UpdateFromHello(const char* action_for_3, const char* action_for_4) {
const auto& allowed = AllowedActions();
auto apply = [&allowed](int count, const char* action) {
if (!action || !*action) return;
if (allowed.count(action) == 0) {
ESP_LOGW(TAG, "Rejected unknown action for click=%d: %s", count, action);
return;
}
WriteNvs(count, action);
ESP_LOGI(TAG, "button_map[%d] = %s", count, action);
};
apply(3, action_for_3);
apply(4, action_for_4);
}
std::string GetAction(int count) {
if (count != 3 && count != 4) return "";
std::string v = ReadNvs(count);
if (!v.empty() && AllowedActions().count(v) > 0) {
return v;
}
// Fallback to legacy hardcoded default
const char* def = LegacyDefault(count);
return def ? std::string(def) : std::string();
}
void Execute(const std::string& action) {
if (action == "friend_mode") {
DoFriendMode();
} else if (action == "network_switch") {
DoNetworkSwitch();
} else if (action == "nothing") {
DoNothing();
} else {
ESP_LOGW(TAG, "Unknown action '%s' — ignored", action.c_str());
}
}
} // namespace button_config

38
main/button_config.h Normal file
View File

@@ -0,0 +1,38 @@
#pragma once
#include <string>
// ADR-004 Phase 2 — button multi-click action map, decoupled from hard-coded
// logic. Only clicks 3 and 4 are configurable; clicks 1 / 2 / long-press are
// hard-coded as safety rails (single-click chat, double-click WiFi config,
// long-press shutdown) and never touched by server config.
//
// Server pushes via hello:
// button_map: { "3": "friend_mode", "4": "network_switch" }
// Firmware caches into NVS namespace "btn_cfg" (keys c3, c4) so device works
// offline after first successful session. Unknown actions fall back to the
// legacy hard-coded default (same as pre-refactor behavior).
namespace button_config {
// Called from WebSocketProtocol hello parser. Writes NVS.
// Only keys "3" / "4" are honored. Unknown actions or invalid values are
// rejected (logged and not written) so server mistakes can't break the
// device.
void UpdateFromHello(const char* action_for_3, const char* action_for_4);
// Resolve the action name for a given click count.
// Priority: NVS value → legacy default → empty.
// count=3 legacy default = "friend_mode"
// count=4 legacy default = "network_switch"
// Other counts always return empty (caller should skip).
std::string GetAction(int count);
// Execute an action by name. Unknown action name is logged and ignored.
// Known actions:
// "friend_mode" — enter BLE friend pairing (same as legacy 3-click)
// "network_switch" — restart into the other network (same as legacy 4-click)
// "nothing" — explicit no-op (for parents who want to disable a slot)
void Execute(const std::string& action);
} // namespace button_config

87
main/conn_error_config.cc Normal file
View File

@@ -0,0 +1,87 @@
#include "conn_error_config.h"
#include "settings.h"
#include <esp_log.h>
#include <cstring>
#define TAG "ConnErrCfg"
namespace {
constexpr const char* kNvsNs = "conn_err";
constexpr const char* kKeySrv = "srv";
constexpr const char* kKeyNet = "net";
// Map a textual prompt group name → enum. Returns false if unknown.
bool ResolveGroup(const std::string& name, PromptGroup* out) {
if (name.empty()) return false;
if (name == "server_error") { *out = kPromptServerError; return true; }
if (name == "no_network") { *out = kPromptNoNetwork; return true; }
if (name == "error") { *out = kPromptError; return true; }
if (name == "wifi_config") { *out = kPromptWifiConfig; return true; }
if (name == "welcome") { *out = kPromptWelcome; return true; }
if (name == "device_already_bound") { *out = kPromptDeviceAlreadyBound; return true; }
// Unknown / not safe to use as an error-prompt: reject.
return false;
}
// Safe NVS read — returns empty string on any failure.
std::string ReadNvsString(const char* key) {
Settings s(kNvsNs, false);
return s.GetString(key);
}
void WriteNvsString(const char* key, const std::string& value) {
Settings s(kNvsNs, true);
s.SetString(key, value);
}
} // namespace
namespace conn_error_config {
void UpdateFromHello(const char* server_unreachable_name, const char* no_network_name) {
if (server_unreachable_name && *server_unreachable_name) {
PromptGroup pg;
if (ResolveGroup(server_unreachable_name, &pg)) {
WriteNvsString(kKeySrv, server_unreachable_name);
ESP_LOGI(TAG, "conn_err.server_unreachable = %s", server_unreachable_name);
} else {
ESP_LOGW(TAG, "Unknown prompt name for server_unreachable: %s (ignored)",
server_unreachable_name);
}
}
if (no_network_name && *no_network_name) {
PromptGroup pg;
if (ResolveGroup(no_network_name, &pg)) {
WriteNvsString(kKeyNet, no_network_name);
ESP_LOGI(TAG, "conn_err.no_network = %s", no_network_name);
} else {
ESP_LOGW(TAG, "Unknown prompt name for no_network: %s (ignored)",
no_network_name);
}
}
}
PromptGroup GetGroupForReason(ConnErrorReason reason) {
AudioPrompt probe;
const char* key = (reason == ConnErrorReason::kServerUnreachable) ? kKeySrv : kKeyNet;
// 1) NVS override
std::string cfg = ReadNvsString(key);
if (!cfg.empty()) {
PromptGroup pg;
if (ResolveGroup(cfg, &pg) && probe.HasPrompts(pg)) {
return pg;
}
ESP_LOGW(TAG, "NVS value %s resolves to missing prompts, falling back", cfg.c_str());
}
// 2) Hard-coded fallback (matches pre-refactor behavior)
if (reason == ConnErrorReason::kServerUnreachable) {
if (probe.HasPrompts(kPromptServerError)) return kPromptServerError;
return kPromptNoNetwork; // fw build may lack server_error prompts
}
return kPromptNoNetwork;
}
} // namespace conn_error_config

35
main/conn_error_config.h Normal file
View File

@@ -0,0 +1,35 @@
#pragma once
#include "audio/audio_prompt.h"
#include <string>
// Connection error prompt config — decoupled from hard-coded logic.
// Server pushes a map via hello:
// connection_error_prompts: {
// "server_unreachable": "server_error",
// "no_network": "no_network"
// }
// Values are prompt group names that map to PromptGroup enum via GetGroupByName.
// Cached in NVS namespace "conn_err"; empty NVS falls back to hard-coded defaults.
enum class ConnErrorReason {
kServerUnreachable, // WiFi 已连,但 OpenAudioChannel 失败(DNS/404/timeout)
kNoNetwork, // WiFi 都没连上
};
namespace conn_error_config {
// Called from WebSocketProtocol hello parser. Writes NVS.
// If any value is invalid or unrecognized, it's ignored (not written).
void UpdateFromHello(const char* server_unreachable_name, const char* no_network_name);
// Called from application.cc when connection fails. Returns the group to play.
// Resolution order:
// 1. NVS value for this reason → lookup by name → PromptGroup (if HasPrompts)
// 2. Hard-coded fallback (kPromptServerError for server_unreachable;
// kPromptNoNetwork for no_network)
// 3. If fallback also lacks prompts, returns kPromptNoNetwork regardless
// (caller is expected to still HasPrompts-check before play)
PromptGroup GetGroupForReason(ConnErrorReason reason);
} // namespace conn_error_config

19
main/idf_component.yml Normal file
View File

@@ -0,0 +1,19 @@
dependencies:
idf: ">=5.3"
# Local components
esp-wifi-connect:
path: ../components/esp-wifi-connect
esp-opus-encoder:
path: ../components/esp-opus-encoder
esp-ml307:
path: ../components/esp-ml307
esp-ble-prov:
version: "1.0.0"
# path: ../components/esp-ble-prov
# Registry components
espressif/esp_codec_dev: "==1.4.0"
espressif/button: "==4.1.3"
espressif/esp-sr: ">=2.0.0"
espressif/led_strip: ">=2.5.0"

26
main/led/led.h Normal file
View File

@@ -0,0 +1,26 @@
#pragma once
enum class LedState {
kOff,
kIdle,
kConnecting,
kListening,
kSpeaking,
kRinging, // Incoming call (green blink)
kCalling, // Active call (green steady)
kUpgrading,
kError,
kWifiConfig,
kShuttingDown,
};
class Led {
public:
virtual ~Led() = default;
virtual void SetState(LedState state) = 0;
};
class NoLed : public Led {
public:
void SetState(LedState /*state*/) override {}
};

223
main/led/single_led.cc Normal file
View File

@@ -0,0 +1,223 @@
#include "single_led.h"
#include <esp_log.h>
#define TAG "SingleLed"
// Brightness levels (aligned with xiaozhi SingleLed)
static constexpr uint8_t DEFAULT_BRIGHTNESS = 4;
static constexpr uint8_t MEDIUM_BRIGHTNESS = 8;
static constexpr uint8_t HIGH_BRIGHTNESS = 16;
static constexpr uint8_t LOW_BRIGHTNESS = 2;
static constexpr uint8_t TINT_BRIGHTNESS = 12; // for compound colors (purple/yellow)
static constexpr int BLINK_INFINITE = -1;
// Breathing animation
static constexpr int BREATH_TICK_MS = 30; // refresh interval
static constexpr int BREATH_SLOW_MS = 4000; // idle (calm)
static constexpr int BREATH_NORMAL_MS = 1500; // speaking
static constexpr int BREATH_FAST_MS = 1000; // connecting
static constexpr int BREATH_SHUTDOWN_MS = 2000; // shutting down
SingleLed::SingleLed(gpio_num_t gpio)
{
led_strip_config_t strip_config = {};
strip_config.strip_gpio_num = gpio;
strip_config.max_leds = 1;
strip_config.color_component_format = LED_STRIP_COLOR_COMPONENT_FMT_GRB;
strip_config.led_model = LED_MODEL_WS2812;
led_strip_rmt_config_t rmt_config = {};
rmt_config.resolution_hz = 10 * 1000 * 1000; // 10MHz
ESP_ERROR_CHECK(led_strip_new_rmt_device(&strip_config, &rmt_config, &led_strip_));
led_strip_clear(led_strip_);
esp_timer_create_args_t blink_timer_args = {
.callback = [](void* arg) {
static_cast<SingleLed*>(arg)->OnBlinkTimer();
},
.arg = this,
.dispatch_method = ESP_TIMER_TASK,
.name = "blink_timer",
.skip_unhandled_events = false,
};
ESP_ERROR_CHECK(esp_timer_create(&blink_timer_args, &blink_timer_));
esp_timer_create_args_t breath_timer_args = {
.callback = [](void* arg) {
static_cast<SingleLed*>(arg)->OnBreathingTimer();
},
.arg = this,
.dispatch_method = ESP_TIMER_TASK,
.name = "breath_timer",
.skip_unhandled_events = false,
};
ESP_ERROR_CHECK(esp_timer_create(&breath_timer_args, &breath_timer_));
ESP_LOGI(TAG, "WS2812 LED initialized on GPIO%d", gpio);
}
SingleLed::~SingleLed()
{
esp_timer_stop(blink_timer_);
esp_timer_delete(blink_timer_);
esp_timer_stop(breath_timer_);
esp_timer_delete(breath_timer_);
if (led_strip_) {
led_strip_del(led_strip_);
}
}
void SingleLed::SetColor(uint8_t r, uint8_t g, uint8_t b)
{
r_ = r;
g_ = g;
b_ = b;
}
void SingleLed::TurnOn()
{
if (!led_strip_) return;
std::lock_guard<std::mutex> lock(mutex_);
esp_timer_stop(blink_timer_);
esp_timer_stop(breath_timer_);
led_strip_set_pixel(led_strip_, 0, r_, g_, b_);
led_strip_refresh(led_strip_);
}
void SingleLed::TurnOff()
{
if (!led_strip_) return;
std::lock_guard<std::mutex> lock(mutex_);
esp_timer_stop(blink_timer_);
esp_timer_stop(breath_timer_);
led_strip_clear(led_strip_);
}
void SingleLed::StartContinuousBlink(int interval_ms)
{
if (!led_strip_) return;
std::lock_guard<std::mutex> lock(mutex_);
esp_timer_stop(blink_timer_);
esp_timer_stop(breath_timer_);
blink_counter_ = BLINK_INFINITE;
esp_timer_start_periodic(blink_timer_, interval_ms * 1000);
}
void SingleLed::StartBreathing(int period_ms)
{
if (!led_strip_) return;
std::lock_guard<std::mutex> lock(mutex_);
esp_timer_stop(blink_timer_);
esp_timer_stop(breath_timer_);
breath_steps_ = period_ms / BREATH_TICK_MS;
if (breath_steps_ < 2) breath_steps_ = 2;
breath_phase_ = 0;
esp_timer_start_periodic(breath_timer_, BREATH_TICK_MS * 1000);
}
void SingleLed::OnBlinkTimer()
{
std::lock_guard<std::mutex> lock(mutex_);
blink_counter_--;
if (blink_counter_ & 1) {
led_strip_set_pixel(led_strip_, 0, r_, g_, b_);
led_strip_refresh(led_strip_);
} else {
led_strip_clear(led_strip_);
if (blink_counter_ == 0) {
esp_timer_stop(blink_timer_);
}
}
}
void SingleLed::OnBreathingTimer()
{
std::lock_guard<std::mutex> lock(mutex_);
if (breath_steps_ < 2) return;
int half = breath_steps_ / 2;
// Triangle wave: phase 0 → half (peak) → steps (back to 0)
int dist = (breath_phase_ <= half) ? breath_phase_ : (breath_steps_ - breath_phase_);
uint8_t r = static_cast<uint8_t>((static_cast<int>(r_) * dist) / half);
uint8_t g = static_cast<uint8_t>((static_cast<int>(g_) * dist) / half);
uint8_t b = static_cast<uint8_t>((static_cast<int>(b_) * dist) / half);
led_strip_set_pixel(led_strip_, 0, r, g, b);
led_strip_refresh(led_strip_);
breath_phase_ = (breath_phase_ + 1) % breath_steps_;
}
void SingleLed::SetState(LedState state)
{
if (state == current_state_) return;
current_state_ = state;
// State → unique (color + behavior). One state, one light signature.
switch (state) {
case LedState::kOff:
TurnOff();
break;
case LedState::kIdle:
// Warm white slow breathing — RGB ratio (8,6,2) compensates for
// WS2812 low-brightness color cast (B over-bright, R weak) so it
// looks like a calm warm-white heartbeat instead of a bluish glow.
SetColor(MEDIUM_BRIGHTNESS, MEDIUM_BRIGHTNESS - 2, LOW_BRIGHTNESS);
StartBreathing(BREATH_SLOW_MS);
break;
case LedState::kConnecting:
// Blue fast breathing
SetColor(0, 0, MEDIUM_BRIGHTNESS);
StartBreathing(BREATH_FAST_MS);
break;
case LedState::kWifiConfig:
// Cyan blink 500ms
SetColor(0, MEDIUM_BRIGHTNESS, MEDIUM_BRIGHTNESS);
StartContinuousBlink(500);
break;
case LedState::kListening:
// Red steady (high brightness)
SetColor(HIGH_BRIGHTNESS, 0, 0);
TurnOn();
break;
case LedState::kSpeaking:
// Green breathing — gentle pulse while TTS plays
SetColor(0, MEDIUM_BRIGHTNESS, 0);
StartBreathing(BREATH_NORMAL_MS);
break;
case LedState::kRinging:
// Purple blink 500ms (incoming call) — distinct from speaking green
SetColor(TINT_BRIGHTNESS, 0, TINT_BRIGHTNESS);
StartContinuousBlink(500);
break;
case LedState::kCalling:
// Green steady high (active call)
SetColor(0, HIGH_BRIGHTNESS, 0);
TurnOn();
break;
case LedState::kUpgrading:
// Yellow blink 200ms — distinct from green family
SetColor(TINT_BRIGHTNESS, MEDIUM_BRIGHTNESS, 0);
StartContinuousBlink(200);
break;
case LedState::kError:
// Red fast blink 100ms
SetColor(HIGH_BRIGHTNESS, 0, 0);
StartContinuousBlink(100);
break;
case LedState::kShuttingDown:
// Orange breathing (slow fade) — warm tone, distinct from red listening
SetColor(MEDIUM_BRIGHTNESS, LOW_BRIGHTNESS, 0);
StartBreathing(BREATH_SHUTDOWN_MS);
break;
}
}

35
main/led/single_led.h Normal file
View File

@@ -0,0 +1,35 @@
#pragma once
#include "led.h"
#include <driver/gpio.h>
#include <led_strip.h>
#include <esp_timer.h>
#include <mutex>
// WS2812 RGB LED — aligned with xiaozhi-server SingleLed (RMT driver)
class SingleLed : public Led {
public:
SingleLed(gpio_num_t gpio);
~SingleLed();
void SetState(LedState state) override;
private:
void SetColor(uint8_t r, uint8_t g, uint8_t b);
void TurnOn();
void TurnOff();
void StartContinuousBlink(int interval_ms);
void StartBreathing(int period_ms);
void OnBlinkTimer();
void OnBreathingTimer();
std::mutex mutex_;
led_strip_handle_t led_strip_ = nullptr;
esp_timer_handle_t blink_timer_ = nullptr;
esp_timer_handle_t breath_timer_ = nullptr;
LedState current_state_ = LedState::kOff;
uint8_t r_ = 0, g_ = 0, b_ = 0; // peak color for steady/blink/breath
int blink_counter_ = 0;
int breath_phase_ = 0;
int breath_steps_ = 0;
};

114
main/main.cc Normal file
View File

@@ -0,0 +1,114 @@
#include "application.h"
#include "system_info.h"
#include "trace_ctx.h"
#include <esp_log.h>
#include <esp_mac.h>
#include <nvs_flash.h>
#include <esp_event.h>
#include <cstdarg>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <sys/time.h>
// MAC 缓存。app_main 早期写一次,之后只读,无需锁。
// 18 = "xx:xx:xx:xx:xx:xx" + '\0'。
static char g_mac_str[18] = "??:??:??:??:??:??";
#ifndef BORLA_MONITORING_LOGS_ONLY
#define BORLA_MONITORING_LOGS_ONLY 0
#endif
#ifndef BORLA_TRACE_LOGS_ENABLED
#define BORLA_TRACE_LOGS_ENABLED 0
#endif
static constexpr bool kMonitoringLogsOnly = BORLA_MONITORING_LOGS_ONLY != 0;
static constexpr bool kTraceLogsEnabled = BORLA_TRACE_LOGS_ENABLED != 0;
static void CacheMacAddress()
{
uint8_t mac[6] = {0};
if (esp_read_mac(mac, ESP_MAC_WIFI_STA) == ESP_OK) {
snprintf(g_mac_str, sizeof(g_mac_str),
"%02x:%02x:%02x:%02x:%02x:%02x",
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
}
}
static bool ShouldEmitLogLine(const char* line)
{
if (strstr(line, "[TRACE]") != nullptr) return kTraceLogsEnabled;
if (!kMonitoringLogsOnly) return true;
// ESP-IDF renders logs as "I (123) TAG: ..." after our "[time mac] "
// prefix. Keep warnings/errors even when ordinary INFO/DEBUG is muted.
const char* p = strchr(line, ']');
if (!p) return false;
++p;
while (*p == ' ') ++p;
if (p[0] == '\033' && p[1] == '[') {
while (*p && *p != 'm') ++p;
if (*p == 'm') ++p;
}
while (*p == ' ') ++p;
char level = *p;
return level == 'W' || level == 'E';
}
// 自定义日志 vprintf:每条日志前加 [yyyy-mm-dd HH:MM:SS MAC] 前缀。
// 未 NTP/ServerHello 同步前,时间会显示 1970-01-01(epoch)。
// MAC 在 app_main 早期就缓存好,全程只读。
//
// 拼到单个栈缓冲再 fwrite,避免两次 printf 在多任务并发时被穿插。
static int LogVprintfWithWallClock(const char* format, va_list args)
{
struct timeval tv;
gettimeofday(&tv, nullptr);
struct tm tm_info;
localtime_r(&tv.tv_sec, &tm_info);
char ts[24];
strftime(ts, sizeof(ts), "%Y-%m-%d %H:%M:%S", &tm_info);
char buf[512];
int n = snprintf(buf, sizeof(buf), "[%s %s] ", ts, g_mac_str);
if (n < 0) n = 0;
if (n >= (int)sizeof(buf)) n = sizeof(buf) - 1;
int m = vsnprintf(buf + n, sizeof(buf) - n, format, args);
if (m < 0) m = 0;
int total = n + m;
if (total >= (int)sizeof(buf)) total = sizeof(buf) - 1;
if (!ShouldEmitLogLine(buf)) return total;
return (int)fwrite(buf, 1, total, stdout);
}
static void InitializeNvs()
{
esp_err_t ret = nvs_flash_init();
if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
ESP_ERROR_CHECK(nvs_flash_erase());
ret = nvs_flash_init();
}
ESP_ERROR_CHECK(ret);
}
extern "C" void app_main(void)
{
// 先缓存 MAC,再注册自定义 log,确保 vprintf 钩子里能直接读 g_mac_str。
CacheMacAddress();
esp_log_set_vprintf(LogVprintfWithWallClock);
// docs/0019 §10.1 · 设备启动即生成一个初始 trace/session。后续 WS 连接成功
// 时再 RefreshSession,每次对话回合再 RefreshTrace。
::borla::TraceCtx::RefreshSession();
::borla::TraceCtx::RefreshTrace("dev");
ESP_ERROR_CHECK(esp_event_loop_create_default());
InitializeNvs();
auto& app = Application::GetInstance();
app.Start();
}

146
main/memory_cache.cc Normal file
View File

@@ -0,0 +1,146 @@
#include "memory_cache.h"
#include <esp_log.h>
#include <esp_partition.h>
#include <cstring>
#include <vector>
#define TAG "MemoryCache"
MemoryCache& MemoryCache::GetInstance()
{
static MemoryCache instance;
return instance;
}
bool MemoryCache::Load()
{
const esp_partition_t* partition = esp_partition_find_first(
ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_SPIFFS, kPartitionLabel);
if (!partition) {
ESP_LOGW(TAG, "Partition '%s' not found", kPartitionLabel);
return false;
}
// Read header: [4B magic] [4B data_len]
uint32_t header[2] = {0, 0};
esp_err_t err = esp_partition_read(partition, 0, header, sizeof(header));
if (err != ESP_OK) {
ESP_LOGW(TAG, "Failed to read header: %s", esp_err_to_name(err));
return false;
}
if (header[0] != kMagic) {
ESP_LOGI(TAG, "No cached data (magic mismatch)");
return false;
}
uint32_t data_len = header[1];
if (data_len == 0 || data_len > 64 * 1024) {
ESP_LOGW(TAG, "Invalid data length: %lu", data_len);
return false;
}
// Read JSON data
std::vector<char> buffer(data_len + 1, 0);
err = esp_partition_read(partition, sizeof(header), buffer.data(), data_len);
if (err != ESP_OK) {
ESP_LOGW(TAG, "Failed to read data: %s", esp_err_to_name(err));
return false;
}
cJSON* root = cJSON_Parse(buffer.data());
if (!root) {
ESP_LOGW(TAG, "Failed to parse cached JSON");
return false;
}
auto* brain = cJSON_GetObjectItem(root, "brain");
if (cJSON_IsString(brain)) profile_text_ = brain->valuestring;
auto* name = cJSON_GetObjectItem(root, "name");
if (cJSON_IsString(name)) child_name_ = name->valuestring;
auto* count = cJSON_GetObjectItem(root, "count");
if (cJSON_IsNumber(count)) interaction_count_ = count->valueint;
cJSON_Delete(root);
ESP_LOGI(TAG, "Loaded: name='%s', interactions=%d, profile=%zuB",
child_name_.c_str(), interaction_count_, profile_text_.size());
return true;
}
bool MemoryCache::Save()
{
const esp_partition_t* partition = esp_partition_find_first(
ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_SPIFFS, kPartitionLabel);
if (!partition) {
ESP_LOGW(TAG, "Partition '%s' not found", kPartitionLabel);
return false;
}
// Build JSON
cJSON* root = cJSON_CreateObject();
cJSON_AddStringToObject(root, "brain", profile_text_.c_str());
cJSON_AddStringToObject(root, "name", child_name_.c_str());
cJSON_AddNumberToObject(root, "count", interaction_count_);
char* json_str = cJSON_PrintUnformatted(root);
cJSON_Delete(root);
if (!json_str) return false;
uint32_t data_len = strlen(json_str);
// Erase first sector (4KB minimum erase unit)
uint32_t erase_size = ((sizeof(uint32_t) * 2 + data_len + 4095) / 4096) * 4096;
esp_err_t err = esp_partition_erase_range(partition, 0, erase_size);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to erase: %s", esp_err_to_name(err));
cJSON_free(json_str);
return false;
}
// Write header
uint32_t header[2] = {kMagic, data_len};
err = esp_partition_write(partition, 0, header, sizeof(header));
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to write header: %s", esp_err_to_name(err));
cJSON_free(json_str);
return false;
}
// Write JSON data
err = esp_partition_write(partition, sizeof(header), json_str, data_len);
cJSON_free(json_str);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to write data: %s", esp_err_to_name(err));
return false;
}
ESP_LOGI(TAG, "Saved %lu bytes to Flash", data_len);
return true;
}
void MemoryCache::UpdateFromServerSync(const cJSON* memory_sync)
{
if (!memory_sync) return;
auto* brain = cJSON_GetObjectItem(memory_sync, "brain_text");
if (cJSON_IsString(brain)) {
profile_text_ = brain->valuestring;
}
auto* name = cJSON_GetObjectItem(memory_sync, "child_name");
if (cJSON_IsString(name)) {
child_name_ = name->valuestring;
}
auto* count = cJSON_GetObjectItem(memory_sync, "interaction_count");
if (cJSON_IsNumber(count)) {
interaction_count_ = count->valueint;
}
Save();
ESP_LOGI(TAG, "Synced from server: name='%s', interactions=%d",
child_name_.c_str(), interaction_count_);
}

40
main/memory_cache.h Normal file
View File

@@ -0,0 +1,40 @@
#pragma once
#include <string>
#include <cJSON.h>
// Device memory cache stored in claude_mem Flash partition
// Uses raw flash read/write with simple header + JSON format
class MemoryCache {
public:
static MemoryCache& GetInstance();
// Load cached data from Flash on boot
bool Load();
// Save current data to Flash
bool Save();
std::string GetProfileText() const { return profile_text_; }
std::string GetChildName() const { return child_name_; }
int GetInteractionCount() const { return interaction_count_; }
void SetProfileText(const std::string& text) { profile_text_ = text; }
void SetChildName(const std::string& name) { child_name_ = name; }
void SetInteractionCount(int count) { interaction_count_ = count; }
// Update from server's memory_sync JSON object, then save to Flash
void UpdateFromServerSync(const cJSON* memory_sync);
bool HasData() const { return !child_name_.empty() || !profile_text_.empty(); }
private:
MemoryCache() = default;
std::string profile_text_;
std::string child_name_;
int interaction_count_ = 0;
static constexpr uint32_t kMagic = 0x424F524C; // "BORL"
static constexpr const char* kPartitionLabel = "claude_mem";
};

290
main/ota.cc Normal file
View File

@@ -0,0 +1,290 @@
#include "ota.h"
#include "system_info.h"
#include "settings.h"
#include "boards/board.h"
#include "application.h"
#include "trace_ctx.h"
#include <sdkconfig.h>
#include <esp_log.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <esp_ota_ops.h>
#include <esp_app_desc.h>
#include <cJSON.h>
#include <http.h>
#include <algorithm>
#include <cstring>
#include <string>
#include <sys/time.h>
#define TAG "OTA"
#ifndef CONFIG_OTA_URL
#define CONFIG_OTA_URL "https://borla-ota.lkall.com/xiaozhi/ota/"
#endif
static constexpr const char* kDevelopmentWebSocketUrl = "wss://borlaws.lkall.com/v1/ws";
static uint64_t TraceMonoMs()
{
return static_cast<uint64_t>(esp_timer_get_time() / 1000ULL);
}
static int64_t TraceEpochMs()
{
struct timeval tv;
gettimeofday(&tv, nullptr);
if (tv.tv_sec < 1700000000) {
return 0;
}
return static_cast<int64_t>(tv.tv_sec) * 1000 + tv.tv_usec / 1000;
}
static std::string MakeTraceId(const char* prefix)
{
std::string mac = SystemInfo::GetMacAddress();
std::replace(mac.begin(), mac.end(), ':', '-');
return std::string(prefix) + "-" + mac + "-" + std::to_string(TraceMonoMs());
}
static bool IsKnownSavedEndpoint(const std::string& url)
{
const bool lkall_host = url.find(".lkall.com") != std::string::npos;
return (lkall_host && (url.find("-dev.") != std::string::npos ||
url.find("-moe.") != std::string::npos ||
url.find("borlaws.lkall.com") != std::string::npos ||
url.find("borla-ota.lkall.com") != std::string::npos)) ||
url.find("192.168.1.121") != std::string::npos ||
url.find("117.50.44.247") != std::string::npos;
}
bool Ota::CheckVersion()
{
Settings wifi_settings("wifi", true);
check_url_ = wifi_settings.GetString("ota_url");
if (check_url_.empty() || IsKnownSavedEndpoint(check_url_)) {
check_url_ = CONFIG_OTA_URL;
wifi_settings.SetString("ota_url", check_url_);
}
current_version_ = SystemInfo::GetAppVersion();
ESP_LOGI(TAG, "Checking at: %s (v%s)", check_url_.c_str(), current_version_.c_str());
// Build request body
cJSON* body = cJSON_CreateObject();
cJSON_AddStringToObject(body, "mac_address", SystemInfo::GetMacAddress().c_str());
cJSON_AddStringToObject(body, "board_type", "borla-s3");
cJSON_AddStringToObject(body, "app_version", current_version_.c_str());
cJSON_AddStringToObject(body, "chip_model", SystemInfo::GetChipModelName().c_str());
cJSON_AddNumberToObject(body, "free_heap", SystemInfo::GetFreeHeapSize());
char* body_str = cJSON_PrintUnformatted(body);
std::string body_content(body_str);
cJSON_free(body_str);
cJSON_Delete(body);
// Use NetworkInterface HTTP (works with both WiFi and 4G)
auto http = Board::GetInstance().GetNetwork()->CreateHttp();
if (!http) {
ESP_LOGE(TAG, "Failed to create HTTP client");
return false;
}
http->SetTimeout(30000);
http->SetHeader("Content-Type", "application/json");
http->SetHeader("Device-Id", SystemInfo::GetMacAddress());
std::string trace_id = MakeTraceId("fw-ota");
::borla::TraceCtx::SetTrace(trace_id.c_str());
std::string request_id = ::borla::TraceCtx::NewRequestId();
uint64_t client_send_ms = TraceMonoMs();
int64_t client_epoch_ms = TraceEpochMs();
http->SetHeader("X-Borla-Trace-Id", trace_id);
http->SetHeader("X-Borla-Session-Id", ::borla::TraceCtx::SessionId());
http->SetHeader("X-Request-Id", request_id);
http->SetHeader("X-Borla-Client-Send-Ms", std::to_string(client_send_ms));
if (client_epoch_ms > 0) {
http->SetHeader("X-Borla-Client-Epoch-Ms", std::to_string(client_epoch_ms));
}
http->SetContent(std::move(body_content));
ESP_LOGI(TAG,
"[TRACE] trace=%s session=%s request_id=%s stage=ota.http.send url=%s client_send_ms=%llu client_epoch_ms=%lld",
trace_id.c_str(), ::borla::TraceCtx::SessionId(), request_id.c_str(),
check_url_.c_str(),
static_cast<unsigned long long>(client_send_ms),
static_cast<long long>(client_epoch_ms));
uint64_t request_start_ms = TraceMonoMs();
if (!http->Open("POST", check_url_)) {
ESP_LOGE(TAG, "HTTP POST failed");
ESP_LOGE(TAG,
"[TRACE] trace=%s session=%s request_id=%s stage=ota.http.open_failed duration_ms=%llu",
trace_id.c_str(), ::borla::TraceCtx::SessionId(), request_id.c_str(),
static_cast<unsigned long long>(TraceMonoMs() - request_start_ms));
http->Close();
return false;
}
int status = http->GetStatusCode();
std::string response = http->ReadAll();
http->Close();
ESP_LOGI(TAG,
"[TRACE] trace=%s session=%s request_id=%s stage=ota.http.recv status=%d duration_ms=%llu response_bytes=%u",
trace_id.c_str(), ::borla::TraceCtx::SessionId(), request_id.c_str(), status,
static_cast<unsigned long long>(TraceMonoMs() - request_start_ms),
static_cast<unsigned>(response.size()));
ESP_LOGI(TAG, "HTTP %d, body: %s", status, response.c_str());
if (status != 200 || response.empty()) {
return false;
}
bool ok = ParseResponse(response.c_str());
// Save WebSocket config to NVS
if (!websocket_url_.empty()) {
if (IsKnownSavedEndpoint(websocket_url_)) {
websocket_url_ = kDevelopmentWebSocketUrl;
}
// Fix 0.0.0.0 → actual server IP from OTA URL
if (websocket_url_.find("0.0.0.0") != std::string::npos) {
std::string ota_host;
size_t start = check_url_.find("://");
if (start != std::string::npos) {
start += 3;
size_t end = check_url_.find(":", start);
if (end == std::string::npos) end = check_url_.find("/", start);
if (end != std::string::npos) ota_host = check_url_.substr(start, end - start);
}
if (!ota_host.empty() && ota_host != "0.0.0.0") {
size_t pos = websocket_url_.find("0.0.0.0");
websocket_url_.replace(pos, 7, ota_host);
}
}
Settings ws("websocket", true);
ws.SetString("url", websocket_url_);
if (!websocket_token_.empty()) {
ws.SetString("token", websocket_token_);
}
ws.SetInt("version", 3);
ESP_LOGI(TAG, "WebSocket URL: %s", websocket_url_.c_str());
}
return ok;
}
bool Ota::ParseResponse(const char* json)
{
cJSON* root = cJSON_Parse(json);
if (!root) {
ESP_LOGE(TAG, "JSON parse failed");
return false;
}
cJSON* firmware = cJSON_GetObjectItem(root, "firmware");
if (cJSON_IsObject(firmware)) {
cJSON* ver = cJSON_GetObjectItem(firmware, "version");
cJSON* url = cJSON_GetObjectItem(firmware, "url");
if (cJSON_IsString(ver) && cJSON_IsString(url)) {
new_version_ = ver->valuestring;
download_url_ = url->valuestring;
has_new_version_ = (new_version_ != current_version_);
}
}
cJSON* ws = cJSON_GetObjectItem(root, "websocket");
if (cJSON_IsObject(ws)) {
cJSON* url = cJSON_GetObjectItem(ws, "url");
if (cJSON_IsString(url)) websocket_url_ = url->valuestring;
cJSON* token = cJSON_GetObjectItem(ws, "token");
if (cJSON_IsString(token)) websocket_token_ = token->valuestring;
}
cJSON* st = cJSON_GetObjectItem(root, "server_time");
has_server_time_ = cJSON_IsObject(st);
// Parse auto-upgrade fields
cJSON* auto_upd = cJSON_GetObjectItem(root, "auto_update");
if (cJSON_IsBool(auto_upd)) auto_update_ = cJSON_IsTrue(auto_upd);
cJSON* force = cJSON_GetObjectItem(root, "force_upgrade");
if (cJSON_IsBool(force)) force_upgrade_ = cJSON_IsTrue(force);
cJSON_Delete(root);
return true;
}
bool Ota::StartUpgrade()
{
if (download_url_.empty()) {
ESP_LOGW(TAG, "Download URL is empty, skip upgrade");
return false;
}
ESP_LOGI(TAG, "Upgrading to %s", download_url_.c_str());
const esp_partition_t* partition = esp_ota_get_next_update_partition(nullptr);
if (!partition) return false;
// Use NetworkInterface HTTP (works with both WiFi and 4G)
auto http = Board::GetInstance().GetNetwork()->CreateHttp();
if (!http) {
ESP_LOGE(TAG, "Failed to create HTTP client for OTA download");
return false;
}
http->SetTimeout(30000);
if (!http->Open("GET", download_url_)) {
ESP_LOGE(TAG, "Failed to open OTA download URL");
http->Close();
return false;
}
size_t content_length = http->GetBodyLength();
esp_ota_handle_t handle;
if (esp_ota_begin(partition, OTA_WITH_SEQUENTIAL_WRITES, &handle) != ESP_OK) {
http->Close();
return false;
}
char buf[1024];
int total = 0;
while (true) {
int n = http->Read(buf, sizeof(buf));
if (n < 0) { esp_ota_abort(handle); http->Close(); return false; }
if (n == 0) break;
if (esp_ota_write(handle, buf, n) != ESP_OK) { esp_ota_abort(handle); http->Close(); return false; }
total += n;
if (content_length > 0) ESP_LOGI(TAG, "OTA: %d%%", (int)(total * 100 / content_length));
}
http->Close();
if (esp_ota_end(handle) != ESP_OK) return false;
if (esp_ota_set_boot_partition(partition) != ESP_OK) return false;
ESP_LOGI(TAG, "OTA done, notifying user before reboot...");
// Notify server to play "upgrade success" TTS before reboot
auto& app = Application::GetInstance();
if (app.GetProtocol() && app.GetProtocol()->IsAudioChannelOpened()) {
app.GetProtocol()->SendText(
"{\"type\":\"ota_notify\",\"text\":\"升级成功,正在重启\"}");
// Wait for TTS playback before restarting
vTaskDelay(pdMS_TO_TICKS(4000));
}
esp_restart();
return true;
}
void Ota::MarkCurrentVersionValid()
{
const esp_partition_t* running = esp_ota_get_running_partition();
esp_ota_img_states_t state;
if (esp_ota_get_state_partition(running, &state) == ESP_OK) {
if (state == ESP_OTA_IMG_PENDING_VERIFY) {
esp_ota_mark_app_valid_cancel_rollback();
}
}
}

51
main/ota.h Normal file
View File

@@ -0,0 +1,51 @@
#pragma once
#include <string>
class Ota {
public:
// 检查版本(POST 到 OTA URL)
bool CheckVersion();
bool HasNewVersion() const { return has_new_version_; }
bool HasWebsocketConfig() const { return !websocket_url_.empty(); }
const std::string& GetCurrentVersion() const { return current_version_; }
const std::string& GetNewVersion() const { return new_version_; }
const std::string& GetDownloadUrl() const { return download_url_; }
const std::string& GetCheckVersionUrl() const { return check_url_; }
// 执行固件升级
bool StartUpgrade();
// A/B 分区回滚保护
void MarkCurrentVersionValid();
bool HasServerTime() const { return has_server_time_; }
// Auto-upgrade decision
bool IsAutoUpdate() const { return auto_update_; }
bool IsForceUpgrade() const { return force_upgrade_; }
bool ShouldUpgrade() const {
if (!has_new_version_) return false;
return auto_update_ || force_upgrade_;
}
bool CanDownload() const { return !download_url_.empty(); }
bool IsAutoUpgradeType() const { return auto_update_ && has_new_version_; }
bool IsForceUpgradeType() const { return !auto_update_ && force_upgrade_ && has_new_version_; }
bool IsOptionalUpgradeType() const { return !auto_update_ && !force_upgrade_ && has_new_version_; }
private:
bool ParseResponse(const char* json);
std::string check_url_;
std::string current_version_;
std::string new_version_;
std::string download_url_;
std::string websocket_url_;
std::string websocket_token_;
bool has_new_version_ = false;
bool has_server_time_ = false;
bool auto_update_ = false;
bool force_upgrade_ = false;
};

195
main/protocols/protocol.cc Normal file
View File

@@ -0,0 +1,195 @@
#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);
}

96
main/protocols/protocol.h Normal file
View File

@@ -0,0 +1,96 @@
#pragma once
#include <cJSON.h>
#include <string>
#include <functional>
#include <chrono>
#include <vector>
#include <cstdint>
#include "audio/audio_service.h"
// 二进制协议 v3 帧头
struct BinaryProtocol3 {
uint8_t type; // 0=Opus, 1=JSON
uint8_t flags; // bit0 = 批量标志(见 kFrameFlagBatch),其余保留
uint16_t payload_size; // 大端序,整个 payload 长度
uint8_t payload[];
} __attribute__((packed));
// flags 位定义
// 批量上行:payload 内部为 [2B len][opus] 的连续列表。仅 type=0 上行使用。
// 目的:减少 4G ML307 的 MIPSEND 命令频率,避免 AT 管线被音频流打爆。
static constexpr uint8_t kFrameFlagBatch = 0x01;
enum AbortReason {
kAbortReasonNone,
kAbortReasonWakeWordDetected,
};
enum ListeningMode {
kListeningModeAutoStop,
kListeningModeManualStop,
kListeningModeRealtime,
};
// 协议抽象基类(与 xiaozhi Protocol 对齐)
class Protocol {
public:
virtual ~Protocol() = default;
int server_sample_rate() const { return server_sample_rate_; }
int server_frame_duration() const { return server_frame_duration_; }
const std::string& session_id() const { return session_id_; }
// 2026-6-23 ckkj debug 设置当前播放内容,用于上下文保持
void SetCurrentPlaybackText(const std::string& text) { current_playback_text_ = text; }
void ClearCurrentPlaybackText() { current_playback_text_.clear(); }
// 回调注册
void OnIncomingAudio(std::function<void(std::unique_ptr<AudioStreamPacket>)> cb);
void OnIncomingJson(std::function<void(const cJSON*)> cb);
void OnAudioChannelOpened(std::function<void()> cb);
void OnAudioChannelClosed(std::function<void()> cb);
void OnNetworkError(std::function<void(const std::string&)> cb);
void OnConnected(std::function<void()> cb);
void OnDisconnected(std::function<void()> cb);
// 生命周期
virtual bool Start() = 0;
virtual bool OpenAudioChannel() = 0;
virtual void CloseAudioChannel() = 0;
virtual bool IsAudioChannelOpened() const = 0;
// 发送
virtual bool SendAudio(std::unique_ptr<AudioStreamPacket> packet) = 0;
// 便捷消息方法
virtual void SendStartListening(ListeningMode mode);
virtual void SendStopListening();
virtual void SendAbortSpeaking(AbortReason reason);
virtual bool SendText(const std::string& text) = 0;
// Heartbeat (see protocols/websocket_protocol.md §心跳).
// Default no-op so non-WebSocket transports don't have to implement.
virtual bool SendHeartbeat() { return false; }
virtual bool HeartbeatTimedOut() const { return false; }
protected:
virtual void SetError(const std::string& message);
virtual bool IsTimeout() const;
std::function<void(const cJSON*)> on_incoming_json_;
std::function<void(std::unique_ptr<AudioStreamPacket>)> on_incoming_audio_;
std::function<void()> on_audio_channel_opened_;
std::function<void()> on_audio_channel_closed_;
std::function<void(const std::string&)> on_network_error_;
std::function<void()> on_connected_;
std::function<void()> on_disconnected_;
int server_sample_rate_ = 24000;
int server_frame_duration_ = 60;
bool error_occurred_ = false;
std::string session_id_;
std::chrono::time_point<std::chrono::steady_clock> last_incoming_time_;
std::string current_playback_text_; // 当前播放内容,用于上下文保持
};

View File

@@ -0,0 +1,659 @@
#include "websocket_protocol.h"
#include "application.h"
#include "boards/board.h"
#include "system_info.h"
#include "settings.h"
#include "memory_cache.h"
#include "conn_error_config.h"
#include "button_config.h"
#include "trace_ctx.h"
#include <algorithm>
#include <cstring>
#include <ctime>
#include <cstdio>
#include <cJSON.h>
#include <esp_log.h>
#include <esp_timer.h>
#include <arpa/inet.h>
#include <sys/time.h>
#define TAG "WS"
static uint64_t TraceMonoMs()
{
return static_cast<uint64_t>(esp_timer_get_time() / 1000ULL);
}
static int64_t TraceEpochMs()
{
struct timeval tv;
gettimeofday(&tv, nullptr);
if (tv.tv_sec < 1700000000)
{
return 0;
}
return static_cast<int64_t>(tv.tv_sec) * 1000 + tv.tv_usec / 1000;
}
static constexpr uint64_t kAudioTraceHeartbeatMs = 5000;
static constexpr float kAudioTraceRelativeChange = 0.20f;
static constexpr size_t kAudioTraceMinByteDelta = 160;
static std::string MakeWsTraceId()
{
std::string mac = SystemInfo::GetMacAddress();
std::replace(mac.begin(), mac.end(), ':', '-');
return std::string("fw-ws-") + mac + "-" + std::to_string(TraceMonoMs());
}
static const char *JsonStringField(const cJSON *root, const char *name)
{
if (!root || !name)
return "-";
auto *item = cJSON_GetObjectItem(root, name);
return cJSON_IsString(item) ? item->valuestring : "-";
}
static const char *SessionForLog(const std::string &session_id)
{
return session_id.empty() ? "-" : session_id.c_str();
}
WebsocketProtocol::WebsocketProtocol()
{
event_group_handle_ = xEventGroupCreate();
}
WebsocketProtocol::~WebsocketProtocol()
{
CloseAudioChannel();
vEventGroupDelete(event_group_handle_);
}
bool WebsocketProtocol::Start()
{
// WebSocket 仅在需要音频通道时连接
return true;
}
bool WebsocketProtocol::SendAudio(std::unique_ptr<AudioStreamPacket> packet)
{
if (!websocket_ || !websocket_->IsConnected())
{
return false;
}
if (packet->payload.empty() || packet->payload.size() > 0xFFFF)
{
return false; // 单帧 2B 长度上限
}
std::lock_guard<std::mutex> lock(audio_batch_mutex_);
audio_batch_.emplace_back(std::move(packet->payload));
if (audio_batch_.size() >= kAudioBatchSize)
{
return FlushAudioBatchLocked();
}
return true;
}
bool WebsocketProtocol::FlushAudioBatchLocked()
{
if (audio_batch_.empty())
return true;
if (!websocket_ || !websocket_->IsConnected())
{
audio_batch_.clear();
return false;
}
// 计算批量 payload 总大小 = sum(2B len + opus size)
size_t payload_size = 0;
for (const auto &f : audio_batch_)
payload_size += 2 + f.size();
if (payload_size > 0xFFFF)
{
// 理论上 5 帧 × 最大 Opus 帧 (< 1275B) 远低于 65535,但保险起见检查
ESP_LOGE(TAG, "Audio batch payload too large: %u", (unsigned)payload_size);
audio_batch_.clear();
return false;
}
std::string buf;
buf.resize(sizeof(BinaryProtocol3) + payload_size);
auto *bp3 = reinterpret_cast<BinaryProtocol3 *>(&buf[0]);
bp3->type = 0; // Opus
bp3->flags = kFrameFlagBatch;
bp3->payload_size = htons(static_cast<uint16_t>(payload_size));
uint8_t *p = bp3->payload;
for (const auto &f : audio_batch_)
{
uint16_t len_be = htons(static_cast<uint16_t>(f.size()));
memcpy(p, &len_be, 2);
p += 2;
memcpy(p, f.data(), f.size());
p += f.size();
}
uint64_t seq = ++trace_audio_batch_seq_;
uint64_t client_send_ms = TraceMonoMs();
int64_t client_epoch_ms = TraceEpochMs();
if (ShouldTraceAudioBatchLocked(seq, audio_batch_.size(), buf.size(), client_send_ms))
{
SendTraceMarkerLocked("ws.audio_batch.send", seq, audio_batch_.size(), buf.size(),
client_send_ms, client_epoch_ms);
ESP_LOGI(TAG,
"[TRACE] trace=%s stage=ws.audio_batch.send seq=%llu frames=%u bytes=%u client_send_ms=%llu client_epoch_ms=%lld",
trace_id_.c_str(), static_cast<unsigned long long>(seq),
static_cast<unsigned>(audio_batch_.size()), static_cast<unsigned>(buf.size()),
static_cast<unsigned long long>(client_send_ms),
static_cast<long long>(client_epoch_ms));
}
bool ok = websocket_->Send(buf.data(), buf.size(), true);
audio_batch_.clear();
if (ok)
last_outgoing_time_ = std::chrono::steady_clock::now();
return ok;
}
bool WebsocketProtocol::ShouldTraceAudioBatchLocked(uint64_t seq, size_t frames,
size_t bytes, uint64_t now_ms)
{
if (last_trace_audio_batch_ms_ == 0 || seq == 1)
{
last_trace_audio_batch_ms_ = now_ms;
last_trace_audio_batch_frames_ = frames;
last_trace_audio_batch_bytes_ = bytes;
return true;
}
size_t prev_bytes = std::max<size_t>(last_trace_audio_batch_bytes_, 1);
size_t byte_delta = bytes > last_trace_audio_batch_bytes_
? bytes - last_trace_audio_batch_bytes_
: last_trace_audio_batch_bytes_ - bytes;
bool frames_changed = frames != last_trace_audio_batch_frames_;
bool bytes_changed = byte_delta >= kAudioTraceMinByteDelta && static_cast<float>(byte_delta) / static_cast<float>(prev_bytes) >= kAudioTraceRelativeChange;
bool heartbeat = now_ms >= last_trace_audio_batch_ms_ && now_ms - last_trace_audio_batch_ms_ >= kAudioTraceHeartbeatMs;
if (!frames_changed && !bytes_changed && !heartbeat)
{
return false;
}
last_trace_audio_batch_ms_ = now_ms;
last_trace_audio_batch_frames_ = frames;
last_trace_audio_batch_bytes_ = bytes;
return true;
}
bool WebsocketProtocol::SendTraceMarkerLocked(const char *stage, uint64_t seq, size_t frames,
size_t bytes, uint64_t client_send_ms,
int64_t client_epoch_ms)
{
if (!websocket_ || !websocket_->IsConnected())
return false;
char marker[256];
int n = snprintf(marker, sizeof(marker),
"{\"type\":\"trace\",\"trace_id\":\"%s\",\"stage\":\"%s\",\"seq\":%llu,"
"\"frames\":%u,\"bytes\":%u,\"client_send_ms\":%llu,\"client_epoch_ms\":%lld}",
trace_id_.c_str(), stage, static_cast<unsigned long long>(seq),
static_cast<unsigned>(frames), static_cast<unsigned>(bytes),
static_cast<unsigned long long>(client_send_ms),
static_cast<long long>(client_epoch_ms));
if (n <= 0 || n >= static_cast<int>(sizeof(marker)) - 1) // 2026-6-23 ckkj debug 防溢出
return false;
return websocket_->Send(std::string(marker));
}
bool WebsocketProtocol::SendText(const std::string &text)
{
if (!websocket_ || !websocket_->IsConnected())
{
if (!OpenAudioChannel())
{
return false;
}
}
// 在发非音频控制消息(listen stop、status 等)前,先把缓冲里的音频全部 flush,
// 保证 server 看到的消息顺序和固件产生的顺序一致。
{
std::lock_guard<std::mutex> lock(audio_batch_mutex_);
FlushAudioBatchLocked();
}
uint64_t client_send_ms = TraceMonoMs();
int64_t client_epoch_ms = TraceEpochMs();
uint64_t seq = ++trace_text_seq_;
cJSON *trace_root = cJSON_Parse(text.c_str());
if (trace_root)
{
ESP_LOGI(TAG,
"[TRACE] trace=%s session=%s stage=ws.text.send seq=%llu bytes=%u type=%s state=%s action=%s group=%s client_send_ms=%llu client_epoch_ms=%lld",
trace_id_.c_str(), SessionForLog(session_id_),
static_cast<unsigned long long>(seq),
static_cast<unsigned>(text.size()),
JsonStringField(trace_root, "type"),
JsonStringField(trace_root, "state"),
JsonStringField(trace_root, "action"),
JsonStringField(trace_root, "group"),
static_cast<unsigned long long>(client_send_ms),
static_cast<long long>(client_epoch_ms));
cJSON_Delete(trace_root);
}
if (!websocket_->Send(text))
{
ESP_LOGE(TAG, "Failed to send text: %s", text.c_str());
SetError("Server communication error");
return false;
}
last_outgoing_time_ = std::chrono::steady_clock::now();
return true;
}
bool WebsocketProtocol::IsAudioChannelOpened() const
{
return websocket_ && websocket_->IsConnected() && !error_occurred_ && !IsTimeout();
}
void WebsocketProtocol::CloseAudioChannel()
{
// 关闭前把挂起的 Opus batch 尽量发出去,避免最后 1-4 帧丢失。
{
std::lock_guard<std::mutex> lock(audio_batch_mutex_);
FlushAudioBatchLocked();
}
websocket_.reset();
}
bool WebsocketProtocol::SendHeartbeat()
{
if (!websocket_ || !websocket_->IsConnected())
{
return false;
}
// Heartbeat trigger must align with death judgment (HeartbeatTimedOut, line below):
// both look at incoming-only. Previous "skip if out_age<3" optimization broke
// the "upstream busy + downstream silent" scenario (e.g. unactivated device:
// fw keeps sending mic frames so out_age stays <3s → ping skipped → server
// never gets a chance to pong → in_age grows past 20s → false death).
// Now: only skip ping when we recently HEARD from server (in_age <3s);
// outgoing alone is irrelevant — without a pong our in_age won't reset.
auto now = std::chrono::steady_clock::now();
auto in_age = std::chrono::duration_cast<std::chrono::seconds>(now - last_incoming_time_).count();
if (in_age < 3)
{
return true; // recently received bytes from server → link known live
}
if (!websocket_->Send(std::string("{\"type\":\"ping\"}")))
{
ESP_LOGW(TAG, "[HB] ping send failed");
SetError("Heartbeat send failed");
return false;
}
last_outgoing_time_ = now;
return true;
}
bool WebsocketProtocol::HeartbeatTimedOut() const
{
if (!websocket_ || !websocket_->IsConnected())
{
return false;
}
auto now = std::chrono::steady_clock::now();
auto age = std::chrono::duration_cast<std::chrono::seconds>(now - last_incoming_time_).count();
return age > 20;
}
bool WebsocketProtocol::OpenAudioChannel()
{
// Block all reconnect attempts during voice-command sleep
if (Application::GetInstance().shutting_down_.load())
{
ESP_LOGW(TAG, "OpenAudioChannel blocked: device is shutting down");
return false;
}
Settings settings("websocket", false);
std::string url = settings.GetString("url");
std::string token = settings.GetString("token");
int version = settings.GetInt("version");
if (version != 0)
{
version_ = version;
}
if (url.empty())
{
ESP_LOGE(TAG, "No WebSocket URL configured");
SetError("No server URL");
return false;
}
error_occurred_ = false;
xEventGroupClearBits(event_group_handle_, WEBSOCKET_PROTOCOL_SERVER_HELLO_EVENT);
last_incoming_time_ = std::chrono::steady_clock::now();
last_outgoing_time_ = last_incoming_time_;
// 通过 Board 的 Network 接口创建 WebSocket(WiFi 和 4G 统一)
auto *network = Board::GetInstance().GetNetwork();
websocket_ = network->CreateWebSocket(1);
if (!websocket_)
{
ESP_LOGE(TAG, "Failed to create websocket");
SetError("WebSocket creation failed");
return false;
}
// 设置 HTTP Header
if (!token.empty())
{
std::string auth = (token.find(' ') == std::string::npos) ? "Bearer " + token : token;
websocket_->SetHeader("Authorization", auth.c_str());
}
::borla::TraceCtx::RefreshSession();
session_id_ = ::borla::TraceCtx::SessionId();
trace_id_ = MakeWsTraceId();
::borla::TraceCtx::SetTrace(trace_id_.c_str());
std::string request_id = ::borla::TraceCtx::NewRequestId();
trace_connect_send_ms_ = TraceMonoMs();
trace_connect_epoch_ms_ = TraceEpochMs();
last_trace_audio_batch_ms_ = 0;
last_trace_audio_batch_frames_ = 0;
last_trace_audio_batch_bytes_ = 0;
trace_downlink_audio_seq_ = 0;
last_trace_downlink_audio_ms_ = 0;
websocket_->SetHeader("Protocol-Version", std::to_string(version_).c_str());
websocket_->SetHeader("Device-Id", SystemInfo::GetMacAddress().c_str());
websocket_->SetHeader("X-Borla-Trace-Id", trace_id_.c_str());
websocket_->SetHeader("X-Borla-Session-Id", ::borla::TraceCtx::SessionId());
websocket_->SetHeader("X-Request-Id", request_id.c_str());
std::string connect_send_ms = std::to_string(trace_connect_send_ms_);
websocket_->SetHeader("X-Borla-Client-Send-Ms", connect_send_ms.c_str());
if (trace_connect_epoch_ms_ > 0)
{
std::string connect_epoch_ms = std::to_string(trace_connect_epoch_ms_);
websocket_->SetHeader("X-Borla-Client-Epoch-Ms", connect_epoch_ms.c_str());
}
// 注册数据回调
websocket_->OnData([this](const char *data, size_t len, bool binary)
{
if (binary) {
// 解包 v3 二进制帧
if (on_incoming_audio_ && len >= sizeof(BinaryProtocol3)) {
auto* bp3 = reinterpret_cast<const BinaryProtocol3*>(data);
uint16_t payload_size = ntohs(bp3->payload_size);
if (sizeof(BinaryProtocol3) + payload_size > len) {
ESP_LOGW(TAG, "Drop malformed binary frame: len=%u payload=%u",
static_cast<unsigned>(len),
static_cast<unsigned>(payload_size));
return;
}
uint64_t seq = ++trace_downlink_audio_seq_;
uint64_t recv_ms = TraceMonoMs();
if (seq == 1 || last_trace_downlink_audio_ms_ == 0 ||
recv_ms - last_trace_downlink_audio_ms_ >= kAudioTraceHeartbeatMs) {
last_trace_downlink_audio_ms_ = recv_ms;
ESP_LOGI(TAG,
"[TRACE] trace=%s session=%s stage=ws.binary.recv seq=%llu bytes=%u payload_bytes=%u client_recv_ms=%llu client_epoch_ms=%lld",
trace_id_.c_str(), SessionForLog(session_id_),
static_cast<unsigned long long>(seq),
static_cast<unsigned>(len),
static_cast<unsigned>(payload_size),
static_cast<unsigned long long>(recv_ms),
static_cast<long long>(TraceEpochMs()));
}
auto pkt = std::make_unique<AudioStreamPacket>();
pkt->sample_rate = server_sample_rate_;
pkt->frame_duration = server_frame_duration_;
pkt->payload.assign(bp3->payload, bp3->payload + payload_size);
on_incoming_audio_(std::move(pkt));
}
} else {
// JSON 文本帧
auto* root = cJSON_ParseWithLength(data, len);
if (!root) return;
auto* type = cJSON_GetObjectItem(root, "type");
if (cJSON_IsString(type)) {
ESP_LOGI(TAG,
"[TRACE] trace=%s session=%s stage=ws.text.recv bytes=%u type=%s state=%s action=%s group=%s client_recv_ms=%llu client_epoch_ms=%lld",
trace_id_.c_str(), SessionForLog(session_id_),
static_cast<unsigned>(len),
type->valuestring,
JsonStringField(root, "state"),
JsonStringField(root, "action"),
JsonStringField(root, "group"),
static_cast<unsigned long long>(TraceMonoMs()),
static_cast<long long>(TraceEpochMs()));
if (strcmp(type->valuestring, "hello") == 0) {
ParseServerHello(root);
} else if (strcmp(type->valuestring, "pong") == 0) {
// Heartbeat response — last_incoming_time_ below proves liveness.
// Don't forward to on_incoming_json_ (would log "Unknown message type").
} else if (on_incoming_json_) {
on_incoming_json_(root);
}
}
cJSON_Delete(root);
}
last_incoming_time_ = std::chrono::steady_clock::now(); });
websocket_->OnDisconnected([this]()
{
ESP_LOGI(TAG, "WebSocket disconnected");
if (on_disconnected_) on_disconnected_();
if (on_audio_channel_closed_) on_audio_channel_closed_(); });
// 连接
ESP_LOGI(TAG, "Connecting to %s (version %d)", url.c_str(), version_);
ESP_LOGI(TAG,
"[TRACE] trace=%s session=%s request_id=%s stage=ws.connect.send url=%s client_send_ms=%llu client_epoch_ms=%lld",
trace_id_.c_str(), SessionForLog(session_id_), request_id.c_str(), url.c_str(),
static_cast<unsigned long long>(trace_connect_send_ms_),
static_cast<long long>(trace_connect_epoch_ms_));
uint64_t connect_start_ms = TraceMonoMs();
if (!websocket_->Connect(url.c_str()))
{
ESP_LOGE(TAG, "Failed to connect to WebSocket server");
ESP_LOGE(TAG,
"[TRACE] trace=%s session=%s request_id=%s stage=ws.connect.failed duration_ms=%llu",
trace_id_.c_str(), SessionForLog(session_id_), request_id.c_str(),
static_cast<unsigned long long>(TraceMonoMs() - connect_start_ms));
SetError("Connection failed");
return false;
}
ESP_LOGI(TAG,
"[TRACE] trace=%s session=%s request_id=%s stage=ws.connect.done duration_ms=%llu",
trace_id_.c_str(), SessionForLog(session_id_), request_id.c_str(),
static_cast<unsigned long long>(TraceMonoMs() - connect_start_ms));
if (on_connected_)
on_connected_();
// 发送 hello 握手
if (!SendText(GetHelloMessage()))
{
return false;
}
// 2026-6-21 ckkj debug 增加超时时间15秒
// 等待 ServerHello(15 秒超时,WiFi模式下SSL握手可能较慢)
EventBits_t bits = xEventGroupWaitBits(event_group_handle_,
WEBSOCKET_PROTOCOL_SERVER_HELLO_EVENT, pdTRUE, pdFALSE, pdMS_TO_TICKS(15000));
if (!(bits & WEBSOCKET_PROTOCOL_SERVER_HELLO_EVENT))
{
ESP_LOGE(TAG, "Timeout waiting for ServerHello");
SetError("Server timeout");
return false;
}
if (on_audio_channel_opened_)
on_audio_channel_opened_();
return true;
}
std::string WebsocketProtocol::GetHelloMessage()
{
cJSON *root = cJSON_CreateObject();
cJSON_AddStringToObject(root, "type", "hello");
cJSON_AddStringToObject(root, "trace_id", trace_id_.c_str());
cJSON_AddNumberToObject(root, "client_send_ms", static_cast<double>(TraceMonoMs()));
int64_t epoch_ms = TraceEpochMs();
if (epoch_ms > 0)
{
cJSON_AddNumberToObject(root, "client_epoch_ms", static_cast<double>(epoch_ms));
}
cJSON_AddNumberToObject(root, "version", version_);
cJSON_AddStringToObject(root, "transport", "websocket");
const char *connect_reason = Application::GetInstance().IdleWatchdogHelloConnectReason();
if (connect_reason && connect_reason[0] != '\0')
{
cJSON_AddStringToObject(root, "connect_reason", connect_reason);
}
cJSON *features = cJSON_CreateObject();
cJSON_AddBoolToObject(features, "mcp", true);
cJSON_AddBoolToObject(features, "local_audio", true);
cJSON_AddBoolToObject(features, "play_local_sequence", true);
cJSON_AddItemToObject(root, "features", features);
cJSON *audio_params = cJSON_CreateObject();
cJSON_AddStringToObject(audio_params, "format", "opus");
cJSON_AddNumberToObject(audio_params, "sample_rate", 16000);
cJSON_AddNumberToObject(audio_params, "channels", 1);
cJSON_AddNumberToObject(audio_params, "frame_duration", OPUS_FRAME_DURATION_MS);
cJSON_AddItemToObject(root, "audio_params", audio_params);
// Attach Flash memory cache for server sync
auto &cache = MemoryCache::GetInstance();
if (cache.HasData())
{
cJSON *mem = cJSON_CreateObject();
if (!cache.GetChildName().empty())
cJSON_AddStringToObject(mem, "child_name", cache.GetChildName().c_str());
if (!cache.GetProfileText().empty())
cJSON_AddStringToObject(mem, "brain_text", cache.GetProfileText().c_str());
cJSON_AddNumberToObject(mem, "interaction_count", cache.GetInteractionCount());
cJSON_AddItemToObject(root, "memory_cache", mem);
}
// Attach NVS friends for server sync (offline-first: stored locally, synced on connect)
Settings friends_store("friends", false);
int friend_count = friends_store.GetInt("count", 0);
if (friend_count > 0)
{
cJSON *friends = cJSON_CreateArray();
for (int i = 0; i < friend_count && i < 20; i++)
{
std::string key = "f_" + std::to_string(i);
std::string val = friends_store.GetString(key.c_str());
if (!val.empty())
{
cJSON *item = cJSON_Parse(val.c_str());
if (item)
cJSON_AddItemToArray(friends, item);
}
}
cJSON_AddItemToObject(root, "friends", friends);
}
char *json_str = cJSON_PrintUnformatted(root);
std::string message(json_str);
cJSON_free(json_str);
cJSON_Delete(root);
return message;
}
void WebsocketProtocol::ParseServerHello(const cJSON *root)
{
auto *session_id = cJSON_GetObjectItem(root, "session_id");
if (cJSON_IsString(session_id))
{
session_id_ = session_id->valuestring;
::borla::TraceCtx::SetSession(session_id_.c_str());
ESP_LOGI(TAG, "Session: %s", session_id_.c_str());
ESP_LOGI(TAG,
"[TRACE] trace=%s session=%s stage=server.hello.recv",
trace_id_.c_str(), SessionForLog(session_id_));
}
auto *audio_params = cJSON_GetObjectItem(root, "audio_params");
if (cJSON_IsObject(audio_params))
{
auto *sr = cJSON_GetObjectItem(audio_params, "sample_rate");
if (cJSON_IsNumber(sr))
server_sample_rate_ = sr->valueint;
auto *fd = cJSON_GetObjectItem(audio_params, "frame_duration");
if (cJSON_IsNumber(fd))
server_frame_duration_ = fd->valueint;
}
ESP_LOGI(TAG, "ServerHello: sample_rate=%d, frame_duration=%d",
server_sample_rate_, server_frame_duration_);
// Parse connection error prompt config (ADR-004 Phase 1)
// Server may override which PromptGroup is played when the WS connection fails.
// Missing field → firmware falls back to hard-coded defaults.
auto *conn_err_prompts = cJSON_GetObjectItem(root, "connection_error_prompts");
if (cJSON_IsObject(conn_err_prompts))
{
auto *srv = cJSON_GetObjectItem(conn_err_prompts, "server_unreachable");
auto *net = cJSON_GetObjectItem(conn_err_prompts, "no_network");
const char *srv_str = cJSON_IsString(srv) ? srv->valuestring : nullptr;
const char *net_str = cJSON_IsString(net) ? net->valuestring : nullptr;
conn_error_config::UpdateFromHello(srv_str, net_str);
}
// Cache device nickname from backend.device.name to NVS so BLE friend
// exchange can use it as local.name (instead of the BLE-advertisement
// placeholder "BorlaF-XXXX"). CallManager also relies on this via the
// server-side conn._device_name for caller_name attribution.
auto *device_name = cJSON_GetObjectItem(root, "device_name");
if (cJSON_IsString(device_name) && device_name->valuestring[0] != '\0')
{
Settings("device", true).SetString("name", device_name->valuestring);
}
// Parse button action map (ADR-004 Phase 2)
// Only keys "3" / "4" are honored server-side; single/double/long-press
// remain hard-coded in firmware for safety.
auto *button_map = cJSON_GetObjectItem(root, "button_map");
if (cJSON_IsObject(button_map))
{
auto *a3 = cJSON_GetObjectItem(button_map, "3");
auto *a4 = cJSON_GetObjectItem(button_map, "4");
const char *a3_str = cJSON_IsString(a3) ? a3->valuestring : nullptr;
const char *a4_str = cJSON_IsString(a4) ? a4->valuestring : nullptr;
button_config::UpdateFromHello(a3_str, a4_str);
}
// 传感器重构 ADR-006 / 决策 #8:不再解析 upright_config(姿态识别已移到 server)。
// Sync device clock from server time (for alarm feature)
auto *server_time = cJSON_GetObjectItem(root, "server_time");
auto *tz_offset = cJSON_GetObjectItem(root, "tz_offset");
if (cJSON_IsNumber(server_time))
{
struct timeval tv = {};
tv.tv_sec = (time_t)server_time->valuedouble;
settimeofday(&tv, nullptr);
// Set timezone via POSIX TZ string (offset is seconds east of UTC)
int offset_hours = cJSON_IsNumber(tz_offset) ? (tz_offset->valueint / 3600) : 8;
char tz_str[16];
snprintf(tz_str, sizeof(tz_str), "UTC-%d", offset_hours);
setenv("TZ", tz_str, 1);
tzset();
time_t now = time(nullptr);
struct tm tm_now;
localtime_r(&now, &tm_now);
ESP_LOGI(TAG, "Clock synced: %04d-%02d-%02d %02d:%02d:%02d (TZ=UTC+%d)",
tm_now.tm_year + 1900, tm_now.tm_mon + 1, tm_now.tm_mday,
tm_now.tm_hour, tm_now.tm_min, tm_now.tm_sec, offset_hours);
}
xEventGroupSetBits(event_group_handle_, WEBSOCKET_PROTOCOL_SERVER_HELLO_EVENT);
}

View File

@@ -0,0 +1,70 @@
#pragma once
#include "protocol.h"
#include <web_socket.h>
#include <freertos/FreeRTOS.h>
#include <freertos/event_groups.h>
#include <memory>
#include <mutex>
#include <string>
#include <vector>
#include <cstdint>
#define WEBSOCKET_PROTOCOL_SERVER_HELLO_EVENT (1 << 0)
// 上行 Opus 批量:5 帧一包(~300ms),用于降低 ML307 MIPSEND 频率。
// 见 protocols/websocket_protocol.md "批量音频"。
static constexpr size_t kAudioBatchSize = 5;
class WebsocketProtocol : public Protocol {
public:
WebsocketProtocol();
~WebsocketProtocol() override;
bool Start() override;
bool SendAudio(std::unique_ptr<AudioStreamPacket> packet) override;
bool OpenAudioChannel() override;
void CloseAudioChannel() override;
bool IsAudioChannelOpened() const override;
bool SendHeartbeat() override;
bool HeartbeatTimedOut() const override;
private:
bool SendText(const std::string& text) override;
std::string GetHelloMessage();
void ParseServerHello(const cJSON* root);
// 批量上行:把累积的 Opus 帧打成一个 v3 二进制帧发出
// 由 SendAudio 在满 kAudioBatchSize 时触发,或由 SendText / CloseAudioChannel
// 在发非音频控制消息前主动 flush 以保证时序。
// 调用方持有 audio_batch_mutex_ 时调用此函数。
bool FlushAudioBatchLocked();
bool SendTraceMarkerLocked(const char* stage, uint64_t seq, size_t frames,
size_t bytes, uint64_t client_send_ms,
int64_t client_epoch_ms);
bool ShouldTraceAudioBatchLocked(uint64_t seq, size_t frames, size_t bytes,
uint64_t now_ms);
EventGroupHandle_t event_group_handle_;
std::unique_ptr<WebSocket> websocket_;
int version_ = 3;
std::string trace_id_;
uint64_t trace_connect_send_ms_ = 0;
int64_t trace_connect_epoch_ms_ = 0;
uint64_t trace_text_seq_ = 0;
uint64_t trace_audio_batch_seq_ = 0;
uint64_t trace_downlink_audio_seq_ = 0;
uint64_t last_trace_downlink_audio_ms_ = 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;
// Last time we successfully wrote to the socket (audio / control / ping).
// Combined with base-class last_incoming_time_, drives the idle-only
// heartbeat: ping only fires when both directions have been silent for ≥3s.
std::chrono::time_point<std::chrono::steady_clock> last_outgoing_time_;
std::mutex audio_batch_mutex_;
std::vector<std::vector<uint8_t>> audio_batch_; // pending opus frames
};

81
main/settings.cc Normal file
View File

@@ -0,0 +1,81 @@
#include "settings.h"
#include <esp_log.h>
#define TAG "Settings"
Settings::Settings(const char* ns, bool read_write) : read_write_(read_write)
{
nvs_open_mode_t mode = read_write ? NVS_READWRITE : NVS_READONLY;
esp_err_t err = nvs_open(ns, mode, &handle_);
if (err != ESP_OK) {
// ESP_ERR_NVS_NOT_FOUND in read-only mode just means the namespace has
// never been written — that's a valid "no data yet" case (e.g. the
// "friends" namespace on first boot), not an error worth warning about.
if (!(err == ESP_ERR_NVS_NOT_FOUND && !read_write)) {
ESP_LOGW(TAG, "Failed to open NVS namespace '%s': %s", ns, esp_err_to_name(err));
}
handle_ = 0;
}
}
Settings::~Settings()
{
if (handle_) {
if (dirty_) {
nvs_commit(handle_);
}
nvs_close(handle_);
}
}
std::string Settings::GetString(const char* key, const std::string& default_val) const
{
if (!handle_) return default_val;
size_t required_size = 0;
if (nvs_get_str(handle_, key, nullptr, &required_size) != ESP_OK) {
return default_val;
}
std::string value(required_size - 1, '\0');
if (nvs_get_str(handle_, key, &value[0], &required_size) != ESP_OK) {
return default_val;
}
return value;
}
void Settings::SetString(const char* key, const std::string& value)
{
if (!handle_ || !read_write_) return;
nvs_set_str(handle_, key, value.c_str());
dirty_ = true;
}
int Settings::GetInt(const char* key, int default_val) const
{
if (!handle_) return default_val;
int32_t value = default_val;
nvs_get_i32(handle_, key, &value);
return value;
}
void Settings::SetInt(const char* key, int value)
{
if (!handle_ || !read_write_) return;
nvs_set_i32(handle_, key, value);
dirty_ = true;
}
void Settings::EraseKey(const char* key)
{
if (!handle_ || !read_write_) return;
nvs_erase_key(handle_, key);
dirty_ = true;
}
void Settings::EraseAll()
{
if (!handle_ || !read_write_) return;
nvs_erase_all(handle_);
dirty_ = true;
}

26
main/settings.h Normal file
View File

@@ -0,0 +1,26 @@
#pragma once
#include <string>
#include "nvs.h"
// NVS 持久化配置存储(与 xiaozhi Settings 对齐)
// 每个实例绑定一个 NVS namespace
class Settings {
public:
Settings(const char* ns, bool read_write = true);
~Settings();
std::string GetString(const char* key, const std::string& default_val = "") const;
void SetString(const char* key, const std::string& value);
int GetInt(const char* key, int default_val = 0) const;
void SetInt(const char* key, int value);
void EraseKey(const char* key);
void EraseAll();
private:
nvs_handle_t handle_ = 0;
bool dirty_ = false;
bool read_write_ = false;
};

84
main/system_info.cc Normal file
View File

@@ -0,0 +1,84 @@
#include "system_info.h"
#include <esp_mac.h>
#include <esp_chip_info.h>
#include <esp_app_desc.h>
#include <esp_heap_caps.h>
#include <esp_system.h>
#include <esp_log.h>
#include <esp_flash.h>
#include <cstdio>
#define TAG "SystemInfo"
std::string SystemInfo::GetMacAddress()
{
// Use base MAC as device unique ID (independent of WiFi/BLE/4G)
// On ESP32-S3: BASE == WIFI_STA, so this is backward compatible
uint8_t mac[6];
esp_read_mac(mac, ESP_MAC_BASE);
char buf[18];
snprintf(buf, sizeof(buf), "%02x:%02x:%02x:%02x:%02x:%02x",
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
return std::string(buf);
}
std::string SystemInfo::BleMacToBaseMac(const std::string& ble_mac)
{
// ESP32-S3: BLE MAC = BASE MAC + 2
// Convert BLE MAC back to BASE MAC for device identification
uint8_t mac[6];
sscanf(ble_mac.c_str(), "%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx",
&mac[0], &mac[1], &mac[2], &mac[3], &mac[4], &mac[5]);
// Subtract 2 from the 48-bit MAC (handle borrow)
uint64_t val = 0;
for (int i = 0; i < 6; i++) val = (val << 8) | mac[i];
val -= 2;
for (int i = 5; i >= 0; i--) { mac[i] = val & 0xFF; val >>= 8; }
char buf[18];
snprintf(buf, sizeof(buf), "%02x:%02x:%02x:%02x:%02x:%02x",
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
return std::string(buf);
}
std::string SystemInfo::GetChipModelName()
{
return CONFIG_IDF_TARGET;
}
std::string SystemInfo::GetAppVersion()
{
const esp_app_desc_t* desc = esp_app_get_description();
return desc ? desc->version : "unknown";
}
std::string SystemInfo::GetUserAgent()
{
return std::string("borla-s3/") + GetAppVersion();
}
uint32_t SystemInfo::GetFreeHeapSize()
{
return esp_get_free_heap_size();
}
uint32_t SystemInfo::GetMinimumFreeHeapSize()
{
return esp_get_minimum_free_heap_size();
}
uint32_t SystemInfo::GetFlashSize()
{
uint32_t flash_size = 0;
esp_flash_get_size(nullptr, &flash_size);
return flash_size;
}
void SystemInfo::PrintHeapStats()
{
ESP_LOGI(TAG, "Free heap: %lu, Min free: %lu, PSRAM free: %lu",
(unsigned long)esp_get_free_heap_size(),
(unsigned long)esp_get_minimum_free_heap_size(),
(unsigned long)heap_caps_get_free_size(MALLOC_CAP_SPIRAM));
}

17
main/system_info.h Normal file
View File

@@ -0,0 +1,17 @@
#pragma once
#include <string>
#include <cstdint>
class SystemInfo {
public:
static std::string GetMacAddress();
static std::string BleMacToBaseMac(const std::string& ble_mac);
static std::string GetChipModelName();
static std::string GetAppVersion();
static std::string GetUserAgent();
static uint32_t GetFreeHeapSize();
static uint32_t GetMinimumFreeHeapSize();
static uint32_t GetFlashSize();
static void PrintHeapStats();
};

61
main/trace_ctx.cc Normal file
View File

@@ -0,0 +1,61 @@
#include "trace_ctx.h"
#include <cstdio>
#include <cstring>
#include <esp_random.h>
namespace borla {
char TraceCtx::trace_id_[TraceCtx::kIdBufSize] = "-";
char TraceCtx::session_id_[TraceCtx::kIdBufSize] = "-";
char TraceCtx::request_id_[TraceCtx::kIdBufSize] = "-";
static void GenHex16(char* out) {
// 16 hex chars from 8 random bytes.
uint8_t buf[8];
esp_fill_random(buf, sizeof(buf));
static const char kHex[] = "0123456789abcdef";
for (int i = 0; i < 8; ++i) {
out[i * 2] = kHex[(buf[i] >> 4) & 0x0F];
out[i * 2 + 1] = kHex[buf[i] & 0x0F];
}
out[16] = '\0';
}
const char* TraceCtx::TraceId() { return trace_id_; }
const char* TraceCtx::SessionId() { return session_id_; }
const char* TraceCtx::RequestId() { return request_id_; }
void TraceCtx::RefreshTrace(const char* prefix) {
char hex[20];
GenHex16(hex);
// 安全拼接到固定缓冲
snprintf(trace_id_, kIdBufSize, "%s-%s", prefix ? prefix : "dev", hex);
}
void TraceCtx::RefreshSession() {
char hex[20];
GenHex16(hex);
snprintf(session_id_, kIdBufSize, "s-%s", hex);
}
const char* TraceCtx::NewRequestId() {
char hex[20];
GenHex16(hex);
snprintf(request_id_, kIdBufSize, "r-%s", hex);
return request_id_;
}
void TraceCtx::SetTrace(const char* trace_id) {
if (!trace_id || !trace_id[0]) return;
strncpy(trace_id_, trace_id, kIdBufSize - 1);
trace_id_[kIdBufSize - 1] = '\0';
}
void TraceCtx::SetSession(const char* session_id) {
if (!session_id || !session_id[0]) return;
strncpy(session_id_, session_id, kIdBufSize - 1);
session_id_[kIdBufSize - 1] = '\0';
}
} // namespace borla

54
main/trace_ctx.h Normal file
View File

@@ -0,0 +1,54 @@
/* TraceCtx — Borla 设备侧追踪上下文(docs/0019 §10.1, §11.3).
3 个 id:
session_id 连接级 · 每次 WS 连接刷新
trace_id 回合级 · 每次设备主动发起对话回合刷新
request_id 每次 HTTP/OTA 调用刷新
每次 BORLA_LOGI/D/W/E 打日志时都自动在前缀里带 [trace_id],
与 server / backend grep 同一 trace_id 拼端到端链路。
*/
#pragma once
#include <cstddef>
#include <cstdint>
namespace borla {
class TraceCtx {
public:
// 长度上限 · prefix + '-' + 16hex + '\0' = 18 + 余量
static constexpr size_t kIdBufSize = 96;
// 取当前 id(线程安全 · 内部用原子指针交换)
static const char* TraceId(); // "ws-xxxx" / "dev-xxxx" / "-"
static const char* SessionId(); // "s-xxxx" / "-"
static const char* RequestId(); // "r-xxxx" / "-"
// 重新生成 id · 用在事件起点
static void RefreshTrace(const char* prefix = "dev");
static void RefreshSession();
static const char* NewRequestId(); // 返回最新 request_id · 用于 HTTP header
// 显式设置(从 server 下行的 trace_id / session_id 透传)
static void SetTrace(const char* trace_id);
static void SetSession(const char* session_id);
private:
static char trace_id_[kIdBufSize];
static char session_id_[kIdBufSize];
static char request_id_[kIdBufSize];
};
} // namespace borla
// 标准日志宏 · 替代裸 ESP_LOGI/D/W/E
#define BORLA_LOGI(tag, fmt, ...) \
ESP_LOGI(tag, "[%s] " fmt, ::borla::TraceCtx::TraceId(), ##__VA_ARGS__)
#define BORLA_LOGD(tag, fmt, ...) \
ESP_LOGD(tag, "[%s] " fmt, ::borla::TraceCtx::TraceId(), ##__VA_ARGS__)
#define BORLA_LOGW(tag, fmt, ...) \
ESP_LOGW(tag, "[%s] " fmt, ::borla::TraceCtx::TraceId(), ##__VA_ARGS__)
#define BORLA_LOGE(tag, fmt, ...) \
ESP_LOGE(tag, "[%s] " fmt, ::borla::TraceCtx::TraceId(), ##__VA_ARGS__)