main.cpp 44 KB

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