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