main.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  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. #include "esp_vfs_fat.h"
  10. #include "ffconf.h"
  11. #include "driver/sdmmc_host.h"
  12. #include "ClassLogFile.h"
  13. #include "connect_wlan.h"
  14. #include "read_wlanini.h"
  15. #include "server_main.h"
  16. #include "MainFlowControl.h"
  17. #include "server_file.h"
  18. #include "server_ota.h"
  19. #include "time_sntp.h"
  20. #include "configFile.h"
  21. #include "server_main.h"
  22. #include "server_camera.h"
  23. #include "basic_auth.h"
  24. #ifdef ENABLE_MQTT
  25. #include "server_mqtt.h"
  26. #endif // ENABLE_MQTT
  27. #include "Helper.h"
  28. #include "statusled.h"
  29. #include "sdcard_check.h"
  30. #include "../../include/defines.h"
  31. #ifdef ENABLE_SOFTAP
  32. #include "softAP.h"
  33. #endif // ENABLE_SOFTAP
  34. #ifdef DISABLE_BROWNOUT_DETECTOR
  35. #include "soc/soc.h"
  36. #include "soc/rtc_cntl_reg.h"
  37. #endif
  38. #ifdef DEBUG_ENABLE_SYSINFO
  39. #if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 0, 0)
  40. #include "esp_sys.h"
  41. #endif
  42. #endif // DEBUG_ENABLE_SYSINFO
  43. // define `gpio_pad_select_gpip` for newer versions of IDF
  44. #if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 3, 0))
  45. #include "esp_rom_gpio.h"
  46. #define gpio_pad_select_gpio esp_rom_gpio_pad_select_gpio
  47. #endif
  48. #ifdef USE_HIMEM_IF_AVAILABLE
  49. #include "esp32/himem.h"
  50. #ifdef DEBUG_HIMEM_MEMORY_CHECK
  51. #include "himem_memory_check.h"
  52. #endif
  53. #endif
  54. // #ifdef CONFIG_HEAP_TRACING_STANDALONE
  55. #if defined HEAP_TRACING_MAIN_WIFI || defined HEAP_TRACING_MAIN_START
  56. #include <esp_heap_trace.h>
  57. #define NUM_RECORDS 300
  58. static heap_trace_record_t trace_record[NUM_RECORDS]; // This buffer must be in internal RAM
  59. #endif
  60. extern const char *GIT_TAG;
  61. extern const char *GIT_REV;
  62. extern const char *GIT_BRANCH;
  63. extern const char *BUILD_TIME;
  64. extern std::string getFwVersion(void);
  65. extern std::string getHTMLversion(void);
  66. extern std::string getHTMLcommit(void);
  67. std::vector<std::string> splitString(const std::string &str);
  68. bool setCpuFrequency(void);
  69. static const char *TAG = "MAIN";
  70. #define MOUNT_POINT "/sdcard"
  71. bool Init_NVS_SDCard()
  72. {
  73. esp_err_t ret = nvs_flash_init();
  74. if (ret == ESP_ERR_NVS_NO_FREE_PAGES)
  75. {
  76. ESP_ERROR_CHECK(nvs_flash_erase());
  77. ret = nvs_flash_init();
  78. }
  79. ESP_LOGD(TAG, "Using SDMMC peripheral");
  80. sdmmc_host_t host = SDMMC_HOST_DEFAULT();
  81. host.max_freq_khz = SDMMC_FREQ_HIGHSPEED;
  82. // For SoCs where the SD power can be supplied both via an internal or external (e.g. on-board LDO) power supply.
  83. // When using specific IO pins (which can be used for ultra high-speed SDMMC) to connect to the SD card
  84. // and the internal LDO power supply, we need to initialize the power supply first.
  85. #if SD_PWR_CTRL_LDO_INTERNAL_IO
  86. sd_pwr_ctrl_ldo_config_t ldo_config = {
  87. .ldo_chan_id = CONFIG_EXAMPLE_SD_PWR_CTRL_LDO_IO_ID,
  88. };
  89. sd_pwr_ctrl_handle_t pwr_ctrl_handle = NULL;
  90. ret = sd_pwr_ctrl_new_on_chip_ldo(&ldo_config, &pwr_ctrl_handle);
  91. if (ret != ESP_OK)
  92. {
  93. ESP_LOGE(TAG, "Failed to create a new on-chip LDO power control driver");
  94. return false;
  95. }
  96. host.pwr_ctrl_handle = pwr_ctrl_handle;
  97. #endif
  98. // This initializes the slot without card detect (CD) and write protect (WP) signals.
  99. // Modify slot_config.gpio_cd and slot_config.gpio_wp if your board has these signals.
  100. #ifdef CONFIG_SOC_SDMMC_USE_GPIO_MATRIX
  101. sdmmc_slot_config_t slot_config = {
  102. .cd = SDMMC_SLOT_NO_CD,
  103. .wp = SDMMC_SLOT_NO_WP,
  104. };
  105. #else
  106. sdmmc_slot_config_t slot_config = SDMMC_SLOT_CONFIG_DEFAULT();
  107. #endif
  108. // Set bus width to use:
  109. #ifdef __SD_USE_ONE_LINE_MODE__
  110. slot_config.width = 1;
  111. #ifdef CONFIG_SOC_SDMMC_USE_GPIO_MATRIX
  112. slot_config.clk = GPIO_SDCARD_CLK;
  113. slot_config.cmd = GPIO_SDCARD_CMD;
  114. slot_config.d0 = GPIO_SDCARD_D0;
  115. #endif // end CONFIG_SOC_SDMMC_USE_GPIO_MATRIX
  116. #else // else __SD_USE_ONE_LINE_MODE__
  117. slot_config.width = 4;
  118. #ifdef CONFIG_SOC_SDMMC_USE_GPIO_MATRIX
  119. slot_config.d1 = GPIO_SDCARD_D1;
  120. slot_config.d2 = GPIO_SDCARD_D2;
  121. slot_config.d3 = GPIO_SDCARD_D3;
  122. #endif // end CONFIG_SOC_SDMMC_USE_GPIO_MATRIX
  123. #endif // end __SD_USE_ONE_LINE_MODE__
  124. // Enable internal pullups on enabled pins. The internal pullups
  125. // are insufficient however, please make sure 10k external pullups are
  126. // connected on the bus. This is for debug / example purpose only.
  127. slot_config.flags |= SDMMC_SLOT_FLAG_INTERNAL_PULLUP;
  128. // Der PullUp des GPIO13 wird durch slot_config.flags |= SDMMC_SLOT_FLAG_INTERNAL_PULLUP;
  129. // nicht gesetzt, da er eigentlich nicht benötigt wird,
  130. // dies führt jedoch bei schlechten Kopien des AI_THINKER Boards
  131. // zu Problemen mit der SD Initialisierung und eventuell sogar zur reboot-loops.
  132. // Um diese Probleme zu kompensieren, wird der PullUp manuel gesetzt.
  133. gpio_set_pull_mode(GPIO_SDCARD_D3, GPIO_PULLUP_ONLY); // HS2_D3
  134. // Options for mounting the filesystem.
  135. // If format_if_mount_failed is set to true, SD card will be partitioned and
  136. // formatted in case when mounting fails.
  137. esp_vfs_fat_sdmmc_mount_config_t mount_config = {
  138. .format_if_mount_failed = false,
  139. .max_files = 8,
  140. .allocation_unit_size = 0, // 0 = auto
  141. .disk_status_check_enable = false,
  142. .use_one_fat = false,
  143. };
  144. sdmmc_card_t *card;
  145. const char mount_point[] = MOUNT_POINT;
  146. // Use settings defined above to initialize SD card and mount FAT filesystem.
  147. // Note: esp_vfs_fat_sdmmc_mount is an all-in-one convenience function.
  148. // Please check its source code and implement error recovery when developing
  149. // production applications.
  150. ret = esp_vfs_fat_sdmmc_mount(mount_point, &host, &slot_config, &mount_config, &card);
  151. if (ret != ESP_OK)
  152. {
  153. if (ret == ESP_FAIL)
  154. {
  155. ESP_LOGE(TAG, "Failed to mount FAT filesystem on SD card. Check SD card filesystem (only FAT supported) or try another card");
  156. StatusLED(SDCARD_INIT, 1, true);
  157. }
  158. else if (ret == 263)
  159. {
  160. // Error code: 0x107 --> usually: SD not found
  161. ESP_LOGE(TAG, "SD card init failed. Check if SD card is properly inserted into SD card slot or try another card");
  162. StatusLED(SDCARD_INIT, 2, true);
  163. }
  164. else
  165. {
  166. ESP_LOGE(TAG, "SD card init failed. Check error code or try another card");
  167. StatusLED(SDCARD_INIT, 3, true);
  168. }
  169. return false;
  170. }
  171. SaveSDCardInfo(card);
  172. return true;
  173. }
  174. extern "C" void app_main(void)
  175. {
  176. // #ifdef CONFIG_HEAP_TRACING_STANDALONE
  177. #if defined HEAP_TRACING_MAIN_WIFI || defined HEAP_TRACING_MAIN_START
  178. // register a buffer to record the memory trace
  179. ESP_ERROR_CHECK(heap_trace_init_standalone(trace_record, NUM_RECORDS));
  180. #endif
  181. #ifdef DISABLE_BROWNOUT_DETECTOR
  182. WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); // disable brownout detector
  183. #endif
  184. #ifdef HEAP_TRACING_MAIN_START
  185. ESP_ERROR_CHECK(heap_trace_start(HEAP_TRACE_LEAKS));
  186. #endif
  187. // ********************************************
  188. // Highlight start of app_main
  189. // ********************************************
  190. ESP_LOGI(TAG, "\n\n\n\n================ Start app_main =================");
  191. // Init SD card
  192. // ********************************************
  193. if (!Init_NVS_SDCard())
  194. {
  195. ESP_LOGE(TAG, "Device init aborted!");
  196. vTaskDelay(pdMS_TO_TICKS(2000));
  197. return; // No way to continue without working SD card!
  198. }
  199. // SD card: Create log directories (if not already existing)
  200. // ********************************************
  201. LogFile.CreateLogDirectories(); // mandatory for logging + image saving
  202. // ********************************************
  203. // Highlight start of logfile logging
  204. // Default Log Level: INFO -> Everything which needs to be logged during boot should be have level INFO, WARN OR ERROR
  205. // ********************************************
  206. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "=================================================");
  207. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "==================== Start ======================");
  208. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "=================================================");
  209. // SD card: basic R/W check
  210. // ********************************************
  211. int iSDCardStatus = SDCardCheckRW();
  212. if (iSDCardStatus < 0)
  213. {
  214. if (iSDCardStatus <= -1 && iSDCardStatus >= -2)
  215. {
  216. // write error
  217. StatusLED(SDCARD_CHECK, 1, true);
  218. }
  219. else if (iSDCardStatus <= -3 && iSDCardStatus >= -5)
  220. {
  221. // read error
  222. StatusLED(SDCARD_CHECK, 2, true);
  223. }
  224. else if (iSDCardStatus == -6)
  225. {
  226. // delete error
  227. StatusLED(SDCARD_CHECK, 3, true);
  228. }
  229. setSystemStatusFlag(SYSTEM_STATUS_SDCARD_CHECK_BAD); // reduced web interface going to be loaded
  230. vTaskDelay(pdMS_TO_TICKS(2000));
  231. return; // No way to continue without working SD card!
  232. }
  233. // SD card: Create further mandatory directories (if not already existing)
  234. // Correct creation of these folders will be checked with function "SDCardCheckFolderFilePresence"
  235. // ********************************************
  236. MakeDir("/sdcard/firmware"); // mandatory for OTA firmware update
  237. MakeDir("/sdcard/img_tmp"); // mandatory for setting up alignment marks
  238. MakeDir("/sdcard/demo"); // mandatory for demo mode
  239. MakeDir("/sdcard/config/certs"); // mandatory for mqtt certificates
  240. // Init external PSRAM
  241. // ********************************************
  242. esp_err_t PSRAMStatus = esp_psram_init();
  243. if (PSRAMStatus == ESP_FAIL)
  244. {
  245. // ESP_FAIL -> Failed to init PSRAM
  246. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "PSRAM init failed (" + std::to_string(PSRAMStatus) + ")! PSRAM not found or defective");
  247. setSystemStatusFlag(SYSTEM_STATUS_PSRAM_BAD);
  248. StatusLED(PSRAM_INIT, 1, true);
  249. vTaskDelay(pdMS_TO_TICKS(2000));
  250. return; // No way to continue without psram
  251. }
  252. else
  253. {
  254. // ESP_OK -> PSRAM init OK --> continue to check PSRAM size
  255. size_t psram_size = esp_psram_get_size(); // size_t psram_size = esp_psram_get_size(); // comming in IDF 5.0
  256. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "PSRAM size: " + std::to_string(psram_size) + " byte (" + std::to_string(psram_size / 1024 / 1024) + "MB / " + std::to_string(psram_size / 1024 / 1024 * 8) + "MBit)");
  257. // Check PSRAM size
  258. // ********************************************
  259. if (psram_size < (4 * 1024 * 1024))
  260. {
  261. // PSRAM is below 4 MBytes (32Mbit)
  262. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "PSRAM size >= 4MB (32Mbit) is mandatory to run this application");
  263. setSystemStatusFlag(SYSTEM_STATUS_PSRAM_BAD);
  264. StatusLED(PSRAM_INIT, 2, true);
  265. vTaskDelay(pdMS_TO_TICKS(2000));
  266. return; // No way to continue without psram
  267. }
  268. else
  269. {
  270. // PSRAM size OK --> continue to check heap size
  271. size_t _hsize = getESPHeapSize();
  272. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Total heap: " + std::to_string(_hsize) + " byte");
  273. // Check heap memory
  274. // ********************************************
  275. if (_hsize < 4000000)
  276. {
  277. // Check available Heap memory for a bit less than 4 MB (a test on a good device showed 4187558 bytes to be available)
  278. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Total heap >= 4000000 byte is mandatory to run this application");
  279. setSystemStatusFlag(SYSTEM_STATUS_HEAP_TOO_SMALL);
  280. StatusLED(PSRAM_INIT, 3, true);
  281. vTaskDelay(pdMS_TO_TICKS(2000));
  282. return; // No way to continue without psram
  283. }
  284. else
  285. {
  286. // HEAP size OK --> continue to reserve shared memory block and check camera init
  287. /* Allocate static PSRAM memory regions */
  288. if (!reserve_psram_shared_region())
  289. {
  290. setSystemStatusFlag(SYSTEM_STATUS_HEAP_TOO_SMALL);
  291. StatusLED(PSRAM_INIT, 3, true);
  292. vTaskDelay(pdMS_TO_TICKS(2000));
  293. return; // No way to continue without psram
  294. }
  295. }
  296. }
  297. }
  298. // Check for updates
  299. // ********************************************
  300. CheckOTAUpdate();
  301. CheckUpdate();
  302. // Init time (as early as possible, but SD card needs to be initialized)
  303. // ********************************************
  304. setupTime(); // NTP time service: Status of time synchronization will be checked after every round (server_tflite.cpp)
  305. // Set CPU Frequency
  306. // ********************************************
  307. setCpuFrequency();
  308. // Start SoftAP for initial remote setup
  309. // Note: Start AP if no wlan.ini and/or config.ini available, e.g. SD card empty; function does not exit anymore until reboot
  310. // ********************************************
  311. #ifdef ENABLE_SOFTAP
  312. CheckStartAPMode();
  313. #endif
  314. // SD card: Check presence of some mandatory folders / files
  315. // ********************************************
  316. if (!SDCardCheckFolderFilePresence())
  317. {
  318. StatusLED(SDCARD_CHECK, 4, true);
  319. setSystemStatusFlag(SYSTEM_STATUS_FOLDER_CHECK_BAD); // reduced web interface going to be loaded
  320. }
  321. // Check version information
  322. // ********************************************
  323. std::string versionFormated = getFwVersion() + ", Date/Time: " + std::string(BUILD_TIME) + ", Web UI: " + getHTMLversion();
  324. if (std::string(GIT_TAG) != "")
  325. {
  326. // We are on a tag, add it as prefix
  327. versionFormated = "Tag: '" + std::string(GIT_TAG) + "', " + versionFormated;
  328. }
  329. LogFile.WriteToFile(ESP_LOG_INFO, TAG, versionFormated);
  330. if (getHTMLcommit().substr(0, 7) == "?")
  331. {
  332. LogFile.WriteToFile(ESP_LOG_WARN, TAG, std::string("Failed to read file html/version.txt to parse Web UI version"));
  333. }
  334. if (getHTMLcommit().substr(0, 7) != std::string(GIT_REV).substr(0, 7))
  335. {
  336. // Compare the first 7 characters of both hashes
  337. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Web UI version (" + getHTMLcommit() + ") does not match firmware version (" + std::string(GIT_REV) + ")");
  338. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Recommendation: Repeat installation using AI-on-the-edge-device__update__*.zip");
  339. }
  340. // Check reboot reason
  341. // ********************************************
  342. CheckIsPlannedReboot();
  343. if (!getIsPlannedReboot() && (esp_reset_reason() == ESP_RST_PANIC))
  344. {
  345. // If system reboot was not triggered by user and reboot was caused by execption
  346. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Reset reason: " + getResetReason());
  347. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Device was rebooted due to a software exception! Log level is set to DEBUG until the next reboot. "
  348. "Flow init is delayed by 5 minutes to check the logs or do an OTA update");
  349. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Keep device running until crash occurs again and check logs after device is up again");
  350. LogFile.setLogLevel(ESP_LOG_DEBUG);
  351. }
  352. else
  353. {
  354. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Reset reason: " + getResetReason());
  355. }
  356. #ifdef HEAP_TRACING_MAIN_START
  357. ESP_ERROR_CHECK(heap_trace_stop());
  358. heap_trace_dump();
  359. #endif
  360. #ifdef HEAP_TRACING_MAIN_WIFI
  361. ESP_ERROR_CHECK(heap_trace_start(HEAP_TRACE_LEAKS));
  362. #endif
  363. // Read WLAN parameter and start WIFI
  364. // ********************************************
  365. int iWLANStatus = LoadWlanFromFile(WLAN_CONFIG_FILE);
  366. if (iWLANStatus == 0)
  367. {
  368. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "WLAN config loaded, init WIFI...");
  369. if (wifi_init_sta() != ESP_OK)
  370. {
  371. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "WIFI init failed. Device init aborted!");
  372. StatusLED(WLAN_INIT, 3, true);
  373. vTaskDelay(pdMS_TO_TICKS(2000));
  374. return;
  375. }
  376. init_basic_auth();
  377. }
  378. else if (iWLANStatus == -1)
  379. {
  380. // wlan.ini not available, potentially empty or content not readable
  381. StatusLED(WLAN_INIT, 1, true);
  382. vTaskDelay(pdMS_TO_TICKS(2000));
  383. return; // No way to continue without reading the wlan.ini
  384. }
  385. else if (iWLANStatus == -2)
  386. {
  387. // SSID or password not configured
  388. StatusLED(WLAN_INIT, 2, true);
  389. vTaskDelay(pdMS_TO_TICKS(2000));
  390. return; // No way to continue with empty SSID or password!
  391. }
  392. // Set log level for wifi component to WARN level (default: INFO; only relevant for serial console)
  393. // ********************************************
  394. esp_log_level_set("wifi", ESP_LOG_WARN);
  395. #ifdef HEAP_TRACING_MAIN_WIFI
  396. ESP_ERROR_CHECK(heap_trace_stop());
  397. heap_trace_dump();
  398. #endif
  399. #ifdef DEBUG_ENABLE_SYSINFO
  400. #if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 0, 0)
  401. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Device Info : " + get_device_info());
  402. ESP_LOGD(TAG, "Device infos %s", get_device_info().c_str());
  403. #endif
  404. #endif // DEBUG_ENABLE_SYSINFO
  405. #ifdef USE_HIMEM_IF_AVAILABLE
  406. #ifdef DEBUG_HIMEM_MEMORY_CHECK
  407. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Himem mem check : " + himem_memory_check());
  408. ESP_LOGD(TAG, "Himem mem check %s", himem_memory_check().c_str());
  409. #endif
  410. #endif
  411. // Init camera
  412. // ********************************************
  413. esp_err_t camStatus = ESP_OK;
  414. Camera.LightOnOff(true);
  415. for (int i = 0; i < 3; i++)
  416. {
  417. camStatus = Camera.InitCam();
  418. if (camStatus == ESP_OK)
  419. {
  420. break;
  421. }
  422. // De-init in case it was already initialized
  423. esp_camera_deinit();
  424. vTaskDelay(pdMS_TO_TICKS(200));
  425. }
  426. if (camStatus != ESP_OK)
  427. {
  428. // Camera init failed, retry to init
  429. char camStatusHex[33];
  430. sprintf(camStatusHex, "0x%02x", camStatus);
  431. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Camera init failed (" + std::string(camStatusHex) + ")! Check camera module and/or proper electrical connection");
  432. setSystemStatusFlag(SYSTEM_STATUS_CAM_BAD);
  433. StatusLED(CAM_INIT, 1, true);
  434. vTaskDelay(pdMS_TO_TICKS(2000));
  435. return; // No way to continue without working Camera!
  436. }
  437. // Camera framebuffer check
  438. // ********************************************
  439. else if (!Camera.testCamera())
  440. {
  441. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Camera framebuffer check failed");
  442. // Easiest would be to simply restart here and try again,
  443. // how ever there seem to be systems where it fails at startup but still work correctly later.
  444. // Therefore we treat it still as successed! */
  445. setSystemStatusFlag(SYSTEM_STATUS_CAM_FB_BAD);
  446. StatusLED(CAM_INIT, 2, false);
  447. // vTaskDelay(pdMS_TO_TICKS(2000));
  448. // return; // No way to continue without working Camera!
  449. }
  450. else
  451. {
  452. // Print camera infos
  453. // ********************************************
  454. char caminfo[50];
  455. sensor_t *sensor = esp_camera_sensor_get();
  456. sprintf(caminfo, "PID: 0x%02x, VER: 0x%02x, MIDL: 0x%02x, MIDH: 0x%02x", sensor->id.PID, sensor->id.VER, sensor->id.MIDH, sensor->id.MIDL);
  457. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Camera info: " + std::string(caminfo));
  458. }
  459. Camera.LightOnOff(false); // make sure flashlight is off before start of flow
  460. // Print Device info
  461. // ********************************************
  462. esp_chip_info_t chipInfo;
  463. esp_chip_info(&chipInfo);
  464. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Device info: CPU cores: " + std::to_string(chipInfo.cores) + ", Chip revision: " + std::to_string(chipInfo.revision));
  465. // Print SD-Card info
  466. // ********************************************
  467. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "SD card info: Name: " + getSDCardName() + ", Capacity: " + getSDCardCapacity() + "MB, Free: " + getSDCardFreePartitionSpace() + "MB");
  468. // Start webserver + register handler
  469. // ********************************************
  470. ESP_LOGD(TAG, "starting servers");
  471. server = start_webserver();
  472. register_server_camera_uri(server);
  473. register_server_main_flow_task_uri(server);
  474. register_server_file_uri(server, "/sdcard");
  475. register_server_ota_sdcard_uri(server);
  476. #ifdef ENABLE_MQTT
  477. register_server_mqtt_uri(server);
  478. #endif // ENABLE_MQTT
  479. gpio_handler_create(server);
  480. ESP_LOGD(TAG, "Before reg server main");
  481. register_server_main_uri(server, "/sdcard");
  482. // manual reset the time
  483. // ********************************************
  484. if (!time_manual_reset_sync())
  485. {
  486. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Manual Time Sync failed during startup");
  487. }
  488. // Check main init + start TFlite task
  489. // ********************************************
  490. if (getSystemStatus() == 0)
  491. {
  492. // No error flag is set
  493. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Initialization completed successfully");
  494. InitializeFlowTask();
  495. }
  496. else if (isSetSystemStatusFlag(SYSTEM_STATUS_CAM_FB_BAD) || isSetSystemStatusFlag(SYSTEM_STATUS_NTP_BAD))
  497. {
  498. // Non critical errors occured, we try to continue...
  499. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Initialization completed with non-critical errors!");
  500. InitializeFlowTask();
  501. }
  502. else
  503. {
  504. // Any other error is critical and makes running the flow impossible. Init is going to abort.
  505. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Initialization failed. Flow task start aborted. Loading reduced web interface...");
  506. }
  507. }
  508. std::vector<std::string> splitString(const std::string &str)
  509. {
  510. std::vector<std::string> tokens;
  511. std::stringstream ss(str);
  512. std::string token;
  513. while (std::getline(ss, token, '\n'))
  514. {
  515. tokens.push_back(token);
  516. }
  517. return tokens;
  518. }
  519. bool setCpuFrequency(void)
  520. {
  521. ConfigFile configFile = ConfigFile(CONFIG_FILE);
  522. string cpuFrequency = "160";
  523. esp_pm_config_t pm_config;
  524. if (!configFile.ConfigFileExists())
  525. {
  526. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "No ConfigFile defined - exit setCpuFrequency()!");
  527. return false;
  528. }
  529. std::vector<std::string> splitted;
  530. std::string line = "";
  531. bool disabledLine = false;
  532. bool eof = false;
  533. /* Load config from config file */
  534. while ((!configFile.GetNextParagraph(line, disabledLine, eof) || (line.compare("[System]") != 0)) && !eof)
  535. {
  536. }
  537. if (eof || disabledLine)
  538. {
  539. return false;
  540. }
  541. while (configFile.getNextLine(&line, disabledLine, eof) && !configFile.isNewParagraph(line))
  542. {
  543. splitted = ZerlegeZeile(line);
  544. if (toUpper(splitted[0]) == "CPUFREQUENCY")
  545. {
  546. if (splitted.size() < 2)
  547. {
  548. cpuFrequency = "160";
  549. }
  550. else
  551. {
  552. cpuFrequency = splitted[1];
  553. }
  554. break;
  555. }
  556. }
  557. if (esp_pm_get_configuration(&pm_config) != ESP_OK)
  558. {
  559. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to read CPU Frequency!");
  560. return false;
  561. }
  562. if (cpuFrequency == "160")
  563. { // 160 is the default
  564. // No change needed
  565. }
  566. else if (cpuFrequency == "240")
  567. {
  568. pm_config.max_freq_mhz = 240;
  569. pm_config.min_freq_mhz = pm_config.max_freq_mhz;
  570. if (esp_pm_configure(&pm_config) != ESP_OK)
  571. {
  572. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to set new CPU frequency!");
  573. return false;
  574. }
  575. }
  576. else
  577. {
  578. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unknown CPU frequency: " + cpuFrequency + "! "
  579. "It must be 160 or 240!");
  580. return false;
  581. }
  582. if (esp_pm_get_configuration(&pm_config) == ESP_OK)
  583. {
  584. LogFile.WriteToFile(ESP_LOG_INFO, TAG, string("CPU frequency: ") + to_string(pm_config.max_freq_mhz) + " MHz");
  585. }
  586. return true;
  587. }