main.cpp 33 KB

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