MainFlowControl.cpp 67 KB

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