MainFlowControl.cpp 67 KB

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