main.cpp 43 KB

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