main.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <regex>
  5. //#include "freertos/FreeRTOS.h"
  6. //#include "freertos/task.h"
  7. //#include "freertos/event_groups.h"
  8. //#include "driver/gpio.h"
  9. //#include "sdkconfig.h"
  10. #include "esp_psram.h"
  11. #include "esp_pm.h"
  12. #include "psram.h"
  13. #include "esp_chip_info.h"
  14. // SD-Card ////////////////////
  15. //#include "nvs_flash.h"
  16. #include "esp_vfs_fat.h"
  17. //#include "sdmmc_cmd.h"
  18. #include "driver/sdmmc_host.h"
  19. //#include "driver/sdmmc_defs.h"
  20. ///////////////////////////////
  21. #include "ClassLogFile.h"
  22. #include "connect_wlan.h"
  23. #include "read_wlanini.h"
  24. #include "server_main.h"
  25. #include "MainFlowControl.h"
  26. #include "server_file.h"
  27. #include "server_ota.h"
  28. #include "time_sntp.h"
  29. #include "configFile.h"
  30. //#include "ClassControllCamera.h"
  31. #include "server_main.h"
  32. #include "server_camera.h"
  33. #ifdef ENABLE_MQTT
  34. #include "server_mqtt.h"
  35. #endif //ENABLE_MQTT
  36. #include "Helper.h"
  37. #include "statusled.h"
  38. #include "sdcard_check.h"
  39. #include "../../include/defines.h"
  40. //#include "server_GPIO.h"
  41. #ifdef ENABLE_SOFTAP
  42. #include "softAP.h"
  43. #endif //ENABLE_SOFTAP
  44. #ifdef DISABLE_BROWNOUT_DETECTOR
  45. #include "soc/soc.h"
  46. #include "soc/rtc_cntl_reg.h"
  47. #endif
  48. #ifdef DEBUG_ENABLE_SYSINFO
  49. #if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL( 4, 0, 0 )
  50. #include "esp_sys.h"
  51. #endif
  52. #endif //DEBUG_ENABLE_SYSINFO
  53. // define `gpio_pad_select_gpip` for newer versions of IDF
  54. #if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 3, 0))
  55. #include "esp_rom_gpio.h"
  56. #define gpio_pad_select_gpio esp_rom_gpio_pad_select_gpio
  57. #endif
  58. #ifdef USE_HIMEM_IF_AVAILABLE
  59. #include "esp32/himem.h"
  60. #ifdef DEBUG_HIMEM_MEMORY_CHECK
  61. #include "himem_memory_check.h"
  62. #endif
  63. #endif
  64. //#ifdef CONFIG_HEAP_TRACING_STANDALONE
  65. #if defined HEAP_TRACING_MAIN_WIFI || defined HEAP_TRACING_MAIN_START
  66. #include <esp_heap_trace.h>
  67. #define NUM_RECORDS 300
  68. static heap_trace_record_t trace_record[NUM_RECORDS]; // This buffer must be in internal RAM
  69. #endif
  70. extern const char* GIT_TAG;
  71. extern const char* GIT_REV;
  72. extern const char* GIT_BRANCH;
  73. extern const char* BUILD_TIME;
  74. extern std::string getFwVersion(void);
  75. extern std::string getHTMLversion(void);
  76. extern std::string getHTMLcommit(void);
  77. std::vector<std::string> splitString(const std::string& str);
  78. void migrateConfiguration(void);
  79. bool setCpuFrequency(void);
  80. static const char *TAG = "MAIN";
  81. bool Init_NVS_SDCard()
  82. {
  83. esp_err_t ret = nvs_flash_init();
  84. if (ret == ESP_ERR_NVS_NO_FREE_PAGES) {
  85. ESP_ERROR_CHECK(nvs_flash_erase());
  86. ret = nvs_flash_init();
  87. }
  88. ESP_LOGD(TAG, "Using SDMMC peripheral");
  89. sdmmc_host_t host = SDMMC_HOST_DEFAULT();
  90. // This initializes the slot without card detect (CD) and write protect (WP) signals.
  91. // Modify slot_config.gpio_cd and slot_config.gpio_wp if your board has these signals.
  92. sdmmc_slot_config_t slot_config = SDMMC_SLOT_CONFIG_DEFAULT();
  93. // To use 1-line SD mode, uncomment the following line:
  94. #ifdef __SD_USE_ONE_LINE_MODE__
  95. slot_config.width = 1;
  96. #endif
  97. // GPIOs 15, 2, 4, 12, 13 should have external 10k pull-ups.
  98. // Internal pull-ups are not sufficient. However, enabling internal pull-ups
  99. // does make a difference some boards, so we do that here.
  100. gpio_set_pull_mode(GPIO_NUM_15, GPIO_PULLUP_ONLY); // CMD, needed in 4- and 1- line modes
  101. gpio_set_pull_mode(GPIO_NUM_2, GPIO_PULLUP_ONLY); // D0, needed in 4- and 1-line modes
  102. #ifndef __SD_USE_ONE_LINE_MODE__
  103. gpio_set_pull_mode(GPIO_NUM_4, GPIO_PULLUP_ONLY); // D1, needed in 4-line mode only
  104. gpio_set_pull_mode(GPIO_NUM_12, GPIO_PULLUP_ONLY); // D2, needed in 4-line mode only
  105. #endif
  106. gpio_set_pull_mode(GPIO_NUM_13, GPIO_PULLUP_ONLY); // D3, needed in 4- and 1-line modes
  107. // Options for mounting the filesystem.
  108. // If format_if_mount_failed is set to true, SD card will be partitioned and
  109. // formatted in case when mounting fails.
  110. esp_vfs_fat_sdmmc_mount_config_t mount_config = {
  111. .format_if_mount_failed = false,
  112. .max_files = 12, // previously -> 2022-09-21: 5, 2023-01-02: 7
  113. .allocation_unit_size = 16 * 1024
  114. };
  115. sdmmc_card_t* card;
  116. // Use settings defined above to initialize SD card and mount FAT filesystem.
  117. // Note: esp_vfs_fat_sdmmc_mount is an all-in-one convenience function.
  118. // Please check its source code and implement error recovery when developing
  119. // production applications.
  120. ret = esp_vfs_fat_sdmmc_mount("/sdcard", &host, &slot_config, &mount_config, &card);
  121. if (ret != ESP_OK) {
  122. if (ret == ESP_FAIL) {
  123. ESP_LOGE(TAG, "Failed to mount FAT filesystem on SD card. Check SD card filesystem (only FAT supported) or try another card");
  124. StatusLED(SDCARD_INIT, 1, true);
  125. }
  126. else if (ret == 263) { // Error code: 0x107 --> usually: SD not found
  127. ESP_LOGE(TAG, "SD card init failed. Check if SD card is properly inserted into SD card slot or try another card");
  128. StatusLED(SDCARD_INIT, 2, true);
  129. }
  130. else {
  131. ESP_LOGE(TAG, "SD card init failed. Check error code or try another card");
  132. StatusLED(SDCARD_INIT, 3, true);
  133. }
  134. return false;
  135. }
  136. //sdmmc_card_print_info(stdout, card); // With activated CONFIG_NEWLIB_NANO_FORMAT --> capacity not printed correctly anymore
  137. SaveSDCardInfo(card);
  138. return true;
  139. }
  140. extern "C" void app_main(void)
  141. {
  142. //#ifdef CONFIG_HEAP_TRACING_STANDALONE
  143. #if defined HEAP_TRACING_MAIN_WIFI || defined HEAP_TRACING_MAIN_START
  144. //register a buffer to record the memory trace
  145. ESP_ERROR_CHECK( heap_trace_init_standalone(trace_record, NUM_RECORDS) );
  146. #endif
  147. TickType_t xDelay;
  148. #ifdef DISABLE_BROWNOUT_DETECTOR
  149. WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); //disable brownout detector
  150. #endif
  151. #ifdef HEAP_TRACING_MAIN_START
  152. ESP_ERROR_CHECK( heap_trace_start(HEAP_TRACE_LEAKS) );
  153. #endif
  154. // ********************************************
  155. // Highlight start of app_main
  156. // ********************************************
  157. ESP_LOGI(TAG, "\n\n\n\n================ Start app_main =================");
  158. // Init SD card
  159. // ********************************************
  160. if (!Init_NVS_SDCard())
  161. {
  162. ESP_LOGE(TAG, "Device init aborted!");
  163. return; // No way to continue without working SD card!
  164. }
  165. // SD card: Create log directories (if not already existing)
  166. // ********************************************
  167. LogFile.CreateLogDirectories(); // mandatory for logging + image saving
  168. // ********************************************
  169. // Highlight start of logfile logging
  170. // Default Log Level: INFO -> Everything which needs to be logged during boot should be have level INFO, WARN OR ERROR
  171. // ********************************************
  172. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "=================================================");
  173. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "==================== Start ======================");
  174. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "=================================================");
  175. // Init external PSRAM
  176. // ********************************************
  177. esp_err_t PSRAMStatus = esp_psram_init();
  178. if (PSRAMStatus != ESP_OK) { // ESP_FAIL -> Failed to init PSRAM
  179. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "PSRAM init failed (" + std::to_string(PSRAMStatus) + ")! PSRAM not found or defective");
  180. setSystemStatusFlag(SYSTEM_STATUS_PSRAM_BAD);
  181. StatusLED(PSRAM_INIT, 1, true);
  182. }
  183. else { // ESP_OK -> PSRAM init OK --> continue to check PSRAM size
  184. size_t psram_size = esp_psram_get_size(); // size_t psram_size = esp_psram_get_size(); // comming in IDF 5.0
  185. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "PSRAM size: " + std::to_string(psram_size) + " byte (" + std::to_string(psram_size/1024/1024) +
  186. "MB / " + std::to_string(psram_size/1024/1024*8) + "MBit)");
  187. // Check PSRAM size
  188. // ********************************************
  189. if (psram_size < (4*1024*1024)) { // PSRAM is below 4 MBytes (32Mbit)
  190. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "PSRAM size >= 4MB (32Mbit) is mandatory to run this application");
  191. setSystemStatusFlag(SYSTEM_STATUS_PSRAM_BAD);
  192. StatusLED(PSRAM_INIT, 2, true);
  193. }
  194. else { // PSRAM size OK --> continue to check heap size
  195. size_t _hsize = getESPHeapSize();
  196. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Total heap: " + std::to_string(_hsize) + " byte");
  197. // Check heap memory
  198. // ********************************************
  199. 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)
  200. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Total heap >= 4000000 byte is mandatory to run this application");
  201. setSystemStatusFlag(SYSTEM_STATUS_HEAP_TOO_SMALL);
  202. StatusLED(PSRAM_INIT, 3, true);
  203. }
  204. else { // HEAP size OK --> continue to reserve shared memory block and check camera init
  205. /* Allocate static PSRAM memory regions */
  206. if (! reserve_psram_shared_region()) {
  207. setSystemStatusFlag(SYSTEM_STATUS_HEAP_TOO_SMALL);
  208. StatusLED(PSRAM_INIT, 3, true);
  209. }
  210. else { // OK
  211. // Init camera
  212. // ********************************************
  213. PowerResetCamera();
  214. esp_err_t camStatus = Camera.InitCam();
  215. Camera.LightOnOff(false);
  216. xDelay = 2000 / portTICK_PERIOD_MS;
  217. ESP_LOGD(TAG, "After camera initialization: sleep for: %ldms", (long) xDelay * CONFIG_FREERTOS_HZ/portTICK_PERIOD_MS);
  218. vTaskDelay( xDelay );
  219. // Check camera init
  220. // ********************************************
  221. if (camStatus != ESP_OK) { // Camera init failed, retry to init
  222. char camStatusHex[33];
  223. sprintf(camStatusHex,"0x%02x", camStatus);
  224. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Camera init failed (" + std::string(camStatusHex) + "), retrying...");
  225. PowerResetCamera();
  226. camStatus = Camera.InitCam();
  227. Camera.LightOnOff(false);
  228. xDelay = 2000 / portTICK_PERIOD_MS;
  229. ESP_LOGD(TAG, "After camera initialization: sleep for: %ldms", (long) xDelay * CONFIG_FREERTOS_HZ/portTICK_PERIOD_MS);
  230. vTaskDelay( xDelay );
  231. if (camStatus != ESP_OK) { // Camera init failed again
  232. sprintf(camStatusHex,"0x%02x", camStatus);
  233. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Camera init failed (" + std::string(camStatusHex) +
  234. ")! Check camera module and/or proper electrical connection");
  235. setSystemStatusFlag(SYSTEM_STATUS_CAM_BAD);
  236. StatusLED(CAM_INIT, 1, true);
  237. }
  238. }
  239. else { // ESP_OK -> Camera init OK --> continue to perform camera framebuffer check
  240. // Camera framebuffer check
  241. // ********************************************
  242. if (!Camera.testCamera()) {
  243. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Camera framebuffer check failed");
  244. // Easiest would be to simply restart here and try again,
  245. // how ever there seem to be systems where it fails at startup but still work correctly later.
  246. // Therefore we treat it still as successed! */
  247. setSystemStatusFlag(SYSTEM_STATUS_CAM_FB_BAD);
  248. StatusLED(CAM_INIT, 2, false);
  249. }
  250. Camera.LightOnOff(false); // make sure flashlight is off before start of flow
  251. // Print camera infos
  252. // ********************************************
  253. char caminfo[50];
  254. sensor_t * s = esp_camera_sensor_get();
  255. 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);
  256. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Camera info: " + std::string(caminfo));
  257. }
  258. }
  259. }
  260. }
  261. }
  262. // SD card: basic R/W check
  263. // ********************************************
  264. int iSDCardStatus = SDCardCheckRW();
  265. if (iSDCardStatus < 0) {
  266. if (iSDCardStatus <= -1 && iSDCardStatus >= -2) { // write error
  267. StatusLED(SDCARD_CHECK, 1, true);
  268. }
  269. else if (iSDCardStatus <= -3 && iSDCardStatus >= -5) { // read error
  270. StatusLED(SDCARD_CHECK, 2, true);
  271. }
  272. else if (iSDCardStatus == -6) { // delete error
  273. StatusLED(SDCARD_CHECK, 3, true);
  274. }
  275. setSystemStatusFlag(SYSTEM_STATUS_SDCARD_CHECK_BAD); // reduced web interface going to be loaded
  276. }
  277. // Migrate parameter in config.ini to new naming (firmware 15.0 and newer)
  278. // ********************************************
  279. migrateConfiguration();
  280. // Init time (as early as possible, but SD card needs to be initialized)
  281. // ********************************************
  282. setupTime(); // NTP time service: Status of time synchronization will be checked after every round (server_tflite.cpp)
  283. // Set CPU Frequency
  284. // ********************************************
  285. setCpuFrequency();
  286. // SD card: Create further mandatory directories (if not already existing)
  287. // Correct creation of these folders will be checked with function "SDCardCheckFolderFilePresence"
  288. // ********************************************
  289. MakeDir("/sdcard/firmware"); // mandatory for OTA firmware update
  290. MakeDir("/sdcard/img_tmp"); // mandatory for setting up alignment marks
  291. MakeDir("/sdcard/demo"); // mandatory for demo mode
  292. // Check for updates
  293. // ********************************************
  294. CheckOTAUpdate();
  295. CheckUpdate();
  296. // Start SoftAP for initial remote setup
  297. // Note: Start AP if no wlan.ini and/or config.ini available, e.g. SD card empty; function does not exit anymore until reboot
  298. // ********************************************
  299. #ifdef ENABLE_SOFTAP
  300. CheckStartAPMode();
  301. #endif
  302. // SD card: Check presence of some mandatory folders / files
  303. // ********************************************
  304. if (!SDCardCheckFolderFilePresence()) {
  305. StatusLED(SDCARD_CHECK, 4, true);
  306. setSystemStatusFlag(SYSTEM_STATUS_FOLDER_CHECK_BAD); // reduced web interface going to be loaded
  307. }
  308. // Check version information
  309. // ********************************************
  310. std::string versionFormated = getFwVersion() + ", Date/Time: " + std::string(BUILD_TIME) + \
  311. ", Web UI: " + getHTMLversion();
  312. if (std::string(GIT_TAG) != "") { // We are on a tag, add it as prefix
  313. versionFormated = "Tag: '" + std::string(GIT_TAG) + "', " + versionFormated;
  314. }
  315. LogFile.WriteToFile(ESP_LOG_INFO, TAG, versionFormated);
  316. if (getHTMLcommit().substr(0, 7) == "?")
  317. LogFile.WriteToFile(ESP_LOG_WARN, TAG, std::string("Failed to read file html/version.txt to parse Web UI version"));
  318. if (getHTMLcommit().substr(0, 7) != std::string(GIT_REV).substr(0, 7)) { // Compare the first 7 characters of both hashes
  319. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Web UI version (" + getHTMLcommit() + ") does not match firmware version (" + std::string(GIT_REV) + ")");
  320. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Recommendation: Repeat installation using AI-on-the-edge-device__update__*.zip");
  321. }
  322. // Check reboot reason
  323. // ********************************************
  324. CheckIsPlannedReboot();
  325. if (!getIsPlannedReboot() && (esp_reset_reason() == ESP_RST_PANIC)) { // If system reboot was not triggered by user and reboot was caused by execption
  326. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Reset reason: " + getResetReason());
  327. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Device was rebooted due to a software exception! Log level is set to DEBUG until the next reboot. "
  328. "Flow init is delayed by 5 minutes to check the logs or do an OTA update");
  329. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Keep device running until crash occurs again and check logs after device is up again");
  330. LogFile.setLogLevel(ESP_LOG_DEBUG);
  331. }
  332. else {
  333. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Reset reason: " + getResetReason());
  334. }
  335. #ifdef HEAP_TRACING_MAIN_START
  336. ESP_ERROR_CHECK( heap_trace_stop() );
  337. heap_trace_dump();
  338. #endif
  339. #ifdef HEAP_TRACING_MAIN_WIFI
  340. ESP_ERROR_CHECK( heap_trace_start(HEAP_TRACE_LEAKS) );
  341. #endif
  342. // Read WLAN parameter and start WIFI
  343. // ********************************************
  344. int iWLANStatus = LoadWlanFromFile(WLAN_CONFIG_FILE);
  345. if (iWLANStatus == 0) {
  346. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "WLAN config loaded, init WIFI...");
  347. if (wifi_init_sta() != ESP_OK) {
  348. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "WIFI init failed. Device init aborted!");
  349. StatusLED(WLAN_INIT, 3, true);
  350. return;
  351. }
  352. }
  353. else if (iWLANStatus == -1) { // wlan.ini not available, potentially empty or content not readable
  354. StatusLED(WLAN_INIT, 1, true);
  355. return; // No way to continue without reading the wlan.ini
  356. }
  357. else if (iWLANStatus == -2) { // SSID or password not configured
  358. StatusLED(WLAN_INIT, 2, true);
  359. return; // No way to continue with empty SSID or password!
  360. }
  361. xDelay = 2000 / portTICK_PERIOD_MS;
  362. ESP_LOGD(TAG, "main: sleep for: %ldms", (long) xDelay * CONFIG_FREERTOS_HZ/portTICK_PERIOD_MS);
  363. vTaskDelay( xDelay );
  364. // manual reset the time
  365. // ********************************************
  366. if (!time_manual_reset_sync())
  367. {
  368. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Manual Time Sync failed during startup" );
  369. }
  370. // Set log level for wifi component to WARN level (default: INFO; only relevant for serial console)
  371. // ********************************************
  372. esp_log_level_set("wifi", ESP_LOG_WARN);
  373. #ifdef HEAP_TRACING_MAIN_WIFI
  374. ESP_ERROR_CHECK( heap_trace_stop() );
  375. heap_trace_dump();
  376. #endif
  377. #ifdef DEBUG_ENABLE_SYSINFO
  378. #if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL( 4, 0, 0 )
  379. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Device Info : " + get_device_info() );
  380. ESP_LOGD(TAG, "Device infos %s", get_device_info().c_str());
  381. #endif
  382. #endif //DEBUG_ENABLE_SYSINFO
  383. #ifdef USE_HIMEM_IF_AVAILABLE
  384. #ifdef DEBUG_HIMEM_MEMORY_CHECK
  385. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Himem mem check : " + himem_memory_check() );
  386. ESP_LOGD(TAG, "Himem mem check %s", himem_memory_check().c_str());
  387. #endif
  388. #endif
  389. // Print Device info
  390. // ********************************************
  391. esp_chip_info_t chipInfo;
  392. esp_chip_info(&chipInfo);
  393. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Device info: CPU cores: " + std::to_string(chipInfo.cores) +
  394. ", Chip revision: " + std::to_string(chipInfo.revision));
  395. // Print SD-Card info
  396. // ********************************************
  397. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "SD card info: Name: " + getSDCardName() + ", Capacity: " +
  398. getSDCardCapacity() + "MB, Free: " + getSDCardFreePartitionSpace() + "MB");
  399. xDelay = 2000 / portTICK_PERIOD_MS;
  400. ESP_LOGD(TAG, "main: sleep for: %ldms", (long) xDelay * CONFIG_FREERTOS_HZ/portTICK_PERIOD_MS);
  401. vTaskDelay( xDelay );
  402. // Start webserver + register handler
  403. // ********************************************
  404. ESP_LOGD(TAG, "starting servers");
  405. server = start_webserver();
  406. register_server_camera_uri(server);
  407. register_server_main_flow_task_uri(server);
  408. register_server_file_uri(server, "/sdcard");
  409. register_server_ota_sdcard_uri(server);
  410. #ifdef ENABLE_MQTT
  411. register_server_mqtt_uri(server);
  412. #endif //ENABLE_MQTT
  413. gpio_handler_create(server);
  414. ESP_LOGD(TAG, "Before reg server main");
  415. register_server_main_uri(server, "/sdcard");
  416. // Only for testing purpose
  417. //setSystemStatusFlag(SYSTEM_STATUS_CAM_FB_BAD);
  418. //setSystemStatusFlag(SYSTEM_STATUS_PSRAM_BAD);
  419. // Check main init + start TFlite task
  420. // ********************************************
  421. if (getSystemStatus() == 0) { // No error flag is set
  422. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Initialization completed successfully! Starting flow task ...");
  423. StartMainFlowTask();
  424. }
  425. else if (isSetSystemStatusFlag(SYSTEM_STATUS_CAM_FB_BAD) || // Non critical errors occured, we try to continue...
  426. isSetSystemStatusFlag(SYSTEM_STATUS_NTP_BAD)) {
  427. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Initialization completed with errors! Starting flow task ...");
  428. StartMainFlowTask();
  429. }
  430. else { // Any other error is critical and makes running the flow impossible. Init is going to abort.
  431. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Initialization failed. Flow task start aborted. Loading reduced web interface...");
  432. }
  433. }
  434. void migrateConfiguration(void) {
  435. bool migrated = false;
  436. if (!FileExists(CONFIG_FILE)) {
  437. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Config file seems to be missing!");
  438. return;
  439. }
  440. std::string section = "";
  441. std::ifstream ifs(CONFIG_FILE);
  442. std::string content((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
  443. /* Split config file it array of lines */
  444. std::vector<std::string> configLines = splitString(content);
  445. /* Process each line */
  446. for (int i = 0; i < configLines.size(); i++) {
  447. //ESP_LOGI(TAG, "Line %d: %s", i, configLines[i].c_str());
  448. if (configLines[i].find("[") != std::string::npos) { // Start of new section
  449. section = configLines[i];
  450. replaceString(section, ";", "", false); // Remove possible semicolon (just for the string comparison)
  451. //ESP_LOGI(TAG, "New section: %s", section.c_str());
  452. }
  453. /* Migrate parameters as needed
  454. * For the boolean parameters, we make them enabled all the time now:
  455. * 1. If they where disabled, set them to their default value
  456. * 2. Enable them
  457. * Notes:
  458. * The migration has some simplifications:
  459. * - Case Sensitiveness must be like in the initial config.ini
  460. * - No Whitespace after a semicollon
  461. * - Only one whitespace before/after the equal sign
  462. */
  463. if (section == "[MakeImage]") {
  464. migrated = migrated | replaceString(configLines[i], "[MakeImage]", "[TakeImage]"); // Rename the section itself
  465. }
  466. if (section == "[MakeImage]" || section == "[TakeImage]") {
  467. migrated = migrated | replaceString(configLines[i], "LogImageLocation", "RawImagesLocation");
  468. migrated = migrated | replaceString(configLines[i], "LogfileRetentionInDays", "RawImagesRetention");
  469. migrated = migrated | replaceString(configLines[i], ";Demo = true", ";Demo = false"); // Set it to its default value
  470. migrated = migrated | replaceString(configLines[i], ";Demo", "Demo"); // Enable it
  471. migrated = migrated | replaceString(configLines[i], ";FixedExposure = true", ";FixedExposure = false"); // Set it to its default value
  472. migrated = migrated | replaceString(configLines[i], ";FixedExposure", "FixedExposure"); // Enable it
  473. }
  474. if (section == "[Alignment]") {
  475. migrated = migrated | replaceString(configLines[i], ";InitialMirror = true", ";InitialMirror = false"); // Set it to its default value
  476. migrated = migrated | replaceString(configLines[i], ";InitialMirror", "InitialMirror"); // Enable it
  477. migrated = migrated | replaceString(configLines[i], ";FlipImageSize = true", ";FlipImageSize = false"); // Set it to its default value
  478. migrated = migrated | replaceString(configLines[i], ";FlipImageSize", "FlipImageSize"); // Enable it
  479. }
  480. if (section == "[Digits]") {
  481. migrated = migrated | replaceString(configLines[i], "LogImageLocation", "ROIImagesLocation");
  482. migrated = migrated | replaceString(configLines[i], "LogfileRetentionInDays", "ROIImagesRetention");
  483. }
  484. if (section == "[Analog]") {
  485. migrated = migrated | replaceString(configLines[i], "LogImageLocation", "ROIImagesLocation");
  486. migrated = migrated | replaceString(configLines[i], "LogfileRetentionInDays", "ROIImagesRetention");
  487. migrated = migrated | replaceString(configLines[i], "ExtendedResolution", ";UNUSED_PARAMETER"); // This parameter is no longer used
  488. }
  489. if (section == "[PostProcessing]") {
  490. migrated = migrated | replaceString(configLines[i], ";PreValueUse = true", ";PreValueUse = false"); // Set it to its default value
  491. migrated = migrated | replaceString(configLines[i], ";PreValueUse", "PreValueUse"); // Enable it
  492. /* AllowNegativeRates has a <NUMBER> as prefix! */
  493. if (isInString(configLines[i], "AllowNegativeRates") && isInString(configLines[i], ";")) { // It is the parameter "AllowNegativeRates" and it is commented out
  494. migrated = migrated | replaceString(configLines[i], "true", "false"); // Set it to its default value
  495. migrated = migrated | replaceString(configLines[i], ";", ""); // Enable it
  496. }
  497. /* IgnoreLeadingNaN has a <NUMBER> as prefix! */
  498. if (isInString(configLines[i], "IgnoreLeadingNaN") && isInString(configLines[i], ";")) { // It is the parameter "IgnoreLeadingNaN" and it is commented out
  499. migrated = migrated | replaceString(configLines[i], "true", "false"); // Set it to its default value
  500. migrated = migrated | replaceString(configLines[i], ";", ""); // Enable it
  501. }
  502. /* ExtendedResolution has a <NUMBER> as prefix! */
  503. if (isInString(configLines[i], "ExtendedResolution") && isInString(configLines[i], ";")) { // It is the parameter "ExtendedResolution" and it is commented out
  504. migrated = migrated | replaceString(configLines[i], "true", "false"); // Set it to its default value
  505. migrated = migrated | replaceString(configLines[i], ";", ""); // Enable it
  506. }
  507. migrated = migrated | replaceString(configLines[i], ";ErrorMessage = true", ";ErrorMessage = false"); // Set it to its default value
  508. migrated = migrated | replaceString(configLines[i], ";ErrorMessage", "ErrorMessage"); // Enable it
  509. migrated = migrated | replaceString(configLines[i], ";CheckDigitIncreaseConsistency = true", ";CheckDigitIncreaseConsistency = false"); // Set it to its default value
  510. migrated = migrated | replaceString(configLines[i], ";CheckDigitIncreaseConsistency", "CheckDigitIncreaseConsistency"); // Enable it
  511. }
  512. if (section == "[MQTT]") {
  513. migrated = migrated | replaceString(configLines[i], "SetRetainFlag", "RetainMessages"); // First rename it, enable it with its default value
  514. migrated = migrated | replaceString(configLines[i], ";RetainMessages = true", ";RetainMessages = false"); // Set it to its default value
  515. migrated = migrated | replaceString(configLines[i], ";RetainMessages", "RetainMessages"); // Enable it
  516. migrated = migrated | replaceString(configLines[i], ";HomeassistantDiscovery = true", ";HomeassistantDiscovery = false"); // Set it to its default value
  517. migrated = migrated | replaceString(configLines[i], ";HomeassistantDiscovery", "HomeassistantDiscovery"); // Enable it
  518. if (configLines[i].rfind("Topic", 0) != std::string::npos) // only if string starts with "Topic" (Was the naming in very old version)
  519. {
  520. migrated = migrated | replaceString(configLines[i], "Topic", "MainTopic");
  521. }
  522. }
  523. if (section == "[InfluxDB]") {
  524. }
  525. if (section == "[GPIO]") {
  526. }
  527. if (section == "[DataLogging]") {
  528. migrated = migrated | replaceString(configLines[i], "DataLogRetentionInDays", "DataFilesRetention");
  529. /* DataLogActive is true by default! */
  530. migrated = migrated | replaceString(configLines[i], ";DataLogActive = false", ";DataLogActive = true"); // Set it to its default value
  531. migrated = migrated | replaceString(configLines[i], ";DataLogActive", "DataLogActive"); // Enable it
  532. }
  533. if (section == "[AutoTimer]") {
  534. migrated = migrated | replaceString(configLines[i], "Intervall", "Interval");
  535. migrated = migrated | replaceString(configLines[i], ";AutoStart = true", ";AutoStart = false"); // Set it to its default value
  536. migrated = migrated | replaceString(configLines[i], ";AutoStart", "AutoStart"); // Enable it
  537. }
  538. if (section == "[Debug]") {
  539. migrated = migrated | replaceString(configLines[i], "Logfile ", "LogLevel "); // Whitespace needed so it does not match `LogfileRetentionInDays`
  540. /* LogLevel (resp. LogFile) was originally a boolean, but we switched it to an int
  541. * For both cases (true/false), we set it to level 2 (WARNING) */
  542. migrated = migrated | replaceString(configLines[i], "LogLevel = true", "LogLevel = 2");
  543. migrated = migrated | replaceString(configLines[i], "LogLevel = false", "LogLevel = 2");
  544. migrated = migrated | replaceString(configLines[i], "LogfileRetentionInDays", "LogfilesRetention");
  545. }
  546. if (section == "[System]") {
  547. migrated = migrated | replaceString(configLines[i], "RSSIThreashold", "RSSIThreshold");
  548. migrated = migrated | replaceString(configLines[i], "AutoAdjustSummertime", ";UNUSED_PARAMETER"); // This parameter is no longer used
  549. migrated = migrated | replaceString(configLines[i], ";SetupMode = true", ";SetupMode = false"); // Set it to its default value
  550. migrated = migrated | replaceString(configLines[i], ";SetupMode", "SetupMode"); // Enable it
  551. }
  552. }
  553. if (migrated) { // At least one replacement happened
  554. if (! RenameFile(CONFIG_FILE, CONFIG_FILE_BACKUP)) {
  555. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to create backup of Config file!");
  556. return;
  557. }
  558. FILE* pfile = fopen(CONFIG_FILE, "w");
  559. for (int i = 0; i < configLines.size(); i++) {
  560. fwrite(configLines[i].c_str() , configLines[i].length(), 1, pfile);
  561. fwrite("\n" , 1, 1, pfile);
  562. }
  563. fclose(pfile);
  564. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Config file migrated. Saved backup to " + string(CONFIG_FILE_BACKUP));
  565. }
  566. }
  567. std::vector<std::string> splitString(const std::string& str) {
  568. std::vector<std::string> tokens;
  569. std::stringstream ss(str);
  570. std::string token;
  571. while (std::getline(ss, token, '\n')) {
  572. tokens.push_back(token);
  573. }
  574. return tokens;
  575. }
  576. /*bool replace_all(std::string& s, std::string const& toReplace, std::string const& replaceWith) {
  577. std::string buf;
  578. std::size_t pos = 0;
  579. std::size_t prevPos;
  580. bool found = false;
  581. // Reserves rough estimate of final size of string.
  582. buf.reserve(s.size());
  583. while (true) {
  584. prevPos = pos;
  585. pos = s.find(toReplace, pos);
  586. if (pos == std::string::npos) {
  587. break;
  588. }
  589. found = true;
  590. buf.append(s, prevPos, pos - prevPos);
  591. buf += replaceWith;
  592. pos += toReplace.size();
  593. }
  594. buf.append(s, prevPos, s.size() - prevPos);
  595. s.swap(buf);
  596. return found;
  597. }*/
  598. bool setCpuFrequency(void) {
  599. ConfigFile configFile = ConfigFile(CONFIG_FILE);
  600. string cpuFrequency = "160";
  601. esp_pm_config_esp32_t pm_config;
  602. if (!configFile.ConfigFileExists()){
  603. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "No ConfigFile defined - exit setCpuFrequency()!");
  604. return false;
  605. }
  606. std::vector<std::string> splitted;
  607. std::string line = "";
  608. bool disabledLine = false;
  609. bool eof = false;
  610. /* Load config from config file */
  611. while ((!configFile.GetNextParagraph(line, disabledLine, eof) ||
  612. (line.compare("[System]") != 0)) && !eof) {}
  613. if (eof) {
  614. return false;
  615. }
  616. if (disabledLine) {
  617. return false;
  618. }
  619. while (configFile.getNextLine(&line, disabledLine, eof) &&
  620. !configFile.isNewParagraph(line)) {
  621. splitted = ZerlegeZeile(line);
  622. if (toUpper(splitted[0]) == "CPUFREQUENCY") {
  623. cpuFrequency = splitted[1];
  624. break;
  625. }
  626. }
  627. if (esp_pm_get_configuration(&pm_config) != ESP_OK) {
  628. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to read CPU Frequency!");
  629. return false;
  630. }
  631. if (cpuFrequency == "160") { // 160 is the default
  632. // No change needed
  633. }
  634. else if (cpuFrequency == "240") {
  635. pm_config.max_freq_mhz = 240;
  636. pm_config.min_freq_mhz = pm_config.max_freq_mhz;
  637. if (esp_pm_configure(&pm_config) != ESP_OK) {
  638. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to set new CPU frequency!");
  639. return false;
  640. }
  641. }
  642. else {
  643. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unknown CPU frequency: " + cpuFrequency + "! "
  644. "It must be 160 or 240!");
  645. return false;
  646. }
  647. if (esp_pm_get_configuration(&pm_config) == ESP_OK) {
  648. LogFile.WriteToFile(ESP_LOG_INFO, TAG, string("CPU frequency: ") + to_string(pm_config.max_freq_mhz) + " MHz");
  649. }
  650. return true;
  651. }