main.cpp 35 KB

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