application.cc 30 KB

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