application.cc 32 KB

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