MainFlowControl.cpp 53 KB

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