main.cpp 44 KB

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