MainFlowControl.cpp 63 KB

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