MainFlowControl.cpp 54 KB

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