MainFlowControl.cpp 66 KB

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