main.cpp 46 KB

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