MainFlowControl.cpp 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679
  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. std::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. std::string query = std::string(_query);
  509. // ESP_LOGD(TAG, "Query: %s, query.c_str());
  510. if (query.find("full") != std::string::npos)
  511. {
  512. std::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. std::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 = std::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. std::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 = std::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. std::string in, out, zw;
  662. httpd_query_key_value(_query, "in", _valuechar, 30);
  663. in = std::string(_valuechar);
  664. httpd_query_key_value(_query, "out", _valuechar, 30);
  665. out = std::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. std::string in, out, zw;
  680. int x = 0, y = 0, dx = 20, dy = 20;
  681. bool enhance = false;
  682. httpd_query_key_value(_query, "in", _valuechar, 30);
  683. in = std::string(_valuechar);
  684. httpd_query_key_value(_query, "out", _valuechar, 30);
  685. out = std::string(_valuechar);
  686. httpd_query_key_value(_query, "x", _valuechar, 30);
  687. std::string _x = std::string(_valuechar);
  688. if (isStringNumeric(_x))
  689. {
  690. x = std::stoi(_x);
  691. }
  692. httpd_query_key_value(_query, "y", _valuechar, 30);
  693. std::string _y = std::string(_valuechar);
  694. if (isStringNumeric(_y))
  695. {
  696. y = std::stoi(_y);
  697. }
  698. httpd_query_key_value(_query, "dx", _valuechar, 30);
  699. std::string _dx = std::string(_valuechar);
  700. if (isStringNumeric(_dx))
  701. {
  702. dx = std::stoi(_dx);
  703. }
  704. httpd_query_key_value(_query, "dy", _valuechar, 30);
  705. std::string _dy = std::string(_valuechar);
  706. if (isStringNumeric(_dy))
  707. {
  708. dy = std::stoi(_dy);
  709. }
  710. #ifdef DEBUG_DETAIL_ON
  711. ESP_LOGD(TAG, "in: %s", in.c_str());
  712. ESP_LOGD(TAG, "out: %s", out.c_str());
  713. ESP_LOGD(TAG, "x: %s", _x.c_str());
  714. ESP_LOGD(TAG, "y: %s", _y.c_str());
  715. ESP_LOGD(TAG, "dx: %s", _dx.c_str());
  716. ESP_LOGD(TAG, "dy: %s", _dy.c_str());
  717. #endif
  718. if (httpd_query_key_value(_query, "enhance", _valuechar, 10) == ESP_OK)
  719. {
  720. string _enhance = std::string(_valuechar);
  721. if (_enhance.compare("true") == 0)
  722. {
  723. enhance = true;
  724. }
  725. }
  726. in = "/sdcard" + in;
  727. out = "/sdcard" + out;
  728. std::string out2 = out.substr(0, out.length() - 4) + "_org.jpg";
  729. if ((flowctrl.SetupModeActive || (*flowctrl.getActStatus() == std::string("Flow finished"))) && psram_init_shared_memory_for_take_image_step())
  730. {
  731. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Taking image for Alignment Mark Update...");
  732. CAlignAndCutImage *caic = new CAlignAndCutImage("cutref", in);
  733. caic->CutAndSave(out2, x, y, dx, dy);
  734. delete caic;
  735. CImageBasis *cim = new CImageBasis("cutref", out2);
  736. if (enhance)
  737. {
  738. cim->Contrast(90);
  739. }
  740. cim->SaveToFile(out);
  741. delete cim;
  742. psram_deinit_shared_memory_for_take_image_step();
  743. zw = "CutImage Done";
  744. }
  745. else
  746. {
  747. 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() + "')!");
  748. zw = "Device Busy";
  749. }
  750. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  751. httpd_resp_send(req, zw.c_str(), zw.length());
  752. }
  753. // wird beim Erstellen eines neuen Referenzbildes aufgerufen
  754. std::string *sys_status = flowctrl.getActStatus();
  755. if ((sys_status->c_str() != std::string("Take Image")) && (sys_status->c_str() != std::string("Aligning")))
  756. {
  757. if ((_task.compare("test_take") == 0) || (_task.compare("cam_settings") == 0))
  758. {
  759. std::string _host = "";
  760. // laden der aktuellen Kameraeinstellungen(CCstatus) in den Zwischenspeicher(CFstatus)
  761. setCCstatusToCFstatus(); // CCstatus >>> CFstatus
  762. if (httpd_query_key_value(_query, "host", _valuechar, 30) == ESP_OK)
  763. {
  764. _host = std::string(_valuechar);
  765. }
  766. if (httpd_query_key_value(_query, "waitb", _valuechar, 30) == ESP_OK)
  767. {
  768. std::string _waitb = std::string(_valuechar);
  769. if (isStringNumeric(_waitb))
  770. {
  771. CFstatus.WaitBeforePicture = std::stoi(_valuechar);
  772. }
  773. }
  774. if (httpd_query_key_value(_query, "qual", _valuechar, 30) == ESP_OK)
  775. {
  776. std::string _qual = std::string(_valuechar);
  777. if (isStringNumeric(_qual))
  778. {
  779. int _qual_ = std::stoi(_valuechar);
  780. CFstatus.ImageQuality = clipInt(_qual_, 63, 6);
  781. }
  782. }
  783. if (httpd_query_key_value(_query, "bri", _valuechar, 30) == ESP_OK)
  784. {
  785. std::string _bri = std::string(_valuechar);
  786. if (isStringNumeric(_bri))
  787. {
  788. int _bri_ = std::stoi(_valuechar);
  789. CFstatus.ImageBrightness = clipInt(_bri_, 2, -2);
  790. }
  791. }
  792. if (httpd_query_key_value(_query, "con", _valuechar, 30) == ESP_OK)
  793. {
  794. std::string _con = std::string(_valuechar);
  795. if (isStringNumeric(_con))
  796. {
  797. int _con_ = std::stoi(_valuechar);
  798. CFstatus.ImageContrast = clipInt(_con_, 2, -2);
  799. }
  800. }
  801. if (httpd_query_key_value(_query, "sat", _valuechar, 30) == ESP_OK)
  802. {
  803. std::string _sat = std::string(_valuechar);
  804. if (isStringNumeric(_sat))
  805. {
  806. int _sat_ = std::stoi(_valuechar);
  807. CFstatus.ImageSaturation = clipInt(_sat_, 2, -2);
  808. }
  809. }
  810. if (httpd_query_key_value(_query, "shp", _valuechar, 30) == ESP_OK)
  811. {
  812. std::string _shp = std::string(_valuechar);
  813. if (isStringNumeric(_shp))
  814. {
  815. int _shp_ = std::stoi(_valuechar);
  816. CFstatus.ImageSaturation = clipInt(_shp_, 2, -2);
  817. }
  818. }
  819. if (httpd_query_key_value(_query, "ashp", _valuechar, 30) == ESP_OK)
  820. {
  821. std::string _ashp = std::string(_valuechar);
  822. CFstatus.ImageAutoSharpness = alphanumericToBoolean(_ashp);
  823. }
  824. if (httpd_query_key_value(_query, "spe", _valuechar, 30) == ESP_OK)
  825. {
  826. std::string _spe = std::string(_valuechar);
  827. if (isStringNumeric(_spe))
  828. {
  829. int _spe_ = std::stoi(_valuechar);
  830. CFstatus.ImageSpecialEffect = clipInt(_spe_, 6, 0);
  831. }
  832. }
  833. if (httpd_query_key_value(_query, "wbm", _valuechar, 30) == ESP_OK)
  834. {
  835. std::string _wbm = std::string(_valuechar);
  836. if (isStringNumeric(_wbm))
  837. {
  838. int _wbm_ = std::stoi(_valuechar);
  839. CFstatus.ImageWbMode = clipInt(_wbm_, 4, 0);
  840. }
  841. }
  842. if (httpd_query_key_value(_query, "awb", _valuechar, 30) == ESP_OK)
  843. {
  844. std::string _awb = std::string(_valuechar);
  845. CFstatus.ImageAwb = alphanumericToBoolean(_awb);
  846. }
  847. if (httpd_query_key_value(_query, "awbg", _valuechar, 30) == ESP_OK)
  848. {
  849. std::string _awbg = std::string(_valuechar);
  850. CFstatus.ImageAwbGain = alphanumericToBoolean(_awbg);
  851. }
  852. if (httpd_query_key_value(_query, "aec", _valuechar, 30) == ESP_OK)
  853. {
  854. std::string _aec = std::string(_valuechar);
  855. CFstatus.ImageAec = alphanumericToBoolean(_aec);
  856. }
  857. if (httpd_query_key_value(_query, "aec2", _valuechar, 30) == ESP_OK)
  858. {
  859. std::string _aec2 = std::string(_valuechar);
  860. CFstatus.ImageAec2 = alphanumericToBoolean(_aec2);
  861. }
  862. if (httpd_query_key_value(_query, "ael", _valuechar, 30) == ESP_OK)
  863. {
  864. std::string _ael = std::string(_valuechar);
  865. if (isStringNumeric(_ael))
  866. {
  867. int _ael_ = std::stoi(_valuechar);
  868. CFstatus.ImageAeLevel = clipInt(_ael_, 2, -2);
  869. }
  870. }
  871. if (httpd_query_key_value(_query, "aecv", _valuechar, 30) == ESP_OK)
  872. {
  873. std::string _aecv = std::string(_valuechar);
  874. if (isStringNumeric(_aecv))
  875. {
  876. int _aecv_ = std::stoi(_valuechar);
  877. CFstatus.ImageAecValue = clipInt(_aecv_, 1200, 0);
  878. }
  879. }
  880. if (httpd_query_key_value(_query, "agc", _valuechar, 30) == ESP_OK)
  881. {
  882. std::string _agc = std::string(_valuechar);
  883. CFstatus.ImageAgc = alphanumericToBoolean(_agc);
  884. }
  885. if (httpd_query_key_value(_query, "agcg", _valuechar, 30) == ESP_OK)
  886. {
  887. std::string _agcg = std::string(_valuechar);
  888. if (isStringNumeric(_agcg))
  889. {
  890. int _agcg_ = std::stoi(_valuechar);
  891. CFstatus.ImageAgcGain = clipInt(_agcg_, 30, 0);
  892. }
  893. }
  894. if (httpd_query_key_value(_query, "bpc", _valuechar, 30) == ESP_OK)
  895. {
  896. std::string _bpc = std::string(_valuechar);
  897. CFstatus.ImageBpc = alphanumericToBoolean(_bpc);
  898. }
  899. if (httpd_query_key_value(_query, "wpc", _valuechar, 30) == ESP_OK)
  900. {
  901. std::string _wpc = std::string(_valuechar);
  902. CFstatus.ImageWpc = alphanumericToBoolean(_wpc);
  903. }
  904. if (httpd_query_key_value(_query, "rgma", _valuechar, 30) == ESP_OK)
  905. {
  906. std::string _rgma = std::string(_valuechar);
  907. CFstatus.ImageRawGma = alphanumericToBoolean(_rgma);
  908. }
  909. if (httpd_query_key_value(_query, "lenc", _valuechar, 30) == ESP_OK)
  910. {
  911. std::string _lenc = std::string(_valuechar);
  912. CFstatus.ImageLenc = alphanumericToBoolean(_lenc);
  913. }
  914. if (httpd_query_key_value(_query, "mirror", _valuechar, 30) == ESP_OK)
  915. {
  916. std::string _mirror = std::string(_valuechar);
  917. CFstatus.ImageHmirror = alphanumericToBoolean(_mirror);
  918. }
  919. if (httpd_query_key_value(_query, "flip", _valuechar, 30) == ESP_OK)
  920. {
  921. std::string _flip = std::string(_valuechar);
  922. CFstatus.ImageVflip = alphanumericToBoolean(_flip);
  923. }
  924. if (httpd_query_key_value(_query, "dcw", _valuechar, 30) == ESP_OK)
  925. {
  926. std::string _dcw = std::string(_valuechar);
  927. CFstatus.ImageDcw = alphanumericToBoolean(_dcw);
  928. }
  929. if (httpd_query_key_value(_query, "zoom", _valuechar, 30) == ESP_OK)
  930. {
  931. std::string _zoom = std::string(_valuechar);
  932. CFstatus.ImageZoomEnabled = alphanumericToBoolean(_zoom);
  933. }
  934. if (httpd_query_key_value(_query, "zoomx", _valuechar, 30) == ESP_OK)
  935. {
  936. std::string _zoomx = std::string(_valuechar);
  937. if (isStringNumeric(_zoomx))
  938. {
  939. int _ImageZoomOffsetX = std::stoi(_valuechar);
  940. CFstatus.ImageZoomOffsetX = clipInt(_ImageZoomOffsetX, 960, -960);
  941. }
  942. }
  943. if (httpd_query_key_value(_query, "zoomy", _valuechar, 30) == ESP_OK)
  944. {
  945. std::string _zoomy = std::string(_valuechar);
  946. if (isStringNumeric(_zoomy))
  947. {
  948. int _ImageZoomOffsetY = std::stoi(_valuechar);
  949. CFstatus.ImageZoomOffsetY = clipInt(_ImageZoomOffsetY, 720, -720);
  950. }
  951. }
  952. if (httpd_query_key_value(_query, "zooms", _valuechar, 30) == ESP_OK)
  953. {
  954. std::string _zooms = std::string(_valuechar);
  955. if (isStringNumeric(_zooms))
  956. {
  957. int _ImageZoomSize = std::stoi(_valuechar);
  958. CFstatus.ImageZoomSize = clipInt(_ImageZoomSize, 29, 0);
  959. }
  960. }
  961. if (httpd_query_key_value(_query, "ledi", _valuechar, 30) == ESP_OK)
  962. {
  963. std::string _ledi = std::string(_valuechar);
  964. if (isStringNumeric(_ledi))
  965. {
  966. float _ImageLedIntensity = std::stof(_valuechar);
  967. Camera.SetLEDIntensity(_ImageLedIntensity);
  968. CFstatus.ImageLedIntensity = CCstatus.ImageLedIntensity;
  969. }
  970. }
  971. if (_task.compare("cam_settings") == 0)
  972. {
  973. // wird aufgerufen, wenn das Referenzbild + Kameraeinstellungen gespeichert wurden
  974. setCFstatusToCCstatus(); // CFstatus >>> CCstatus
  975. // Kameraeinstellungen wurden verädert
  976. CFstatus.changedCameraSettings = true;
  977. ESP_LOGD(TAG, "Cam Settings set");
  978. std::string _zw = "CamSettingsSet";
  979. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  980. httpd_resp_send(req, _zw.c_str(), _zw.length());
  981. }
  982. else
  983. {
  984. // wird aufgerufen, wenn ein neues Referenzbild erstellt oder aktualisiert wurde
  985. // CFstatus >>> Kamera
  986. setCFstatusToCam();
  987. Camera.SetQualityZoomSize(CFstatus.ImageQuality, CFstatus.ImageFrameSize, CFstatus.ImageZoomEnabled, CFstatus.ImageZoomOffsetX, CFstatus.ImageZoomOffsetY, CFstatus.ImageZoomSize);
  988. // Camera.SetZoomSize(CFstatus.ImageZoomEnabled, CFstatus.ImageZoomOffsetX, CFstatus.ImageZoomOffsetY, CFstatus.ImageZoomSize);
  989. // Kameraeinstellungen wurden verädert
  990. CFstatus.changedCameraSettings = true;
  991. ESP_LOGD(TAG, "test_take - vor TakeImage");
  992. std::string image_temp = flowctrl.doSingleStep("[TakeImage]", _host);
  993. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  994. httpd_resp_send(req, image_temp.c_str(), image_temp.length());
  995. }
  996. }
  997. if (_task.compare("test_align") == 0)
  998. {
  999. std::string _host = "";
  1000. if (httpd_query_key_value(_query, "host", _valuechar, 30) == ESP_OK)
  1001. {
  1002. _host = std::string(_valuechar);
  1003. }
  1004. std::string zw = flowctrl.doSingleStep("[Alignment]", _host);
  1005. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  1006. httpd_resp_send(req, zw.c_str(), zw.length());
  1007. }
  1008. }
  1009. else
  1010. {
  1011. std::string _zw = "DeviceIsBusy";
  1012. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  1013. httpd_resp_send(req, _zw.c_str(), _zw.length());
  1014. }
  1015. #ifdef DEBUG_DETAIL_ON
  1016. LogFile.WriteHeapInfo("handler_editflow - Done");
  1017. #endif
  1018. return ESP_OK;
  1019. }
  1020. esp_err_t handler_statusflow(httpd_req_t *req)
  1021. {
  1022. #ifdef DEBUG_DETAIL_ON
  1023. LogFile.WriteHeapInfo("handler_statusflow - Start");
  1024. #endif
  1025. const char *resp_str;
  1026. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  1027. if (bTaskAutoFlowCreated)
  1028. {
  1029. #ifdef DEBUG_DETAIL_ON
  1030. ESP_LOGD(TAG, "handler_statusflow: %s", req->uri);
  1031. #endif
  1032. string *zw = flowctrl.getActStatusWithTime();
  1033. resp_str = zw->c_str();
  1034. httpd_resp_send(req, resp_str, HTTPD_RESP_USE_STRLEN);
  1035. }
  1036. else
  1037. {
  1038. resp_str = "Flow task not yet created";
  1039. httpd_resp_send(req, resp_str, HTTPD_RESP_USE_STRLEN);
  1040. }
  1041. #ifdef DEBUG_DETAIL_ON
  1042. LogFile.WriteHeapInfo("handler_statusflow - Done");
  1043. #endif
  1044. return ESP_OK;
  1045. }
  1046. esp_err_t handler_cputemp(httpd_req_t *req)
  1047. {
  1048. #ifdef DEBUG_DETAIL_ON
  1049. LogFile.WriteHeapInfo("handler_cputemp - Start");
  1050. #endif
  1051. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  1052. httpd_resp_send(req, std::to_string((int)temperatureRead()).c_str(), HTTPD_RESP_USE_STRLEN);
  1053. #ifdef DEBUG_DETAIL_ON
  1054. LogFile.WriteHeapInfo("handler_cputemp - End");
  1055. #endif
  1056. return ESP_OK;
  1057. }
  1058. esp_err_t handler_rssi(httpd_req_t *req)
  1059. {
  1060. #ifdef DEBUG_DETAIL_ON
  1061. LogFile.WriteHeapInfo("handler_rssi - Start");
  1062. #endif
  1063. if (getWIFIisConnected())
  1064. {
  1065. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  1066. httpd_resp_send(req, std::to_string(get_WIFI_RSSI()).c_str(), HTTPD_RESP_USE_STRLEN);
  1067. }
  1068. else
  1069. {
  1070. httpd_resp_send_err(req, HTTPD_403_FORBIDDEN, "WIFI not (yet) connected: REST API /rssi not available!");
  1071. return ESP_ERR_NOT_FOUND;
  1072. }
  1073. #ifdef DEBUG_DETAIL_ON
  1074. LogFile.WriteHeapInfo("handler_rssi - End");
  1075. #endif
  1076. return ESP_OK;
  1077. }
  1078. esp_err_t handler_uptime(httpd_req_t *req)
  1079. {
  1080. #ifdef DEBUG_DETAIL_ON
  1081. LogFile.WriteHeapInfo("handler_uptime - Start");
  1082. #endif
  1083. std::string formatedUptime = getFormatedUptime(false);
  1084. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  1085. httpd_resp_send(req, formatedUptime.c_str(), formatedUptime.length());
  1086. #ifdef DEBUG_DETAIL_ON
  1087. LogFile.WriteHeapInfo("handler_uptime - End");
  1088. #endif
  1089. return ESP_OK;
  1090. }
  1091. esp_err_t handler_prevalue(httpd_req_t *req)
  1092. {
  1093. #ifdef DEBUG_DETAIL_ON
  1094. LogFile.WriteHeapInfo("handler_prevalue - Start");
  1095. ESP_LOGD(TAG, "handler_prevalue: %s", req->uri);
  1096. #endif
  1097. // Default usage message when handler gets called without any parameter
  1098. const std::string RESTUsageInfo =
  1099. "00: Handler usage:<br>"
  1100. "- To retrieve actual PreValue, please provide only a numbersname, e.g. /setPreValue?numbers=main<br>"
  1101. "- To set PreValue to a new value, please provide a numbersname and a value, e.g. /setPreValue?numbers=main&value=1234.5678<br>"
  1102. "NOTE:<br>"
  1103. "value >= 0.0: Set PreValue to provided value<br>"
  1104. "value < 0.0: Set PreValue to actual RAW value (as long RAW value is a valid number, without N)";
  1105. // Default return error message when no return is programmed
  1106. std::string sReturnMessage = "E90: Uninitialized";
  1107. char _query[100];
  1108. char _numbersname[50] = "default";
  1109. char _value[20] = "";
  1110. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  1111. if (httpd_req_get_url_query_str(req, _query, 100) == ESP_OK)
  1112. {
  1113. #ifdef DEBUG_DETAIL_ON
  1114. ESP_LOGD(TAG, "Query: %s", _query);
  1115. #endif
  1116. if (httpd_query_key_value(_query, "numbers", _numbersname, 50) != ESP_OK)
  1117. {
  1118. // If request is incomplete
  1119. sReturnMessage = "E91: Query parameter incomplete or not valid!<br> "
  1120. "Call /setPreValue to show REST API usage info and/or check documentation";
  1121. httpd_resp_send(req, sReturnMessage.c_str(), sReturnMessage.length());
  1122. return ESP_FAIL;
  1123. }
  1124. if (httpd_query_key_value(_query, "value", _value, 20) == ESP_OK)
  1125. {
  1126. #ifdef DEBUG_DETAIL_ON
  1127. ESP_LOGD(TAG, "Value: %s", _value);
  1128. #endif
  1129. }
  1130. }
  1131. else
  1132. {
  1133. // if no parameter is provided, print handler usage
  1134. httpd_resp_send(req, RESTUsageInfo.c_str(), RESTUsageInfo.length());
  1135. return ESP_OK;
  1136. }
  1137. if (strlen(_value) == 0)
  1138. {
  1139. // If no value is povided --> return actual PreValue
  1140. sReturnMessage = flowctrl.GetPrevalue(std::string(_numbersname));
  1141. if (sReturnMessage.empty())
  1142. {
  1143. sReturnMessage = "E92: Numbers name not found";
  1144. httpd_resp_send(req, sReturnMessage.c_str(), sReturnMessage.length());
  1145. return ESP_FAIL;
  1146. }
  1147. }
  1148. else
  1149. {
  1150. // New value is positive: Set PreValue to provided value and return value
  1151. // New value is negative and actual RAW value is a valid number: Set PreValue to RAW value and return value
  1152. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "REST API handler_prevalue called: numbersname: " + std::string(_numbersname) + ", value: " + std::string(_value));
  1153. if (!flowctrl.UpdatePrevalue(_value, _numbersname, true))
  1154. {
  1155. sReturnMessage = "E93: Update request rejected. Please check device logs for more details";
  1156. httpd_resp_send(req, sReturnMessage.c_str(), sReturnMessage.length());
  1157. return ESP_FAIL;
  1158. }
  1159. sReturnMessage = flowctrl.GetPrevalue(std::string(_numbersname));
  1160. if (sReturnMessage.empty())
  1161. {
  1162. sReturnMessage = "E94: Numbers name not found";
  1163. httpd_resp_send(req, sReturnMessage.c_str(), sReturnMessage.length());
  1164. return ESP_FAIL;
  1165. }
  1166. }
  1167. httpd_resp_send(req, sReturnMessage.c_str(), sReturnMessage.length());
  1168. #ifdef DEBUG_DETAIL_ON
  1169. LogFile.WriteHeapInfo("handler_prevalue - End");
  1170. #endif
  1171. return ESP_OK;
  1172. }
  1173. void task_autodoFlow(void *pvParameter)
  1174. {
  1175. int64_t fr_start, fr_delta_ms;
  1176. bTaskAutoFlowCreated = true;
  1177. if (!isPlannedReboot && (esp_reset_reason() == ESP_RST_PANIC))
  1178. {
  1179. flowctrl.setActStatus("Initialization (delayed)");
  1180. // #ifdef ENABLE_MQTT
  1181. // MQTTPublish(mqttServer_getMainTopic() + "/" + "status", "Initialization (delayed)", false); // Right now, not possible -> MQTT Service is going to be started later
  1182. // #endif //ENABLE_MQTT
  1183. vTaskDelay(60 * 5000 / portTICK_PERIOD_MS); // Wait 5 minutes to give time to do an OTA update or fetch the log
  1184. }
  1185. ESP_LOGD(TAG, "task_autodoFlow: start");
  1186. doInit();
  1187. flowctrl.setAutoStartInterval(auto_interval);
  1188. autostartIsEnabled = flowctrl.getIsAutoStart();
  1189. if (isSetupModusActive())
  1190. {
  1191. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "We are in Setup Mode -> Not starting Auto Flow!");
  1192. autostartIsEnabled = false;
  1193. // 15.7.0 Setup Wizard cannot take a Reference Picture #2953
  1194. // std::string zw_time = getCurrentTimeString(LOGFILE_TIME_FORMAT);
  1195. // flowctrl.doFlowTakeImageOnly(zw_time);
  1196. }
  1197. if (autostartIsEnabled)
  1198. {
  1199. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Starting Flow...");
  1200. }
  1201. else
  1202. {
  1203. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Autostart is not enabled -> Not starting Flow");
  1204. }
  1205. while (autostartIsEnabled)
  1206. {
  1207. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "----------------------------------------------------------------"); // Clear separation between runs
  1208. time_t roundStartTime = getUpTime();
  1209. std::string _zw = "Round #" + std::to_string(++countRounds) + " started";
  1210. LogFile.WriteToFile(ESP_LOG_INFO, TAG, _zw);
  1211. fr_start = esp_timer_get_time();
  1212. if (flowisrunning)
  1213. {
  1214. #ifdef DEBUG_DETAIL_ON
  1215. ESP_LOGD(TAG, "Autoflow: doFlow is already running!");
  1216. #endif
  1217. }
  1218. else
  1219. {
  1220. #ifdef DEBUG_DETAIL_ON
  1221. ESP_LOGD(TAG, "Autoflow: doFlow is started");
  1222. #endif
  1223. flowisrunning = true;
  1224. doflow();
  1225. #ifdef DEBUG_DETAIL_ON
  1226. ESP_LOGD(TAG, "Remove older log files");
  1227. #endif
  1228. LogFile.RemoveOldLogFile();
  1229. LogFile.RemoveOldDataLog();
  1230. }
  1231. // Round finished -> Logfile
  1232. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Round #" + std::to_string(countRounds) + " completed (" + std::to_string(getUpTime() - roundStartTime) + " seconds)");
  1233. // CPU Temp -> Logfile
  1234. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "CPU Temperature: " + std::to_string((int)temperatureRead()) + "°C");
  1235. // WIFI Signal Strength (RSSI) -> Logfile
  1236. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "WIFI Signal (RSSI): " + std::to_string(get_WIFI_RSSI()) + "dBm");
  1237. // Check if time is synchronized (if NTP is configured)
  1238. if (getUseNtp() && !getTimeIsSet())
  1239. {
  1240. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Time server is configured, but time is not yet set!");
  1241. StatusLED(TIME_CHECK, 1, false);
  1242. }
  1243. #if (defined WLAN_USE_MESH_ROAMING && defined WLAN_USE_MESH_ROAMING_ACTIVATE_CLIENT_TRIGGERED_QUERIES)
  1244. wifiRoamingQuery();
  1245. #endif
  1246. // Scan channels and check if an AP with better RSSI is available, then disconnect and try to reconnect to AP with better RSSI
  1247. // NOTE: Keep this direct before the following task delay, because scan is done in blocking mode and this takes ca. 1,5 - 2s.
  1248. #ifdef WLAN_USE_ROAMING_BY_SCANNING
  1249. wifiRoamByScanning();
  1250. #endif
  1251. fr_delta_ms = (esp_timer_get_time() - fr_start) / 1000;
  1252. if (auto_interval > fr_delta_ms)
  1253. {
  1254. const TickType_t xDelay = (auto_interval - fr_delta_ms) / portTICK_PERIOD_MS;
  1255. ESP_LOGD(TAG, "Autoflow: sleep for: %ldms", (long)xDelay);
  1256. vTaskDelay(xDelay);
  1257. }
  1258. }
  1259. while (1)
  1260. {
  1261. // Keep flow task running to handle necessary sub tasks like reboot handler, etc..
  1262. vTaskDelay(2000 / portTICK_PERIOD_MS);
  1263. }
  1264. vTaskDelete(NULL); // Delete this task if it exits from the loop above
  1265. xHandletask_autodoFlow = NULL;
  1266. ESP_LOGD(TAG, "task_autodoFlow: end");
  1267. }
  1268. void InitializeFlowTask(void)
  1269. {
  1270. BaseType_t xReturned;
  1271. ESP_LOGD(TAG, "getESPHeapInfo: %s", getESPHeapInfo().c_str());
  1272. uint32_t stackSize = 16 * 1024;
  1273. xReturned = xTaskCreatePinnedToCore(&task_autodoFlow, "task_autodoFlow", stackSize, NULL, tskIDLE_PRIORITY + 2, &xHandletask_autodoFlow, 0);
  1274. if (xReturned != pdPASS)
  1275. {
  1276. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Creation task_autodoFlow failed. Requested stack size:" + std::to_string(stackSize));
  1277. LogFile.WriteHeapInfo("Creation task_autodoFlow failed");
  1278. }
  1279. ESP_LOGD(TAG, "getESPHeapInfo: %s", getESPHeapInfo().c_str());
  1280. }
  1281. void register_server_main_flow_task_uri(httpd_handle_t server)
  1282. {
  1283. ESP_LOGI(TAG, "server_main_flow_task - Registering URI handlers");
  1284. httpd_uri_t camuri = {};
  1285. camuri.method = HTTP_GET;
  1286. camuri.uri = "/doinit";
  1287. camuri.handler = handler_init;
  1288. camuri.user_ctx = (void *)"Light On";
  1289. httpd_register_uri_handler(server, &camuri);
  1290. // Legacy API => New: "/setPreValue"
  1291. camuri.uri = "/setPreValue.html";
  1292. camuri.handler = handler_prevalue;
  1293. camuri.user_ctx = (void *)"Prevalue";
  1294. httpd_register_uri_handler(server, &camuri);
  1295. camuri.uri = "/setPreValue";
  1296. camuri.handler = handler_prevalue;
  1297. camuri.user_ctx = (void *)"Prevalue";
  1298. httpd_register_uri_handler(server, &camuri);
  1299. camuri.uri = "/flow_start";
  1300. camuri.handler = handler_flow_start;
  1301. camuri.user_ctx = (void *)"Flow Start";
  1302. httpd_register_uri_handler(server, &camuri);
  1303. camuri.uri = "/statusflow.html";
  1304. camuri.handler = handler_statusflow;
  1305. camuri.user_ctx = (void *)"Light Off";
  1306. httpd_register_uri_handler(server, &camuri);
  1307. camuri.uri = "/statusflow";
  1308. camuri.handler = handler_statusflow;
  1309. camuri.user_ctx = (void *)"Light Off";
  1310. httpd_register_uri_handler(server, &camuri);
  1311. // Legacy API => New: "/cpu_temperature"
  1312. camuri.uri = "/cputemp.html";
  1313. camuri.handler = handler_cputemp;
  1314. camuri.user_ctx = (void *)"Light Off";
  1315. httpd_register_uri_handler(server, &camuri);
  1316. camuri.uri = "/cpu_temperature";
  1317. camuri.handler = handler_cputemp;
  1318. camuri.user_ctx = (void *)"Light Off";
  1319. httpd_register_uri_handler(server, &camuri);
  1320. // Legacy API => New: "/rssi"
  1321. camuri.uri = "/rssi.html";
  1322. camuri.handler = handler_rssi;
  1323. camuri.user_ctx = (void *)"Light Off";
  1324. httpd_register_uri_handler(server, &camuri);
  1325. camuri.uri = "/rssi";
  1326. camuri.handler = handler_rssi;
  1327. camuri.user_ctx = (void *)"Light Off";
  1328. httpd_register_uri_handler(server, &camuri);
  1329. camuri.uri = "/uptime";
  1330. camuri.handler = handler_uptime;
  1331. camuri.user_ctx = (void *)"Light Off";
  1332. httpd_register_uri_handler(server, &camuri);
  1333. camuri.uri = "/editflow";
  1334. camuri.handler = handler_editflow;
  1335. camuri.user_ctx = (void *)"EditFlow";
  1336. httpd_register_uri_handler(server, &camuri);
  1337. // Legacy API => New: "/value"
  1338. camuri.uri = "/value.html";
  1339. camuri.handler = handler_wasserzaehler;
  1340. camuri.user_ctx = (void *)"Value";
  1341. httpd_register_uri_handler(server, &camuri);
  1342. camuri.uri = "/value";
  1343. camuri.handler = handler_wasserzaehler;
  1344. camuri.user_ctx = (void *)"Value";
  1345. httpd_register_uri_handler(server, &camuri);
  1346. // Legacy API => New: "/value"
  1347. camuri.uri = "/wasserzaehler.html";
  1348. camuri.handler = handler_wasserzaehler;
  1349. camuri.user_ctx = (void *)"Wasserzaehler";
  1350. httpd_register_uri_handler(server, &camuri);
  1351. camuri.uri = "/json";
  1352. camuri.handler = handler_json;
  1353. camuri.user_ctx = (void *)"JSON";
  1354. httpd_register_uri_handler(server, &camuri);
  1355. camuri.uri = "/heap";
  1356. camuri.handler = handler_get_heap;
  1357. camuri.user_ctx = (void *)"Heap";
  1358. httpd_register_uri_handler(server, &camuri);
  1359. camuri.uri = "/stream";
  1360. camuri.handler = handler_stream;
  1361. camuri.user_ctx = (void *)"stream";
  1362. httpd_register_uri_handler(server, &camuri);
  1363. /** will handle metrics requests */
  1364. camuri.uri = "/metrics";
  1365. camuri.handler = handler_openmetrics;
  1366. camuri.user_ctx = (void *)"metrics";
  1367. httpd_register_uri_handler(server, &camuri);
  1368. /** when adding a new handler, make sure to increment the value for config.max_uri_handlers in `main/server_main.cpp` */
  1369. }