application.cc 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854
  1. #include "application.h"
  2. #include "board.h"
  3. #include "display.h"
  4. #include "system_info.h"
  5. #include "ml307_ssl_transport.h"
  6. #include "audio_codec.h"
  7. #include "mqtt_protocol.h"
  8. #include "websocket_protocol.h"
  9. #include "font_awesome_symbols.h"
  10. #include "iot/thing_manager.h"
  11. #include "assets/lang_config.h"
  12. #include <cstring>
  13. #include <esp_log.h>
  14. #include <cJSON.h>
  15. #include <driver/gpio.h>
  16. #include <arpa/inet.h>
  17. #include <esp_app_desc.h>
  18. #include "esp_err.h"
  19. #include "freertos/FreeRTOS.h"
  20. #include "freertos/queue.h"
  21. #include "freertos/task.h"
  22. #define TAG "Application"
  23. static QueueHandle_t gpio_evt_queue = NULL;
  24. static const char* const STATE_STRINGS[] = {
  25. "unknown",
  26. "starting",
  27. "configuring",
  28. "idle",
  29. "connecting",
  30. "listening",
  31. "speaking",
  32. "upgrading",
  33. "activating",
  34. "fatal_error",
  35. "invalid_state"
  36. };
  37. Application::Application() {
  38. event_group_ = xEventGroupCreate();
  39. background_task_ = new BackgroundTask(4096 * 8);
  40. esp_timer_create_args_t clock_timer_args = {
  41. .callback = [](void* arg) {
  42. Application* app = (Application*)arg;
  43. app->OnClockTimer();
  44. },
  45. .arg = this,
  46. .dispatch_method = ESP_TIMER_TASK,
  47. .name = "clock_timer",
  48. .skip_unhandled_events = true
  49. };
  50. esp_timer_create(&clock_timer_args, &clock_timer_handle_);
  51. }
  52. Application::~Application() {
  53. if (clock_timer_handle_ != nullptr) {
  54. esp_timer_stop(clock_timer_handle_);
  55. esp_timer_delete(clock_timer_handle_);
  56. }
  57. if (background_task_ != nullptr) {
  58. delete background_task_;
  59. }
  60. vEventGroupDelete(event_group_);
  61. }
  62. void Application::CheckNewVersion() {
  63. auto& board = Board::GetInstance();
  64. auto display = board.GetDisplay();
  65. // Check if there is a new firmware version available
  66. ota_.SetPostData(board.GetJson());
  67. const int MAX_RETRY = 10;
  68. int retry_count = 0;
  69. while (true) {
  70. if (!ota_.CheckVersion()) {
  71. retry_count++;
  72. if (retry_count >= MAX_RETRY) {
  73. ESP_LOGE(TAG, "Too many retries, exit version check");
  74. return;
  75. }
  76. ESP_LOGW(TAG, "Check new version failed, retry in %d seconds (%d/%d)", 60, retry_count, MAX_RETRY);
  77. vTaskDelay(pdMS_TO_TICKS(60000));
  78. continue;
  79. }
  80. retry_count = 0;
  81. if (ota_.HasNewVersion()) {
  82. Alert(Lang::Strings::OTA_UPGRADE, Lang::Strings::UPGRADING, "happy", Lang::Sounds::P3_UPGRADE);
  83. // Wait for the chat state to be idle
  84. do {
  85. vTaskDelay(pdMS_TO_TICKS(3000));
  86. } while (GetDeviceState() != kDeviceStateIdle);
  87. // Use main task to do the upgrade, not cancelable
  88. Schedule([this, display]() {
  89. SetDeviceState(kDeviceStateUpgrading);
  90. display->SetIcon(FONT_AWESOME_DOWNLOAD);
  91. std::string message = std::string(Lang::Strings::NEW_VERSION) + ota_.GetFirmwareVersion();
  92. display->SetChatMessage("system", message.c_str());
  93. auto& board = Board::GetInstance();
  94. board.SetPowerSaveMode(false);
  95. #if CONFIG_USE_WAKE_WORD_DETECT
  96. wake_word_detect_.StopDetection();
  97. #endif
  98. // 预先关闭音频输出,避免升级过程有音频操作
  99. auto codec = board.GetAudioCodec();
  100. codec->EnableInput(false);
  101. codec->EnableOutput(false);
  102. {
  103. std::lock_guard<std::mutex> lock(mutex_);
  104. audio_decode_queue_.clear();
  105. }
  106. background_task_->WaitForCompletion();
  107. delete background_task_;
  108. background_task_ = nullptr;
  109. vTaskDelay(pdMS_TO_TICKS(1000));
  110. ota_.StartUpgrade([display](int progress, size_t speed) {
  111. char buffer[64];
  112. snprintf(buffer, sizeof(buffer), "%d%% %zuKB/s", progress, speed / 1024);
  113. display->SetChatMessage("system", buffer);
  114. });
  115. // If upgrade success, the device will reboot and never reach here
  116. display->SetStatus(Lang::Strings::UPGRADE_FAILED);
  117. ESP_LOGI(TAG, "Firmware upgrade failed...");
  118. vTaskDelay(pdMS_TO_TICKS(3000));
  119. Reboot();
  120. });
  121. return;
  122. }
  123. // No new version, mark the current version as valid
  124. ota_.MarkCurrentVersionValid();
  125. std::string message = std::string(Lang::Strings::VERSION) + ota_.GetCurrentVersion();
  126. display->ShowNotification(message.c_str());
  127. if (ota_.HasActivationCode()) {
  128. // Activation code is valid
  129. SetDeviceState(kDeviceStateActivating);
  130. ShowActivationCode();
  131. // Check again in 60 seconds or until the device is idle
  132. for (int i = 0; i < 60; ++i) {
  133. if (device_state_ == kDeviceStateIdle) {
  134. break;
  135. }
  136. vTaskDelay(pdMS_TO_TICKS(1000));
  137. }
  138. continue;
  139. }
  140. SetDeviceState(kDeviceStateIdle);
  141. display->SetChatMessage("system", "");
  142. PlaySound(Lang::Sounds::P3_SUCCESS);
  143. // Exit the loop if upgrade or idle
  144. break;
  145. }
  146. }
  147. void Application::ShowActivationCode() {
  148. auto& message = ota_.GetActivationMessage();
  149. auto& code = ota_.GetActivationCode();
  150. struct digit_sound {
  151. char digit;
  152. const std::string_view& sound;
  153. };
  154. static const std::array<digit_sound, 10> digit_sounds{{
  155. digit_sound{'0', Lang::Sounds::P3_0},
  156. digit_sound{'1', Lang::Sounds::P3_1},
  157. digit_sound{'2', Lang::Sounds::P3_2},
  158. digit_sound{'3', Lang::Sounds::P3_3},
  159. digit_sound{'4', Lang::Sounds::P3_4},
  160. digit_sound{'5', Lang::Sounds::P3_5},
  161. digit_sound{'6', Lang::Sounds::P3_6},
  162. digit_sound{'7', Lang::Sounds::P3_7},
  163. digit_sound{'8', Lang::Sounds::P3_8},
  164. digit_sound{'9', Lang::Sounds::P3_9}
  165. }};
  166. // This sentence uses 9KB of SRAM, so we need to wait for it to finish
  167. Alert(Lang::Strings::ACTIVATION, message.c_str(), "happy", Lang::Sounds::P3_ACTIVATION);
  168. vTaskDelay(pdMS_TO_TICKS(1000));
  169. background_task_->WaitForCompletion();
  170. for (const auto& digit : code) {
  171. auto it = std::find_if(digit_sounds.begin(), digit_sounds.end(),
  172. [digit](const digit_sound& ds) { return ds.digit == digit; });
  173. if (it != digit_sounds.end()) {
  174. PlaySound(it->sound);
  175. }
  176. }
  177. }
  178. void Application::Alert(const char* status, const char* message, const char* emotion, const std::string_view& sound) {
  179. ESP_LOGW(TAG, "Alert %s: %s [%s]", status, message, emotion);
  180. auto display = Board::GetInstance().GetDisplay();
  181. display->SetStatus(status);
  182. display->SetEmotion(emotion);
  183. display->SetChatMessage("system", message);
  184. if (!sound.empty()) {
  185. PlaySound(sound);
  186. }
  187. }
  188. void Application::DismissAlert() {
  189. if (device_state_ == kDeviceStateIdle) {
  190. auto display = Board::GetInstance().GetDisplay();
  191. display->SetStatus(Lang::Strings::STANDBY);
  192. display->SetEmotion("neutral");
  193. display->SetChatMessage("system", "");
  194. }
  195. }
  196. void Application::PlaySound(const std::string_view& sound) {
  197. auto codec = Board::GetInstance().GetAudioCodec();
  198. codec->EnableOutput(true);
  199. SetDecodeSampleRate(16000);
  200. const char* data = sound.data();
  201. size_t size = sound.size();
  202. for (const char* p = data; p < data + size; ) {
  203. auto p3 = (BinaryProtocol3*)p;
  204. p += sizeof(BinaryProtocol3);
  205. auto payload_size = ntohs(p3->payload_size);
  206. std::vector<uint8_t> opus;
  207. opus.resize(payload_size);
  208. memcpy(opus.data(), p3->payload, payload_size);
  209. p += payload_size;
  210. std::lock_guard<std::mutex> lock(mutex_);
  211. audio_decode_queue_.emplace_back(std::move(opus));
  212. }
  213. }
  214. void Application::ToggleChatState() {
  215. if (device_state_ == kDeviceStateActivating) {
  216. SetDeviceState(kDeviceStateIdle);
  217. return;
  218. }
  219. if (!protocol_) {
  220. ESP_LOGE(TAG, "Protocol not initialized");
  221. return;
  222. }
  223. if (device_state_ == kDeviceStateIdle) {
  224. Schedule([this]() {
  225. SetDeviceState(kDeviceStateConnecting);
  226. if (!protocol_->OpenAudioChannel()) {
  227. return;
  228. }
  229. keep_listening_ = true;
  230. protocol_->SendStartListening(kListeningModeAutoStop);
  231. SetDeviceState(kDeviceStateListening);
  232. });
  233. } else if (device_state_ == kDeviceStateSpeaking) {
  234. Schedule([this]() {
  235. AbortSpeaking(kAbortReasonNone);
  236. });
  237. } else if (device_state_ == kDeviceStateListening) {
  238. Schedule([this]() {
  239. protocol_->CloseAudioChannel();
  240. });
  241. }
  242. }
  243. void Application::StartListening() {
  244. if (device_state_ == kDeviceStateActivating) {
  245. SetDeviceState(kDeviceStateIdle);
  246. return;
  247. }
  248. if (!protocol_) {
  249. ESP_LOGE(TAG, "Protocol not initialized");
  250. return;
  251. }
  252. keep_listening_ = false;
  253. if (device_state_ == kDeviceStateIdle) {
  254. Schedule([this]() {
  255. if (!protocol_->IsAudioChannelOpened()) {
  256. SetDeviceState(kDeviceStateConnecting);
  257. if (!protocol_->OpenAudioChannel()) {
  258. return;
  259. }
  260. }
  261. protocol_->SendStartListening(kListeningModeManualStop);
  262. SetDeviceState(kDeviceStateListening);
  263. });
  264. } else if (device_state_ == kDeviceStateSpeaking) {
  265. Schedule([this]() {
  266. AbortSpeaking(kAbortReasonNone);
  267. protocol_->SendStartListening(kListeningModeManualStop);
  268. SetDeviceState(kDeviceStateListening);
  269. });
  270. }
  271. }
  272. void Application::StopListening() {
  273. Schedule([this]() {
  274. if (device_state_ == kDeviceStateListening) {
  275. protocol_->SendStopListening();
  276. SetDeviceState(kDeviceStateIdle);
  277. }
  278. });
  279. }
  280. void Application::Start() {
  281. auto& board = Board::GetInstance();
  282. SetDeviceState(kDeviceStateStarting);
  283. auto display = board.GetDisplay();
  284. /* Setup the audio codec */
  285. auto codec = board.GetAudioCodec();
  286. opus_decode_sample_rate_ = codec->output_sample_rate();
  287. opus_decoder_ = std::make_unique<OpusDecoderWrapper>(opus_decode_sample_rate_, 1);
  288. opus_encoder_ = std::make_unique<OpusEncoderWrapper>(16000, 1, OPUS_FRAME_DURATION_MS);
  289. // For ML307 boards, we use complexity 5 to save bandwidth
  290. // For other boards, we use complexity 3 to save CPU
  291. if (board.GetBoardType() == "ml307") {
  292. ESP_LOGI(TAG, "ML307 board detected, setting opus encoder complexity to 5");
  293. opus_encoder_->SetComplexity(5);
  294. } else {
  295. ESP_LOGI(TAG, "WiFi board detected, setting opus encoder complexity to 3");
  296. opus_encoder_->SetComplexity(3);
  297. }
  298. if (codec->input_sample_rate() != 16000) {
  299. input_resampler_.Configure(codec->input_sample_rate(), 16000);
  300. reference_resampler_.Configure(codec->input_sample_rate(), 16000);
  301. }
  302. codec->OnInputReady([this, codec]() {
  303. BaseType_t higher_priority_task_woken = pdFALSE;
  304. xEventGroupSetBitsFromISR(event_group_, AUDIO_INPUT_READY_EVENT, &higher_priority_task_woken);
  305. return higher_priority_task_woken == pdTRUE;
  306. });
  307. codec->OnOutputReady([this]() {
  308. BaseType_t higher_priority_task_woken = pdFALSE;
  309. xEventGroupSetBitsFromISR(event_group_, AUDIO_OUTPUT_READY_EVENT, &higher_priority_task_woken);
  310. return higher_priority_task_woken == pdTRUE;
  311. });
  312. codec->Start();
  313. /* Start the main loop */
  314. xTaskCreate([](void* arg) {
  315. Application* app = (Application*)arg;
  316. app->MainLoop();
  317. vTaskDelete(NULL);
  318. }, "main_loop", 4096 * 2, this, 4, nullptr);
  319. /* Wait for the network to be ready */
  320. board.StartNetwork();
  321. // Initialize the protocol
  322. display->SetStatus(Lang::Strings::LOADING_PROTOCOL);
  323. #ifdef CONFIG_CONNECTION_TYPE_WEBSOCKET
  324. protocol_ = std::make_unique<WebsocketProtocol>();
  325. #else
  326. protocol_ = std::make_unique<MqttProtocol>();
  327. #endif
  328. protocol_->OnNetworkError([this](const std::string& message) {
  329. SetDeviceState(kDeviceStateIdle);
  330. Alert(Lang::Strings::ERROR, message.c_str(), "sad", Lang::Sounds::P3_EXCLAMATION);
  331. });
  332. protocol_->OnIncomingAudio([this](std::vector<uint8_t>&& data) {
  333. std::lock_guard<std::mutex> lock(mutex_);
  334. if (device_state_ == kDeviceStateSpeaking) {
  335. audio_decode_queue_.emplace_back(std::move(data));
  336. }
  337. });
  338. protocol_->OnAudioChannelOpened([this, codec, &board]() {
  339. board.SetPowerSaveMode(false);
  340. if (protocol_->server_sample_rate() != codec->output_sample_rate()) {
  341. ESP_LOGW(TAG, "Server sample rate %d does not match device output sample rate %d, resampling may cause distortion",
  342. protocol_->server_sample_rate(), codec->output_sample_rate());
  343. }
  344. SetDecodeSampleRate(protocol_->server_sample_rate());
  345. auto& thing_manager = iot::ThingManager::GetInstance();
  346. protocol_->SendIotDescriptors(thing_manager.GetDescriptorsJson());
  347. std::string states;
  348. if (thing_manager.GetStatesJson(states, false)) {
  349. protocol_->SendIotStates(states);
  350. }
  351. });
  352. protocol_->OnAudioChannelClosed([this, &board]() {
  353. board.SetPowerSaveMode(true);
  354. Schedule([this]() {
  355. auto display = Board::GetInstance().GetDisplay();
  356. display->SetChatMessage("system", "");
  357. SetDeviceState(kDeviceStateIdle);
  358. });
  359. });
  360. protocol_->OnIncomingJson([this, display](const cJSON* root) {
  361. // Parse JSON data
  362. auto type = cJSON_GetObjectItem(root, "type");
  363. if (strcmp(type->valuestring, "tts") == 0) {
  364. auto state = cJSON_GetObjectItem(root, "state");
  365. if (strcmp(state->valuestring, "start") == 0) {
  366. Schedule([this]() {
  367. aborted_ = false;
  368. if (device_state_ == kDeviceStateIdle || device_state_ == kDeviceStateListening) {
  369. SetDeviceState(kDeviceStateSpeaking);
  370. }
  371. });
  372. } else if (strcmp(state->valuestring, "stop") == 0) {
  373. Schedule([this]() {
  374. if (device_state_ == kDeviceStateSpeaking) {
  375. background_task_->WaitForCompletion();
  376. if (keep_listening_) {
  377. protocol_->SendStartListening(kListeningModeAutoStop);
  378. SetDeviceState(kDeviceStateListening);
  379. } else {
  380. SetDeviceState(kDeviceStateIdle);
  381. }
  382. }
  383. });
  384. } else if (strcmp(state->valuestring, "sentence_start") == 0) {
  385. auto text = cJSON_GetObjectItem(root, "text");
  386. if (text != NULL) {
  387. ESP_LOGI(TAG, "<< %s", text->valuestring);
  388. std::string message = text->valuestring;
  389. if (message != last_displayed_message_) {
  390. last_displayed_message_ = message; // 更新上一次显示的消息
  391. display->SetChatMessage("assistant", message.c_str());
  392. }
  393. }
  394. }
  395. } else if (strcmp(type->valuestring, "stt") == 0) {
  396. auto text = cJSON_GetObjectItem(root, "text");
  397. if (text != NULL) {
  398. ESP_LOGI(TAG, ">> %s", text->valuestring);
  399. Schedule([this, display, message = std::string(text->valuestring)]() {
  400. display->SetChatMessage("user", message.c_str());
  401. });
  402. }
  403. } else if (strcmp(type->valuestring, "llm") == 0) {
  404. auto emotion = cJSON_GetObjectItem(root, "emotion");
  405. if (emotion != NULL) {
  406. Schedule([this, display, emotion_str = std::string(emotion->valuestring)]() {
  407. display->SetEmotion(emotion_str.c_str());
  408. });
  409. }
  410. } else if (strcmp(type->valuestring, "iot") == 0) {
  411. auto commands = cJSON_GetObjectItem(root, "commands");
  412. if (commands != NULL) {
  413. auto& thing_manager = iot::ThingManager::GetInstance();
  414. for (int i = 0; i < cJSON_GetArraySize(commands); ++i) {
  415. auto command = cJSON_GetArrayItem(commands, i);
  416. thing_manager.Invoke(command);
  417. }
  418. }
  419. }
  420. });
  421. protocol_->Start();
  422. codec->SetOutputVolume(90);
  423. // Check for new firmware version or get the MQTT broker address
  424. ota_.SetCheckVersionUrl(CONFIG_OTA_VERSION_URL);
  425. ota_.SetHeader("Device-Id", SystemInfo::GetMacAddress().c_str());
  426. ota_.SetHeader("Client-Id", board.GetUuid());
  427. ota_.SetHeader("Accept-Language", Lang::CODE);
  428. auto app_desc = esp_app_get_description();
  429. ota_.SetHeader("User-Agent", std::string(BOARD_NAME "/") + app_desc->version);
  430. xTaskCreate([](void* arg) {
  431. Application* app = (Application*)arg;
  432. app->CheckNewVersion();
  433. vTaskDelete(NULL); //这个意思是任务完成之后自动删除自身
  434. }, "check_new_version", 4096 * 2, this, 2, nullptr);
  435. #if CONFIG_USE_AUDIO_PROCESSOR
  436. audio_processor_.Initialize(codec->input_channels(), codec->input_reference());
  437. audio_processor_.OnOutput([this](std::vector<int16_t>&& data) {
  438. background_task_->Schedule([this, data = std::move(data)]() mutable {
  439. opus_encoder_->Encode(std::move(data), [this](std::vector<uint8_t>&& opus) {
  440. Schedule([this, opus = std::move(opus)]() {
  441. protocol_->SendAudio(opus);
  442. });
  443. });
  444. });
  445. });
  446. audio_processor_.OnVadStateChange([this](bool speaking) {
  447. if (device_state_ == kDeviceStateListening) {
  448. Schedule([this, speaking]() {
  449. if (speaking) {
  450. voice_detected_ = true;
  451. } else {
  452. voice_detected_ = false;
  453. }
  454. auto led = Board::GetInstance().GetLed();
  455. led->OnStateChanged();
  456. });
  457. }
  458. });
  459. #endif
  460. #if CONFIG_USE_WAKE_WORD_DETECT
  461. wake_word_detect_.Initialize(codec->input_channels(), codec->input_reference());
  462. wake_word_detect_.OnWakeWordDetected([this](const std::string& wake_word) {
  463. Schedule([this, &wake_word]() {
  464. if (device_state_ == kDeviceStateIdle) {
  465. SetDeviceState(kDeviceStateConnecting);
  466. wake_word_detect_.EncodeWakeWordData();
  467. if (!protocol_->OpenAudioChannel()) {
  468. wake_word_detect_.StartDetection();
  469. return;
  470. }
  471. std::vector<uint8_t> opus;
  472. // Encode and send the wake word data to the server
  473. while (wake_word_detect_.GetWakeWordOpus(opus)) {
  474. protocol_->SendAudio(opus);
  475. }
  476. // Set the chat state to wake word detected
  477. protocol_->SendWakeWordDetected(wake_word);
  478. ESP_LOGI(TAG, "Wake word detected: %s", wake_word.c_str());
  479. keep_listening_ = true;
  480. SetDeviceState(kDeviceStateIdle);
  481. } else if (device_state_ == kDeviceStateSpeaking) {
  482. AbortSpeaking(kAbortReasonWakeWordDetected);
  483. } else if (device_state_ == kDeviceStateActivating) {
  484. SetDeviceState(kDeviceStateIdle);
  485. }
  486. });
  487. });
  488. wake_word_detect_.StartDetection();
  489. #endif
  490. SetDeviceState(kDeviceStateIdle);
  491. esp_timer_start_periodic(clock_timer_handle_, 1000000);
  492. }
  493. void Application::OnClockTimer() {
  494. vTaskPrioritySet(NULL, 1);
  495. clock_ticks_++;
  496. // Print the debug info every 10 seconds
  497. if (clock_ticks_ % 10 == 0) {
  498. // SystemInfo::PrintTaskList();
  499. // SystemInfo::PrintRealTimeStats(pdMS_TO_TICKS(1000));
  500. int free_sram = heap_caps_get_free_size(MALLOC_CAP_INTERNAL);
  501. int min_free_sram = heap_caps_get_minimum_free_size(MALLOC_CAP_INTERNAL);
  502. ESP_LOGI(TAG, "Free internal: %u minimal internal: %u", free_sram, min_free_sram);
  503. // If we have synchronized server time, set the status to clock "HH:MM" if the device is idle
  504. if (ota_.HasServerTime()) {
  505. if (device_state_ == kDeviceStateIdle) {
  506. Schedule([this]() {
  507. // Set status to clock "HH:MM"
  508. time_t now = time(NULL);
  509. char time_str[64];
  510. strftime(time_str, sizeof(time_str), "%H:%M ", localtime(&now));
  511. const char* TestShow = "邗江区民政服务小助手";
  512. Board::GetInstance().GetDisplay()->SetStatus(TestShow);
  513. });
  514. }
  515. }
  516. }
  517. }
  518. void Application::Schedule(std::function<void()> callback) {
  519. {
  520. std::lock_guard<std::mutex> lock(mutex_);
  521. main_tasks_.push_back(std::move(callback));
  522. }
  523. xEventGroupSetBits(event_group_, SCHEDULE_EVENT);
  524. }
  525. // The Main Loop controls the chat state and websocket connection
  526. // If other tasks need to access the websocket or chat state,
  527. // they should use Schedule to call this function
  528. void Application::MainLoop() {
  529. while (true) {
  530. auto bits = xEventGroupWaitBits(event_group_,
  531. SCHEDULE_EVENT | AUDIO_INPUT_READY_EVENT | AUDIO_OUTPUT_READY_EVENT,
  532. pdTRUE, pdFALSE, portMAX_DELAY);
  533. if (bits & AUDIO_INPUT_READY_EVENT) {
  534. InputAudio();
  535. }
  536. if (bits & AUDIO_OUTPUT_READY_EVENT) {
  537. OutputAudio();
  538. }
  539. if (bits & SCHEDULE_EVENT) {
  540. std::unique_lock<std::mutex> lock(mutex_);
  541. std::list<std::function<void()>> tasks = std::move(main_tasks_);
  542. lock.unlock();
  543. for (auto& task : tasks) {
  544. task();
  545. }
  546. }
  547. }
  548. }
  549. void Application::ResetDecoder() {
  550. std::lock_guard<std::mutex> lock(mutex_);
  551. opus_decoder_->ResetState();
  552. audio_decode_queue_.clear();
  553. last_output_time_ = std::chrono::steady_clock::now();
  554. }
  555. void Application::OutputAudio() {
  556. auto now = std::chrono::steady_clock::now();
  557. auto codec = Board::GetInstance().GetAudioCodec();
  558. const int max_silence_seconds = 10;
  559. std::unique_lock<std::mutex> lock(mutex_);
  560. if (audio_decode_queue_.empty()) {
  561. // Disable the output if there is no audio data for a long time
  562. if (device_state_ == kDeviceStateIdle) {
  563. auto duration = std::chrono::duration_cast<std::chrono::seconds>(now - last_output_time_).count();
  564. if (duration > max_silence_seconds) {
  565. codec->EnableOutput(false);
  566. }
  567. }
  568. return;
  569. }
  570. if (device_state_ == kDeviceStateListening) {
  571. audio_decode_queue_.clear();
  572. return;
  573. }
  574. last_output_time_ = now;
  575. auto opus = std::move(audio_decode_queue_.front());
  576. audio_decode_queue_.pop_front();
  577. lock.unlock();
  578. background_task_->Schedule([this, codec, opus = std::move(opus)]() mutable {
  579. if (aborted_) {
  580. return;
  581. }
  582. std::vector<int16_t> pcm;
  583. if (!opus_decoder_->Decode(std::move(opus), pcm)) {
  584. return;
  585. }
  586. // Resample if the sample rate is different
  587. if (opus_decode_sample_rate_ != codec->output_sample_rate()) {
  588. int target_size = output_resampler_.GetOutputSamples(pcm.size());
  589. std::vector<int16_t> resampled(target_size);
  590. output_resampler_.Process(pcm.data(), pcm.size(), resampled.data());
  591. pcm = std::move(resampled);
  592. }
  593. codec->OutputData(pcm);
  594. });
  595. }
  596. void Application::InputAudio() {
  597. auto codec = Board::GetInstance().GetAudioCodec();
  598. std::vector<int16_t> data;
  599. if (!codec->InputData(data)) {
  600. return;
  601. }
  602. if (codec->input_sample_rate() != 16000) {
  603. if (codec->input_channels() == 2) {
  604. auto mic_channel = std::vector<int16_t>(data.size() / 2);
  605. auto reference_channel = std::vector<int16_t>(data.size() / 2);
  606. for (size_t i = 0, j = 0; i < mic_channel.size(); ++i, j += 2) {
  607. mic_channel[i] = data[j];
  608. reference_channel[i] = data[j + 1];
  609. }
  610. auto resampled_mic = std::vector<int16_t>(input_resampler_.GetOutputSamples(mic_channel.size()));
  611. auto resampled_reference = std::vector<int16_t>(reference_resampler_.GetOutputSamples(reference_channel.size()));
  612. input_resampler_.Process(mic_channel.data(), mic_channel.size(), resampled_mic.data());
  613. reference_resampler_.Process(reference_channel.data(), reference_channel.size(), resampled_reference.data());
  614. data.resize(resampled_mic.size() + resampled_reference.size());
  615. for (size_t i = 0, j = 0; i < resampled_mic.size(); ++i, j += 2) {
  616. data[j] = resampled_mic[i];
  617. data[j + 1] = resampled_reference[i];
  618. }
  619. } else {
  620. auto resampled = std::vector<int16_t>(input_resampler_.GetOutputSamples(data.size()));
  621. input_resampler_.Process(data.data(), data.size(), resampled.data());
  622. data = std::move(resampled);
  623. }
  624. }
  625. #if CONFIG_USE_WAKE_WORD_DETECT
  626. if (wake_word_detect_.IsDetectionRunning()) {
  627. wake_word_detect_.Feed(data);
  628. }
  629. #endif
  630. #if CONFIG_USE_AUDIO_PROCESSOR
  631. if (audio_processor_.IsRunning()) {
  632. audio_processor_.Input(data);
  633. }
  634. #else
  635. if (device_state_ == kDeviceStateListening) {
  636. background_task_->Schedule([this, data = std::move(data)]() mutable {
  637. opus_encoder_->Encode(std::move(data), [this](std::vector<uint8_t>&& opus) {
  638. Schedule([this, opus = std::move(opus)]() {
  639. protocol_->SendAudio(opus);
  640. });
  641. });
  642. });
  643. }
  644. #endif
  645. }
  646. void Application::AbortSpeaking(AbortReason reason) {
  647. ESP_LOGI(TAG, "Abort speaking");
  648. aborted_ = true;
  649. protocol_->SendAbortSpeaking(reason);
  650. }
  651. void Application::SetDeviceState(DeviceState state) {
  652. if (device_state_ == state) {
  653. return;
  654. }
  655. clock_ticks_ = 0;
  656. auto previous_state = device_state_;
  657. device_state_ = state;
  658. ESP_LOGI(TAG, "STATE: %s", STATE_STRINGS[device_state_]);
  659. // The state is changed, wait for all background tasks to finish
  660. background_task_->WaitForCompletion();
  661. auto& board = Board::GetInstance();
  662. auto codec = board.GetAudioCodec();
  663. auto display = board.GetDisplay();
  664. auto led = board.GetLed();
  665. led->OnStateChanged();
  666. switch (state) {
  667. case kDeviceStateUnknown:
  668. case kDeviceStateIdle:
  669. display->SetStatus(Lang::Strings::STANDBY);
  670. display->SetEmotion("neutral");
  671. #if CONFIG_USE_AUDIO_PROCESSOR
  672. audio_processor_.Stop();
  673. #endif
  674. #if CONFIG_USE_WAKE_WORD_DETECT
  675. wake_word_detect_.StartDetection();
  676. #endif
  677. break;
  678. case kDeviceStateConnecting:
  679. display->SetStatus(Lang::Strings::CONNECTING);
  680. display->SetEmotion("neutral");
  681. display->SetChatMessage("system", "");
  682. break;
  683. case kDeviceStateListening:
  684. display->SetStatus(Lang::Strings::LISTENING);
  685. display->SetEmotion("neutral");
  686. ResetDecoder();
  687. opus_encoder_->ResetState();
  688. #if CONFIG_USE_AUDIO_PROCESSOR
  689. audio_processor_.Start();
  690. #endif
  691. #if CONFIG_USE_WAKE_WORD_DETECT
  692. wake_word_detect_.StopDetection();
  693. #endif
  694. UpdateIotStates();
  695. if (previous_state == kDeviceStateSpeaking) {
  696. // FIXME: Wait for the speaker to empty the buffer
  697. vTaskDelay(pdMS_TO_TICKS(120));
  698. }
  699. break;
  700. case kDeviceStateSpeaking:
  701. display->SetStatus(Lang::Strings::SPEAKING);
  702. ResetDecoder();
  703. codec->EnableOutput(true);
  704. #if CONFIG_USE_AUDIO_PROCESSOR
  705. audio_processor_.Stop();
  706. #endif
  707. #if CONFIG_USE_WAKE_WORD_DETECT
  708. wake_word_detect_.StartDetection();
  709. #endif
  710. break;
  711. default:
  712. // Do nothing
  713. break;
  714. }
  715. }
  716. void Application::SetDecodeSampleRate(int sample_rate) {
  717. if (opus_decode_sample_rate_ == sample_rate) {
  718. return;
  719. }
  720. opus_decode_sample_rate_ = sample_rate;
  721. opus_decoder_.reset();
  722. opus_decoder_ = std::make_unique<OpusDecoderWrapper>(opus_decode_sample_rate_, 1);
  723. auto codec = Board::GetInstance().GetAudioCodec();
  724. if (opus_decode_sample_rate_ != codec->output_sample_rate()) {
  725. ESP_LOGI(TAG, "Resampling audio from %d to %d", opus_decode_sample_rate_, codec->output_sample_rate());
  726. output_resampler_.Configure(opus_decode_sample_rate_, codec->output_sample_rate());
  727. }
  728. }
  729. void Application::UpdateIotStates() {
  730. auto& thing_manager = iot::ThingManager::GetInstance();
  731. std::string states;
  732. if (thing_manager.GetStatesJson(states, true)) {
  733. protocol_->SendIotStates(states);
  734. }
  735. }
  736. void Application::Reboot() {
  737. ESP_LOGI(TAG, "Rebooting...");
  738. esp_restart();
  739. }
  740. void Application::WakeWordInvoke(const std::string& wake_word) {
  741. if (device_state_ == kDeviceStateIdle) {
  742. ToggleChatState();
  743. Schedule([this, wake_word]() {
  744. if (protocol_) {
  745. protocol_->SendWakeWordDetected(wake_word);
  746. }
  747. });
  748. } else if (device_state_ == kDeviceStateSpeaking) {
  749. Schedule([this]() {
  750. AbortSpeaking(kAbortReasonNone);
  751. });
  752. } else if (device_state_ == kDeviceStateListening) {
  753. Schedule([this]() {
  754. if (protocol_) {
  755. protocol_->CloseAudioChannel();
  756. }
  757. });
  758. }
  759. }
  760. bool Application::CanEnterSleepMode() {
  761. if (device_state_ != kDeviceStateIdle) {
  762. return false;
  763. }
  764. if (protocol_ && protocol_->IsAudioChannelOpened()) {
  765. return false;
  766. }
  767. // Now it is safe to enter sleep mode
  768. return true;
  769. }