main.cpp 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005
  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 ret;
  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. // Init external PSRAM
  214. // ********************************************
  215. esp_err_t PSRAMStatus = esp_psram_init();
  216. if (PSRAMStatus == ESP_FAIL) { // ESP_FAIL -> Failed to init PSRAM
  217. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "PSRAM init failed (" + std::to_string(PSRAMStatus) + ")! PSRAM not found or defective");
  218. setSystemStatusFlag(SYSTEM_STATUS_PSRAM_BAD);
  219. StatusLED(PSRAM_INIT, 1, true);
  220. }
  221. else { // ESP_OK -> PSRAM init OK --> continue to check PSRAM size
  222. size_t psram_size = esp_psram_get_size(); // size_t psram_size = esp_psram_get_size(); // comming in IDF 5.0
  223. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "PSRAM size: " + std::to_string(psram_size) + " byte (" + std::to_string(psram_size/1024/1024) +
  224. "MB / " + std::to_string(psram_size/1024/1024*8) + "MBit)");
  225. // Check PSRAM size
  226. // ********************************************
  227. if (psram_size < (4*1024*1024)) { // PSRAM is below 4 MBytes (32Mbit)
  228. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "PSRAM size >= 4MB (32Mbit) is mandatory to run this application");
  229. setSystemStatusFlag(SYSTEM_STATUS_PSRAM_BAD);
  230. StatusLED(PSRAM_INIT, 2, true);
  231. }
  232. else { // PSRAM size OK --> continue to check heap size
  233. size_t _hsize = getESPHeapSize();
  234. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Total heap: " + std::to_string(_hsize) + " byte");
  235. // Check heap memory
  236. // ********************************************
  237. 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)
  238. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Total heap >= 4000000 byte is mandatory to run this application");
  239. setSystemStatusFlag(SYSTEM_STATUS_HEAP_TOO_SMALL);
  240. StatusLED(PSRAM_INIT, 3, true);
  241. }
  242. else { // HEAP size OK --> continue to reserve shared memory block and check camera init
  243. /* Allocate static PSRAM memory regions */
  244. if (! reserve_psram_shared_region()) {
  245. setSystemStatusFlag(SYSTEM_STATUS_HEAP_TOO_SMALL);
  246. StatusLED(PSRAM_INIT, 3, true);
  247. }
  248. else { // OK
  249. // Init camera
  250. // ********************************************
  251. PowerResetCamera();
  252. esp_err_t camStatus = Camera.InitCam();
  253. Camera.LightOnOff(false);
  254. xDelay = 2000 / portTICK_PERIOD_MS;
  255. ESP_LOGD(TAG, "After camera initialization: sleep for: %ldms", (long) xDelay * CONFIG_FREERTOS_HZ/portTICK_PERIOD_MS);
  256. vTaskDelay( xDelay );
  257. // Check camera init
  258. // ********************************************
  259. if (camStatus != ESP_OK) { // Camera init failed, retry to init
  260. char camStatusHex[33];
  261. sprintf(camStatusHex,"0x%02x", camStatus);
  262. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Camera init failed (" + std::string(camStatusHex) + "), retrying...");
  263. PowerResetCamera();
  264. camStatus = Camera.InitCam();
  265. Camera.LightOnOff(false);
  266. xDelay = 2000 / portTICK_PERIOD_MS;
  267. ESP_LOGD(TAG, "After camera initialization: sleep for: %ldms", (long) xDelay * CONFIG_FREERTOS_HZ/portTICK_PERIOD_MS);
  268. vTaskDelay( xDelay );
  269. if (camStatus != ESP_OK) { // Camera init failed again
  270. sprintf(camStatusHex,"0x%02x", camStatus);
  271. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Camera init failed (" + std::string(camStatusHex) +
  272. ")! Check camera module and/or proper electrical connection");
  273. setSystemStatusFlag(SYSTEM_STATUS_CAM_BAD);
  274. StatusLED(CAM_INIT, 1, true);
  275. }
  276. }
  277. else { // ESP_OK -> Camera init OK --> continue to perform camera framebuffer check
  278. // Camera framebuffer check
  279. // ********************************************
  280. if (!Camera.testCamera()) {
  281. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Camera framebuffer check failed");
  282. // Easiest would be to simply restart here and try again,
  283. // how ever there seem to be systems where it fails at startup but still work correctly later.
  284. // Therefore we treat it still as successed! */
  285. setSystemStatusFlag(SYSTEM_STATUS_CAM_FB_BAD);
  286. StatusLED(CAM_INIT, 2, false);
  287. }
  288. Camera.LightOnOff(false); // make sure flashlight is off before start of flow
  289. // Print camera infos
  290. // ********************************************
  291. char caminfo[50];
  292. sensor_t * s = esp_camera_sensor_get();
  293. 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);
  294. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Camera info: " + std::string(caminfo));
  295. }
  296. }
  297. }
  298. }
  299. }
  300. // SD card: basic R/W check
  301. // ********************************************
  302. int iSDCardStatus = SDCardCheckRW();
  303. if (iSDCardStatus < 0) {
  304. if (iSDCardStatus <= -1 && iSDCardStatus >= -2) { // write error
  305. StatusLED(SDCARD_CHECK, 1, true);
  306. }
  307. else if (iSDCardStatus <= -3 && iSDCardStatus >= -5) { // read error
  308. StatusLED(SDCARD_CHECK, 2, true);
  309. }
  310. else if (iSDCardStatus == -6) { // delete error
  311. StatusLED(SDCARD_CHECK, 3, true);
  312. }
  313. setSystemStatusFlag(SYSTEM_STATUS_SDCARD_CHECK_BAD); // reduced web interface going to be loaded
  314. }
  315. // Migrate parameter in config.ini to new naming (firmware 15.0 and newer)
  316. // ********************************************
  317. migrateConfiguration();
  318. // Init time (as early as possible, but SD card needs to be initialized)
  319. // ********************************************
  320. setupTime(); // NTP time service: Status of time synchronization will be checked after every round (server_tflite.cpp)
  321. // Set CPU Frequency
  322. // ********************************************
  323. setCpuFrequency();
  324. // SD card: Create further mandatory directories (if not already existing)
  325. // Correct creation of these folders will be checked with function "SDCardCheckFolderFilePresence"
  326. // ********************************************
  327. MakeDir("/sdcard/firmware"); // mandatory for OTA firmware update
  328. MakeDir("/sdcard/img_tmp"); // mandatory for setting up alignment marks
  329. MakeDir("/sdcard/demo"); // mandatory for demo mode
  330. MakeDir("/sdcard/config/certs"); // mandatory for mqtt certificates
  331. // Check for updates
  332. // ********************************************
  333. CheckOTAUpdate();
  334. CheckUpdate();
  335. // Start SoftAP for initial remote setup
  336. // Note: Start AP if no wlan.ini and/or config.ini available, e.g. SD card empty; function does not exit anymore until reboot
  337. // ********************************************
  338. #ifdef ENABLE_SOFTAP
  339. CheckStartAPMode();
  340. #endif
  341. // SD card: Check presence of some mandatory folders / files
  342. // ********************************************
  343. if (!SDCardCheckFolderFilePresence()) {
  344. StatusLED(SDCARD_CHECK, 4, true);
  345. setSystemStatusFlag(SYSTEM_STATUS_FOLDER_CHECK_BAD); // reduced web interface going to be loaded
  346. }
  347. // Check version information
  348. // ********************************************
  349. std::string versionFormated = getFwVersion() + ", Date/Time: " + std::string(BUILD_TIME) + \
  350. ", Web UI: " + getHTMLversion();
  351. if (std::string(GIT_TAG) != "") { // We are on a tag, add it as prefix
  352. versionFormated = "Tag: '" + std::string(GIT_TAG) + "', " + versionFormated;
  353. }
  354. LogFile.WriteToFile(ESP_LOG_INFO, TAG, versionFormated);
  355. if (getHTMLcommit().substr(0, 7) == "?")
  356. LogFile.WriteToFile(ESP_LOG_WARN, TAG, std::string("Failed to read file html/version.txt to parse Web UI version"));
  357. if (getHTMLcommit().substr(0, 7) != std::string(GIT_REV).substr(0, 7)) { // Compare the first 7 characters of both hashes
  358. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Web UI version (" + getHTMLcommit() + ") does not match firmware version (" + std::string(GIT_REV) + ")");
  359. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Recommendation: Repeat installation using AI-on-the-edge-device__update__*.zip");
  360. }
  361. // Check reboot reason
  362. // ********************************************
  363. CheckIsPlannedReboot();
  364. if (!getIsPlannedReboot() && (esp_reset_reason() == ESP_RST_PANIC)) { // If system reboot was not triggered by user and reboot was caused by execption
  365. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Reset reason: " + getResetReason());
  366. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Device was rebooted due to a software exception! Log level is set to DEBUG until the next reboot. "
  367. "Flow init is delayed by 5 minutes to check the logs or do an OTA update");
  368. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Keep device running until crash occurs again and check logs after device is up again");
  369. LogFile.setLogLevel(ESP_LOG_DEBUG);
  370. }
  371. else {
  372. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Reset reason: " + getResetReason());
  373. }
  374. #ifdef HEAP_TRACING_MAIN_START
  375. ESP_ERROR_CHECK( heap_trace_stop() );
  376. heap_trace_dump();
  377. #endif
  378. #ifdef HEAP_TRACING_MAIN_WIFI
  379. ESP_ERROR_CHECK( heap_trace_start(HEAP_TRACE_LEAKS) );
  380. #endif
  381. // Read WLAN parameter and start WIFI
  382. // ********************************************
  383. int iWLANStatus = LoadWlanFromFile(WLAN_CONFIG_FILE);
  384. if (iWLANStatus == 0) {
  385. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "WLAN config loaded, init WIFI...");
  386. if (wifi_init_sta() != ESP_OK) {
  387. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "WIFI init failed. Device init aborted!");
  388. StatusLED(WLAN_INIT, 3, true);
  389. return;
  390. }
  391. init_basic_auth();
  392. }
  393. else if (iWLANStatus == -1) { // wlan.ini not available, potentially empty or content not readable
  394. StatusLED(WLAN_INIT, 1, true);
  395. return; // No way to continue without reading the wlan.ini
  396. }
  397. else if (iWLANStatus == -2) { // SSID or password not configured
  398. StatusLED(WLAN_INIT, 2, true);
  399. return; // No way to continue with empty SSID or password!
  400. }
  401. xDelay = 2000 / portTICK_PERIOD_MS;
  402. ESP_LOGD(TAG, "main: sleep for: %ldms", (long) xDelay * CONFIG_FREERTOS_HZ/portTICK_PERIOD_MS);
  403. vTaskDelay( xDelay );
  404. // manual reset the time
  405. // ********************************************
  406. if (!time_manual_reset_sync())
  407. {
  408. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Manual Time Sync failed during startup" );
  409. }
  410. // Set log level for wifi component to WARN level (default: INFO; only relevant for serial console)
  411. // ********************************************
  412. esp_log_level_set("wifi", ESP_LOG_WARN);
  413. #ifdef HEAP_TRACING_MAIN_WIFI
  414. ESP_ERROR_CHECK( heap_trace_stop() );
  415. heap_trace_dump();
  416. #endif
  417. #ifdef DEBUG_ENABLE_SYSINFO
  418. #if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL( 4, 0, 0 )
  419. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Device Info : " + get_device_info() );
  420. ESP_LOGD(TAG, "Device infos %s", get_device_info().c_str());
  421. #endif
  422. #endif //DEBUG_ENABLE_SYSINFO
  423. #ifdef USE_HIMEM_IF_AVAILABLE
  424. #ifdef DEBUG_HIMEM_MEMORY_CHECK
  425. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Himem mem check : " + himem_memory_check() );
  426. ESP_LOGD(TAG, "Himem mem check %s", himem_memory_check().c_str());
  427. #endif
  428. #endif
  429. // Print Device info
  430. // ********************************************
  431. esp_chip_info_t chipInfo;
  432. esp_chip_info(&chipInfo);
  433. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Device info: CPU cores: " + std::to_string(chipInfo.cores) +
  434. ", Chip revision: " + std::to_string(chipInfo.revision));
  435. // Print SD-Card info
  436. // ********************************************
  437. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "SD card info: Name: " + getSDCardName() + ", Capacity: " +
  438. getSDCardCapacity() + "MB, Free: " + getSDCardFreePartitionSpace() + "MB");
  439. xDelay = 2000 / portTICK_PERIOD_MS;
  440. ESP_LOGD(TAG, "main: sleep for: %ldms", (long) xDelay * CONFIG_FREERTOS_HZ/portTICK_PERIOD_MS);
  441. vTaskDelay( xDelay );
  442. // Start webserver + register handler
  443. // ********************************************
  444. ESP_LOGD(TAG, "starting servers");
  445. server = start_webserver();
  446. register_server_camera_uri(server);
  447. register_server_main_flow_task_uri(server);
  448. register_server_file_uri(server, "/sdcard");
  449. register_server_ota_sdcard_uri(server);
  450. #ifdef ENABLE_MQTT
  451. register_server_mqtt_uri(server);
  452. #endif //ENABLE_MQTT
  453. gpio_handler_create(server);
  454. ESP_LOGD(TAG, "Before reg server main");
  455. register_server_main_uri(server, "/sdcard");
  456. // Only for testing purpose
  457. //setSystemStatusFlag(SYSTEM_STATUS_CAM_FB_BAD);
  458. //setSystemStatusFlag(SYSTEM_STATUS_PSRAM_BAD);
  459. // Check main init + start TFlite task
  460. // ********************************************
  461. if (getSystemStatus() == 0) { // No error flag is set
  462. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Initialization completed successfully");
  463. InitializeFlowTask();
  464. }
  465. else if (isSetSystemStatusFlag(SYSTEM_STATUS_CAM_FB_BAD) || // Non critical errors occured, we try to continue...
  466. isSetSystemStatusFlag(SYSTEM_STATUS_NTP_BAD)) {
  467. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Initialization completed with non-critical errors!");
  468. InitializeFlowTask();
  469. }
  470. else { // Any other error is critical and makes running the flow impossible. Init is going to abort.
  471. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Initialization failed. Flow task start aborted. Loading reduced web interface...");
  472. }
  473. }
  474. void migrateConfiguration(void) {
  475. std::vector<string> splitted;
  476. bool migrated = false;
  477. bool CamZoom_found = false;
  478. int CamZoom_lines = 0;
  479. bool CamZoom_value = false;
  480. int CamZoomSize_lines = 0;
  481. int CamZoomSize_value = 0;
  482. int CamZoomOffsetX_lines = 0;
  483. int CamZoomOffsetX_value = 0;
  484. int CamZoomOffsetY_lines = 0;
  485. int CamZoomOffsetY_value = 0;
  486. if (!FileExists(CONFIG_FILE)) {
  487. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Config file seems to be missing!");
  488. return;
  489. }
  490. std::string section = "";
  491. std::ifstream ifs(CONFIG_FILE);
  492. std::string content((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
  493. /* Split config file it array of lines */
  494. std::vector<std::string> configLines = splitString(content);
  495. /* Process each line */
  496. for (int i = 0; i < configLines.size(); i++) {
  497. // ESP_LOGI(TAG, "Line %d: %s", i, configLines[i].c_str());
  498. if (configLines[i].find("[") != std::string::npos) {
  499. // Start of new section
  500. section = configLines[i];
  501. replaceString(section, ";", "", false); // Remove possible semicolon (just for the string comparison)
  502. // ESP_LOGI(TAG, "New section: %s", section.c_str());
  503. }
  504. else {
  505. splitted = ZerlegeZeile(configLines[i]);
  506. }
  507. /* Migrate parameters as needed
  508. * For the boolean parameters, we make them enabled all the time now:
  509. * 1. If they where disabled, set them to their default value
  510. * 2. Enable them
  511. * Notes:
  512. * The migration has some simplifications:
  513. * - Case Sensitiveness must be like in the initial config.ini
  514. * - No Whitespace after a semicollon
  515. * - Only one whitespace before/after the equal sign
  516. */
  517. if (section == "[MakeImage]") {
  518. migrated = migrated | replaceString(configLines[i], "[MakeImage]", "[TakeImage]"); // Rename the section itself
  519. }
  520. if (section == "[MakeImage]" || section == "[TakeImage]") {
  521. if ((isInString(configLines[i], "Brightness")) && (!isInString(configLines[i], "CamBrightness"))) {
  522. migrated = migrated | replaceString(configLines[i], "Brightness", "CamBrightness");
  523. }
  524. else if ((isInString(configLines[i], "Contrast")) && (!isInString(configLines[i], "CamContrast"))) {
  525. migrated = migrated | replaceString(configLines[i], "Contrast", "CamContrast");
  526. }
  527. else if ((isInString(configLines[i], "Saturation")) && (!isInString(configLines[i], "CamSaturation"))) {
  528. migrated = migrated | replaceString(configLines[i], "Saturation", "CamSaturation");
  529. }
  530. else if ((isInString(configLines[i], "Sharpness")) && (!isInString(configLines[i], "CamSharpness")) && (!isInString(configLines[i], "CamAutoSharpness"))) {
  531. migrated = migrated | replaceString(configLines[i], "Sharpness", "CamSharpness");
  532. }
  533. else if ((isInString(configLines[i], "Aec2")) && (!isInString(configLines[i], "CamAec")) && (!isInString(configLines[i], "CamAec2"))) {
  534. migrated = migrated | replaceString(configLines[i], "Aec2", "CamAec2");
  535. }
  536. else if ((isInString(configLines[i], "Zoom")) && (!isInString(configLines[i], "CamZoom")) && (!isInString(configLines[i], "ZoomMode")) && (!isInString(configLines[i], "ZoomOffsetX")) && (!isInString(configLines[i], "ZoomOffsetY"))) {
  537. CamZoom_lines = i;
  538. if (splitted.size() < 2) {
  539. CamZoom_value = false;
  540. }
  541. else {
  542. ESP_LOGE(TAG, "splitted[1]: %s", splitted[1].c_str());
  543. CamZoom_value = alphanumericToBoolean(splitted[1]);
  544. }
  545. CamZoom_found = true;
  546. }
  547. else if ((isInString(configLines[i], "ZoomMode")) && (!isInString(configLines[i], "CamZoom"))) {
  548. CamZoomSize_lines = i;
  549. if (splitted.size() < 2) {
  550. CamZoomSize_value = 0;
  551. }
  552. else {
  553. if (isStringNumeric(splitted[1])) {
  554. CamZoomSize_value = std::stof(splitted[1]);
  555. }
  556. else {
  557. CamZoomSize_value = 0;
  558. }
  559. }
  560. CamZoom_found = true;
  561. }
  562. else if ((isInString(configLines[i], "ZoomOffsetX")) && (!isInString(configLines[i], "CamZoom")) && (!isInString(configLines[i], "ZoomOffsetY"))) {
  563. CamZoomOffsetX_lines = i;
  564. if (splitted.size() < 2) {
  565. CamZoomOffsetX_value = 0;
  566. }
  567. else {
  568. if (isStringNumeric(splitted[1])) {
  569. CamZoomOffsetX_value = std::stof(splitted[1]);
  570. }
  571. else {
  572. CamZoomOffsetX_value = 0;
  573. }
  574. }
  575. CamZoom_found = true;
  576. }
  577. else if ((isInString(configLines[i], "ZoomOffsetY")) && (!isInString(configLines[i], "CamZoom")) && (!isInString(configLines[i], "ZoomOffsetX"))) {
  578. CamZoomOffsetY_lines = i;
  579. if (splitted.size() < 2) {
  580. CamZoomOffsetY_value = 0;
  581. }
  582. else {
  583. if (isStringNumeric(splitted[1])) {
  584. CamZoomOffsetY_value = std::stof(splitted[1]);
  585. }
  586. else {
  587. CamZoomOffsetY_value = 0;
  588. }
  589. }
  590. CamZoom_found = true;
  591. }
  592. else {
  593. migrated = migrated | replaceString(configLines[i], "LogImageLocation", "RawImagesLocation");
  594. migrated = migrated | replaceString(configLines[i], "LogfileRetentionInDays", "RawImagesRetention");
  595. migrated = migrated | replaceString(configLines[i], ";Demo = true", ";Demo = false"); // Set it to its default value
  596. migrated = migrated | replaceString(configLines[i], ";Demo", "Demo"); // Enable it
  597. migrated = migrated | replaceString(configLines[i], "ImageQuality", "CamQuality");
  598. migrated = migrated | replaceString(configLines[i], "AutoExposureLevel", "CamAeLevel");
  599. migrated = migrated | replaceString(configLines[i], "FixedExposure", "CamAec");
  600. migrated = migrated | replaceString(configLines[i], "ImageSize", ";UNUSED_PARAMETER"); // This parameter is no longer used
  601. migrated = migrated | replaceString(configLines[i], "Grayscale", ";UNUSED_PARAMETER"); // This parameter is no longer used
  602. migrated = migrated | replaceString(configLines[i], "Negative", ";UNUSED_PARAMETER"); // This parameter is no longer used
  603. }
  604. }
  605. else if (section == "[Alignment]") {
  606. migrated = migrated | replaceString(configLines[i], "InitialMirror", ";UNUSED_PARAMETER"); // This parameter is no longer used
  607. migrated = migrated | replaceString(configLines[i], ";InitialMirror", ";UNUSED_PARAMETER"); // This parameter is no longer used
  608. migrated = migrated | replaceString(configLines[i], "FlipImageSize", ";UNUSED_PARAMETER"); // This parameter is no longer used
  609. migrated = migrated | replaceString(configLines[i], ";FlipImageSize", ";UNUSED_PARAMETER"); // This parameter is no longer used
  610. }
  611. else if (section == "[Digits]") {
  612. migrated = migrated | replaceString(configLines[i], "LogImageLocation", "ROIImagesLocation");
  613. migrated = migrated | replaceString(configLines[i], "LogfileRetentionInDays", "ROIImagesRetention");
  614. }
  615. else if (section == "[Analog]") {
  616. migrated = migrated | replaceString(configLines[i], "LogImageLocation", "ROIImagesLocation");
  617. migrated = migrated | replaceString(configLines[i], "LogfileRetentionInDays", "ROIImagesRetention");
  618. migrated = migrated | replaceString(configLines[i], "ExtendedResolution", ";UNUSED_PARAMETER"); // This parameter is no longer used
  619. }
  620. else if (section == "[PostProcessing]") {
  621. /* AllowNegativeRates has a <NUMBER> as prefix! */
  622. if (isInString(configLines[i], "AllowNegativeRates") && isInString(configLines[i], ";")) {
  623. // It is the parameter "AllowNegativeRates" and it is commented out
  624. migrated = migrated | replaceString(configLines[i], "true", "false"); // Set it to its default value
  625. migrated = migrated | replaceString(configLines[i], ";", ""); // Enable it
  626. }
  627. /* IgnoreLeadingNaN has a <NUMBER> as prefix! */
  628. else if (isInString(configLines[i], "IgnoreLeadingNaN") && isInString(configLines[i], ";")) {
  629. // It is the parameter "IgnoreLeadingNaN" and it is commented out
  630. migrated = migrated | replaceString(configLines[i], "true", "false"); // Set it to its default value
  631. migrated = migrated | replaceString(configLines[i], ";", ""); // Enable it
  632. }
  633. /* ExtendedResolution has a <NUMBER> as prefix! */
  634. else if (isInString(configLines[i], "ExtendedResolution") && isInString(configLines[i], ";")) {
  635. // It is the parameter "ExtendedResolution" and it is commented out
  636. migrated = migrated | replaceString(configLines[i], "true", "false"); // Set it to its default value
  637. migrated = migrated | replaceString(configLines[i], ";", ""); // Enable it
  638. }
  639. else {
  640. migrated = migrated | replaceString(configLines[i], ";PreValueUse = true", ";PreValueUse = false"); // Set it to its default value
  641. migrated = migrated | replaceString(configLines[i], ";PreValueUse", "PreValueUse"); // Enable it
  642. migrated = migrated | replaceString(configLines[i], ";ErrorMessage = true", ";ErrorMessage = false"); // Set it to its default value
  643. migrated = migrated | replaceString(configLines[i], ";ErrorMessage", "ErrorMessage"); // Enable it
  644. migrated = migrated | replaceString(configLines[i], ";CheckDigitIncreaseConsistency = true", ";CheckDigitIncreaseConsistency = false"); // Set it to its default value
  645. migrated = migrated | replaceString(configLines[i], ";CheckDigitIncreaseConsistency", "CheckDigitIncreaseConsistency"); // Enable it
  646. }
  647. }
  648. else if (section == "[MQTT]") {
  649. migrated = migrated | replaceString(configLines[i], "SetRetainFlag", "RetainMessages"); // First rename it, enable it with its default value
  650. migrated = migrated | replaceString(configLines[i], ";RetainMessages = true", ";RetainMessages = false"); // Set it to its default value
  651. migrated = migrated | replaceString(configLines[i], ";RetainMessages", "RetainMessages"); // Enable it
  652. migrated = migrated | replaceString(configLines[i], ";HomeassistantDiscovery = true", ";HomeassistantDiscovery = false"); // Set it to its default value
  653. migrated = migrated | replaceString(configLines[i], ";HomeassistantDiscovery", "HomeassistantDiscovery"); // Enable it
  654. // only if string starts with "Topic" (Was the naming in very old version)
  655. if (configLines[i].rfind("Topic", 0) != std::string::npos) {
  656. migrated = migrated | replaceString(configLines[i], "Topic", "MainTopic");
  657. }
  658. }
  659. else if (section == "[InfluxDB]") {
  660. /* Fieldname has a <NUMBER> as prefix! */
  661. if (isInString(configLines[i], "Fieldname")) {
  662. // It is the parameter "Fieldname"
  663. migrated = migrated | replaceString(configLines[i], "Fieldname", "Field"); // Rename it to Field
  664. }
  665. }
  666. else if (section == "[InfluxDBv2]") {
  667. /* Fieldname has a <NUMBER> as prefix! */
  668. if (isInString(configLines[i], "Fieldname")) {
  669. // It is the parameter "Fieldname"
  670. migrated = migrated | replaceString(configLines[i], "Fieldname", "Field"); // Rename it to Field
  671. }
  672. /* Database got renamed to Bucket! */
  673. else if (isInString(configLines[i], "Database")) {
  674. // It is the parameter "Database"
  675. migrated = migrated | replaceString(configLines[i], "Database", "Bucket"); // Rename it to Bucket
  676. }
  677. }
  678. else if (section == "[GPIO]") {
  679. }
  680. else if (section == "[DataLogging]") {
  681. migrated = migrated | replaceString(configLines[i], "DataLogRetentionInDays", "DataFilesRetention");
  682. /* DataLogActive is true by default! */
  683. migrated = migrated | replaceString(configLines[i], ";DataLogActive = false", ";DataLogActive = true"); // Set it to its default value
  684. migrated = migrated | replaceString(configLines[i], ";DataLogActive", "DataLogActive"); // Enable it
  685. }
  686. else if (section == "[AutoTimer]") {
  687. migrated = migrated | replaceString(configLines[i], "Intervall", "Interval");
  688. migrated = migrated | replaceString(configLines[i], "Autostart", ";UNUSED_PARAMETER"); // This parameter is no longer used
  689. }
  690. else if (section == "[Debug]") {
  691. migrated = migrated | replaceString(configLines[i], "Logfile ", "LogLevel "); // Whitespace needed so it does not match `LogfileRetentionInDays`
  692. /* LogLevel (resp. LogFile) was originally a boolean, but we switched it to an int
  693. * For both cases (true/false), we set it to level 2 (WARNING) */
  694. migrated = migrated | replaceString(configLines[i], "LogLevel = true", "LogLevel = 2");
  695. migrated = migrated | replaceString(configLines[i], "LogLevel = false", "LogLevel = 2");
  696. migrated = migrated | replaceString(configLines[i], "LogfileRetentionInDays", "LogfilesRetention");
  697. }
  698. else if (section == "[System]") {
  699. migrated = migrated | replaceString(configLines[i], "RSSIThreashold", "RSSIThreshold");
  700. migrated = migrated | replaceString(configLines[i], "AutoAdjustSummertime", ";UNUSED_PARAMETER"); // This parameter is no longer used
  701. migrated = migrated | replaceString(configLines[i], ";SetupMode = true", ";SetupMode = false"); // Set it to its default value
  702. migrated = migrated | replaceString(configLines[i], ";SetupMode", "SetupMode"); // Enable it
  703. }
  704. }
  705. if (CamZoom_found == true) {
  706. if (CamZoomSize_value == 0) {
  707. // mode0
  708. // 1600 - 640 = 960 / 2 = max-Offset (+/-) 480
  709. // 1200 - 480 = 720 / 2 = max-Offset (+/-) 360
  710. if (CamZoomOffsetX_value > 960) {
  711. CamZoomOffsetX_value = 960;
  712. }
  713. else {
  714. CamZoomOffsetX_value = (floor((CamZoomOffsetX_value - 480) / 8) * 8);
  715. }
  716. if (CamZoomOffsetY_value > 720) {
  717. CamZoomOffsetY_value = 720;
  718. }
  719. else {
  720. CamZoomOffsetY_value = (floor((CamZoomOffsetY_value - 360) / 8) * 8);
  721. }
  722. CamZoomSize_value = 29;
  723. }
  724. else {
  725. // mode1
  726. // 800 - 640 = 160 / 2 = max-Offset (+/-) 80
  727. // 600 - 480 = 120 / 2 = max-Offset (+/-) 60
  728. if (CamZoomOffsetX_value > 160) {
  729. CamZoomOffsetX_value = 160;
  730. }
  731. else {
  732. CamZoomOffsetX_value = (floor(((CamZoomOffsetX_value - 80) * 2) / 8) * 8);
  733. }
  734. if (CamZoomOffsetY_value > 120) {
  735. CamZoomOffsetY_value = 120;
  736. }
  737. else {
  738. CamZoomOffsetY_value = (floor(((CamZoomOffsetY_value - 60) * 2) / 8) * 8);
  739. }
  740. CamZoomSize_value = 9;
  741. }
  742. if (CamZoom_lines > 0) {
  743. if (CamZoom_value) {
  744. configLines[CamZoom_lines] = ("CamZoom = true");
  745. }
  746. else {
  747. configLines[CamZoom_lines] = ("CamZoom = false");
  748. }
  749. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Migrated Configfile line 'Zoom' to 'CamZoom'");
  750. migrated = true;
  751. }
  752. if (CamZoomSize_lines > 0) {
  753. configLines[CamZoomSize_lines] = ("CamZoomSize = " + std::to_string(CamZoomSize_value));
  754. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Migrated Configfile line 'ZoomMode' to 'CamZoomSize'");
  755. migrated = true;
  756. }
  757. if (CamZoomOffsetX_lines > 0) {
  758. configLines[CamZoomOffsetX_lines] = ("CamZoomOffsetX = " + std::to_string(CamZoomOffsetX_value));
  759. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Migrated Configfile line 'ZoomOffsetX' to 'CamZoomOffsetX'");
  760. migrated = true;
  761. }
  762. if (CamZoomOffsetY_lines > 0) {
  763. configLines[CamZoomOffsetY_lines] = ("CamZoomOffsetY = " + std::to_string(CamZoomOffsetY_value));
  764. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Migrated Configfile line 'ZoomOffsetY' to 'CamZoomOffsetY'");
  765. migrated = true;
  766. }
  767. }
  768. if (migrated) {
  769. // At least one replacement happened
  770. if (!RenameFile(CONFIG_FILE, CONFIG_FILE_BACKUP)) {
  771. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to create backup of Config file!");
  772. return;
  773. }
  774. FILE *pfile = fopen(CONFIG_FILE, "w");
  775. for (int i = 0; i < configLines.size(); i++) {
  776. if (!isInString(configLines[i], ";UNUSED_PARAMETER")) {
  777. fwrite(configLines[i].c_str(), configLines[i].length(), 1, pfile);
  778. fwrite("\n", 1, 1, pfile);
  779. }
  780. }
  781. fclose(pfile);
  782. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Config file migrated. Saved backup to " + string(CONFIG_FILE_BACKUP));
  783. }
  784. }
  785. std::vector<std::string> splitString(const std::string& str) {
  786. std::vector<std::string> tokens;
  787. std::stringstream ss(str);
  788. std::string token;
  789. while (std::getline(ss, token, '\n')) {
  790. tokens.push_back(token);
  791. }
  792. return tokens;
  793. }
  794. /*bool replace_all(std::string& s, std::string const& toReplace, std::string const& replaceWith) {
  795. std::string buf;
  796. std::size_t pos = 0;
  797. std::size_t prevPos;
  798. bool found = false;
  799. // Reserves rough estimate of final size of string.
  800. buf.reserve(s.size());
  801. while (true) {
  802. prevPos = pos;
  803. pos = s.find(toReplace, pos);
  804. if (pos == std::string::npos) {
  805. break;
  806. }
  807. found = true;
  808. buf.append(s, prevPos, pos - prevPos);
  809. buf += replaceWith;
  810. pos += toReplace.size();
  811. }
  812. buf.append(s, prevPos, s.size() - prevPos);
  813. s.swap(buf);
  814. return found;
  815. }*/
  816. bool setCpuFrequency(void) {
  817. ConfigFile configFile = ConfigFile(CONFIG_FILE);
  818. string cpuFrequency = "160";
  819. esp_pm_config_t pm_config;
  820. if (!configFile.ConfigFileExists()){
  821. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "No ConfigFile defined - exit setCpuFrequency()!");
  822. return false;
  823. }
  824. std::vector<std::string> splitted;
  825. std::string line = "";
  826. bool disabledLine = false;
  827. bool eof = false;
  828. /* Load config from config file */
  829. while ((!configFile.GetNextParagraph(line, disabledLine, eof) ||
  830. (line.compare("[System]") != 0)) && !eof) {}
  831. if (eof || disabledLine) {
  832. return false;
  833. }
  834. while (configFile.getNextLine(&line, disabledLine, eof) &&
  835. !configFile.isNewParagraph(line)) {
  836. splitted = ZerlegeZeile(line);
  837. if (toUpper(splitted[0]) == "CPUFREQUENCY") {
  838. if (splitted.size() < 2) {
  839. cpuFrequency = "160";
  840. }
  841. else {
  842. cpuFrequency = splitted[1];
  843. }
  844. break;
  845. }
  846. }
  847. if (esp_pm_get_configuration(&pm_config) != ESP_OK) {
  848. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to read CPU Frequency!");
  849. return false;
  850. }
  851. if (cpuFrequency == "160") { // 160 is the default
  852. // No change needed
  853. }
  854. else if (cpuFrequency == "240") {
  855. pm_config.max_freq_mhz = 240;
  856. pm_config.min_freq_mhz = pm_config.max_freq_mhz;
  857. if (esp_pm_configure(&pm_config) != ESP_OK) {
  858. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to set new CPU frequency!");
  859. return false;
  860. }
  861. }
  862. else {
  863. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unknown CPU frequency: " + cpuFrequency + "! "
  864. "It must be 160 or 240!");
  865. return false;
  866. }
  867. if (esp_pm_get_configuration(&pm_config) == ESP_OK) {
  868. LogFile.WriteToFile(ESP_LOG_INFO, TAG, string("CPU frequency: ") + to_string(pm_config.max_freq_mhz) + " MHz");
  869. }
  870. return true;
  871. }