MainFlowControl.cpp 55 KB

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