MainFlowControl.cpp 64 KB

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