application.cc 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861
  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. // 创建GPIO5中断处理器实例并初始化,暂时不用
  284. // static Gpio5InterruptHandler gpio5_handler;
  285. // if (gpio5_handler.init() != ESP_OK) {
  286. // ESP_LOGE("main", "GPIO5 interrupt initialization failed");
  287. // return;
  288. // }
  289. /* Setup the display */
  290. auto display = board.GetDisplay();
  291. /* Setup the audio codec */
  292. auto codec = board.GetAudioCodec();
  293. opus_decode_sample_rate_ = codec->output_sample_rate();
  294. opus_decoder_ = std::make_unique<OpusDecoderWrapper>(opus_decode_sample_rate_, 1);
  295. opus_encoder_ = std::make_unique<OpusEncoderWrapper>(16000, 1, OPUS_FRAME_DURATION_MS);
  296. // For ML307 boards, we use complexity 5 to save bandwidth
  297. // For other boards, we use complexity 3 to save CPU
  298. if (board.GetBoardType() == "ml307") {
  299. ESP_LOGI(TAG, "ML307 board detected, setting opus encoder complexity to 5");
  300. opus_encoder_->SetComplexity(5);
  301. } else {
  302. ESP_LOGI(TAG, "WiFi board detected, setting opus encoder complexity to 3");
  303. opus_encoder_->SetComplexity(3);
  304. }
  305. if (codec->input_sample_rate() != 16000) {
  306. input_resampler_.Configure(codec->input_sample_rate(), 16000);
  307. reference_resampler_.Configure(codec->input_sample_rate(), 16000);
  308. }
  309. codec->OnInputReady([this, codec]() {
  310. BaseType_t higher_priority_task_woken = pdFALSE;
  311. xEventGroupSetBitsFromISR(event_group_, AUDIO_INPUT_READY_EVENT, &higher_priority_task_woken);
  312. return higher_priority_task_woken == pdTRUE;
  313. });
  314. codec->OnOutputReady([this]() {
  315. BaseType_t higher_priority_task_woken = pdFALSE;
  316. xEventGroupSetBitsFromISR(event_group_, AUDIO_OUTPUT_READY_EVENT, &higher_priority_task_woken);
  317. return higher_priority_task_woken == pdTRUE;
  318. });
  319. codec->Start();
  320. /* Start the main loop */
  321. xTaskCreate([](void* arg) {
  322. Application* app = (Application*)arg;
  323. app->MainLoop();
  324. vTaskDelete(NULL);
  325. }, "main_loop", 4096 * 2, this, 4, nullptr);
  326. /* Wait for the network to be ready */
  327. board.StartNetwork();
  328. // Initialize the protocol
  329. display->SetStatus(Lang::Strings::LOADING_PROTOCOL);
  330. #ifdef CONFIG_CONNECTION_TYPE_WEBSOCKET
  331. protocol_ = std::make_unique<WebsocketProtocol>();
  332. #else
  333. protocol_ = std::make_unique<MqttProtocol>();
  334. #endif
  335. protocol_->OnNetworkError([this](const std::string& message) {
  336. SetDeviceState(kDeviceStateIdle);
  337. Alert(Lang::Strings::ERROR, message.c_str(), "sad", Lang::Sounds::P3_EXCLAMATION);
  338. });
  339. protocol_->OnIncomingAudio([this](std::vector<uint8_t>&& data) {
  340. std::lock_guard<std::mutex> lock(mutex_);
  341. if (device_state_ == kDeviceStateSpeaking) {
  342. audio_decode_queue_.emplace_back(std::move(data));
  343. }
  344. });
  345. protocol_->OnAudioChannelOpened([this, codec, &board]() {
  346. board.SetPowerSaveMode(false);
  347. if (protocol_->server_sample_rate() != codec->output_sample_rate()) {
  348. ESP_LOGW(TAG, "Server sample rate %d does not match device output sample rate %d, resampling may cause distortion",
  349. protocol_->server_sample_rate(), codec->output_sample_rate());
  350. }
  351. SetDecodeSampleRate(protocol_->server_sample_rate());
  352. auto& thing_manager = iot::ThingManager::GetInstance();
  353. protocol_->SendIotDescriptors(thing_manager.GetDescriptorsJson());
  354. std::string states;
  355. if (thing_manager.GetStatesJson(states, false)) {
  356. protocol_->SendIotStates(states);
  357. }
  358. });
  359. protocol_->OnAudioChannelClosed([this, &board]() {
  360. board.SetPowerSaveMode(true);
  361. Schedule([this]() {
  362. auto display = Board::GetInstance().GetDisplay();
  363. display->SetChatMessage("system", "");
  364. SetDeviceState(kDeviceStateIdle);
  365. });
  366. });
  367. protocol_->OnIncomingJson([this, display](const cJSON* root) {
  368. // Parse JSON data
  369. auto type = cJSON_GetObjectItem(root, "type");
  370. if (strcmp(type->valuestring, "tts") == 0) {
  371. auto state = cJSON_GetObjectItem(root, "state");
  372. if (strcmp(state->valuestring, "start") == 0) {
  373. Schedule([this]() {
  374. aborted_ = false;
  375. if (device_state_ == kDeviceStateIdle || device_state_ == kDeviceStateListening) {
  376. SetDeviceState(kDeviceStateSpeaking);
  377. }
  378. });
  379. } else if (strcmp(state->valuestring, "stop") == 0) {
  380. Schedule([this]() {
  381. if (device_state_ == kDeviceStateSpeaking) {
  382. background_task_->WaitForCompletion();
  383. if (keep_listening_) {
  384. protocol_->SendStartListening(kListeningModeAutoStop);
  385. SetDeviceState(kDeviceStateListening);
  386. } else {
  387. SetDeviceState(kDeviceStateIdle);
  388. }
  389. }
  390. });
  391. } else if (strcmp(state->valuestring, "sentence_start") == 0) {
  392. auto text = cJSON_GetObjectItem(root, "text");
  393. if (text != NULL) {
  394. ESP_LOGI(TAG, "<< %s", text->valuestring);
  395. std::string message = text->valuestring;
  396. if (message != last_displayed_message_) {
  397. last_displayed_message_ = message; // 更新上一次显示的消息
  398. display->SetChatMessage("assistant", message.c_str());
  399. }
  400. }
  401. }
  402. } else if (strcmp(type->valuestring, "stt") == 0) {
  403. auto text = cJSON_GetObjectItem(root, "text");
  404. if (text != NULL) {
  405. ESP_LOGI(TAG, ">> %s", text->valuestring);
  406. Schedule([this, display, message = std::string(text->valuestring)]() {
  407. display->SetChatMessage("user", message.c_str());
  408. });
  409. }
  410. } else if (strcmp(type->valuestring, "llm") == 0) {
  411. auto emotion = cJSON_GetObjectItem(root, "emotion");
  412. if (emotion != NULL) {
  413. Schedule([this, display, emotion_str = std::string(emotion->valuestring)]() {
  414. display->SetEmotion(emotion_str.c_str());
  415. });
  416. }
  417. } else if (strcmp(type->valuestring, "iot") == 0) {
  418. auto commands = cJSON_GetObjectItem(root, "commands");
  419. if (commands != NULL) {
  420. auto& thing_manager = iot::ThingManager::GetInstance();
  421. for (int i = 0; i < cJSON_GetArraySize(commands); ++i) {
  422. auto command = cJSON_GetArrayItem(commands, i);
  423. thing_manager.Invoke(command);
  424. }
  425. }
  426. }
  427. });
  428. protocol_->Start();
  429. codec->SetOutputVolume(90);
  430. // Check for new firmware version or get the MQTT broker address
  431. ota_.SetCheckVersionUrl(CONFIG_OTA_VERSION_URL);
  432. ota_.SetHeader("Device-Id", SystemInfo::GetMacAddress().c_str());
  433. ota_.SetHeader("Client-Id", board.GetUuid());
  434. ota_.SetHeader("Accept-Language", Lang::CODE);
  435. auto app_desc = esp_app_get_description();
  436. ota_.SetHeader("User-Agent", std::string(BOARD_NAME "/") + app_desc->version);
  437. xTaskCreate([](void* arg) {
  438. Application* app = (Application*)arg;
  439. app->CheckNewVersion();
  440. vTaskDelete(NULL); //这个意思是任务完成之后自动删除自身
  441. }, "check_new_version", 4096 * 2, this, 2, nullptr);
  442. #if CONFIG_USE_AUDIO_PROCESSOR
  443. audio_processor_.Initialize(codec->input_channels(), codec->input_reference());
  444. audio_processor_.OnOutput([this](std::vector<int16_t>&& data) {
  445. background_task_->Schedule([this, data = std::move(data)]() mutable {
  446. opus_encoder_->Encode(std::move(data), [this](std::vector<uint8_t>&& opus) {
  447. Schedule([this, opus = std::move(opus)]() {
  448. protocol_->SendAudio(opus);
  449. });
  450. });
  451. });
  452. });
  453. audio_processor_.OnVadStateChange([this](bool speaking) {
  454. if (device_state_ == kDeviceStateListening) {
  455. Schedule([this, speaking]() {
  456. if (speaking) {
  457. voice_detected_ = true;
  458. } else {
  459. voice_detected_ = false;
  460. }
  461. auto led = Board::GetInstance().GetLed();
  462. led->OnStateChanged();
  463. });
  464. }
  465. });
  466. #endif
  467. #if CONFIG_USE_WAKE_WORD_DETECT
  468. wake_word_detect_.Initialize(codec->input_channels(), codec->input_reference());
  469. wake_word_detect_.OnWakeWordDetected([this](const std::string& wake_word) {
  470. Schedule([this, &wake_word]() {
  471. if (device_state_ == kDeviceStateIdle) {
  472. SetDeviceState(kDeviceStateConnecting);
  473. wake_word_detect_.EncodeWakeWordData();
  474. if (!protocol_->OpenAudioChannel()) {
  475. wake_word_detect_.StartDetection();
  476. return;
  477. }
  478. std::vector<uint8_t> opus;
  479. // Encode and send the wake word data to the server
  480. while (wake_word_detect_.GetWakeWordOpus(opus)) {
  481. protocol_->SendAudio(opus);
  482. }
  483. // Set the chat state to wake word detected
  484. protocol_->SendWakeWordDetected(wake_word);
  485. ESP_LOGI(TAG, "Wake word detected: %s", wake_word.c_str());
  486. keep_listening_ = true;
  487. SetDeviceState(kDeviceStateIdle);
  488. } else if (device_state_ == kDeviceStateSpeaking) {
  489. AbortSpeaking(kAbortReasonWakeWordDetected);
  490. } else if (device_state_ == kDeviceStateActivating) {
  491. SetDeviceState(kDeviceStateIdle);
  492. }
  493. });
  494. });
  495. wake_word_detect_.StartDetection();
  496. #endif
  497. SetDeviceState(kDeviceStateIdle);
  498. esp_timer_start_periodic(clock_timer_handle_, 1000000);
  499. }
  500. void Application::OnClockTimer() {
  501. vTaskPrioritySet(NULL, 1);
  502. clock_ticks_++;
  503. // Print the debug info every 10 seconds
  504. if (clock_ticks_ % 10 == 0) {
  505. // SystemInfo::PrintTaskList();
  506. // SystemInfo::PrintRealTimeStats(pdMS_TO_TICKS(1000));
  507. int free_sram = heap_caps_get_free_size(MALLOC_CAP_INTERNAL);
  508. int min_free_sram = heap_caps_get_minimum_free_size(MALLOC_CAP_INTERNAL);
  509. ESP_LOGI(TAG, "Free internal: %u minimal internal: %u", free_sram, min_free_sram);
  510. // If we have synchronized server time, set the status to clock "HH:MM" if the device is idle
  511. if (ota_.HasServerTime()) {
  512. if (device_state_ == kDeviceStateIdle) {
  513. Schedule([this]() {
  514. // Set status to clock "HH:MM"
  515. time_t now = time(NULL);
  516. char time_str[64];
  517. strftime(time_str, sizeof(time_str), "%H:%M ", localtime(&now));
  518. const char* TestShow = "邗江区民政服务小助手";
  519. Board::GetInstance().GetDisplay()->SetStatus(TestShow);
  520. });
  521. }
  522. }
  523. }
  524. }
  525. void Application::Schedule(std::function<void()> callback) {
  526. {
  527. std::lock_guard<std::mutex> lock(mutex_);
  528. main_tasks_.push_back(std::move(callback));
  529. }
  530. xEventGroupSetBits(event_group_, SCHEDULE_EVENT);
  531. }
  532. // The Main Loop controls the chat state and websocket connection
  533. // If other tasks need to access the websocket or chat state,
  534. // they should use Schedule to call this function
  535. void Application::MainLoop() {
  536. while (true) {
  537. auto bits = xEventGroupWaitBits(event_group_,
  538. SCHEDULE_EVENT | AUDIO_INPUT_READY_EVENT | AUDIO_OUTPUT_READY_EVENT,
  539. pdTRUE, pdFALSE, portMAX_DELAY);
  540. if (bits & AUDIO_INPUT_READY_EVENT) {
  541. InputAudio();
  542. }
  543. if (bits & AUDIO_OUTPUT_READY_EVENT) {
  544. OutputAudio();
  545. }
  546. if (bits & SCHEDULE_EVENT) {
  547. std::unique_lock<std::mutex> lock(mutex_);
  548. std::list<std::function<void()>> tasks = std::move(main_tasks_);
  549. lock.unlock();
  550. for (auto& task : tasks) {
  551. task();
  552. }
  553. }
  554. }
  555. }
  556. void Application::ResetDecoder() {
  557. std::lock_guard<std::mutex> lock(mutex_);
  558. opus_decoder_->ResetState();
  559. audio_decode_queue_.clear();
  560. last_output_time_ = std::chrono::steady_clock::now();
  561. }
  562. void Application::OutputAudio() {
  563. auto now = std::chrono::steady_clock::now();
  564. auto codec = Board::GetInstance().GetAudioCodec();
  565. const int max_silence_seconds = 10;
  566. std::unique_lock<std::mutex> lock(mutex_);
  567. if (audio_decode_queue_.empty()) {
  568. // Disable the output if there is no audio data for a long time
  569. if (device_state_ == kDeviceStateIdle) {
  570. auto duration = std::chrono::duration_cast<std::chrono::seconds>(now - last_output_time_).count();
  571. if (duration > max_silence_seconds) {
  572. codec->EnableOutput(false);
  573. }
  574. }
  575. return;
  576. }
  577. if (device_state_ == kDeviceStateListening) {
  578. audio_decode_queue_.clear();
  579. return;
  580. }
  581. last_output_time_ = now;
  582. auto opus = std::move(audio_decode_queue_.front());
  583. audio_decode_queue_.pop_front();
  584. lock.unlock();
  585. background_task_->Schedule([this, codec, opus = std::move(opus)]() mutable {
  586. if (aborted_) {
  587. return;
  588. }
  589. std::vector<int16_t> pcm;
  590. if (!opus_decoder_->Decode(std::move(opus), pcm)) {
  591. return;
  592. }
  593. // Resample if the sample rate is different
  594. if (opus_decode_sample_rate_ != codec->output_sample_rate()) {
  595. int target_size = output_resampler_.GetOutputSamples(pcm.size());
  596. std::vector<int16_t> resampled(target_size);
  597. output_resampler_.Process(pcm.data(), pcm.size(), resampled.data());
  598. pcm = std::move(resampled);
  599. }
  600. codec->OutputData(pcm);
  601. });
  602. }
  603. void Application::InputAudio() {
  604. auto codec = Board::GetInstance().GetAudioCodec();
  605. std::vector<int16_t> data;
  606. if (!codec->InputData(data)) {
  607. return;
  608. }
  609. if (codec->input_sample_rate() != 16000) {
  610. if (codec->input_channels() == 2) {
  611. auto mic_channel = std::vector<int16_t>(data.size() / 2);
  612. auto reference_channel = std::vector<int16_t>(data.size() / 2);
  613. for (size_t i = 0, j = 0; i < mic_channel.size(); ++i, j += 2) {
  614. mic_channel[i] = data[j];
  615. reference_channel[i] = data[j + 1];
  616. }
  617. auto resampled_mic = std::vector<int16_t>(input_resampler_.GetOutputSamples(mic_channel.size()));
  618. auto resampled_reference = std::vector<int16_t>(reference_resampler_.GetOutputSamples(reference_channel.size()));
  619. input_resampler_.Process(mic_channel.data(), mic_channel.size(), resampled_mic.data());
  620. reference_resampler_.Process(reference_channel.data(), reference_channel.size(), resampled_reference.data());
  621. data.resize(resampled_mic.size() + resampled_reference.size());
  622. for (size_t i = 0, j = 0; i < resampled_mic.size(); ++i, j += 2) {
  623. data[j] = resampled_mic[i];
  624. data[j + 1] = resampled_reference[i];
  625. }
  626. } else {
  627. auto resampled = std::vector<int16_t>(input_resampler_.GetOutputSamples(data.size()));
  628. input_resampler_.Process(data.data(), data.size(), resampled.data());
  629. data = std::move(resampled);
  630. }
  631. }
  632. #if CONFIG_USE_WAKE_WORD_DETECT
  633. if (wake_word_detect_.IsDetectionRunning()) {
  634. wake_word_detect_.Feed(data);
  635. }
  636. #endif
  637. #if CONFIG_USE_AUDIO_PROCESSOR
  638. if (audio_processor_.IsRunning()) {
  639. audio_processor_.Input(data);
  640. }
  641. #else
  642. if (device_state_ == kDeviceStateListening) {
  643. background_task_->Schedule([this, data = std::move(data)]() mutable {
  644. opus_encoder_->Encode(std::move(data), [this](std::vector<uint8_t>&& opus) {
  645. Schedule([this, opus = std::move(opus)]() {
  646. protocol_->SendAudio(opus);
  647. });
  648. });
  649. });
  650. }
  651. #endif
  652. }
  653. void Application::AbortSpeaking(AbortReason reason) {
  654. ESP_LOGI(TAG, "Abort speaking");
  655. aborted_ = true;
  656. protocol_->SendAbortSpeaking(reason);
  657. }
  658. void Application::SetDeviceState(DeviceState state) {
  659. if (device_state_ == state) {
  660. return;
  661. }
  662. clock_ticks_ = 0;
  663. auto previous_state = device_state_;
  664. device_state_ = state;
  665. ESP_LOGI(TAG, "STATE: %s", STATE_STRINGS[device_state_]);
  666. // The state is changed, wait for all background tasks to finish
  667. background_task_->WaitForCompletion();
  668. auto& board = Board::GetInstance();
  669. auto codec = board.GetAudioCodec();
  670. auto display = board.GetDisplay();
  671. auto led = board.GetLed();
  672. led->OnStateChanged();
  673. switch (state) {
  674. case kDeviceStateUnknown:
  675. case kDeviceStateIdle:
  676. display->SetStatus(Lang::Strings::STANDBY);
  677. display->SetEmotion("neutral");
  678. #if CONFIG_USE_AUDIO_PROCESSOR
  679. audio_processor_.Stop();
  680. #endif
  681. #if CONFIG_USE_WAKE_WORD_DETECT
  682. wake_word_detect_.StartDetection();
  683. #endif
  684. break;
  685. case kDeviceStateConnecting:
  686. display->SetStatus(Lang::Strings::CONNECTING);
  687. display->SetEmotion("neutral");
  688. display->SetChatMessage("system", "");
  689. break;
  690. case kDeviceStateListening:
  691. display->SetStatus(Lang::Strings::LISTENING);
  692. display->SetEmotion("neutral");
  693. ResetDecoder();
  694. opus_encoder_->ResetState();
  695. #if CONFIG_USE_AUDIO_PROCESSOR
  696. audio_processor_.Start();
  697. #endif
  698. #if CONFIG_USE_WAKE_WORD_DETECT
  699. wake_word_detect_.StopDetection();
  700. #endif
  701. UpdateIotStates();
  702. if (previous_state == kDeviceStateSpeaking) {
  703. // FIXME: Wait for the speaker to empty the buffer
  704. vTaskDelay(pdMS_TO_TICKS(120));
  705. }
  706. break;
  707. case kDeviceStateSpeaking:
  708. display->SetStatus(Lang::Strings::SPEAKING);
  709. ResetDecoder();
  710. codec->EnableOutput(true);
  711. #if CONFIG_USE_AUDIO_PROCESSOR
  712. audio_processor_.Stop();
  713. #endif
  714. #if CONFIG_USE_WAKE_WORD_DETECT
  715. wake_word_detect_.StartDetection();
  716. #endif
  717. break;
  718. default:
  719. // Do nothing
  720. break;
  721. }
  722. }
  723. void Application::SetDecodeSampleRate(int sample_rate) {
  724. if (opus_decode_sample_rate_ == sample_rate) {
  725. return;
  726. }
  727. opus_decode_sample_rate_ = sample_rate;
  728. opus_decoder_.reset();
  729. opus_decoder_ = std::make_unique<OpusDecoderWrapper>(opus_decode_sample_rate_, 1);
  730. auto codec = Board::GetInstance().GetAudioCodec();
  731. if (opus_decode_sample_rate_ != codec->output_sample_rate()) {
  732. ESP_LOGI(TAG, "Resampling audio from %d to %d", opus_decode_sample_rate_, codec->output_sample_rate());
  733. output_resampler_.Configure(opus_decode_sample_rate_, codec->output_sample_rate());
  734. }
  735. }
  736. void Application::UpdateIotStates() {
  737. auto& thing_manager = iot::ThingManager::GetInstance();
  738. std::string states;
  739. if (thing_manager.GetStatesJson(states, true)) {
  740. protocol_->SendIotStates(states);
  741. }
  742. }
  743. void Application::Reboot() {
  744. ESP_LOGI(TAG, "Rebooting...");
  745. esp_restart();
  746. }
  747. void Application::WakeWordInvoke(const std::string& wake_word) {
  748. if (device_state_ == kDeviceStateIdle) {
  749. ToggleChatState();
  750. Schedule([this, wake_word]() {
  751. if (protocol_) {
  752. protocol_->SendWakeWordDetected(wake_word);
  753. }
  754. });
  755. } else if (device_state_ == kDeviceStateSpeaking) {
  756. Schedule([this]() {
  757. AbortSpeaking(kAbortReasonNone);
  758. });
  759. } else if (device_state_ == kDeviceStateListening) {
  760. Schedule([this]() {
  761. if (protocol_) {
  762. protocol_->CloseAudioChannel();
  763. }
  764. });
  765. }
  766. }
  767. bool Application::CanEnterSleepMode() {
  768. if (device_state_ != kDeviceStateIdle) {
  769. return false;
  770. }
  771. if (protocol_ && protocol_->IsAudioChannelOpened()) {
  772. return false;
  773. }
  774. // Now it is safe to enter sleep mode
  775. return true;
  776. }