main.cpp 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <regex>
  5. #include "esp_psram.h"
  6. #include "esp_pm.h"
  7. #include "psram.h"
  8. #include "esp_chip_info.h"
  9. // SD-Card ////////////////////
  10. #include "esp_vfs_fat.h"
  11. #include "ffconf.h"
  12. #include "driver/sdmmc_host.h"
  13. #if (ESP_IDF_VERSION <= ESP_IDF_VERSION_VAL(5, 1, 2))
  14. #include "sdcard_init.h"
  15. #endif
  16. ///////////////////////////////
  17. #include "ClassLogFile.h"
  18. #include "connect_wlan.h"
  19. #include "read_wlanini.h"
  20. #include "server_main.h"
  21. #include "MainFlowControl.h"
  22. #include "server_file.h"
  23. #include "server_ota.h"
  24. #include "time_sntp.h"
  25. #include "configFile.h"
  26. #include "server_main.h"
  27. #include "server_camera.h"
  28. #ifdef ENABLE_MQTT
  29. #include "server_mqtt.h"
  30. #endif //ENABLE_MQTT
  31. #include "Helper.h"
  32. #include "statusled.h"
  33. #include "sdcard_check.h"
  34. #include "../../include/defines.h"
  35. #ifdef ENABLE_SOFTAP
  36. #include "softAP.h"
  37. #endif //ENABLE_SOFTAP
  38. #ifdef DISABLE_BROWNOUT_DETECTOR
  39. #include "soc/soc.h"
  40. #include "soc/rtc_cntl_reg.h"
  41. #endif
  42. #ifdef DEBUG_ENABLE_SYSINFO
  43. #if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL( 4, 0, 0 )
  44. #include "esp_sys.h"
  45. #endif
  46. #endif //DEBUG_ENABLE_SYSINFO
  47. // define `gpio_pad_select_gpip` for newer versions of IDF
  48. #if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 3, 0))
  49. #include "esp_rom_gpio.h"
  50. #define gpio_pad_select_gpio esp_rom_gpio_pad_select_gpio
  51. #endif
  52. #ifdef USE_HIMEM_IF_AVAILABLE
  53. #include "esp32/himem.h"
  54. #ifdef DEBUG_HIMEM_MEMORY_CHECK
  55. #include "himem_memory_check.h"
  56. #endif
  57. #endif
  58. //#ifdef CONFIG_HEAP_TRACING_STANDALONE
  59. #if defined HEAP_TRACING_MAIN_WIFI || defined HEAP_TRACING_MAIN_START
  60. #include <esp_heap_trace.h>
  61. #define NUM_RECORDS 300
  62. static heap_trace_record_t trace_record[NUM_RECORDS]; // This buffer must be in internal RAM
  63. #endif
  64. extern const char* GIT_TAG;
  65. extern const char* GIT_REV;
  66. extern const char* GIT_BRANCH;
  67. extern const char* BUILD_TIME;
  68. extern std::string getFwVersion(void);
  69. extern std::string getHTMLversion(void);
  70. extern std::string getHTMLcommit(void);
  71. std::vector<std::string> splitString(const std::string& str);
  72. void migrateConfiguration(void);
  73. bool setCpuFrequency(void);
  74. static const char *TAG = "MAIN";
  75. #define MOUNT_POINT "/sdcard"
  76. bool Init_NVS_SDCard()
  77. {
  78. esp_err_t ret = nvs_flash_init();
  79. if (ret == ESP_ERR_NVS_NO_FREE_PAGES) {
  80. ESP_ERROR_CHECK(nvs_flash_erase());
  81. ret = nvs_flash_init();
  82. }
  83. ESP_LOGD(TAG, "Using SDMMC peripheral");
  84. sdmmc_host_t host = SDMMC_HOST_DEFAULT();
  85. host.max_freq_khz = SDMMC_FREQ_HIGHSPEED;
  86. // This initializes the slot without card detect (CD) and write protect (WP) signals.
  87. // Modify slot_config.gpio_cd and slot_config.gpio_wp if your board has these signals.
  88. sdmmc_slot_config_t slot_config = SDMMC_SLOT_CONFIG_DEFAULT();
  89. // Set bus width to use:
  90. #ifdef __SD_USE_ONE_LINE_MODE__
  91. slot_config.width = 1;
  92. #ifdef SOC_SDMMC_USE_GPIO_MATRIX
  93. slot_config.clk = GPIO_SDCARD_CLK;
  94. slot_config.cmd = GPIO_SDCARD_CMD;
  95. slot_config.d0 = GPIO_SDCARD_D0;
  96. #endif
  97. #else
  98. slot_config.width = 4;
  99. #ifdef SOC_SDMMC_USE_GPIO_MATRIX
  100. slot_config.d1 = GPIO_SDCARD_D1;
  101. slot_config.d2 = GPIO_SDCARD_D2;
  102. slot_config.d3 = GPIO_SDCARD_D3;
  103. #endif
  104. #endif
  105. // Enable internal pullups on enabled pins. The internal pullups
  106. // are insufficient however, please make sure 10k external pullups are
  107. // connected on the bus. This is for debug / example purpose only.
  108. slot_config.flags |= SDMMC_SLOT_FLAG_INTERNAL_PULLUP;
  109. // Der PullUp des GPIO13 wird durch slot_config.flags |= SDMMC_SLOT_FLAG_INTERNAL_PULLUP;
  110. // nicht gesetzt, da er eigentlich nicht benötigt wird,
  111. // dies führt jedoch bei schlechten Kopien des AI_THINKER Boards
  112. // zu Problemen mit der SD Initialisierung und eventuell sogar zur reboot-loops.
  113. // Um diese Probleme zu kompensieren, wird der PullUp manuel gesetzt.
  114. gpio_set_pull_mode(GPIO_SDCARD_D3, GPIO_PULLUP_ONLY); // HS2_D3
  115. // Options for mounting the filesystem.
  116. // If format_if_mount_failed is set to true, SD card will be partitioned and
  117. // formatted in case when mounting fails.
  118. esp_vfs_fat_sdmmc_mount_config_t mount_config = {
  119. .format_if_mount_failed = false,
  120. .max_files = 12, // previously -> 2022-09-21: 5, 2023-01-02: 7
  121. .allocation_unit_size = 0, // 0 = auto
  122. .disk_status_check_enable = 0
  123. };
  124. sdmmc_card_t* card;
  125. const char mount_point[] = MOUNT_POINT;
  126. // Use settings defined above to initialize SD card and mount FAT filesystem.
  127. // Note: esp_vfs_fat_sdmmc_mount is an all-in-one convenience function.
  128. // Please check its source code and implement error recovery when developing
  129. // production applications.
  130. #if (ESP_IDF_VERSION <= ESP_IDF_VERSION_VAL(5, 1, 2))
  131. ret = esp_vfs_fat_sdmmc_mount_mh(mount_point, &host, &slot_config, &mount_config, &card);
  132. #else
  133. ret = esp_vfs_fat_sdmmc_mount(mount_point, &host, &slot_config, &mount_config, &card);
  134. #endif
  135. if (ret != ESP_OK) {
  136. if (ret == ESP_FAIL) {
  137. ESP_LOGE(TAG, "Failed to mount FAT filesystem on SD card. Check SD card filesystem (only FAT supported) or try another card");
  138. StatusLED(SDCARD_INIT, 1, true);
  139. }
  140. else if (ret == 263) { // Error code: 0x107 --> usually: SD not found
  141. ESP_LOGE(TAG, "SD card init failed. Check if SD card is properly inserted into SD card slot or try another card");
  142. StatusLED(SDCARD_INIT, 2, true);
  143. }
  144. else {
  145. ESP_LOGE(TAG, "SD card init failed. Check error code or try another card");
  146. StatusLED(SDCARD_INIT, 3, true);
  147. }
  148. return false;
  149. }
  150. //sdmmc_card_print_info(stdout, card); // With activated CONFIG_NEWLIB_NANO_FORMAT --> capacity not printed correctly anymore
  151. SaveSDCardInfo(card);
  152. return true;
  153. }
  154. extern "C" void app_main(void)
  155. {
  156. //#ifdef CONFIG_HEAP_TRACING_STANDALONE
  157. #if defined HEAP_TRACING_MAIN_WIFI || defined HEAP_TRACING_MAIN_START
  158. //register a buffer to record the memory trace
  159. ESP_ERROR_CHECK( heap_trace_init_standalone(trace_record, NUM_RECORDS) );
  160. #endif
  161. TickType_t xDelay;
  162. #ifdef DISABLE_BROWNOUT_DETECTOR
  163. WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); //disable brownout detector
  164. #endif
  165. #ifdef HEAP_TRACING_MAIN_START
  166. ESP_ERROR_CHECK( heap_trace_start(HEAP_TRACE_LEAKS) );
  167. #endif
  168. // ********************************************
  169. // Highlight start of app_main
  170. // ********************************************
  171. ESP_LOGI(TAG, "\n\n\n\n================ Start app_main =================");
  172. // Init SD card
  173. // ********************************************
  174. if (!Init_NVS_SDCard())
  175. {
  176. ESP_LOGE(TAG, "Device init aborted!");
  177. return; // No way to continue without working SD card!
  178. }
  179. // SD card: Create log directories (if not already existing)
  180. // ********************************************
  181. LogFile.CreateLogDirectories(); // mandatory for logging + image saving
  182. // ********************************************
  183. // Highlight start of logfile logging
  184. // Default Log Level: INFO -> Everything which needs to be logged during boot should be have level INFO, WARN OR ERROR
  185. // ********************************************
  186. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "=================================================");
  187. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "==================== Start ======================");
  188. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "=================================================");
  189. // Init external PSRAM
  190. // ********************************************
  191. esp_err_t PSRAMStatus = esp_psram_init();
  192. if (PSRAMStatus == ESP_FAIL) { // ESP_FAIL -> Failed to init PSRAM
  193. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "PSRAM init failed (" + std::to_string(PSRAMStatus) + ")! PSRAM not found or defective");
  194. setSystemStatusFlag(SYSTEM_STATUS_PSRAM_BAD);
  195. StatusLED(PSRAM_INIT, 1, true);
  196. }
  197. else { // ESP_OK -> PSRAM init OK --> continue to check PSRAM size
  198. size_t psram_size = esp_psram_get_size(); // size_t psram_size = esp_psram_get_size(); // comming in IDF 5.0
  199. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "PSRAM size: " + std::to_string(psram_size) + " byte (" + std::to_string(psram_size/1024/1024) +
  200. "MB / " + std::to_string(psram_size/1024/1024*8) + "MBit)");
  201. // Check PSRAM size
  202. // ********************************************
  203. if (psram_size < (4*1024*1024)) { // PSRAM is below 4 MBytes (32Mbit)
  204. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "PSRAM size >= 4MB (32Mbit) is mandatory to run this application");
  205. setSystemStatusFlag(SYSTEM_STATUS_PSRAM_BAD);
  206. StatusLED(PSRAM_INIT, 2, true);
  207. }
  208. else { // PSRAM size OK --> continue to check heap size
  209. size_t _hsize = getESPHeapSize();
  210. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Total heap: " + std::to_string(_hsize) + " byte");
  211. // Check heap memory
  212. // ********************************************
  213. if (_hsize < 4000000) { // Check available Heap memory for a bit less than 4 MB (a test on a good device showed 4187558 bytes to be available)
  214. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Total heap >= 4000000 byte is mandatory to run this application");
  215. setSystemStatusFlag(SYSTEM_STATUS_HEAP_TOO_SMALL);
  216. StatusLED(PSRAM_INIT, 3, true);
  217. }
  218. else { // HEAP size OK --> continue to reserve shared memory block and check camera init
  219. /* Allocate static PSRAM memory regions */
  220. if (! reserve_psram_shared_region()) {
  221. setSystemStatusFlag(SYSTEM_STATUS_HEAP_TOO_SMALL);
  222. StatusLED(PSRAM_INIT, 3, true);
  223. }
  224. else { // OK
  225. // Init camera
  226. // ********************************************
  227. PowerResetCamera();
  228. esp_err_t camStatus = Camera.InitCam();
  229. Camera.LightOnOff(false);
  230. xDelay = 2000 / portTICK_PERIOD_MS;
  231. ESP_LOGD(TAG, "After camera initialization: sleep for: %ldms", (long) xDelay * CONFIG_FREERTOS_HZ/portTICK_PERIOD_MS);
  232. vTaskDelay( xDelay );
  233. // Check camera init
  234. // ********************************************
  235. if (camStatus != ESP_OK) { // Camera init failed, retry to init
  236. char camStatusHex[33];
  237. sprintf(camStatusHex,"0x%02x", camStatus);
  238. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Camera init failed (" + std::string(camStatusHex) + "), retrying...");
  239. PowerResetCamera();
  240. camStatus = Camera.InitCam();
  241. Camera.LightOnOff(false);
  242. xDelay = 2000 / portTICK_PERIOD_MS;
  243. ESP_LOGD(TAG, "After camera initialization: sleep for: %ldms", (long) xDelay * CONFIG_FREERTOS_HZ/portTICK_PERIOD_MS);
  244. vTaskDelay( xDelay );
  245. if (camStatus != ESP_OK) { // Camera init failed again
  246. sprintf(camStatusHex,"0x%02x", camStatus);
  247. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Camera init failed (" + std::string(camStatusHex) +
  248. ")! Check camera module and/or proper electrical connection");
  249. setSystemStatusFlag(SYSTEM_STATUS_CAM_BAD);
  250. StatusLED(CAM_INIT, 1, true);
  251. }
  252. }
  253. else { // ESP_OK -> Camera init OK --> continue to perform camera framebuffer check
  254. // Camera framebuffer check
  255. // ********************************************
  256. if (!Camera.testCamera()) {
  257. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Camera framebuffer check failed");
  258. // Easiest would be to simply restart here and try again,
  259. // how ever there seem to be systems where it fails at startup but still work correctly later.
  260. // Therefore we treat it still as successed! */
  261. setSystemStatusFlag(SYSTEM_STATUS_CAM_FB_BAD);
  262. StatusLED(CAM_INIT, 2, false);
  263. }
  264. Camera.LightOnOff(false); // make sure flashlight is off before start of flow
  265. // Print camera infos
  266. // ********************************************
  267. char caminfo[50];
  268. sensor_t * s = esp_camera_sensor_get();
  269. sprintf(caminfo, "PID: 0x%02x, VER: 0x%02x, MIDL: 0x%02x, MIDH: 0x%02x", s->id.PID, s->id.VER, s->id.MIDH, s->id.MIDL);
  270. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Camera info: " + std::string(caminfo));
  271. }
  272. }
  273. }
  274. }
  275. }
  276. // SD card: basic R/W check
  277. // ********************************************
  278. int iSDCardStatus = SDCardCheckRW();
  279. if (iSDCardStatus < 0) {
  280. if (iSDCardStatus <= -1 && iSDCardStatus >= -2) { // write error
  281. StatusLED(SDCARD_CHECK, 1, true);
  282. }
  283. else if (iSDCardStatus <= -3 && iSDCardStatus >= -5) { // read error
  284. StatusLED(SDCARD_CHECK, 2, true);
  285. }
  286. else if (iSDCardStatus == -6) { // delete error
  287. StatusLED(SDCARD_CHECK, 3, true);
  288. }
  289. setSystemStatusFlag(SYSTEM_STATUS_SDCARD_CHECK_BAD); // reduced web interface going to be loaded
  290. }
  291. // Migrate parameter in config.ini to new naming (firmware 15.0 and newer)
  292. // ********************************************
  293. migrateConfiguration();
  294. // Init time (as early as possible, but SD card needs to be initialized)
  295. // ********************************************
  296. setupTime(); // NTP time service: Status of time synchronization will be checked after every round (server_tflite.cpp)
  297. // Set CPU Frequency
  298. // ********************************************
  299. setCpuFrequency();
  300. // SD card: Create further mandatory directories (if not already existing)
  301. // Correct creation of these folders will be checked with function "SDCardCheckFolderFilePresence"
  302. // ********************************************
  303. MakeDir("/sdcard/firmware"); // mandatory for OTA firmware update
  304. MakeDir("/sdcard/img_tmp"); // mandatory for setting up alignment marks
  305. MakeDir("/sdcard/demo"); // mandatory for demo mode
  306. MakeDir("/sdcard/config/certs"); // mandatory for mqtt certificates
  307. // Check for updates
  308. // ********************************************
  309. CheckOTAUpdate();
  310. CheckUpdate();
  311. // Start SoftAP for initial remote setup
  312. // Note: Start AP if no wlan.ini and/or config.ini available, e.g. SD card empty; function does not exit anymore until reboot
  313. // ********************************************
  314. #ifdef ENABLE_SOFTAP
  315. CheckStartAPMode();
  316. #endif
  317. // SD card: Check presence of some mandatory folders / files
  318. // ********************************************
  319. if (!SDCardCheckFolderFilePresence()) {
  320. StatusLED(SDCARD_CHECK, 4, true);
  321. setSystemStatusFlag(SYSTEM_STATUS_FOLDER_CHECK_BAD); // reduced web interface going to be loaded
  322. }
  323. // Check version information
  324. // ********************************************
  325. std::string versionFormated = getFwVersion() + ", Date/Time: " + std::string(BUILD_TIME) + \
  326. ", Web UI: " + getHTMLversion();
  327. if (std::string(GIT_TAG) != "") { // We are on a tag, add it as prefix
  328. versionFormated = "Tag: '" + std::string(GIT_TAG) + "', " + versionFormated;
  329. }
  330. LogFile.WriteToFile(ESP_LOG_INFO, TAG, versionFormated);
  331. if (getHTMLcommit().substr(0, 7) == "?")
  332. LogFile.WriteToFile(ESP_LOG_WARN, TAG, std::string("Failed to read file html/version.txt to parse Web UI version"));
  333. if (getHTMLcommit().substr(0, 7) != std::string(GIT_REV).substr(0, 7)) { // Compare the first 7 characters of both hashes
  334. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Web UI version (" + getHTMLcommit() + ") does not match firmware version (" + std::string(GIT_REV) + ")");
  335. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Recommendation: Repeat installation using AI-on-the-edge-device__update__*.zip");
  336. }
  337. // Check reboot reason
  338. // ********************************************
  339. CheckIsPlannedReboot();
  340. if (!getIsPlannedReboot() && (esp_reset_reason() == ESP_RST_PANIC)) { // If system reboot was not triggered by user and reboot was caused by execption
  341. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Reset reason: " + getResetReason());
  342. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Device was rebooted due to a software exception! Log level is set to DEBUG until the next reboot. "
  343. "Flow init is delayed by 5 minutes to check the logs or do an OTA update");
  344. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Keep device running until crash occurs again and check logs after device is up again");
  345. LogFile.setLogLevel(ESP_LOG_DEBUG);
  346. }
  347. else {
  348. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Reset reason: " + getResetReason());
  349. }
  350. #ifdef HEAP_TRACING_MAIN_START
  351. ESP_ERROR_CHECK( heap_trace_stop() );
  352. heap_trace_dump();
  353. #endif
  354. #ifdef HEAP_TRACING_MAIN_WIFI
  355. ESP_ERROR_CHECK( heap_trace_start(HEAP_TRACE_LEAKS) );
  356. #endif
  357. // Read WLAN parameter and start WIFI
  358. // ********************************************
  359. int iWLANStatus = LoadWlanFromFile(WLAN_CONFIG_FILE);
  360. if (iWLANStatus == 0) {
  361. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "WLAN config loaded, init WIFI...");
  362. if (wifi_init_sta() != ESP_OK) {
  363. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "WIFI init failed. Device init aborted!");
  364. StatusLED(WLAN_INIT, 3, true);
  365. return;
  366. }
  367. }
  368. else if (iWLANStatus == -1) { // wlan.ini not available, potentially empty or content not readable
  369. StatusLED(WLAN_INIT, 1, true);
  370. return; // No way to continue without reading the wlan.ini
  371. }
  372. else if (iWLANStatus == -2) { // SSID or password not configured
  373. StatusLED(WLAN_INIT, 2, true);
  374. return; // No way to continue with empty SSID or password!
  375. }
  376. xDelay = 2000 / portTICK_PERIOD_MS;
  377. ESP_LOGD(TAG, "main: sleep for: %ldms", (long) xDelay * CONFIG_FREERTOS_HZ/portTICK_PERIOD_MS);
  378. vTaskDelay( xDelay );
  379. // manual reset the time
  380. // ********************************************
  381. if (!time_manual_reset_sync())
  382. {
  383. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Manual Time Sync failed during startup" );
  384. }
  385. // Set log level for wifi component to WARN level (default: INFO; only relevant for serial console)
  386. // ********************************************
  387. esp_log_level_set("wifi", ESP_LOG_WARN);
  388. #ifdef HEAP_TRACING_MAIN_WIFI
  389. ESP_ERROR_CHECK( heap_trace_stop() );
  390. heap_trace_dump();
  391. #endif
  392. #ifdef DEBUG_ENABLE_SYSINFO
  393. #if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL( 4, 0, 0 )
  394. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Device Info : " + get_device_info() );
  395. ESP_LOGD(TAG, "Device infos %s", get_device_info().c_str());
  396. #endif
  397. #endif //DEBUG_ENABLE_SYSINFO
  398. #ifdef USE_HIMEM_IF_AVAILABLE
  399. #ifdef DEBUG_HIMEM_MEMORY_CHECK
  400. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Himem mem check : " + himem_memory_check() );
  401. ESP_LOGD(TAG, "Himem mem check %s", himem_memory_check().c_str());
  402. #endif
  403. #endif
  404. // Print Device info
  405. // ********************************************
  406. esp_chip_info_t chipInfo;
  407. esp_chip_info(&chipInfo);
  408. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Device info: CPU cores: " + std::to_string(chipInfo.cores) +
  409. ", Chip revision: " + std::to_string(chipInfo.revision));
  410. // Print SD-Card info
  411. // ********************************************
  412. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "SD card info: Name: " + getSDCardName() + ", Capacity: " +
  413. getSDCardCapacity() + "MB, Free: " + getSDCardFreePartitionSpace() + "MB");
  414. xDelay = 2000 / portTICK_PERIOD_MS;
  415. ESP_LOGD(TAG, "main: sleep for: %ldms", (long) xDelay * CONFIG_FREERTOS_HZ/portTICK_PERIOD_MS);
  416. vTaskDelay( xDelay );
  417. // Start webserver + register handler
  418. // ********************************************
  419. ESP_LOGD(TAG, "starting servers");
  420. server = start_webserver();
  421. register_server_camera_uri(server);
  422. register_server_main_flow_task_uri(server);
  423. register_server_file_uri(server, "/sdcard");
  424. register_server_ota_sdcard_uri(server);
  425. #ifdef ENABLE_MQTT
  426. register_server_mqtt_uri(server);
  427. #endif //ENABLE_MQTT
  428. gpio_handler_create(server);
  429. ESP_LOGD(TAG, "Before reg server main");
  430. register_server_main_uri(server, "/sdcard");
  431. // Only for testing purpose
  432. //setSystemStatusFlag(SYSTEM_STATUS_CAM_FB_BAD);
  433. //setSystemStatusFlag(SYSTEM_STATUS_PSRAM_BAD);
  434. // Check main init + start TFlite task
  435. // ********************************************
  436. if (getSystemStatus() == 0) { // No error flag is set
  437. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Initialization completed successfully");
  438. InitializeFlowTask();
  439. }
  440. else if (isSetSystemStatusFlag(SYSTEM_STATUS_CAM_FB_BAD) || // Non critical errors occured, we try to continue...
  441. isSetSystemStatusFlag(SYSTEM_STATUS_NTP_BAD)) {
  442. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Initialization completed with non-critical errors!");
  443. InitializeFlowTask();
  444. }
  445. else { // Any other error is critical and makes running the flow impossible. Init is going to abort.
  446. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Initialization failed. Flow task start aborted. Loading reduced web interface...");
  447. }
  448. }
  449. void migrateConfiguration(void) {
  450. std::vector<string> splitted;
  451. bool migrated = false;
  452. bool CamZoom_found = false;
  453. int CamZoom_lines = 0;
  454. bool CamZoom_value = false;
  455. int CamZoomSize_lines = 0;
  456. int CamZoomSize_value = 0;
  457. int CamZoomOffsetX_lines = 0;
  458. int CamZoomOffsetX_value = 0;
  459. int CamZoomOffsetY_lines = 0;
  460. int CamZoomOffsetY_value = 0;
  461. if (!FileExists(CONFIG_FILE)) {
  462. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Config file seems to be missing!");
  463. return;
  464. }
  465. std::string section = "";
  466. std::ifstream ifs(CONFIG_FILE);
  467. std::string content((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
  468. /* Split config file it array of lines */
  469. std::vector<std::string> configLines = splitString(content);
  470. /* Process each line */
  471. for (int i = 0; i < configLines.size(); i++) {
  472. // ESP_LOGI(TAG, "Line %d: %s", i, configLines[i].c_str());
  473. if (configLines[i].find("[") != std::string::npos) {
  474. // Start of new section
  475. section = configLines[i];
  476. replaceString(section, ";", "", false); // Remove possible semicolon (just for the string comparison)
  477. // ESP_LOGI(TAG, "New section: %s", section.c_str());
  478. }
  479. else {
  480. splitted = ZerlegeZeile(configLines[i]);
  481. }
  482. /* Migrate parameters as needed
  483. * For the boolean parameters, we make them enabled all the time now:
  484. * 1. If they where disabled, set them to their default value
  485. * 2. Enable them
  486. * Notes:
  487. * The migration has some simplifications:
  488. * - Case Sensitiveness must be like in the initial config.ini
  489. * - No Whitespace after a semicollon
  490. * - Only one whitespace before/after the equal sign
  491. */
  492. if (section == "[MakeImage]") {
  493. migrated = migrated | replaceString(configLines[i], "[MakeImage]", "[TakeImage]"); // Rename the section itself
  494. }
  495. if (section == "[MakeImage]" || section == "[TakeImage]") {
  496. if ((isInString(configLines[i], "Brightness")) && (!isInString(configLines[i], "CamBrightness"))) {
  497. migrated = migrated | replaceString(configLines[i], "Brightness", "CamBrightness");
  498. }
  499. else if ((isInString(configLines[i], "Contrast")) && (!isInString(configLines[i], "CamContrast"))) {
  500. migrated = migrated | replaceString(configLines[i], "Contrast", "CamContrast");
  501. }
  502. else if ((isInString(configLines[i], "Saturation")) && (!isInString(configLines[i], "CamSaturation"))) {
  503. migrated = migrated | replaceString(configLines[i], "Saturation", "CamSaturation");
  504. }
  505. else if ((isInString(configLines[i], "Sharpness")) && (!isInString(configLines[i], "CamSharpness")) && (!isInString(configLines[i], "CamAutoSharpness"))) {
  506. migrated = migrated | replaceString(configLines[i], "Sharpness", "CamSharpness");
  507. }
  508. else if ((isInString(configLines[i], "Aec2")) && (!isInString(configLines[i], "CamAec")) && (!isInString(configLines[i], "CamAec2"))) {
  509. migrated = migrated | replaceString(configLines[i], "Aec2", "CamAec2");
  510. }
  511. else if ((isInString(configLines[i], "Zoom")) && (!isInString(configLines[i], "CamZoom")) && (!isInString(configLines[i], "ZoomMode")) && (!isInString(configLines[i], "ZoomOffsetX")) && (!isInString(configLines[i], "ZoomOffsetY"))) {
  512. CamZoom_lines = i;
  513. if (splitted.size() < 2) {
  514. CamZoom_value = false;
  515. }
  516. else {
  517. ESP_LOGE(TAG, "splitted[1]: %s", splitted[1].c_str());
  518. CamZoom_value = alphanumericToBoolean(splitted[1]);
  519. }
  520. CamZoom_found = true;
  521. }
  522. else if ((isInString(configLines[i], "ZoomMode")) && (!isInString(configLines[i], "CamZoom"))) {
  523. CamZoomSize_lines = i;
  524. if (splitted.size() < 2) {
  525. CamZoomSize_value = 0;
  526. }
  527. else {
  528. if (isStringNumeric(splitted[1])) {
  529. CamZoomSize_value = std::stof(splitted[1]);
  530. }
  531. else {
  532. CamZoomSize_value = 0;
  533. }
  534. }
  535. CamZoom_found = true;
  536. }
  537. else if ((isInString(configLines[i], "ZoomOffsetX")) && (!isInString(configLines[i], "CamZoom")) && (!isInString(configLines[i], "ZoomOffsetY"))) {
  538. CamZoomOffsetX_lines = i;
  539. if (splitted.size() < 2) {
  540. CamZoomOffsetX_value = 0;
  541. }
  542. else {
  543. if (isStringNumeric(splitted[1])) {
  544. CamZoomOffsetX_value = std::stof(splitted[1]);
  545. }
  546. else {
  547. CamZoomOffsetX_value = 0;
  548. }
  549. }
  550. CamZoom_found = true;
  551. }
  552. else if ((isInString(configLines[i], "ZoomOffsetY")) && (!isInString(configLines[i], "CamZoom")) && (!isInString(configLines[i], "ZoomOffsetX"))) {
  553. CamZoomOffsetY_lines = i;
  554. if (splitted.size() < 2) {
  555. CamZoomOffsetY_value = 0;
  556. }
  557. else {
  558. if (isStringNumeric(splitted[1])) {
  559. CamZoomOffsetY_value = std::stof(splitted[1]);
  560. }
  561. else {
  562. CamZoomOffsetY_value = 0;
  563. }
  564. }
  565. CamZoom_found = true;
  566. }
  567. else {
  568. migrated = migrated | replaceString(configLines[i], "LogImageLocation", "RawImagesLocation");
  569. migrated = migrated | replaceString(configLines[i], "LogfileRetentionInDays", "RawImagesRetention");
  570. migrated = migrated | replaceString(configLines[i], ";Demo = true", ";Demo = false"); // Set it to its default value
  571. migrated = migrated | replaceString(configLines[i], ";Demo", "Demo"); // Enable it
  572. migrated = migrated | replaceString(configLines[i], "ImageQuality", "CamQuality");
  573. migrated = migrated | replaceString(configLines[i], "AutoExposureLevel", "CamAeLevel");
  574. migrated = migrated | replaceString(configLines[i], "FixedExposure", "CamAec");
  575. migrated = migrated | replaceString(configLines[i], "ImageSize", ";UNUSED_PARAMETER"); // This parameter is no longer used
  576. migrated = migrated | replaceString(configLines[i], "Grayscale", ";UNUSED_PARAMETER"); // This parameter is no longer used
  577. migrated = migrated | replaceString(configLines[i], "Negative", ";UNUSED_PARAMETER"); // This parameter is no longer used
  578. }
  579. }
  580. else if (section == "[Alignment]") {
  581. migrated = migrated | replaceString(configLines[i], "InitialMirror", ";UNUSED_PARAMETER"); // This parameter is no longer used
  582. migrated = migrated | replaceString(configLines[i], ";InitialMirror", ";UNUSED_PARAMETER"); // This parameter is no longer used
  583. migrated = migrated | replaceString(configLines[i], "FlipImageSize", ";UNUSED_PARAMETER"); // This parameter is no longer used
  584. migrated = migrated | replaceString(configLines[i], ";FlipImageSize", ";UNUSED_PARAMETER"); // This parameter is no longer used
  585. }
  586. else if (section == "[Digits]") {
  587. migrated = migrated | replaceString(configLines[i], "LogImageLocation", "ROIImagesLocation");
  588. migrated = migrated | replaceString(configLines[i], "LogfileRetentionInDays", "ROIImagesRetention");
  589. }
  590. else if (section == "[Analog]") {
  591. migrated = migrated | replaceString(configLines[i], "LogImageLocation", "ROIImagesLocation");
  592. migrated = migrated | replaceString(configLines[i], "LogfileRetentionInDays", "ROIImagesRetention");
  593. migrated = migrated | replaceString(configLines[i], "ExtendedResolution", ";UNUSED_PARAMETER"); // This parameter is no longer used
  594. }
  595. else if (section == "[PostProcessing]") {
  596. /* AllowNegativeRates has a <NUMBER> as prefix! */
  597. if (isInString(configLines[i], "AllowNegativeRates") && isInString(configLines[i], ";")) {
  598. // It is the parameter "AllowNegativeRates" and it is commented out
  599. migrated = migrated | replaceString(configLines[i], "true", "false"); // Set it to its default value
  600. migrated = migrated | replaceString(configLines[i], ";", ""); // Enable it
  601. }
  602. /* IgnoreLeadingNaN has a <NUMBER> as prefix! */
  603. else if (isInString(configLines[i], "IgnoreLeadingNaN") && isInString(configLines[i], ";")) {
  604. // It is the parameter "IgnoreLeadingNaN" and it is commented out
  605. migrated = migrated | replaceString(configLines[i], "true", "false"); // Set it to its default value
  606. migrated = migrated | replaceString(configLines[i], ";", ""); // Enable it
  607. }
  608. /* ExtendedResolution has a <NUMBER> as prefix! */
  609. else if (isInString(configLines[i], "ExtendedResolution") && isInString(configLines[i], ";")) {
  610. // It is the parameter "ExtendedResolution" and it is commented out
  611. migrated = migrated | replaceString(configLines[i], "true", "false"); // Set it to its default value
  612. migrated = migrated | replaceString(configLines[i], ";", ""); // Enable it
  613. }
  614. else {
  615. migrated = migrated | replaceString(configLines[i], ";PreValueUse = true", ";PreValueUse = false"); // Set it to its default value
  616. migrated = migrated | replaceString(configLines[i], ";PreValueUse", "PreValueUse"); // Enable it
  617. migrated = migrated | replaceString(configLines[i], ";ErrorMessage = true", ";ErrorMessage = false"); // Set it to its default value
  618. migrated = migrated | replaceString(configLines[i], ";ErrorMessage", "ErrorMessage"); // Enable it
  619. migrated = migrated | replaceString(configLines[i], ";CheckDigitIncreaseConsistency = true", ";CheckDigitIncreaseConsistency = false"); // Set it to its default value
  620. migrated = migrated | replaceString(configLines[i], ";CheckDigitIncreaseConsistency", "CheckDigitIncreaseConsistency"); // Enable it
  621. }
  622. }
  623. else if (section == "[MQTT]") {
  624. migrated = migrated | replaceString(configLines[i], "SetRetainFlag", "RetainMessages"); // First rename it, enable it with its default value
  625. migrated = migrated | replaceString(configLines[i], ";RetainMessages = true", ";RetainMessages = false"); // Set it to its default value
  626. migrated = migrated | replaceString(configLines[i], ";RetainMessages", "RetainMessages"); // Enable it
  627. migrated = migrated | replaceString(configLines[i], ";HomeassistantDiscovery = true", ";HomeassistantDiscovery = false"); // Set it to its default value
  628. migrated = migrated | replaceString(configLines[i], ";HomeassistantDiscovery", "HomeassistantDiscovery"); // Enable it
  629. // only if string starts with "Topic" (Was the naming in very old version)
  630. if (configLines[i].rfind("Topic", 0) != std::string::npos) {
  631. migrated = migrated | replaceString(configLines[i], "Topic", "MainTopic");
  632. }
  633. }
  634. else if (section == "[InfluxDB]") {
  635. /* Fieldname has a <NUMBER> as prefix! */
  636. if (isInString(configLines[i], "Fieldname")) {
  637. // It is the parameter "Fieldname"
  638. migrated = migrated | replaceString(configLines[i], "Fieldname", "Field"); // Rename it to Field
  639. }
  640. }
  641. else if (section == "[InfluxDBv2]") {
  642. /* Fieldname has a <NUMBER> as prefix! */
  643. if (isInString(configLines[i], "Fieldname")) {
  644. // It is the parameter "Fieldname"
  645. migrated = migrated | replaceString(configLines[i], "Fieldname", "Field"); // Rename it to Field
  646. }
  647. /* Database got renamed to Bucket! */
  648. else if (isInString(configLines[i], "Database")) {
  649. // It is the parameter "Database"
  650. migrated = migrated | replaceString(configLines[i], "Database", "Bucket"); // Rename it to Bucket
  651. }
  652. }
  653. else if (section == "[GPIO]") {
  654. }
  655. else if (section == "[DataLogging]") {
  656. migrated = migrated | replaceString(configLines[i], "DataLogRetentionInDays", "DataFilesRetention");
  657. /* DataLogActive is true by default! */
  658. migrated = migrated | replaceString(configLines[i], ";DataLogActive = false", ";DataLogActive = true"); // Set it to its default value
  659. migrated = migrated | replaceString(configLines[i], ";DataLogActive", "DataLogActive"); // Enable it
  660. }
  661. else if (section == "[AutoTimer]") {
  662. migrated = migrated | replaceString(configLines[i], "Intervall", "Interval");
  663. migrated = migrated | replaceString(configLines[i], "Autostart", ";UNUSED_PARAMETER"); // This parameter is no longer used
  664. }
  665. else if (section == "[Debug]") {
  666. migrated = migrated | replaceString(configLines[i], "Logfile ", "LogLevel "); // Whitespace needed so it does not match `LogfileRetentionInDays`
  667. /* LogLevel (resp. LogFile) was originally a boolean, but we switched it to an int
  668. * For both cases (true/false), we set it to level 2 (WARNING) */
  669. migrated = migrated | replaceString(configLines[i], "LogLevel = true", "LogLevel = 2");
  670. migrated = migrated | replaceString(configLines[i], "LogLevel = false", "LogLevel = 2");
  671. migrated = migrated | replaceString(configLines[i], "LogfileRetentionInDays", "LogfilesRetention");
  672. }
  673. else if (section == "[System]") {
  674. migrated = migrated | replaceString(configLines[i], "RSSIThreashold", "RSSIThreshold");
  675. migrated = migrated | replaceString(configLines[i], "AutoAdjustSummertime", ";UNUSED_PARAMETER"); // This parameter is no longer used
  676. migrated = migrated | replaceString(configLines[i], ";SetupMode = true", ";SetupMode = false"); // Set it to its default value
  677. migrated = migrated | replaceString(configLines[i], ";SetupMode", "SetupMode"); // Enable it
  678. }
  679. }
  680. if (CamZoom_found == true) {
  681. if (CamZoomSize_value == 0) {
  682. // mode0
  683. // 1600 - 640 = 960 / 2 = max-Offset (+/-) 480
  684. // 1200 - 480 = 720 / 2 = max-Offset (+/-) 360
  685. if (CamZoomOffsetX_value > 960) {
  686. CamZoomOffsetX_value = 960;
  687. }
  688. else {
  689. CamZoomOffsetX_value = (floor((CamZoomOffsetX_value - 480) / 8) * 8);
  690. }
  691. if (CamZoomOffsetY_value > 720) {
  692. CamZoomOffsetY_value = 720;
  693. }
  694. else {
  695. CamZoomOffsetY_value = (floor((CamZoomOffsetY_value - 360) / 8) * 8);
  696. }
  697. CamZoomSize_value = 29;
  698. }
  699. else {
  700. // mode1
  701. // 800 - 640 = 160 / 2 = max-Offset (+/-) 80
  702. // 600 - 480 = 120 / 2 = max-Offset (+/-) 60
  703. if (CamZoomOffsetX_value > 160) {
  704. CamZoomOffsetX_value = 160;
  705. }
  706. else {
  707. CamZoomOffsetX_value = (floor(((CamZoomOffsetX_value - 80) * 2) / 8) * 8);
  708. }
  709. if (CamZoomOffsetY_value > 120) {
  710. CamZoomOffsetY_value = 120;
  711. }
  712. else {
  713. CamZoomOffsetY_value = (floor(((CamZoomOffsetY_value - 60) * 2) / 8) * 8);
  714. }
  715. CamZoomSize_value = 9;
  716. }
  717. if (CamZoom_lines > 0) {
  718. if (CamZoom_value) {
  719. configLines[CamZoom_lines] = ("CamZoom = true");
  720. }
  721. else {
  722. configLines[CamZoom_lines] = ("CamZoom = false");
  723. }
  724. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Migrated Configfile line 'Zoom' to 'CamZoom'");
  725. migrated = true;
  726. }
  727. if (CamZoomSize_lines > 0) {
  728. configLines[CamZoomSize_lines] = ("CamZoomSize = " + std::to_string(CamZoomSize_value));
  729. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Migrated Configfile line 'ZoomMode' to 'CamZoomSize'");
  730. migrated = true;
  731. }
  732. if (CamZoomOffsetX_lines > 0) {
  733. configLines[CamZoomOffsetX_lines] = ("CamZoomOffsetX = " + std::to_string(CamZoomOffsetX_value));
  734. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Migrated Configfile line 'ZoomOffsetX' to 'CamZoomOffsetX'");
  735. migrated = true;
  736. }
  737. if (CamZoomOffsetY_lines > 0) {
  738. configLines[CamZoomOffsetY_lines] = ("CamZoomOffsetY = " + std::to_string(CamZoomOffsetY_value));
  739. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Migrated Configfile line 'ZoomOffsetY' to 'CamZoomOffsetY'");
  740. migrated = true;
  741. }
  742. }
  743. if (migrated) {
  744. // At least one replacement happened
  745. if (!RenameFile(CONFIG_FILE, CONFIG_FILE_BACKUP)) {
  746. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to create backup of Config file!");
  747. return;
  748. }
  749. FILE *pfile = fopen(CONFIG_FILE, "w");
  750. for (int i = 0; i < configLines.size(); i++) {
  751. if (!isInString(configLines[i], ";UNUSED_PARAMETER")) {
  752. fwrite(configLines[i].c_str(), configLines[i].length(), 1, pfile);
  753. fwrite("\n", 1, 1, pfile);
  754. }
  755. }
  756. fclose(pfile);
  757. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Config file migrated. Saved backup to " + string(CONFIG_FILE_BACKUP));
  758. }
  759. }
  760. std::vector<std::string> splitString(const std::string& str) {
  761. std::vector<std::string> tokens;
  762. std::stringstream ss(str);
  763. std::string token;
  764. while (std::getline(ss, token, '\n')) {
  765. tokens.push_back(token);
  766. }
  767. return tokens;
  768. }
  769. /*bool replace_all(std::string& s, std::string const& toReplace, std::string const& replaceWith) {
  770. std::string buf;
  771. std::size_t pos = 0;
  772. std::size_t prevPos;
  773. bool found = false;
  774. // Reserves rough estimate of final size of string.
  775. buf.reserve(s.size());
  776. while (true) {
  777. prevPos = pos;
  778. pos = s.find(toReplace, pos);
  779. if (pos == std::string::npos) {
  780. break;
  781. }
  782. found = true;
  783. buf.append(s, prevPos, pos - prevPos);
  784. buf += replaceWith;
  785. pos += toReplace.size();
  786. }
  787. buf.append(s, prevPos, s.size() - prevPos);
  788. s.swap(buf);
  789. return found;
  790. }*/
  791. bool setCpuFrequency(void) {
  792. ConfigFile configFile = ConfigFile(CONFIG_FILE);
  793. string cpuFrequency = "160";
  794. esp_pm_config_t pm_config;
  795. if (!configFile.ConfigFileExists()){
  796. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "No ConfigFile defined - exit setCpuFrequency()!");
  797. return false;
  798. }
  799. std::vector<std::string> splitted;
  800. std::string line = "";
  801. bool disabledLine = false;
  802. bool eof = false;
  803. /* Load config from config file */
  804. while ((!configFile.GetNextParagraph(line, disabledLine, eof) ||
  805. (line.compare("[System]") != 0)) && !eof) {}
  806. if (eof) {
  807. return false;
  808. }
  809. if (disabledLine) {
  810. return false;
  811. }
  812. while (configFile.getNextLine(&line, disabledLine, eof) &&
  813. !configFile.isNewParagraph(line)) {
  814. splitted = ZerlegeZeile(line);
  815. if (toUpper(splitted[0]) == "CPUFREQUENCY") {
  816. if (splitted.size() < 2) {
  817. cpuFrequency = 160;
  818. }
  819. else {
  820. cpuFrequency = splitted[1];
  821. }
  822. break;
  823. }
  824. }
  825. if (esp_pm_get_configuration(&pm_config) != ESP_OK) {
  826. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to read CPU Frequency!");
  827. return false;
  828. }
  829. if (cpuFrequency == "160") { // 160 is the default
  830. // No change needed
  831. }
  832. else if (cpuFrequency == "240") {
  833. pm_config.max_freq_mhz = 240;
  834. pm_config.min_freq_mhz = pm_config.max_freq_mhz;
  835. if (esp_pm_configure(&pm_config) != ESP_OK) {
  836. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to set new CPU frequency!");
  837. return false;
  838. }
  839. }
  840. else {
  841. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unknown CPU frequency: " + cpuFrequency + "! "
  842. "It must be 160 or 240!");
  843. return false;
  844. }
  845. if (esp_pm_get_configuration(&pm_config) == ESP_OK) {
  846. LogFile.WriteToFile(ESP_LOG_INFO, TAG, string("CPU frequency: ") + to_string(pm_config.max_freq_mhz) + " MHz");
  847. }
  848. return true;
  849. }