main.cpp 30 KB

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