MainFlowControl.cpp 65 KB

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