application.cc 33 KB

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