application.cc 30 KB

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