application.cc 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965
  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(80);
  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 , 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. // ESP_LOGI(TAG, "Stop 后的 Listening");
  436. // protocol_->SendStartListening(kListeningModeAutoStop);
  437. SetDeviceState(kDeviceStateListening);
  438. } else {
  439. SetDeviceState(kDeviceStateIdle);
  440. }
  441. }
  442. });
  443. } else if (strcmp(state->valuestring, "sentence_start") == 0) {
  444. auto text = cJSON_GetObjectItem(root, "text");
  445. if (text != NULL) {
  446. ESP_LOGI(TAG, "<< %s", text->valuestring);
  447. Schedule([this, display, message = std::string(text->valuestring)]() {
  448. display->SetChatMessage("assistant", message.c_str());
  449. });
  450. }
  451. }
  452. } else if (strcmp(type->valuestring, "stt") == 0) {
  453. auto text = cJSON_GetObjectItem(root, "text");
  454. if (text != NULL) {
  455. ESP_LOGI(TAG, ">> %s", text->valuestring);
  456. Schedule([this, display, message = std::string(text->valuestring)]() {
  457. display->SetChatMessage("user", message.c_str());
  458. });
  459. }
  460. } else if (strcmp(type->valuestring, "llm") == 0) {
  461. auto emotion = cJSON_GetObjectItem(root, "emotion");
  462. if (emotion != NULL) {
  463. Schedule([this, display, emotion_str = std::string(emotion->valuestring)]() {
  464. display->SetEmotion(emotion_str.c_str());
  465. });
  466. }
  467. } else if (strcmp(type->valuestring, "iot") == 0) {
  468. auto commands = cJSON_GetObjectItem(root, "commands");
  469. if (commands != NULL) {
  470. auto& thing_manager = iot::ThingManager::GetInstance();
  471. for (int i = 0; i < cJSON_GetArraySize(commands); ++i) {
  472. auto command = cJSON_GetArrayItem(commands, i);
  473. thing_manager.Invoke(command);
  474. }
  475. }
  476. }
  477. });
  478. protocol_->Start();
  479. // // Check for new firmware version or get the MQTT broker address
  480. // ota_.SetCheckVersionUrl(CONFIG_OTA_VERSION_URL);
  481. // ota_.SetHeader("Device-Id", SystemInfo::GetMacAddress().c_str());
  482. // ota_.SetHeader("Client-Id", board.GetUuid());
  483. // ota_.SetHeader("Accept-Language", Lang::CODE);
  484. // auto app_desc = esp_app_get_description();
  485. // ota_.SetHeader("User-Agent", std::string(BOARD_NAME "/") + app_desc->version);
  486. // xTaskCreate([](void* arg) {
  487. // Application* app = (Application*)arg;
  488. // app->CheckNewVersion();
  489. // vTaskDelete(NULL);
  490. // }, "check_new_version", 4096 * 2, this, 2, nullptr);
  491. SetDeviceState(kDeviceStateIdle);
  492. codec->SetOutputVolume(80);
  493. PlaySound(Lang::Sounds::P3_LINKWIFI);
  494. #if CONFIG_USE_AUDIO_PROCESSOR
  495. audio_processor_.Initialize(codec->input_channels(), codec->input_reference());
  496. audio_processor_.OnOutput([this](std::vector<int16_t>&& data) {
  497. background_task_->Schedule([this, data = std::move(data)]() mutable {
  498. opus_encoder_->Encode(std::move(data), [this](std::vector<uint8_t>&& opus) {
  499. Schedule([this, opus = std::move(opus)]() {
  500. protocol_->SendAudio(opus);
  501. });
  502. });
  503. });
  504. });
  505. #endif
  506. #if CONFIG_USE_WAKE_WORD_DETECT
  507. wake_word_detect_.Initialize(codec->input_channels(), codec->input_reference());
  508. wake_word_detect_.OnVadStateChange([this](bool speaking) {
  509. Schedule([this, speaking]() {
  510. if (device_state_ == kDeviceStateListening) {
  511. if (speaking) {
  512. voice_detected_ = true;
  513. } else {
  514. voice_detected_ = false;
  515. }
  516. auto led = Board::GetInstance().GetLed();
  517. led->OnStateChanged();
  518. }
  519. });
  520. });
  521. wake_word_detect_.OnWakeWordDetected([this](const std::string& wake_word) {
  522. Schedule([this, &wake_word]() {
  523. if (device_state_ == kDeviceStateIdle) {
  524. SetDeviceState(kDeviceStateConnecting);
  525. wake_word_detect_.EncodeWakeWordData();
  526. if (!protocol_->OpenAudioChannel()) {//尝试打开音频通道,如果打开失败,则重新启动唤醒词检测并返回。
  527. wake_word_detect_.StartDetection();
  528. return;
  529. }
  530. std::vector<uint8_t> opus;
  531. // Encode and send the wake word data to the server
  532. while (wake_word_detect_.GetWakeWordOpus(opus)) {
  533. protocol_->SendAudio(opus);
  534. }
  535. // Set the chat state to wake word detected
  536. protocol_->SendWakeWordDetected(wake_word);
  537. ESP_LOGI(TAG, "Wake word detected: %s", wake_word.c_str());
  538. keep_listening_ = true;
  539. SetDeviceState(kDeviceStateIdle);
  540. } else if (device_state_ == kDeviceStateSpeaking) {
  541. AbortSpeaking(kAbortReasonWakeWordDetected);
  542. } else if (device_state_ == kDeviceStateActivating) {
  543. SetDeviceState(kDeviceStateIdle);
  544. }
  545. // Resume detection
  546. wake_word_detect_.StartDetection();
  547. });
  548. });
  549. wake_word_detect_.StartDetection();
  550. #endif
  551. SetDeviceState(kDeviceStateIdle);
  552. esp_timer_start_periodic(clock_timer_handle_, 1000000);
  553. }
  554. void Application::OnClockTimer() {
  555. clock_ticks_++;
  556. // Print the debug info every 10 seconds
  557. if (clock_ticks_ % 10 == 0) {
  558. // SystemInfo::PrintRealTimeStats(pdMS_TO_TICKS(1000));
  559. int free_sram = heap_caps_get_free_size(MALLOC_CAP_INTERNAL);
  560. int min_free_sram = heap_caps_get_minimum_free_size(MALLOC_CAP_INTERNAL);
  561. ESP_LOGI(TAG, "Free internal: %u minimal internal: %u", free_sram, min_free_sram);
  562. // If we have synchronized server time, set the status to clock "HH:MM" if the device is idle
  563. if (ota_.HasServerTime()) {
  564. if (device_state_ == kDeviceStateIdle) {
  565. Schedule([this]() {
  566. // Set status to clock "HH:MM"
  567. time_t now = time(NULL);
  568. char time_str[64];
  569. strftime(time_str, sizeof(time_str), "%H:%M ", localtime(&now));
  570. Board::GetInstance().GetDisplay()->SetStatus(time_str);
  571. });
  572. }
  573. }
  574. }
  575. }
  576. void Application::Schedule(std::function<void()> callback) {
  577. {
  578. std::lock_guard<std::mutex> lock(mutex_);
  579. main_tasks_.push_back(std::move(callback));
  580. }
  581. xEventGroupSetBits(event_group_, SCHEDULE_EVENT);
  582. }
  583. // The Main Loop controls the chat state and websocket connection
  584. // If other tasks need to access the websocket or chat state,
  585. // they should use Schedule to call this function
  586. //主循环切换首发音频:由xEventGroupWaitBits事件触发。
  587. /**
  588. * EventBits_t xEventGroupWaitBits(
  589. EventGroupHandle_t xEventGroup, // 事件组句柄
  590. const EventBits_t uxBitsToWaitFor, // 等待的标志位掩码
  591. const BaseType_t xClearOnExit, // 退出时是否清除标志位
  592. const BaseType_t xWaitForAllBits, // 是否等待所有位(1)或任意位(0)
  593. TickType_t xTicksToWait // 等待超时时间
  594. );
  595. *
  596. */
  597. // 初始化函数中创建音频任务
  598. void Application::Init() {
  599. // 创建音频输入任务
  600. xTaskCreate([](void* arg) {
  601. Application* app = (Application*)arg;
  602. while(true) {
  603. auto bits = xEventGroupWaitBits(app->event_group_,
  604. AUDIO_INPUT_READY_EVENT,
  605. pdTRUE, pdFALSE, portMAX_DELAY);
  606. if (bits & AUDIO_INPUT_READY_EVENT) {
  607. app->InputAudio();
  608. }
  609. // ESP_LOGI(TAG, "录音中");
  610. }
  611. }, "audio_input_task", 4096*2, this, 2, &inputTaskHandle);
  612. // 创建音频输出任务
  613. xTaskCreate([](void* arg) {
  614. Application* app = (Application*)arg;
  615. while(true) {
  616. auto bits = xEventGroupWaitBits(app->event_group_,
  617. AUDIO_OUTPUT_READY_EVENT,
  618. pdTRUE, pdFALSE, portMAX_DELAY);
  619. if (bits & AUDIO_OUTPUT_READY_EVENT) {
  620. app->OutputAudio();
  621. }
  622. // ESP_LOGI(TAG, "播放中");
  623. }
  624. }, "audio_output_task", 4096*2, this, 2, &outputTaskHandle);
  625. }
  626. void Application::MainLoop() {
  627. Init();
  628. while (true) {
  629. auto bits = xEventGroupWaitBits(event_group_,
  630. SCHEDULE_EVENT,
  631. pdTRUE, pdFALSE, portMAX_DELAY);
  632. if (bits & SCHEDULE_EVENT) {
  633. std::unique_lock<std::mutex> lock(mutex_);
  634. std::list<std::function<void()>> tasks = std::move(main_tasks_);
  635. lock.unlock();
  636. for (auto& task : tasks) {
  637. task();
  638. }
  639. }
  640. }
  641. }
  642. void Application::ResetDecoder() {
  643. std::lock_guard<std::mutex> lock(mutex_);
  644. opus_decoder_->ResetState();
  645. audio_decode_queue_.clear();
  646. last_output_time_ = std::chrono::steady_clock::now();
  647. }
  648. void Application::OutputAudio() {
  649. auto now = std::chrono::steady_clock::now(); //获取当前时间点的函数
  650. auto codec = Board::GetInstance().GetAudioCodec();
  651. const int max_silence_seconds = 10;
  652. std::unique_lock<std::mutex> lock(mutex_); //是 C++ 中用于线程同步的互斥锁(Mutex),用于保护共享资源,防止多个线程同时访问导致数据竞争(Data Race)
  653. if (audio_decode_queue_.empty()) {
  654. // Disable the output if there is no audio data for a long time
  655. if (device_state_ == kDeviceStateIdle) {
  656. auto duration = std::chrono::duration_cast<std::chrono::seconds>(now - last_output_time_).count();
  657. if (duration > max_silence_seconds) {
  658. codec->EnableOutput(false);
  659. }
  660. }
  661. return;
  662. }
  663. if (device_state_ == kDeviceStateListening) {
  664. audio_decode_queue_.clear();
  665. return;
  666. }
  667. last_output_time_ = now;
  668. auto opus = std::move(audio_decode_queue_.front());
  669. audio_decode_queue_.pop_front();
  670. lock.unlock();
  671. background_task_->Schedule([this, codec, opus = std::move(opus)]() mutable {
  672. // ESP_LOGI(TAG, "进入此处1");
  673. if (aborted_) {
  674. // ESP_LOGI(TAG, "进入此处2");
  675. return;
  676. }
  677. std::vector<int16_t> pcm;
  678. if (!opus_decoder_->Decode(std::move(opus), pcm)) {
  679. return;
  680. }
  681. // Resample if the sample rate is different
  682. if (opus_decode_sample_rate_ != codec->output_sample_rate()) {
  683. int target_size = output_resampler_.GetOutputSamples(pcm.size());
  684. std::vector<int16_t> resampled(target_size);
  685. output_resampler_.Process(pcm.data(), pcm.size(), resampled.data());
  686. pcm = std::move(resampled);
  687. }
  688. codec->OutputData(pcm);
  689. });
  690. }
  691. void Application::InputAudio() {
  692. auto codec = Board::GetInstance().GetAudioCodec();
  693. std::vector<int16_t> data;
  694. if (!codec->InputData(data)) {
  695. return;
  696. }
  697. if (codec->input_sample_rate() != 16000) {
  698. if (codec->input_channels() == 2) {
  699. auto mic_channel = std::vector<int16_t>(data.size() / 2);
  700. auto reference_channel = std::vector<int16_t>(data.size() / 2);
  701. for (size_t i = 0, j = 0; i < mic_channel.size(); ++i, j += 2) {
  702. mic_channel[i] = data[j];
  703. reference_channel[i] = data[j + 1];
  704. }
  705. auto resampled_mic = std::vector<int16_t>(input_resampler_.GetOutputSamples(mic_channel.size()));
  706. auto resampled_reference = std::vector<int16_t>(reference_resampler_.GetOutputSamples(reference_channel.size()));
  707. input_resampler_.Process(mic_channel.data(), mic_channel.size(), resampled_mic.data());
  708. reference_resampler_.Process(reference_channel.data(), reference_channel.size(), resampled_reference.data());
  709. data.resize(resampled_mic.size() + resampled_reference.size());
  710. for (size_t i = 0, j = 0; i < resampled_mic.size(); ++i, j += 2) {
  711. data[j] = resampled_mic[i];
  712. data[j + 1] = resampled_reference[i];
  713. }
  714. } else {
  715. auto resampled = std::vector<int16_t>(input_resampler_.GetOutputSamples(data.size()));
  716. input_resampler_.Process(data.data(), data.size(), resampled.data());
  717. data = std::move(resampled);
  718. }
  719. }
  720. #if CONFIG_USE_WAKE_WORD_DETECT
  721. if (wake_word_detect_.IsDetectionRunning()) {
  722. wake_word_detect_.Feed(data);
  723. }
  724. #endif
  725. #if CONFIG_USE_AUDIO_PROCESSOR
  726. if (audio_processor_.IsRunning()) {
  727. audio_processor_.Input(data);
  728. }
  729. #else
  730. if (device_state_ == kDeviceStateListening) {
  731. background_task_->Schedule([this, data = std::move(data)]() mutable {
  732. opus_encoder_->Encode(std::move(data), [this](std::vector<uint8_t>&& opus) {
  733. Schedule([this, opus = std::move(opus)]() {
  734. protocol_->SendAudio(opus);
  735. });
  736. });
  737. });
  738. }
  739. #endif
  740. }
  741. void Application::AbortSpeaking(AbortReason reason) {
  742. ESP_LOGI(TAG, "Abort speaking");
  743. aborted_ = true;
  744. protocol_->SendAbortSpeaking(reason);
  745. // ResetDecoder();
  746. // //播放 Lang::Sounds::P3_HUNDRED
  747. // PlaySound(Lang::Sounds:: );
  748. // //等待播放完成
  749. // background_task_->WaitForCompletion();
  750. // vTaskDelay(pdMS_TO_TICKS(1000));
  751. }
  752. void Application::SetDeviceState(DeviceState state) {
  753. if (device_state_ == state) {
  754. return;
  755. }
  756. clock_ticks_ = 0;
  757. auto previous_state = device_state_;
  758. device_state_ = state;
  759. ESP_LOGI(TAG, "STATE: %s", STATE_STRINGS[device_state_]);
  760. // The state is changed, wait for all background tasks to finish
  761. background_task_->WaitForCompletion();
  762. auto& board = Board::GetInstance();
  763. auto codec = board.GetAudioCodec();
  764. auto display = board.GetDisplay();
  765. auto led = board.GetLed();
  766. led->OnStateChanged();
  767. switch (state) {
  768. case kDeviceStateUnknown:
  769. case kDeviceStateIdle:
  770. display->SetStatus(Lang::Strings::STANDBY);
  771. display->SetEmotion("neutral");
  772. #if CONFIG_USE_AUDIO_PROCESSOR
  773. audio_processor_.Stop();
  774. code_init_flag = false;
  775. #endif
  776. break;
  777. case kDeviceStateConnecting:
  778. display->SetStatus(Lang::Strings::CONNECTING);
  779. display->SetEmotion("neutral");
  780. display->SetChatMessage("system", "");
  781. break;
  782. case kDeviceStateListening:
  783. display->SetStatus(Lang::Strings::LISTENING);
  784. display->SetEmotion("neutral");
  785. ResetDecoder();
  786. // vTaskDelay(pdMS_TO_TICKS(1000));//这里的延迟可以避免音频处理芯片异常时候,导致程序崩溃。但是还是没解决音频异常后的处理。
  787. if (!code_init_flag){
  788. code_init_flag = true;
  789. opus_encoder_->ResetState();
  790. #if CONFIG_USE_AUDIO_PROCESSOR
  791. audio_processor_.Start();
  792. #endif
  793. }
  794. UpdateIotStates();
  795. if (previous_state == kDeviceStateSpeaking) {
  796. // FIXME: Wait for the speaker to empty the buffer
  797. vTaskDelay(pdMS_TO_TICKS(120));
  798. }
  799. break;
  800. case kDeviceStateSpeaking:
  801. display->SetStatus(Lang::Strings::SPEAKING);
  802. ResetDecoder();
  803. codec->EnableOutput(true);
  804. //成功打断,但是8次左右,系统会崩溃
  805. // protocol_->SendStartListening(kListeningModeAutoStop);
  806. #if CONFIG_USE_AUDIO_PROCESSOR
  807. // audio_processor_.Stop();
  808. #endif
  809. break;
  810. default:
  811. // Do nothing
  812. break;
  813. }
  814. }
  815. void Application::SetDecodeSampleRate(int sample_rate) {
  816. if (opus_decode_sample_rate_ == sample_rate) {
  817. return;
  818. }
  819. opus_decode_sample_rate_ = sample_rate;
  820. opus_decoder_.reset();
  821. opus_decoder_ = std::make_unique<OpusDecoderWrapper>(opus_decode_sample_rate_, 1);
  822. auto codec = Board::GetInstance().GetAudioCodec();
  823. if (opus_decode_sample_rate_ != codec->output_sample_rate()) {
  824. ESP_LOGI(TAG, "Resampling audio from %d to %d", opus_decode_sample_rate_, codec->output_sample_rate());
  825. output_resampler_.Configure(opus_decode_sample_rate_, codec->output_sample_rate());
  826. }
  827. }
  828. void Application::UpdateIotStates() {
  829. auto& thing_manager = iot::ThingManager::GetInstance();
  830. std::string states;
  831. if (thing_manager.GetStatesJson(states, true)) {
  832. protocol_->SendIotStates(states);
  833. }
  834. }
  835. void Application::Reboot() {
  836. ESP_LOGI(TAG, "Rebooting...");
  837. esp_restart();
  838. }
  839. void Application::WakeWordInvoke(const std::string& wake_word) {
  840. if (device_state_ == kDeviceStateIdle) {
  841. ToggleChatState();
  842. Schedule([this, wake_word]() {
  843. if (protocol_) {
  844. protocol_->SendWakeWordDetected(wake_word);
  845. }
  846. });
  847. } else if (device_state_ == kDeviceStateSpeaking) {
  848. Schedule([this]() {
  849. AbortSpeaking(kAbortReasonNone);
  850. });
  851. } else if (device_state_ == kDeviceStateListening) {
  852. Schedule([this]() {
  853. if (protocol_) {
  854. protocol_->CloseAudioChannel();
  855. }
  856. });
  857. }
  858. }
  859. bool Application::CanEnterSleepMode() {
  860. if (device_state_ != kDeviceStateIdle) {
  861. return false;
  862. }
  863. if (protocol_ && protocol_->IsAudioChannelOpened()) {
  864. return false;
  865. }
  866. // Now it is safe to enter sleep mode
  867. return true;
  868. }