main.cpp 43 KB

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