MainFlowControl.cpp 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947
  1. #include "MainFlowControl.h"
  2. #include <new>
  3. #include <string>
  4. #include <vector>
  5. #include "string.h"
  6. #include "esp_log.h"
  7. #include <esp_timer.h>
  8. #include "freertos/FreeRTOS.h"
  9. #include "freertos/task.h"
  10. #include <iomanip>
  11. #include <sstream>
  12. #include "../../include/defines.h"
  13. #include "Helper.h"
  14. #include "statusled.h"
  15. #include "esp_camera.h"
  16. #include "time_sntp.h"
  17. #include "ClassControllCamera.h"
  18. #include "ClassFlowControll.h"
  19. #include "ClassLogFile.h"
  20. #include "server_GPIO.h"
  21. #include "server_file.h"
  22. #include "server_ota.h"
  23. #include "read_wlanini.h"
  24. #include "connect_wlan.h"
  25. #include "psram.h"
  26. #include "basic_auth.h"
  27. // support IDF 5.x
  28. #ifndef portTICK_RATE_MS
  29. #define portTICK_RATE_MS portTICK_PERIOD_MS
  30. #endif
  31. ClassFlowControll flowctrl;
  32. camera_flow_config_temp_t CFstatus;
  33. TaskHandle_t xHandletask_autodoFlow = NULL;
  34. bool bTaskAutoFlowCreated = false;
  35. // True only while the flow objects are fully built. bTaskAutoFlowCreated is already true during the
  36. // post-panic init delay and while doInit() rebuilds the flow, when flowctrl's post-processing is NULL
  37. // or half-built, so REST handlers that read the results must check this flag instead.
  38. bool bFlowInitialized = false;
  39. bool flowisrunning = false;
  40. // Flow control state is shared by the HTTP server task and the flow task (different cores).
  41. static portMUX_TYPE flowControlMux = portMUX_INITIALIZER_UNLOCKED;
  42. static bool flowPauseRequested = false;
  43. static bool flowPaused = false;
  44. static bool flowManualRunRequested = false;
  45. static bool IsFlowRunning()
  46. {
  47. bool running;
  48. portENTER_CRITICAL(&flowControlMux);
  49. running = flowisrunning;
  50. portEXIT_CRITICAL(&flowControlMux);
  51. return running;
  52. }
  53. static void SetFlowRunning(bool running)
  54. {
  55. portENTER_CRITICAL(&flowControlMux);
  56. flowisrunning = running;
  57. portEXIT_CRITICAL(&flowControlMux);
  58. }
  59. static bool IsFlowPauseRequested()
  60. {
  61. bool requested;
  62. portENTER_CRITICAL(&flowControlMux);
  63. requested = flowPauseRequested;
  64. portEXIT_CRITICAL(&flowControlMux);
  65. return requested;
  66. }
  67. static bool IsFlowPaused()
  68. {
  69. bool paused;
  70. portENTER_CRITICAL(&flowControlMux);
  71. paused = flowPaused;
  72. portEXIT_CRITICAL(&flowControlMux);
  73. return paused;
  74. }
  75. static void RequestFlowPause()
  76. {
  77. portENTER_CRITICAL(&flowControlMux);
  78. flowPauseRequested = true;
  79. portEXIT_CRITICAL(&flowControlMux);
  80. }
  81. static void RequestFlowResume()
  82. {
  83. portENTER_CRITICAL(&flowControlMux);
  84. flowPauseRequested = false;
  85. flowPaused = false;
  86. flowManualRunRequested = false;
  87. portEXIT_CRITICAL(&flowControlMux);
  88. }
  89. static bool QueueManualRunWhilePaused()
  90. {
  91. bool queued = false;
  92. portENTER_CRITICAL(&flowControlMux);
  93. if (flowPauseRequested && !flowisrunning)
  94. {
  95. flowManualRunRequested = true;
  96. queued = true;
  97. }
  98. portEXIT_CRITICAL(&flowControlMux);
  99. return queued;
  100. }
  101. // Called only by task_autodoFlow at the start of each scheduling iteration.
  102. // A queued manual run is allowed through once, but the automatic pause remains set.
  103. static bool UpdateFlowPauseStateForTask()
  104. {
  105. bool shouldPause = false;
  106. portENTER_CRITICAL(&flowControlMux);
  107. if (flowPauseRequested && flowManualRunRequested && !flowisrunning)
  108. {
  109. flowManualRunRequested = false;
  110. flowPaused = false;
  111. }
  112. else if (flowPauseRequested)
  113. {
  114. flowPaused = true;
  115. shouldPause = true;
  116. }
  117. else
  118. {
  119. flowPaused = false;
  120. flowManualRunRequested = false;
  121. }
  122. portEXIT_CRITICAL(&flowControlMux);
  123. return shouldPause;
  124. }
  125. static void ResetFlowControlState()
  126. {
  127. portENTER_CRITICAL(&flowControlMux);
  128. flowPauseRequested = false;
  129. flowPaused = false;
  130. flowManualRunRequested = false;
  131. flowisrunning = false;
  132. portEXIT_CRITICAL(&flowControlMux);
  133. }
  134. long auto_interval = 0;
  135. bool autostartIsEnabled = false;
  136. int countRounds = 0;
  137. bool isPlannedReboot = false;
  138. static const char *TAG = "MAINCTRL";
  139. // #define DEBUG_DETAIL_ON
  140. void CheckIsPlannedReboot(void)
  141. {
  142. FILE *pfile;
  143. if ((pfile = fopen("/sdcard/reboot.txt", "r")) == NULL)
  144. {
  145. // LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Initial boot or not a planned reboot");
  146. isPlannedReboot = false;
  147. }
  148. else
  149. {
  150. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Planned reboot");
  151. DeleteFile("/sdcard/reboot.txt"); // Prevent Boot Loop!!!
  152. isPlannedReboot = true;
  153. }
  154. }
  155. bool getIsPlannedReboot(void)
  156. {
  157. return isPlannedReboot;
  158. }
  159. int getCountFlowRounds(void)
  160. {
  161. return countRounds;
  162. }
  163. esp_err_t GetJPG(std::string _filename, httpd_req_t *req)
  164. {
  165. return flowctrl.GetJPGStream(_filename, req);
  166. }
  167. esp_err_t GetRawJPG(httpd_req_t *req, bool previewCapture)
  168. {
  169. return flowctrl.SendRawJPG(req, previewCapture);
  170. }
  171. bool isSetupModusActive(void)
  172. {
  173. return flowctrl.getStatusSetupModus();
  174. }
  175. void DeleteMainFlowTask(void)
  176. {
  177. #ifdef DEBUG_DETAIL_ON
  178. ESP_LOGD(TAG, "DeleteMainFlowTask: xHandletask_autodoFlow: %ld", (long)xHandletask_autodoFlow);
  179. #endif
  180. if (xHandletask_autodoFlow != NULL)
  181. {
  182. vTaskDelete(xHandletask_autodoFlow);
  183. xHandletask_autodoFlow = NULL;
  184. }
  185. #ifdef DEBUG_DETAIL_ON
  186. ESP_LOGD(TAG, "Killed: xHandletask_autodoFlow");
  187. #endif
  188. }
  189. void doInit(void)
  190. {
  191. bFlowInitialized = false;
  192. #ifdef DEBUG_DETAIL_ON
  193. ESP_LOGD(TAG, "Start flowctrl.InitFlow(config);");
  194. #endif
  195. flowctrl.InitFlow(CONFIG_FILE);
  196. bFlowInitialized = true;
  197. #ifdef DEBUG_DETAIL_ON
  198. ESP_LOGD(TAG, "Finished flowctrl.InitFlow(config);");
  199. #endif
  200. /* GPIO handler has to be initialized before MQTT init to ensure proper topic subscription */
  201. gpio_handler_init();
  202. #ifdef ENABLE_MQTT
  203. flowctrl.StartMQTTService();
  204. #endif // ENABLE_MQTT
  205. }
  206. bool doflow(void)
  207. {
  208. std::string zw_time = getCurrentTimeString(LOGFILE_TIME_FORMAT);
  209. ESP_LOGD(TAG, "doflow - start %s", zw_time.c_str());
  210. SetFlowRunning(true);
  211. flowctrl.doFlow(zw_time);
  212. SetFlowRunning(false);
  213. #ifdef DEBUG_DETAIL_ON
  214. ESP_LOGD(TAG, "doflow - end %s", zw_time.c_str());
  215. #endif
  216. return true;
  217. }
  218. esp_err_t handler_get_heap(httpd_req_t *req)
  219. {
  220. #ifdef DEBUG_DETAIL_ON
  221. LogFile.WriteHeapInfo("handler_get_heap - Start");
  222. ESP_LOGD(TAG, "handler_get_heap uri: %s", req->uri);
  223. #endif
  224. std::string zw = "Heap info:<br>" + getESPHeapInfo();
  225. #ifdef TASK_ANALYSIS_ON
  226. char *pcTaskList = (char *)calloc_psram_heap(std::string(TAG) + "->pcTaskList", 1, sizeof(char) * 768, MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM);
  227. if (pcTaskList)
  228. {
  229. vTaskList(pcTaskList);
  230. zw = zw + "<br><br>Task info:<br><pre>Name | State | Prio | Lowest stacksize | Creation order | CPU (-1=NoAffinity)<br>" + std::string(pcTaskList) + "</pre>";
  231. free_psram_heap(std::string(TAG) + "->pcTaskList", pcTaskList);
  232. }
  233. else
  234. {
  235. zw = zw + "<br><br>Task info:<br>ERROR - Allocation of TaskList buffer in PSRAM failed";
  236. }
  237. #endif
  238. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  239. if (zw.length() > 0)
  240. {
  241. httpd_resp_send(req, zw.c_str(), zw.length());
  242. }
  243. else
  244. {
  245. httpd_resp_send(req, NULL, 0);
  246. }
  247. #ifdef DEBUG_DETAIL_ON
  248. LogFile.WriteHeapInfo("handler_get_heap - Done");
  249. #endif
  250. return ESP_OK;
  251. }
  252. esp_err_t handler_init(httpd_req_t *req)
  253. {
  254. #ifdef DEBUG_DETAIL_ON
  255. LogFile.WriteHeapInfo("handler_init - Start");
  256. ESP_LOGD(TAG, "handler_doinit uri: %s", req->uri);
  257. #endif
  258. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  259. // Rebuilding the flow at runtime is not safe: InitFlow() keeps the old ClassFlow objects (a second full
  260. // pipeline, ~1.2 MB PSRAM, until allocations fail and the device panics) and races with a running round.
  261. // Apply the configuration with a reboot instead.
  262. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "/doinit requested -> rebooting to apply the configuration");
  263. const char *resp_str = "Reboot to apply the configuration<br>";
  264. httpd_resp_send(req, resp_str, HTTPD_RESP_USE_STRLEN);
  265. doReboot();
  266. #ifdef DEBUG_DETAIL_ON
  267. LogFile.WriteHeapInfo("handler_init - Done");
  268. #endif
  269. return ESP_OK;
  270. }
  271. static esp_err_t handler_stream_worker(httpd_req_t *req)
  272. {
  273. char _query[50] = "";
  274. char _value[10];
  275. bool flashlightOn = false;
  276. if (httpd_req_get_url_query_str(req, _query, 50) == ESP_OK)
  277. {
  278. if (httpd_query_key_value(_query, "flashlight", _value, 10) == ESP_OK &&
  279. strlen(_value) > 0)
  280. {
  281. flashlightOn = true;
  282. }
  283. }
  284. return Camera.CaptureToStream(req, flashlightOn);
  285. }
  286. esp_err_t handler_stream(httpd_req_t *req)
  287. {
  288. return dispatch_camera_http_request_async(req, handler_stream_worker, "stream");
  289. }
  290. esp_err_t handler_flow_start(httpd_req_t *req)
  291. {
  292. #ifdef DEBUG_DETAIL_ON
  293. LogFile.WriteHeapInfo("handler_flow_start - Start");
  294. #endif
  295. ESP_LOGD(TAG, "handler_flow_start uri: %s", req->uri);
  296. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  297. if (autostartIsEnabled && bTaskAutoFlowCreated && bFlowInitialized)
  298. {
  299. if (IsFlowRunning())
  300. {
  301. const char *resp_str = "A flow round is already running";
  302. httpd_resp_send(req, resp_str, HTTPD_RESP_USE_STRLEN);
  303. }
  304. else if (IsFlowPauseRequested())
  305. {
  306. QueueManualRunWhilePaused();
  307. if (xHandletask_autodoFlow != NULL) xTaskAbortDelay(xHandletask_autodoFlow);
  308. const char *resp_str = "One manual round is triggered; the automatic flow will remain paused afterwards";
  309. httpd_resp_send(req, resp_str, HTTPD_RESP_USE_STRLEN);
  310. }
  311. else
  312. {
  313. if (xHandletask_autodoFlow != NULL) xTaskAbortDelay(xHandletask_autodoFlow);
  314. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Flow start triggered by REST API /flow_start");
  315. const char *resp_str = "The flow is going to be started immediately";
  316. httpd_resp_send(req, resp_str, HTTPD_RESP_USE_STRLEN);
  317. }
  318. }
  319. else
  320. {
  321. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Flow start triggered by REST API, but flow is not active!");
  322. httpd_resp_send_err(req, HTTPD_403_FORBIDDEN, "Flow start triggered by REST API, but flow is not active");
  323. }
  324. #ifdef DEBUG_DETAIL_ON
  325. LogFile.WriteHeapInfo("handler_flow_start - Done");
  326. #endif
  327. return ESP_OK;
  328. }
  329. esp_err_t handler_flow_pause(httpd_req_t *req)
  330. {
  331. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  332. if (!autostartIsEnabled || !bTaskAutoFlowCreated || !bFlowInitialized)
  333. {
  334. httpd_resp_send_err(req, HTTPD_403_FORBIDDEN, "Flow is not active and cannot be paused");
  335. return ESP_FAIL;
  336. }
  337. if (IsFlowPaused())
  338. {
  339. const char *resp_str = "Flow is already paused";
  340. httpd_resp_send(req, resp_str, HTTPD_RESP_USE_STRLEN);
  341. return ESP_OK;
  342. }
  343. RequestFlowPause();
  344. if (xHandletask_autodoFlow != NULL) xTaskAbortDelay(xHandletask_autodoFlow);
  345. const char *resp_str = IsFlowRunning()
  346. ? "Pause requested. The current round will finish before the flow pauses"
  347. : "Pause requested. No further automatic round will start";
  348. httpd_resp_send(req, resp_str, HTTPD_RESP_USE_STRLEN);
  349. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Flow pause requested through Web-UI");
  350. return ESP_OK;
  351. }
  352. esp_err_t handler_flow_resume(httpd_req_t *req)
  353. {
  354. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  355. if (!autostartIsEnabled || !bTaskAutoFlowCreated || !bFlowInitialized)
  356. {
  357. httpd_resp_send_err(req, HTTPD_403_FORBIDDEN, "Flow is not active and cannot be resumed");
  358. return ESP_FAIL;
  359. }
  360. RequestFlowResume();
  361. if (xHandletask_autodoFlow != NULL) xTaskAbortDelay(xHandletask_autodoFlow);
  362. const char *resp_str = "Automatic flow resumed. The next round starts immediately";
  363. httpd_resp_send(req, resp_str, HTTPD_RESP_USE_STRLEN);
  364. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Automatic flow resumed through Web-UI");
  365. return ESP_OK;
  366. }
  367. #ifdef ENABLE_MQTT
  368. esp_err_t MQTTCtrlFlowStart(std::string _topic)
  369. {
  370. #ifdef DEBUG_DETAIL_ON
  371. LogFile.WriteHeapInfo("MQTTCtrlFlowStart - Start");
  372. #endif
  373. ESP_LOGD(TAG, "MQTTCtrlFlowStart: topic %s", _topic.c_str());
  374. if (autostartIsEnabled)
  375. {
  376. if (IsFlowPauseRequested())
  377. {
  378. if (!IsFlowRunning() && QueueManualRunWhilePaused() && xHandletask_autodoFlow != NULL)
  379. xTaskAbortDelay(xHandletask_autodoFlow);
  380. }
  381. else if (xHandletask_autodoFlow != NULL)
  382. {
  383. xTaskAbortDelay(xHandletask_autodoFlow); // Start immediately if the flow task is in its interval delay.
  384. }
  385. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Flow start triggered by MQTT topic " + _topic);
  386. }
  387. else
  388. {
  389. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Flow start triggered by MQTT topic " + _topic + ", but flow is not active!");
  390. }
  391. #ifdef DEBUG_DETAIL_ON
  392. LogFile.WriteHeapInfo("MQTTCtrlFlowStart - Done");
  393. #endif
  394. return ESP_OK;
  395. }
  396. #endif // ENABLE_MQTT
  397. esp_err_t handler_json(httpd_req_t *req)
  398. {
  399. #ifdef DEBUG_DETAIL_ON
  400. LogFile.WriteHeapInfo("handler_json - Start");
  401. #endif
  402. ESP_LOGD(TAG, "handler_JSON uri: %s", req->uri);
  403. if (bTaskAutoFlowCreated && bFlowInitialized)
  404. {
  405. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  406. httpd_resp_set_type(req, "application/json");
  407. std::string zw = flowctrl.getJSON();
  408. if (zw.length() > 0)
  409. {
  410. httpd_resp_send(req, zw.c_str(), zw.length());
  411. }
  412. else
  413. {
  414. httpd_resp_send(req, NULL, 0);
  415. }
  416. }
  417. else
  418. {
  419. httpd_resp_send_err(req, HTTPD_403_FORBIDDEN, "Flow not (yet) started: REST API /json not yet available!");
  420. return ESP_ERR_NOT_FOUND;
  421. }
  422. #ifdef DEBUG_DETAIL_ON
  423. LogFile.WriteHeapInfo("handler_JSON - Done");
  424. #endif
  425. return ESP_OK;
  426. }
  427. /**
  428. * Generates a http response containing the OpenMetrics (https://openmetrics.io/) text wire format
  429. * according to https://github.com/OpenObservability/OpenMetrics/blob/main/specification/OpenMetrics.md#text-format.
  430. *
  431. * A MetricFamily with a Metric for each Sequence is provided. If no valid value is available, the metric is not provided.
  432. * MetricPoints are provided without a timestamp. Additional metrics with some device information is also provided.
  433. *
  434. * The metric name prefix is 'ai_on_the_edge_device_'.
  435. *
  436. * example configuration for Prometheus (`prometheus.yml`):
  437. *
  438. * - job_name: watermeter
  439. * static_configs:
  440. * - targets: ['watermeter.fritz.box']
  441. *
  442. */
  443. esp_err_t handler_openmetrics(httpd_req_t *req)
  444. {
  445. #ifdef DEBUG_DETAIL_ON
  446. LogFile.WriteHeapInfo("handler_openmetrics - Start");
  447. #endif
  448. ESP_LOGD(TAG, "handler_openmetrics uri: %s", req->uri);
  449. if (bTaskAutoFlowCreated && bFlowInitialized)
  450. {
  451. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  452. httpd_resp_set_type(req, "text/plain"); // application/openmetrics-text is not yet supported by prometheus so we use text/plain for now
  453. const string metricNamePrefix = "ai_on_the_edge_device";
  454. // get current measurement (flow)
  455. string response = createSequenceMetrics(metricNamePrefix, flowctrl.getNumbers());
  456. // CPU Temperature
  457. response += createMetric(metricNamePrefix + "_cpu_temperature_celsius", "current cpu temperature in celsius", "gauge", std::to_string((int)temperatureRead()));
  458. // WiFi signal strength
  459. response += createMetric(metricNamePrefix + "_rssi_dbm", "current WiFi signal strength in dBm", "gauge", std::to_string(get_WIFI_RSSI()));
  460. // memory info
  461. response += createMetric(metricNamePrefix + "_memory_heap_free_bytes", "available heap memory", "gauge", std::to_string(getESPHeapSize()));
  462. // device uptime
  463. response += createMetric(metricNamePrefix + "_uptime_seconds", "device uptime in seconds", "gauge", std::to_string((long)getUpTime()));
  464. // data aquisition round
  465. response += createMetric(metricNamePrefix + "_rounds_total", "data aquisition rounds since device startup", "counter", std::to_string(countRounds));
  466. // the response always contains at least the metadata (HELP, TYPE) for the MetricFamily so no length check is needed
  467. httpd_resp_send(req, response.c_str(), response.length());
  468. }
  469. else
  470. {
  471. httpd_resp_send_err(req, HTTPD_403_FORBIDDEN, "Flow not (yet) started: REST API /metrics not yet available!");
  472. return ESP_ERR_NOT_FOUND;
  473. }
  474. #ifdef DEBUG_DETAIL_ON
  475. LogFile.WriteHeapInfo("handler_openmetrics - Done");
  476. #endif
  477. return ESP_OK;
  478. }
  479. esp_err_t handler_wasserzaehler(httpd_req_t *req)
  480. {
  481. #ifdef DEBUG_DETAIL_ON
  482. LogFile.WriteHeapInfo("handler water counter - Start");
  483. #endif
  484. if (bTaskAutoFlowCreated)
  485. {
  486. bool _rawValue = false;
  487. bool _noerror = false;
  488. bool _all = false;
  489. std::string _type = "value";
  490. std::string zw;
  491. ESP_LOGD(TAG, "handler water counter uri: %s", req->uri);
  492. char _query[100] = ""; // stays empty when the request has no query string
  493. char _size[10];
  494. if (httpd_req_get_url_query_str(req, _query, 100) == ESP_OK)
  495. {
  496. // ESP_LOGD(TAG, "Query: %s", _query);
  497. if (httpd_query_key_value(_query, "all", _size, 10) == ESP_OK)
  498. {
  499. #ifdef DEBUG_DETAIL_ON
  500. ESP_LOGD(TAG, "all is found%s", _size);
  501. #endif
  502. _all = true;
  503. }
  504. if (httpd_query_key_value(_query, "type", _size, 10) == ESP_OK)
  505. {
  506. #ifdef DEBUG_DETAIL_ON
  507. ESP_LOGD(TAG, "all is found: %s", _size);
  508. #endif
  509. _type = std::string(_size);
  510. }
  511. if (httpd_query_key_value(_query, "rawvalue", _size, 10) == ESP_OK)
  512. {
  513. #ifdef DEBUG_DETAIL_ON
  514. ESP_LOGD(TAG, "rawvalue is found: %s", _size);
  515. #endif
  516. _rawValue = true;
  517. }
  518. if (httpd_query_key_value(_query, "noerror", _size, 10) == ESP_OK)
  519. {
  520. #ifdef DEBUG_DETAIL_ON
  521. ESP_LOGD(TAG, "noerror is found: %s", _size);
  522. #endif
  523. _noerror = true;
  524. }
  525. }
  526. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  527. if (_all)
  528. {
  529. httpd_resp_set_type(req, "text/plain");
  530. ESP_LOGD(TAG, "TYPE: %s", _type.c_str());
  531. int _intype = READOUT_TYPE_VALUE;
  532. if (_type == "prevalue")
  533. {
  534. _intype = READOUT_TYPE_PREVALUE;
  535. }
  536. if (_type == "raw")
  537. {
  538. _intype = READOUT_TYPE_RAWVALUE;
  539. }
  540. if (_type == "error")
  541. {
  542. _intype = READOUT_TYPE_ERROR;
  543. }
  544. zw = flowctrl.getReadoutAll(_intype);
  545. ESP_LOGD(TAG, "ZW: %s", zw.c_str());
  546. if (zw.length() > 0)
  547. {
  548. httpd_resp_send(req, zw.c_str(), zw.length());
  549. }
  550. return ESP_OK;
  551. }
  552. std::string status = flowctrl.getActStatus();
  553. std::string query = std::string(_query);
  554. // ESP_LOGD(TAG, "Query: %s, query.c_str());
  555. if (query.find("full") != std::string::npos)
  556. {
  557. std::string txt;
  558. httpd_resp_set_type(req, "text/html; charset=utf-8");
  559. txt = "<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"UTF-8\"></head><body style=\"font-family: arial\">";
  560. if ((countRounds <= 1) && (status != std::string("Flow finished")))
  561. {
  562. // First round not completed yet
  563. txt += "<h3>Please wait for the first round to complete!</h3><h3>Current state: " + status + "</h3>\n";
  564. }
  565. else
  566. {
  567. txt += "<h3>Value</h3>";
  568. }
  569. httpd_resp_sendstr_chunk(req, txt.c_str());
  570. }
  571. if (query.find("full") == std::string::npos)
  572. {
  573. httpd_resp_set_type(req, "text/plain");
  574. }
  575. zw = flowctrl.getReadout(_rawValue, _noerror, 0);
  576. if (zw.length() > 0)
  577. {
  578. httpd_resp_sendstr_chunk(req, zw.c_str());
  579. }
  580. if (query.find("full") != std::string::npos)
  581. {
  582. std::string txt, zw;
  583. if ((countRounds <= 1) && (status != std::string("Flow finished")))
  584. {
  585. // First round not completed yet
  586. // Nothing to do
  587. }
  588. else
  589. {
  590. /* Digit ROIs */
  591. txt = "<hr><h3>Recognized Digit ROIs (previous round)</h3>\n";
  592. txt += "<table style=\"border-spacing: 5px\"><tr style=\"text-align: center; vertical-align: top;\">\n";
  593. std::vector<HTMLInfo *> htmlinfodig;
  594. htmlinfodig = flowctrl.GetAllDigit();
  595. for (int i = 0; i < htmlinfodig.size(); ++i)
  596. {
  597. if (flowctrl.GetTypeDigit() == Digit)
  598. {
  599. // Numbers greater than 10 and less than 0 indicate NaN, since a Roi can only have values ​​from 0 to 9.
  600. if ((htmlinfodig[i]->val >= 10) || (htmlinfodig[i]->val < 0))
  601. {
  602. zw = "NaN";
  603. }
  604. else
  605. {
  606. zw = std::to_string((int)htmlinfodig[i]->val);
  607. }
  608. txt += "<td style=\"width: 100px\"><h4>" + zw + "</h4><p><img src=\"/img_tmp/" + htmlinfodig[i]->filename + "\"></p></td>\n";
  609. }
  610. else
  611. {
  612. std::stringstream stream;
  613. stream << std::fixed << std::setprecision(1) << htmlinfodig[i]->val;
  614. zw = stream.str();
  615. // Numbers greater than 10 and less than 0 indicate NaN, since a Roi can only have values ​​from 0 to 9.
  616. if ((std::stod(zw) >= 10) || (std::stod(zw) < 0))
  617. {
  618. zw = "NaN";
  619. }
  620. txt += "<td style=\"width: 100px\"><h4>" + zw + "</h4><p><img src=\"/img_tmp/" + htmlinfodig[i]->filename + "\"></p></td>\n";
  621. }
  622. delete htmlinfodig[i];
  623. }
  624. htmlinfodig.clear();
  625. txt += "</tr></table>\n";
  626. httpd_resp_sendstr_chunk(req, txt.c_str());
  627. /* Analog ROIs */
  628. txt = "<hr><h3>Recognized Analog ROIs (previous round)</h3>\n";
  629. txt += "<table style=\"border-spacing: 5px\"><tr style=\"text-align: center; vertical-align: top;\">\n";
  630. std::vector<HTMLInfo *> htmlinfoana;
  631. htmlinfoana = flowctrl.GetAllAnalog();
  632. for (int i = 0; i < htmlinfoana.size(); ++i)
  633. {
  634. std::stringstream stream;
  635. stream << std::fixed << std::setprecision(1) << htmlinfoana[i]->val;
  636. zw = stream.str();
  637. // Numbers greater than 10 and less than 0 indicate NaN, since a Roi can only have values ​​from 0 to 9.
  638. if ((std::stod(zw) >= 10) || (std::stod(zw) < 0))
  639. {
  640. zw = "NaN";
  641. }
  642. txt += "<td style=\"width: 150px;\"><h4>" + zw + "</h4><p><img src=\"/img_tmp/" + htmlinfoana[i]->filename + "\"></p></td>\n";
  643. delete htmlinfoana[i];
  644. }
  645. htmlinfoana.clear();
  646. txt += "</tr>\n</table>\n";
  647. httpd_resp_sendstr_chunk(req, txt.c_str());
  648. /* Full Image
  649. * Only show it after the image got taken */
  650. txt = "<hr><h3>Full Image (current round)</h3>\n";
  651. if ((status == std::string("Initialization")) ||
  652. (status == std::string("Initialization (delayed)")) ||
  653. (status == std::string("Take Image")))
  654. {
  655. txt += "<p>Current state: " + status + "</p>\n";
  656. }
  657. else
  658. {
  659. txt += "<img src=\"/img_tmp/alg_roi.jpg\">\n";
  660. }
  661. httpd_resp_sendstr_chunk(req, txt.c_str());
  662. }
  663. }
  664. if (query.find("full") != std::string::npos)
  665. {
  666. httpd_resp_sendstr_chunk(req, "</body></html>");
  667. }
  668. /* Respond with an empty chunk to signal HTTP response completion */
  669. httpd_resp_sendstr_chunk(req, NULL);
  670. }
  671. else
  672. {
  673. httpd_resp_send_err(req, HTTPD_403_FORBIDDEN, "Flow not (yet) started: REST API /value not available!");
  674. return ESP_ERR_NOT_FOUND;
  675. }
  676. #ifdef DEBUG_DETAIL_ON
  677. LogFile.WriteHeapInfo("handler_wasserzaehler - Done");
  678. #endif
  679. return ESP_OK;
  680. }
  681. esp_err_t handler_editflow(httpd_req_t *req)
  682. {
  683. #ifdef DEBUG_DETAIL_ON
  684. LogFile.WriteHeapInfo("handler_editflow - Start");
  685. #endif
  686. ESP_LOGD(TAG, "handler_editflow uri: %s", req->uri);
  687. char _query[512] = ""; // stays empty when the request has no query string
  688. char _valuechar[30];
  689. std::string _task;
  690. if (httpd_req_get_url_query_str(req, _query, 512) == ESP_OK)
  691. {
  692. if (httpd_query_key_value(_query, "task", _valuechar, 30) == ESP_OK)
  693. {
  694. #ifdef DEBUG_DETAIL_ON
  695. ESP_LOGD(TAG, "task is found: %s", _valuechar);
  696. #endif
  697. _task = std::string(_valuechar);
  698. }
  699. }
  700. if (_task.compare("lists") == 0)
  701. {
  702. ESP_LOGD(TAG, "Get combined editflow lists");
  703. return get_editflow_lists_file_handler(req);
  704. }
  705. if (_task.compare("namenumbers") == 0)
  706. {
  707. ESP_LOGD(TAG, "Get NUMBER list");
  708. return get_numbers_file_handler(req);
  709. }
  710. if (_task.compare("data") == 0)
  711. {
  712. ESP_LOGD(TAG, "Get data list");
  713. return get_data_file_handler(req);
  714. }
  715. if (_task.compare("tflite") == 0)
  716. {
  717. ESP_LOGD(TAG, "Get tflite list");
  718. return get_tflite_file_handler(req);
  719. }
  720. if (_task.compare("copy") == 0)
  721. {
  722. std::string in, out, zw;
  723. httpd_query_key_value(_query, "in", _valuechar, 30);
  724. in = std::string(_valuechar);
  725. httpd_query_key_value(_query, "out", _valuechar, 30);
  726. out = std::string(_valuechar);
  727. #ifdef DEBUG_DETAIL_ON
  728. ESP_LOGD(TAG, "in: %s", in.c_str());
  729. ESP_LOGD(TAG, "out: %s", out.c_str());
  730. #endif
  731. in = "/sdcard" + in;
  732. out = "/sdcard" + out;
  733. CopyFile(in, out);
  734. zw = "Copy Done";
  735. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  736. httpd_resp_send(req, zw.c_str(), zw.length());
  737. }
  738. if (_task.compare("cutref") == 0)
  739. {
  740. std::string in, out, zw;
  741. int x = 0, y = 0, dx = 20, dy = 20;
  742. bool enhance = false;
  743. httpd_query_key_value(_query, "in", _valuechar, 30);
  744. in = std::string(_valuechar);
  745. httpd_query_key_value(_query, "out", _valuechar, 30);
  746. out = std::string(_valuechar);
  747. httpd_query_key_value(_query, "x", _valuechar, 30);
  748. std::string _x = std::string(_valuechar);
  749. if (isStringNumeric(_x))
  750. {
  751. x = std::stoi(_x);
  752. }
  753. httpd_query_key_value(_query, "y", _valuechar, 30);
  754. std::string _y = std::string(_valuechar);
  755. if (isStringNumeric(_y))
  756. {
  757. y = std::stoi(_y);
  758. }
  759. httpd_query_key_value(_query, "dx", _valuechar, 30);
  760. std::string _dx = std::string(_valuechar);
  761. if (isStringNumeric(_dx))
  762. {
  763. dx = std::stoi(_dx);
  764. }
  765. httpd_query_key_value(_query, "dy", _valuechar, 30);
  766. std::string _dy = std::string(_valuechar);
  767. if (isStringNumeric(_dy))
  768. {
  769. dy = std::stoi(_dy);
  770. }
  771. #ifdef DEBUG_DETAIL_ON
  772. ESP_LOGD(TAG, "in: %s", in.c_str());
  773. ESP_LOGD(TAG, "out: %s", out.c_str());
  774. ESP_LOGD(TAG, "x: %s", _x.c_str());
  775. ESP_LOGD(TAG, "y: %s", _y.c_str());
  776. ESP_LOGD(TAG, "dx: %s", _dx.c_str());
  777. ESP_LOGD(TAG, "dy: %s", _dy.c_str());
  778. #endif
  779. if (httpd_query_key_value(_query, "enhance", _valuechar, 10) == ESP_OK)
  780. {
  781. string _enhance = std::string(_valuechar);
  782. if (_enhance.compare("true") == 0)
  783. {
  784. enhance = true;
  785. }
  786. }
  787. in = "/sdcard" + in;
  788. out = "/sdcard" + out;
  789. std::string out2 = out.substr(0, out.length() - 4) + "_org.jpg";
  790. if ((flowctrl.SetupModeActive || IsFlowPaused() || (flowctrl.getActStatus() == std::string("Flow finished"))) && psram_init_shared_memory_for_take_image_step())
  791. {
  792. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Taking image for Alignment Mark Update...");
  793. bool operationOk = false;
  794. CAlignAndCutImage *caic = new (std::nothrow) CAlignAndCutImage("cutref", in);
  795. if (caic != NULL) {
  796. caic->CutAndSave(out2, x, y, dx, dy);
  797. delete caic;
  798. CImageBasis *cim = new (std::nothrow) CImageBasis("cutref", out2);
  799. if (cim != NULL && cim->ImageOkay()) {
  800. if (enhance) cim->Contrast(90);
  801. cim->SaveToFile(out);
  802. operationOk = true;
  803. }
  804. delete cim;
  805. }
  806. if (operationOk) zw = "CutImage Done";
  807. else {
  808. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Alignment mark update failed due to an allocation or image I/O error");
  809. zw = "CutImage Failed";
  810. }
  811. // Release only after every STBI-backed temporary image has been destroyed.
  812. psram_deinit_shared_memory_for_take_image_step();
  813. }
  814. else
  815. {
  816. LogFile.WriteToFile(ESP_LOG_WARN, TAG, std::string("Taking image for Alignment Mark not possible while device") + " is busy with a round (Current State: '" + flowctrl.getActStatus() + "')!");
  817. zw = "Device Busy";
  818. }
  819. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  820. httpd_resp_send(req, zw.c_str(), zw.length());
  821. }
  822. // wird beim Erstellen eines neuen Referenzbildes aufgerufen
  823. std::string sys_status = flowctrl.getActStatus();
  824. if ((sys_status != "Take Image") && (sys_status != "Aligning"))
  825. {
  826. if ((_task.compare("test_take") == 0) || (_task.compare("cam_settings") == 0))
  827. {
  828. std::string _host = "";
  829. // CFstatus is only used as the temporary settings copy for test_take.
  830. const bool isTestTake = (_task.compare("test_take") == 0);
  831. CameraSettings *settingsTarget = &static_cast<CameraSettings &>(CCstatus);
  832. if (isTestTake)
  833. {
  834. static_cast<CameraSettings &>(CFstatus) =
  835. static_cast<const CameraSettings &>(CCstatus);
  836. settingsTarget = &static_cast<CameraSettings &>(CFstatus);
  837. }
  838. CameraSettings &settings = *settingsTarget;
  839. if (httpd_query_key_value(_query, "host", _valuechar, 30) == ESP_OK)
  840. {
  841. _host = std::string(_valuechar);
  842. }
  843. if (httpd_query_key_value(_query, "xclk", _valuechar, 30) == ESP_OK)
  844. {
  845. std::string _xclk = std::string(_valuechar);
  846. if (isStringNumeric(_xclk))
  847. {
  848. settings.CamXclkFreqMhz = clipInt(std::stoi(_xclk), 20, 1);
  849. }
  850. }
  851. if (httpd_query_key_value(_query, "waitb", _valuechar, 30) == ESP_OK)
  852. {
  853. std::string _waitb = std::string(_valuechar);
  854. if (isStringNumeric(_waitb))
  855. {
  856. settings.WaitBeforePicture = std::max(0, std::stoi(_valuechar));
  857. }
  858. }
  859. if (httpd_query_key_value(_query, "aecgc", _valuechar, 30) == ESP_OK)
  860. {
  861. std::string _aecgc = std::string(_valuechar);
  862. if (isStringNumeric(_aecgc))
  863. {
  864. int _aecgc_ = std::stoi(_valuechar);
  865. switch (_aecgc_)
  866. {
  867. case 1:
  868. settings.ImageGainceiling = GAINCEILING_4X;
  869. break;
  870. case 2:
  871. settings.ImageGainceiling = GAINCEILING_8X;
  872. break;
  873. case 3:
  874. settings.ImageGainceiling = GAINCEILING_16X;
  875. break;
  876. case 4:
  877. settings.ImageGainceiling = GAINCEILING_32X;
  878. break;
  879. case 5:
  880. settings.ImageGainceiling = GAINCEILING_64X;
  881. break;
  882. case 6:
  883. settings.ImageGainceiling = GAINCEILING_128X;
  884. break;
  885. default:
  886. settings.ImageGainceiling = GAINCEILING_2X;
  887. }
  888. }
  889. else
  890. {
  891. if (_aecgc == "X4") {
  892. settings.ImageGainceiling = GAINCEILING_4X;
  893. }
  894. else if (_aecgc == "X8") {
  895. settings.ImageGainceiling = GAINCEILING_8X;
  896. }
  897. else if (_aecgc == "X16") {
  898. settings.ImageGainceiling = GAINCEILING_16X;
  899. }
  900. else if (_aecgc == "X32") {
  901. settings.ImageGainceiling = GAINCEILING_32X;
  902. }
  903. else if (_aecgc == "X64") {
  904. settings.ImageGainceiling = GAINCEILING_64X;
  905. }
  906. else if (_aecgc == "X128") {
  907. settings.ImageGainceiling = GAINCEILING_128X;
  908. }
  909. else {
  910. settings.ImageGainceiling = GAINCEILING_2X;
  911. }
  912. }
  913. }
  914. if (httpd_query_key_value(_query, "qual", _valuechar, 30) == ESP_OK)
  915. {
  916. std::string _qual = std::string(_valuechar);
  917. if (isStringNumeric(_qual))
  918. {
  919. int _qual_ = std::stoi(_valuechar);
  920. settings.ImageQuality = clipInt(_qual_, 63, 6);
  921. }
  922. }
  923. if (httpd_query_key_value(_query, "bri", _valuechar, 30) == ESP_OK)
  924. {
  925. std::string _bri = std::string(_valuechar);
  926. if (isStringNumeric(_bri))
  927. {
  928. int _bri_ = std::stoi(_valuechar);
  929. settings.ImageBrightness = clipInt(_bri_, 2, -2);
  930. }
  931. }
  932. if (httpd_query_key_value(_query, "con", _valuechar, 30) == ESP_OK)
  933. {
  934. std::string _con = std::string(_valuechar);
  935. if (isStringNumeric(_con))
  936. {
  937. int _con_ = std::stoi(_valuechar);
  938. settings.ImageContrast = clipInt(_con_, 2, -2);
  939. }
  940. }
  941. if (httpd_query_key_value(_query, "sat", _valuechar, 30) == ESP_OK)
  942. {
  943. std::string _sat = std::string(_valuechar);
  944. if (isStringNumeric(_sat))
  945. {
  946. int _sat_ = std::stoi(_valuechar);
  947. settings.ImageSaturation = clipInt(_sat_, 2, -2);
  948. }
  949. }
  950. if (httpd_query_key_value(_query, "shp", _valuechar, 30) == ESP_OK)
  951. {
  952. std::string _shp = std::string(_valuechar);
  953. if (isStringNumeric(_shp))
  954. {
  955. int _shp_ = std::stoi(_valuechar);
  956. if (CCstatus.CamSensor_id == OV2640_PID)
  957. {
  958. settings.ImageSharpness = clipInt(_shp_, 2, -2);
  959. }
  960. else
  961. {
  962. settings.ImageSharpness = clipInt(_shp_, 3, -3);
  963. }
  964. }
  965. }
  966. if (httpd_query_key_value(_query, "ashp", _valuechar, 30) == ESP_OK)
  967. {
  968. std::string _ashp = std::string(_valuechar);
  969. settings.ImageAutoSharpness = alphanumericToBoolean(_ashp);
  970. }
  971. if (httpd_query_key_value(_query, "spe", _valuechar, 30) == ESP_OK)
  972. {
  973. std::string _spe = std::string(_valuechar);
  974. if (isStringNumeric(_spe))
  975. {
  976. int _spe_ = std::stoi(_valuechar);
  977. settings.ImageSpecialEffect = clipInt(_spe_, 6, 0);
  978. }
  979. else
  980. {
  981. if (_spe == "negative") {
  982. settings.ImageSpecialEffect = 1;
  983. }
  984. else if (_spe == "grayscale") {
  985. settings.ImageSpecialEffect = 2;
  986. }
  987. else if (_spe == "red") {
  988. settings.ImageSpecialEffect = 3;
  989. }
  990. else if (_spe == "green") {
  991. settings.ImageSpecialEffect = 4;
  992. }
  993. else if (_spe == "blue") {
  994. settings.ImageSpecialEffect = 5;
  995. }
  996. else if (_spe == "retro") {
  997. settings.ImageSpecialEffect = 6;
  998. }
  999. else {
  1000. settings.ImageSpecialEffect = 0;
  1001. }
  1002. }
  1003. }
  1004. if (httpd_query_key_value(_query, "wbm", _valuechar, 30) == ESP_OK)
  1005. {
  1006. std::string _wbm = std::string(_valuechar);
  1007. if (isStringNumeric(_wbm))
  1008. {
  1009. int _wbm_ = std::stoi(_valuechar);
  1010. settings.ImageWbMode = clipInt(_wbm_, 4, 0);
  1011. }
  1012. else
  1013. {
  1014. if (_wbm == "sunny") {
  1015. settings.ImageWbMode = 1;
  1016. }
  1017. else if (_wbm == "cloudy") {
  1018. settings.ImageWbMode = 2;
  1019. }
  1020. else if (_wbm == "office") {
  1021. settings.ImageWbMode = 3;
  1022. }
  1023. else if (_wbm == "home") {
  1024. settings.ImageWbMode = 4;
  1025. }
  1026. else {
  1027. settings.ImageWbMode = 0;
  1028. }
  1029. }
  1030. }
  1031. if (httpd_query_key_value(_query, "awb", _valuechar, 30) == ESP_OK)
  1032. {
  1033. std::string _awb = std::string(_valuechar);
  1034. settings.ImageAwb = alphanumericToBoolean(_awb);
  1035. }
  1036. if (httpd_query_key_value(_query, "awbg", _valuechar, 30) == ESP_OK)
  1037. {
  1038. std::string _awbg = std::string(_valuechar);
  1039. settings.ImageAwbGain = alphanumericToBoolean(_awbg);
  1040. }
  1041. if (httpd_query_key_value(_query, "aec", _valuechar, 30) == ESP_OK)
  1042. {
  1043. std::string _aec = std::string(_valuechar);
  1044. settings.ImageAec = alphanumericToBoolean(_aec);
  1045. }
  1046. if (httpd_query_key_value(_query, "aec2", _valuechar, 30) == ESP_OK)
  1047. {
  1048. std::string _aec2 = std::string(_valuechar);
  1049. settings.ImageAec2 = alphanumericToBoolean(_aec2);
  1050. }
  1051. if (httpd_query_key_value(_query, "ael", _valuechar, 30) == ESP_OK)
  1052. {
  1053. std::string _ael = std::string(_valuechar);
  1054. if (isStringNumeric(_ael))
  1055. {
  1056. int _ael_ = std::stoi(_valuechar);
  1057. if (CCstatus.CamSensor_id == OV2640_PID)
  1058. {
  1059. settings.ImageAeLevel = clipInt(_ael_, 2, -2);
  1060. }
  1061. else
  1062. {
  1063. settings.ImageAeLevel = clipInt(_ael_, 5, -5);
  1064. }
  1065. }
  1066. }
  1067. if (httpd_query_key_value(_query, "aecv", _valuechar, 30) == ESP_OK)
  1068. {
  1069. std::string _aecv = std::string(_valuechar);
  1070. if (isStringNumeric(_aecv))
  1071. {
  1072. int _aecv_ = std::stoi(_valuechar);
  1073. settings.ImageAecValue = clipInt(_aecv_, 1200, 0);
  1074. }
  1075. }
  1076. if (httpd_query_key_value(_query, "agc", _valuechar, 30) == ESP_OK)
  1077. {
  1078. std::string _agc = std::string(_valuechar);
  1079. settings.ImageAgc = alphanumericToBoolean(_agc);
  1080. }
  1081. if (httpd_query_key_value(_query, "agcg", _valuechar, 30) == ESP_OK)
  1082. {
  1083. std::string _agcg = std::string(_valuechar);
  1084. if (isStringNumeric(_agcg))
  1085. {
  1086. int _agcg_ = std::stoi(_valuechar);
  1087. settings.ImageAgcGain = clipInt(_agcg_, 30, 0);
  1088. }
  1089. }
  1090. if (httpd_query_key_value(_query, "bpc", _valuechar, 30) == ESP_OK)
  1091. {
  1092. std::string _bpc = std::string(_valuechar);
  1093. settings.ImageBpc = alphanumericToBoolean(_bpc);
  1094. }
  1095. if (httpd_query_key_value(_query, "wpc", _valuechar, 30) == ESP_OK)
  1096. {
  1097. std::string _wpc = std::string(_valuechar);
  1098. settings.ImageWpc = alphanumericToBoolean(_wpc);
  1099. }
  1100. if (httpd_query_key_value(_query, "rgma", _valuechar, 30) == ESP_OK)
  1101. {
  1102. std::string _rgma = std::string(_valuechar);
  1103. settings.ImageRawGma = alphanumericToBoolean(_rgma);
  1104. }
  1105. if (httpd_query_key_value(_query, "lenc", _valuechar, 30) == ESP_OK)
  1106. {
  1107. std::string _lenc = std::string(_valuechar);
  1108. settings.ImageLenc = alphanumericToBoolean(_lenc);
  1109. }
  1110. if (httpd_query_key_value(_query, "mirror", _valuechar, 30) == ESP_OK)
  1111. {
  1112. std::string _mirror = std::string(_valuechar);
  1113. settings.ImageHmirror = alphanumericToBoolean(_mirror);
  1114. }
  1115. if (httpd_query_key_value(_query, "flip", _valuechar, 30) == ESP_OK)
  1116. {
  1117. std::string _flip = std::string(_valuechar);
  1118. settings.ImageVflip = alphanumericToBoolean(_flip);
  1119. }
  1120. if (httpd_query_key_value(_query, "dcw", _valuechar, 30) == ESP_OK)
  1121. {
  1122. std::string _dcw = std::string(_valuechar);
  1123. settings.ImageDcw = alphanumericToBoolean(_dcw);
  1124. }
  1125. if (httpd_query_key_value(_query, "den", _valuechar, 30) == ESP_OK)
  1126. {
  1127. std::string _idlv = std::string(_valuechar);
  1128. if (isStringNumeric(_idlv))
  1129. {
  1130. int _ImageDenoiseLevel = std::stoi(_valuechar);
  1131. if (CCstatus.CamSensor_id == OV2640_PID)
  1132. {
  1133. settings.ImageDenoiseLevel = 0;
  1134. }
  1135. else
  1136. {
  1137. settings.ImageDenoiseLevel = clipInt(_ImageDenoiseLevel, 8, 0);
  1138. }
  1139. }
  1140. }
  1141. if (httpd_query_key_value(_query, "zoom", _valuechar, 30) == ESP_OK)
  1142. {
  1143. std::string _zoom = std::string(_valuechar);
  1144. settings.ImageZoomEnabled = alphanumericToBoolean(_zoom);
  1145. }
  1146. if (httpd_query_key_value(_query, "zoomx", _valuechar, 30) == ESP_OK)
  1147. {
  1148. std::string _zoomx = std::string(_valuechar);
  1149. if (isStringNumeric(_zoomx))
  1150. {
  1151. int _ImageZoomOffsetX = std::stoi(_valuechar);
  1152. if (CCstatus.CamSensor_id == OV2640_PID)
  1153. {
  1154. settings.ImageZoomOffsetX = clipInt(_ImageZoomOffsetX, 480, -480);
  1155. }
  1156. else if (CCstatus.CamSensor_id == OV3660_PID)
  1157. {
  1158. settings.ImageZoomOffsetX = clipInt(_ImageZoomOffsetX, 704, -704);
  1159. }
  1160. else if (CCstatus.CamSensor_id == OV5640_PID)
  1161. {
  1162. settings.ImageZoomOffsetX = clipInt(_ImageZoomOffsetX, 960, -960);
  1163. }
  1164. }
  1165. }
  1166. if (httpd_query_key_value(_query, "zoomy", _valuechar, 30) == ESP_OK)
  1167. {
  1168. std::string _zoomy = std::string(_valuechar);
  1169. if (isStringNumeric(_zoomy))
  1170. {
  1171. int _ImageZoomOffsetY = std::stoi(_valuechar);
  1172. if (CCstatus.CamSensor_id == OV2640_PID)
  1173. {
  1174. settings.ImageZoomOffsetY = clipInt(_ImageZoomOffsetY, 360, -360);
  1175. }
  1176. else if (CCstatus.CamSensor_id == OV3660_PID)
  1177. {
  1178. settings.ImageZoomOffsetY = clipInt(_ImageZoomOffsetY, 528, -528);
  1179. }
  1180. else if (CCstatus.CamSensor_id == OV5640_PID)
  1181. {
  1182. settings.ImageZoomOffsetY = clipInt(_ImageZoomOffsetY, 720, -720);
  1183. }
  1184. }
  1185. }
  1186. if (httpd_query_key_value(_query, "zooms", _valuechar, 30) == ESP_OK)
  1187. {
  1188. std::string _zooms = std::string(_valuechar);
  1189. if (isStringNumeric(_zooms))
  1190. {
  1191. int _ImageZoomSize = std::stoi(_valuechar);
  1192. if (CCstatus.CamSensor_id == OV2640_PID)
  1193. {
  1194. settings.ImageZoomSize = clipInt(_ImageZoomSize, 29, 0);
  1195. }
  1196. else if (CCstatus.CamSensor_id == OV3660_PID)
  1197. {
  1198. settings.ImageZoomSize = clipInt(_ImageZoomSize, 43, 0);
  1199. }
  1200. else if (CCstatus.CamSensor_id == OV5640_PID)
  1201. {
  1202. settings.ImageZoomSize = clipInt(_ImageZoomSize, 59, 0);
  1203. }
  1204. }
  1205. }
  1206. if (httpd_query_key_value(_query, "ledi", _valuechar, 30) == ESP_OK)
  1207. {
  1208. std::string _ledi = std::string(_valuechar);
  1209. if (isStringNumeric(_ledi))
  1210. {
  1211. int _ImageLedIntensity = std::stoi(_valuechar);
  1212. settings.ImageLedIntensity = Camera.SetLEDIntensity(_ImageLedIntensity);
  1213. }
  1214. }
  1215. if (!isTestTake)
  1216. {
  1217. // Saved camera settings are committed in CCstatus.
  1218. if (Camera.setSensorDatenFromCCstatus() != ESP_OK)
  1219. {
  1220. httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Could not apply committed camera settings");
  1221. return ESP_FAIL;
  1222. }
  1223. ESP_LOGD(TAG, "Cam Settings set");
  1224. std::string _zw = "CamSettingsSet";
  1225. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  1226. httpd_resp_send(req, _zw.c_str(), _zw.length());
  1227. }
  1228. else
  1229. {
  1230. // Only test_take applies temporary camera settings.
  1231. if (Camera.ApplyPreviewSettings(settings) != ESP_OK)
  1232. {
  1233. httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Could not apply temporary camera settings");
  1234. return ESP_FAIL;
  1235. }
  1236. ESP_LOGD(TAG, "test_take - vor TakeImage");
  1237. std::string image_temp = flowctrl.doSingleStep("[TakeImage]", _host);
  1238. const std::string rawImagePath = "/img_tmp/raw.jpg";
  1239. const std::size_t rawImagePosition = image_temp.find(rawImagePath);
  1240. if (rawImagePosition != std::string::npos)
  1241. {
  1242. image_temp.replace(rawImagePosition, rawImagePath.length(),
  1243. rawImagePath + "?preview=1");
  1244. }
  1245. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  1246. httpd_resp_send(req, image_temp.c_str(), image_temp.length());
  1247. }
  1248. }
  1249. if (_task.compare("test_align") == 0)
  1250. {
  1251. std::string _host = "";
  1252. if (httpd_query_key_value(_query, "host", _valuechar, 30) == ESP_OK)
  1253. {
  1254. _host = std::string(_valuechar);
  1255. }
  1256. std::string zw = flowctrl.doSingleStep("[Alignment]", _host);
  1257. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  1258. httpd_resp_send(req, zw.c_str(), zw.length());
  1259. }
  1260. }
  1261. else
  1262. {
  1263. std::string _zw = "DeviceIsBusy";
  1264. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  1265. httpd_resp_send(req, _zw.c_str(), _zw.length());
  1266. }
  1267. #ifdef DEBUG_DETAIL_ON
  1268. LogFile.WriteHeapInfo("handler_editflow - Done");
  1269. #endif
  1270. return ESP_OK;
  1271. }
  1272. esp_err_t handler_statusflow(httpd_req_t *req)
  1273. {
  1274. #ifdef DEBUG_DETAIL_ON
  1275. LogFile.WriteHeapInfo("handler_statusflow - Start");
  1276. #endif
  1277. const char *resp_str;
  1278. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  1279. if (bTaskAutoFlowCreated)
  1280. {
  1281. #ifdef DEBUG_DETAIL_ON
  1282. ESP_LOGD(TAG, "handler_statusflow: %s", req->uri);
  1283. #endif
  1284. std::string zw = flowctrl.getActStatusWithTime();
  1285. resp_str = zw.c_str();
  1286. httpd_resp_send(req, resp_str, HTTPD_RESP_USE_STRLEN);
  1287. }
  1288. else
  1289. {
  1290. resp_str = "Flow task not yet created";
  1291. httpd_resp_send(req, resp_str, HTTPD_RESP_USE_STRLEN);
  1292. }
  1293. #ifdef DEBUG_DETAIL_ON
  1294. LogFile.WriteHeapInfo("handler_statusflow - Done");
  1295. #endif
  1296. return ESP_OK;
  1297. }
  1298. esp_err_t handler_cputemp(httpd_req_t *req)
  1299. {
  1300. #ifdef DEBUG_DETAIL_ON
  1301. LogFile.WriteHeapInfo("handler_cputemp - Start");
  1302. #endif
  1303. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  1304. httpd_resp_send(req, std::to_string((int)temperatureRead()).c_str(), HTTPD_RESP_USE_STRLEN);
  1305. #ifdef DEBUG_DETAIL_ON
  1306. LogFile.WriteHeapInfo("handler_cputemp - End");
  1307. #endif
  1308. return ESP_OK;
  1309. }
  1310. esp_err_t handler_rssi(httpd_req_t *req)
  1311. {
  1312. #ifdef DEBUG_DETAIL_ON
  1313. LogFile.WriteHeapInfo("handler_rssi - Start");
  1314. #endif
  1315. if (getWIFIisConnected())
  1316. {
  1317. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  1318. httpd_resp_send(req, std::to_string(get_WIFI_RSSI()).c_str(), HTTPD_RESP_USE_STRLEN);
  1319. }
  1320. else
  1321. {
  1322. httpd_resp_send_err(req, HTTPD_403_FORBIDDEN, "WIFI not (yet) connected: REST API /rssi not available!");
  1323. return ESP_ERR_NOT_FOUND;
  1324. }
  1325. #ifdef DEBUG_DETAIL_ON
  1326. LogFile.WriteHeapInfo("handler_rssi - End");
  1327. #endif
  1328. return ESP_OK;
  1329. }
  1330. esp_err_t handler_current_date(httpd_req_t *req)
  1331. {
  1332. #ifdef DEBUG_DETAIL_ON
  1333. LogFile.WriteHeapInfo("handler_uptime - Start");
  1334. #endif
  1335. std::string formatedDateAndTime = getCurrentTimeString("%Y-%m-%d %H:%M:%S");
  1336. // std::string formatedDate = getCurrentTimeString("%Y-%m-%d");
  1337. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  1338. httpd_resp_send(req, formatedDateAndTime.c_str(), formatedDateAndTime.length());
  1339. #ifdef DEBUG_DETAIL_ON
  1340. LogFile.WriteHeapInfo("handler_uptime - End");
  1341. #endif
  1342. return ESP_OK;
  1343. }
  1344. esp_err_t handler_uptime(httpd_req_t *req)
  1345. {
  1346. #ifdef DEBUG_DETAIL_ON
  1347. LogFile.WriteHeapInfo("handler_uptime - Start");
  1348. #endif
  1349. std::string formatedUptime = getFormatedUptime(false);
  1350. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  1351. httpd_resp_send(req, formatedUptime.c_str(), formatedUptime.length());
  1352. #ifdef DEBUG_DETAIL_ON
  1353. LogFile.WriteHeapInfo("handler_uptime - End");
  1354. #endif
  1355. return ESP_OK;
  1356. }
  1357. esp_err_t handler_prevalue(httpd_req_t *req)
  1358. {
  1359. #ifdef DEBUG_DETAIL_ON
  1360. LogFile.WriteHeapInfo("handler_prevalue - Start");
  1361. ESP_LOGD(TAG, "handler_prevalue: %s", req->uri);
  1362. #endif
  1363. // Default usage message when handler gets called without any parameter
  1364. const std::string RESTUsageInfo =
  1365. "00: Handler usage:<br>"
  1366. "- To retrieve actual PreValue, please provide only a numbersname, e.g. /setPreValue?numbers=main<br>"
  1367. "- To set PreValue to a new value, please provide a numbersname and a value, e.g. /setPreValue?numbers=main&value=1234.5678<br>"
  1368. "NOTE:<br>"
  1369. "value >= 0.0: Set PreValue to provided value<br>"
  1370. "value < 0.0: Set PreValue to actual RAW value (as long RAW value is a valid number, without N)";
  1371. // Default return error message when no return is programmed
  1372. std::string sReturnMessage = "E90: Uninitialized";
  1373. char _query[100] = ""; // stays empty when the request has no query string
  1374. char _numbersname[50] = "default";
  1375. char _value[20] = "";
  1376. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  1377. if (httpd_req_get_url_query_str(req, _query, 100) == ESP_OK)
  1378. {
  1379. #ifdef DEBUG_DETAIL_ON
  1380. ESP_LOGD(TAG, "Query: %s", _query);
  1381. #endif
  1382. if (httpd_query_key_value(_query, "numbers", _numbersname, 50) != ESP_OK)
  1383. {
  1384. // If request is incomplete
  1385. sReturnMessage = "E91: Query parameter incomplete or not valid!<br> "
  1386. "Call /setPreValue to show REST API usage info and/or check documentation";
  1387. httpd_resp_send(req, sReturnMessage.c_str(), sReturnMessage.length());
  1388. return ESP_FAIL;
  1389. }
  1390. if (httpd_query_key_value(_query, "value", _value, 20) == ESP_OK)
  1391. {
  1392. #ifdef DEBUG_DETAIL_ON
  1393. ESP_LOGD(TAG, "Value: %s", _value);
  1394. #endif
  1395. }
  1396. }
  1397. else
  1398. {
  1399. // if no parameter is provided, print handler usage
  1400. httpd_resp_send(req, RESTUsageInfo.c_str(), RESTUsageInfo.length());
  1401. return ESP_OK;
  1402. }
  1403. if (strlen(_value) == 0)
  1404. {
  1405. // If no value is povided --> return actual PreValue
  1406. sReturnMessage = flowctrl.GetPrevalue(std::string(_numbersname));
  1407. if (sReturnMessage.empty())
  1408. {
  1409. sReturnMessage = "E92: Numbers name not found";
  1410. httpd_resp_send(req, sReturnMessage.c_str(), sReturnMessage.length());
  1411. return ESP_FAIL;
  1412. }
  1413. }
  1414. else
  1415. {
  1416. // New value is positive: Set PreValue to provided value and return value
  1417. // New value is negative and actual RAW value is a valid number: Set PreValue to RAW value and return value
  1418. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "REST API handler_prevalue called: numbersname: " + std::string(_numbersname) + ", value: " + std::string(_value));
  1419. if (!flowctrl.UpdatePrevalue(_value, _numbersname, true))
  1420. {
  1421. sReturnMessage = "E93: Update request rejected. Please check device logs for more details";
  1422. httpd_resp_send(req, sReturnMessage.c_str(), sReturnMessage.length());
  1423. return ESP_FAIL;
  1424. }
  1425. sReturnMessage = flowctrl.GetPrevalue(std::string(_numbersname));
  1426. if (sReturnMessage.empty())
  1427. {
  1428. sReturnMessage = "E94: Numbers name not found";
  1429. httpd_resp_send(req, sReturnMessage.c_str(), sReturnMessage.length());
  1430. return ESP_FAIL;
  1431. }
  1432. }
  1433. httpd_resp_send(req, sReturnMessage.c_str(), sReturnMessage.length());
  1434. #ifdef DEBUG_DETAIL_ON
  1435. LogFile.WriteHeapInfo("handler_prevalue - End");
  1436. #endif
  1437. return ESP_OK;
  1438. }
  1439. void task_autodoFlow(void *pvParameter)
  1440. {
  1441. int64_t fr_start, fr_delta_ms;
  1442. bTaskAutoFlowCreated = true;
  1443. if (!isPlannedReboot && (esp_reset_reason() == ESP_RST_PANIC))
  1444. {
  1445. flowctrl.setActStatus("Initialization (delayed)");
  1446. // #ifdef ENABLE_MQTT
  1447. // MQTTPublish(mqttServer_getMainTopic() + "/" + "status", "Initialization (delayed)", false); // Right now, not possible -> MQTT Service is going to be started later
  1448. // #endif //ENABLE_MQTT
  1449. vTaskDelay(60 * 5000 / portTICK_PERIOD_MS); // Wait 5 minutes to give time to do an OTA update or fetch the log
  1450. }
  1451. ESP_LOGD(TAG, "task_autodoFlow: start");
  1452. doInit();
  1453. flowctrl.setAutoStartInterval(auto_interval);
  1454. autostartIsEnabled = flowctrl.getIsAutoStart();
  1455. if (isSetupModusActive())
  1456. {
  1457. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "We are in Setup Mode -> Not starting Auto Flow!");
  1458. autostartIsEnabled = false;
  1459. // 15.7.0 Setup Wizard cannot take a Reference Picture #2953
  1460. // std::string zw_time = getCurrentTimeString(LOGFILE_TIME_FORMAT);
  1461. // flowctrl.doFlowTakeImageOnly(zw_time);
  1462. }
  1463. if (autostartIsEnabled)
  1464. {
  1465. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Starting Flow...");
  1466. }
  1467. else
  1468. {
  1469. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Autostart is not enabled -> Not starting Flow");
  1470. }
  1471. while (autostartIsEnabled)
  1472. {
  1473. if (UpdateFlowPauseStateForTask())
  1474. {
  1475. if (flowctrl.getActStatus() != "Flow paused")
  1476. {
  1477. flowctrl.setActStatus("Flow paused");
  1478. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Flow paused; waiting for resume or one manual round");
  1479. }
  1480. vTaskDelay(pdMS_TO_TICKS(250));
  1481. continue;
  1482. }
  1483. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "----------------------------------------------------------------"); // Clear separation between runs
  1484. time_t roundStartTime = getUpTime();
  1485. std::string _zw = "Round #" + std::to_string(++countRounds) + " started";
  1486. LogFile.WriteToFile(ESP_LOG_INFO, TAG, _zw);
  1487. fr_start = esp_timer_get_time();
  1488. if (IsFlowRunning())
  1489. {
  1490. #ifdef DEBUG_DETAIL_ON
  1491. ESP_LOGD(TAG, "Autoflow: doFlow is already running!");
  1492. #endif
  1493. }
  1494. else
  1495. {
  1496. #ifdef DEBUG_DETAIL_ON
  1497. ESP_LOGD(TAG, "Autoflow: doFlow is started");
  1498. #endif
  1499. doflow();
  1500. #ifdef DEBUG_DETAIL_ON
  1501. ESP_LOGD(TAG, "Remove older log files");
  1502. #endif
  1503. int64_t cleanupStartUs = esp_timer_get_time();
  1504. LogFile.RemoveOldLogFile();
  1505. LogFile.WriteToFile(ESP_LOG_INFO, TAG,
  1506. "Timing RemoveOldLogFile: " +
  1507. std::to_string((esp_timer_get_time() - cleanupStartUs) / 1000) + " ms");
  1508. cleanupStartUs = esp_timer_get_time();
  1509. LogFile.RemoveOldDataLog();
  1510. LogFile.WriteToFile(ESP_LOG_INFO, TAG,
  1511. "Timing RemoveOldDataLog: " +
  1512. std::to_string((esp_timer_get_time() - cleanupStartUs) / 1000) + " ms");
  1513. }
  1514. // Round finished -> Logfile
  1515. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Round #" + std::to_string(countRounds) + " completed (" + std::to_string(getUpTime() - roundStartTime) + " seconds)");
  1516. // CPU Temp -> Logfile
  1517. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "CPU Temperature: " + std::to_string((int)temperatureRead()) + "°C");
  1518. // WIFI Signal Strength (RSSI) -> Logfile
  1519. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "WIFI Signal (RSSI): " + std::to_string(get_WIFI_RSSI()) + "dBm");
  1520. // Check if time is synchronized (if NTP is configured)
  1521. if (getUseNtp() && !getTimeIsSet())
  1522. {
  1523. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Time server is configured, but time is not yet set!");
  1524. StatusLED(TIME_CHECK, 1, false);
  1525. }
  1526. #if (defined WLAN_USE_MESH_ROAMING && defined WLAN_USE_MESH_ROAMING_ACTIVATE_CLIENT_TRIGGERED_QUERIES)
  1527. wifiRoamingQuery();
  1528. #endif
  1529. // Scan channels and check if an AP with better RSSI is available, then disconnect and try to reconnect to AP with better RSSI
  1530. // NOTE: Keep this direct before the following task delay, because scan is done in blocking mode and this takes ca. 1,5 - 2s.
  1531. #ifdef WLAN_USE_ROAMING_BY_SCANNING
  1532. wifiRoamByScanning();
  1533. #endif
  1534. fr_delta_ms = (esp_timer_get_time() - fr_start) / 1000;
  1535. if (IsFlowPauseRequested())
  1536. {
  1537. continue; // Finish the current round, then enter the paused state at the top of the loop.
  1538. }
  1539. if (auto_interval > fr_delta_ms)
  1540. {
  1541. const TickType_t xDelay = (auto_interval - fr_delta_ms) / portTICK_PERIOD_MS;
  1542. ESP_LOGD(TAG, "Autoflow: sleep for: %ldms", (long)xDelay);
  1543. vTaskDelay(xDelay);
  1544. }
  1545. }
  1546. while (1)
  1547. {
  1548. // Keep flow task running to handle necessary sub tasks like reboot handler, etc..
  1549. vTaskDelay(2000 / portTICK_PERIOD_MS);
  1550. }
  1551. vTaskDelete(NULL); // Delete this task if it exits from the loop above
  1552. xHandletask_autodoFlow = NULL;
  1553. ESP_LOGD(TAG, "task_autodoFlow: end");
  1554. }
  1555. void InitializeFlowTask(void)
  1556. {
  1557. BaseType_t xReturned;
  1558. ResetFlowControlState();
  1559. ESP_LOGD(TAG, "getESPHeapInfo: %s", getESPHeapInfo().c_str());
  1560. uint32_t stackSize = 16 * 1024;
  1561. xReturned = xTaskCreatePinnedToCore(&task_autodoFlow, "task_autodoFlow", stackSize, NULL, tskIDLE_PRIORITY + 2, &xHandletask_autodoFlow, 0);
  1562. if (xReturned != pdPASS)
  1563. {
  1564. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Creation task_autodoFlow failed. Requested stack size:" + std::to_string(stackSize));
  1565. LogFile.WriteHeapInfo("Creation task_autodoFlow failed");
  1566. }
  1567. ESP_LOGD(TAG, "getESPHeapInfo: %s", getESPHeapInfo().c_str());
  1568. }
  1569. void register_server_main_flow_task_uri(httpd_handle_t server)
  1570. {
  1571. ESP_LOGI(TAG, "server_main_flow_task - Registering URI handlers");
  1572. httpd_uri_t camuri = {};
  1573. camuri.method = HTTP_GET;
  1574. camuri.uri = "/doinit";
  1575. camuri.handler = APPLY_BASIC_AUTH_FILTER(handler_init);
  1576. camuri.user_ctx = NULL;
  1577. httpd_register_uri_handler(server, &camuri);
  1578. camuri.uri = "/setPreValue";
  1579. camuri.handler = APPLY_BASIC_AUTH_FILTER(handler_prevalue);
  1580. camuri.user_ctx = NULL;
  1581. httpd_register_uri_handler(server, &camuri);
  1582. camuri.uri = "/flow_start";
  1583. camuri.handler = APPLY_BASIC_AUTH_FILTER(handler_flow_start);
  1584. camuri.user_ctx = NULL;
  1585. httpd_register_uri_handler(server, &camuri);
  1586. camuri.uri = "/flow_pause";
  1587. camuri.handler = APPLY_BASIC_AUTH_FILTER(handler_flow_pause);
  1588. camuri.user_ctx = NULL;
  1589. httpd_register_uri_handler(server, &camuri);
  1590. camuri.uri = "/flow_resume";
  1591. camuri.handler = APPLY_BASIC_AUTH_FILTER(handler_flow_resume);
  1592. camuri.user_ctx = NULL;
  1593. httpd_register_uri_handler(server, &camuri);
  1594. camuri.uri = "/statusflow";
  1595. camuri.handler = APPLY_BASIC_AUTH_FILTER(handler_statusflow);
  1596. camuri.user_ctx = NULL;
  1597. httpd_register_uri_handler(server, &camuri);
  1598. camuri.uri = "/cpu_temperature";
  1599. camuri.handler = APPLY_BASIC_AUTH_FILTER(handler_cputemp);
  1600. camuri.user_ctx = NULL;
  1601. httpd_register_uri_handler(server, &camuri);
  1602. camuri.uri = "/rssi";
  1603. camuri.handler = APPLY_BASIC_AUTH_FILTER(handler_rssi);
  1604. camuri.user_ctx = NULL;
  1605. httpd_register_uri_handler(server, &camuri);
  1606. camuri.uri = "/date";
  1607. camuri.handler = APPLY_BASIC_AUTH_FILTER(handler_current_date);
  1608. camuri.user_ctx = NULL;
  1609. httpd_register_uri_handler(server, &camuri);
  1610. camuri.uri = "/uptime";
  1611. camuri.handler = APPLY_BASIC_AUTH_FILTER(handler_uptime);
  1612. camuri.user_ctx = NULL;
  1613. httpd_register_uri_handler(server, &camuri);
  1614. camuri.uri = "/editflow";
  1615. camuri.handler = APPLY_BASIC_AUTH_FILTER(handler_editflow);
  1616. camuri.user_ctx = NULL;
  1617. httpd_register_uri_handler(server, &camuri);
  1618. camuri.uri = "/value";
  1619. camuri.handler = APPLY_BASIC_AUTH_FILTER(handler_wasserzaehler);
  1620. camuri.user_ctx = NULL;
  1621. httpd_register_uri_handler(server, &camuri);
  1622. camuri.uri = "/json";
  1623. camuri.handler = APPLY_BASIC_AUTH_FILTER(handler_json);
  1624. camuri.user_ctx = NULL;
  1625. httpd_register_uri_handler(server, &camuri);
  1626. camuri.uri = "/heap";
  1627. camuri.handler = APPLY_BASIC_AUTH_FILTER(handler_get_heap);
  1628. camuri.user_ctx = NULL;
  1629. httpd_register_uri_handler(server, &camuri);
  1630. camuri.uri = "/stream";
  1631. camuri.handler = APPLY_BASIC_AUTH_FILTER(handler_stream);
  1632. camuri.user_ctx = NULL;
  1633. httpd_register_uri_handler(server, &camuri);
  1634. /** will handle metrics requests */
  1635. camuri.uri = "/metrics";
  1636. camuri.handler = APPLY_BASIC_AUTH_FILTER(handler_openmetrics);
  1637. camuri.user_ctx = NULL;
  1638. httpd_register_uri_handler(server, &camuri);
  1639. /** when adding a new handler, make sure to increment the value for config.max_uri_handlers in `main/server_main.cpp` */
  1640. }