main.cpp 45 KB

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