application.cc 32 KB

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