main.cpp 34 KB

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