MainFlowControl.cpp 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148
  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. TaskHandle_t xHandletask_autodoFlow = NULL;
  28. bool bTaskAutoFlowCreated = false;
  29. bool flowisrunning = false;
  30. long auto_interval = 0;
  31. bool auto_isrunning = false;
  32. int countRounds = 0;
  33. bool isPlannedReboot = false;
  34. static const char *TAG = "MAINCTRL";
  35. //#define DEBUG_DETAIL_ON
  36. void CheckIsPlannedReboot()
  37. {
  38. FILE *pfile;
  39. if ((pfile = fopen("/sdcard/reboot.txt", "r")) == NULL) {
  40. //LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Initial boot or not a planned reboot");
  41. isPlannedReboot = false;
  42. }
  43. else {
  44. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Planned reboot");
  45. DeleteFile("/sdcard/reboot.txt"); // Prevent Boot Loop!!!
  46. isPlannedReboot = true;
  47. }
  48. }
  49. bool getIsPlannedReboot()
  50. {
  51. return isPlannedReboot;
  52. }
  53. int getCountFlowRounds()
  54. {
  55. return countRounds;
  56. }
  57. esp_err_t GetJPG(std::string _filename, httpd_req_t *req)
  58. {
  59. return flowctrl.GetJPGStream(_filename, req);
  60. }
  61. esp_err_t GetRawJPG(httpd_req_t *req)
  62. {
  63. return flowctrl.SendRawJPG(req);
  64. }
  65. bool isSetupModusActive()
  66. {
  67. return flowctrl.getStatusSetupModus();
  68. }
  69. void DeleteMainFlowTask()
  70. {
  71. #ifdef DEBUG_DETAIL_ON
  72. ESP_LOGD(TAG, "DeleteMainFlowTask: xHandletask_autodoFlow: %ld", (long) xHandletask_autodoFlow);
  73. #endif
  74. if( xHandletask_autodoFlow != NULL )
  75. {
  76. vTaskDelete(xHandletask_autodoFlow);
  77. xHandletask_autodoFlow = NULL;
  78. }
  79. #ifdef DEBUG_DETAIL_ON
  80. ESP_LOGD(TAG, "Killed: xHandletask_autodoFlow");
  81. #endif
  82. }
  83. void doInit(void)
  84. {
  85. #ifdef DEBUG_DETAIL_ON
  86. ESP_LOGD(TAG, "Start flowctrl.InitFlow(config);");
  87. #endif
  88. flowctrl.InitFlow(CONFIG_FILE);
  89. #ifdef DEBUG_DETAIL_ON
  90. ESP_LOGD(TAG, "Finished flowctrl.InitFlow(config);");
  91. #endif
  92. /* GPIO handler has to be initialized before MQTT init to ensure proper topic subscription */
  93. gpio_handler_init();
  94. #ifdef ENABLE_MQTT
  95. flowctrl.StartMQTTService();
  96. #endif //ENABLE_MQTT
  97. }
  98. bool doflow(void)
  99. {
  100. std::string zw_time = getCurrentTimeString(LOGFILE_TIME_FORMAT);
  101. ESP_LOGD(TAG, "doflow - start %s", zw_time.c_str());
  102. flowisrunning = true;
  103. flowctrl.doFlow(zw_time);
  104. flowisrunning = false;
  105. #ifdef DEBUG_DETAIL_ON
  106. ESP_LOGD(TAG, "doflow - end %s", zw_time.c_str());
  107. #endif
  108. return true;
  109. }
  110. esp_err_t handler_get_heap(httpd_req_t *req)
  111. {
  112. #ifdef DEBUG_DETAIL_ON
  113. LogFile.WriteHeapInfo("handler_get_heap - Start");
  114. ESP_LOGD(TAG, "handler_get_heap uri: %s", req->uri);
  115. #endif
  116. std::string zw = "Heap info:<br>" + getESPHeapInfo();
  117. #ifdef TASK_ANALYSIS_ON
  118. char* pcTaskList = (char*) calloc_psram_heap(std::string(TAG) + "->pcTaskList", 1, sizeof(char) * 768, MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM);
  119. if (pcTaskList) {
  120. vTaskList(pcTaskList);
  121. zw = zw + "<br><br>Task info:<br><pre>Name | State | Prio | Lowest stacksize | Creation order | CPU (-1=NoAffinity)<br>"
  122. + std::string(pcTaskList) + "</pre>";
  123. free_psram_heap(std::string(TAG) + "->pcTaskList", pcTaskList);
  124. }
  125. else {
  126. zw = zw + "<br><br>Task info:<br>ERROR - Allocation of TaskList buffer in PSRAM failed";
  127. }
  128. #endif
  129. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  130. if (zw.length() > 0)
  131. {
  132. httpd_resp_send(req, zw.c_str(), zw.length());
  133. }
  134. else
  135. {
  136. httpd_resp_send(req, NULL, 0);
  137. }
  138. #ifdef DEBUG_DETAIL_ON
  139. LogFile.WriteHeapInfo("handler_get_heap - Done");
  140. #endif
  141. return ESP_OK;
  142. }
  143. esp_err_t handler_init(httpd_req_t *req)
  144. {
  145. #ifdef DEBUG_DETAIL_ON
  146. LogFile.WriteHeapInfo("handler_init - Start");
  147. ESP_LOGD(TAG, "handler_doinit uri: %s", req->uri);
  148. #endif
  149. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  150. const char* resp_str = "Init started<br>";
  151. httpd_resp_send(req, resp_str, HTTPD_RESP_USE_STRLEN);
  152. doInit();
  153. resp_str = "Init done<br>";
  154. httpd_resp_send(req, resp_str, HTTPD_RESP_USE_STRLEN);
  155. #ifdef DEBUG_DETAIL_ON
  156. LogFile.WriteHeapInfo("handler_init - Done");
  157. #endif
  158. return ESP_OK;
  159. }
  160. esp_err_t handler_stream(httpd_req_t *req)
  161. {
  162. #ifdef DEBUG_DETAIL_ON
  163. LogFile.WriteHeapInfo("handler_stream - Start");
  164. ESP_LOGD(TAG, "handler_stream uri: %s", req->uri);
  165. #endif
  166. char _query[50];
  167. char _value[10];
  168. bool flashlightOn = false;
  169. if (httpd_req_get_url_query_str(req, _query, 50) == ESP_OK)
  170. {
  171. // ESP_LOGD(TAG, "Query: %s", _query);
  172. if (httpd_query_key_value(_query, "flashlight", _value, 10) == ESP_OK)
  173. {
  174. #ifdef DEBUG_DETAIL_ON
  175. ESP_LOGD(TAG, "flashlight is found%s", _size);
  176. #endif
  177. if (strlen(_value) > 0)
  178. flashlightOn = true;
  179. }
  180. }
  181. Camera.CaptureToStream(req, flashlightOn);
  182. #ifdef DEBUG_DETAIL_ON
  183. LogFile.WriteHeapInfo("handler_stream - Done");
  184. #endif
  185. return ESP_OK;
  186. }
  187. esp_err_t handler_flow_start(httpd_req_t *req) {
  188. #ifdef DEBUG_DETAIL_ON
  189. LogFile.WriteHeapInfo("handler_flow_start - Start");
  190. #endif
  191. ESP_LOGD(TAG, "handler_flow_start uri: %s", req->uri);
  192. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  193. if (auto_isrunning) {
  194. xTaskAbortDelay(xHandletask_autodoFlow); // Delay will be aborted if task is in blocked (waiting) state. If task is already running, no action
  195. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Flow start triggered by REST API /flow_start");
  196. const char* resp_str = "The flow is going to be started immediately or is already running";
  197. httpd_resp_send(req, resp_str, HTTPD_RESP_USE_STRLEN);
  198. }
  199. else {
  200. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Flow start triggered by REST API, but flow is not active!");
  201. const char* resp_str = "WARNING: Flow start triggered by REST API, but flow is not active";
  202. httpd_resp_send(req, resp_str, HTTPD_RESP_USE_STRLEN);
  203. }
  204. #ifdef DEBUG_DETAIL_ON
  205. LogFile.WriteHeapInfo("handler_flow_start - Done");
  206. #endif
  207. return ESP_OK;
  208. }
  209. #ifdef ENABLE_MQTT
  210. esp_err_t MQTTCtrlFlowStart(std::string _topic) {
  211. #ifdef DEBUG_DETAIL_ON
  212. LogFile.WriteHeapInfo("MQTTCtrlFlowStart - Start");
  213. #endif
  214. ESP_LOGD(TAG, "MQTTCtrlFlowStart: topic %s", _topic.c_str());
  215. if (auto_isrunning)
  216. {
  217. xTaskAbortDelay(xHandletask_autodoFlow); // Delay will be aborted if task is in blocked (waiting) state. If task is already running, no action
  218. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Flow start triggered by MQTT topic " + _topic);
  219. }
  220. else
  221. {
  222. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Flow start triggered by MQTT topic " + _topic + ", but flow is not active!");
  223. }
  224. #ifdef DEBUG_DETAIL_ON
  225. LogFile.WriteHeapInfo("MQTTCtrlFlowStart - Done");
  226. #endif
  227. return ESP_OK;
  228. }
  229. #endif //ENABLE_MQTT
  230. esp_err_t handler_json(httpd_req_t *req)
  231. {
  232. #ifdef DEBUG_DETAIL_ON
  233. LogFile.WriteHeapInfo("handler_json - Start");
  234. #endif
  235. ESP_LOGD(TAG, "handler_JSON uri: %s", req->uri);
  236. if (bTaskAutoFlowCreated)
  237. {
  238. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  239. httpd_resp_set_type(req, "application/json");
  240. std::string zw = flowctrl.getJSON();
  241. if (zw.length() > 0)
  242. {
  243. httpd_resp_send(req, zw.c_str(), zw.length());
  244. }
  245. else
  246. {
  247. httpd_resp_send(req, NULL, 0);
  248. }
  249. }
  250. else
  251. {
  252. httpd_resp_send_err(req, HTTPD_403_FORBIDDEN, "Flow not (yet) started: REST API /json not yet available!");
  253. return ESP_ERR_NOT_FOUND;
  254. }
  255. #ifdef DEBUG_DETAIL_ON
  256. LogFile.WriteHeapInfo("handler_JSON - Done");
  257. #endif
  258. return ESP_OK;
  259. }
  260. esp_err_t handler_wasserzaehler(httpd_req_t *req)
  261. {
  262. #ifdef DEBUG_DETAIL_ON
  263. LogFile.WriteHeapInfo("handler water counter - Start");
  264. #endif
  265. if (bTaskAutoFlowCreated)
  266. {
  267. bool _rawValue = false;
  268. bool _noerror = false;
  269. bool _all = false;
  270. std::string _type = "value";
  271. string zw;
  272. ESP_LOGD(TAG, "handler water counter uri: %s", req->uri);
  273. char _query[100];
  274. char _size[10];
  275. if (httpd_req_get_url_query_str(req, _query, 100) == ESP_OK)
  276. {
  277. // ESP_LOGD(TAG, "Query: %s", _query);
  278. if (httpd_query_key_value(_query, "all", _size, 10) == ESP_OK)
  279. {
  280. #ifdef DEBUG_DETAIL_ON
  281. ESP_LOGD(TAG, "all is found%s", _size);
  282. #endif
  283. _all = true;
  284. }
  285. if (httpd_query_key_value(_query, "type", _size, 10) == ESP_OK)
  286. {
  287. #ifdef DEBUG_DETAIL_ON
  288. ESP_LOGD(TAG, "all is found: %s", _size);
  289. #endif
  290. _type = std::string(_size);
  291. }
  292. if (httpd_query_key_value(_query, "rawvalue", _size, 10) == ESP_OK)
  293. {
  294. #ifdef DEBUG_DETAIL_ON
  295. ESP_LOGD(TAG, "rawvalue is found: %s", _size);
  296. #endif
  297. _rawValue = true;
  298. }
  299. if (httpd_query_key_value(_query, "noerror", _size, 10) == ESP_OK)
  300. {
  301. #ifdef DEBUG_DETAIL_ON
  302. ESP_LOGD(TAG, "noerror is found: %s", _size);
  303. #endif
  304. _noerror = true;
  305. }
  306. }
  307. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  308. if (_all)
  309. {
  310. httpd_resp_set_type(req, "text/plain");
  311. ESP_LOGD(TAG, "TYPE: %s", _type.c_str());
  312. int _intype = READOUT_TYPE_VALUE;
  313. if (_type == "prevalue")
  314. _intype = READOUT_TYPE_PREVALUE;
  315. if (_type == "raw")
  316. _intype = READOUT_TYPE_RAWVALUE;
  317. if (_type == "error")
  318. _intype = READOUT_TYPE_ERROR;
  319. zw = flowctrl.getReadoutAll(_intype);
  320. ESP_LOGD(TAG, "ZW: %s", zw.c_str());
  321. if (zw.length() > 0)
  322. httpd_resp_send(req, zw.c_str(), zw.length());
  323. return ESP_OK;
  324. }
  325. std::string *status = flowctrl.getActStatus();
  326. string query = std::string(_query);
  327. // ESP_LOGD(TAG, "Query: %s, query.c_str());
  328. if (query.find("full") != std::string::npos)
  329. {
  330. string txt;
  331. txt = "<body style=\"font-family: arial\">";
  332. if ((countRounds <= 1) && (*status != std::string("Flow finished"))) { // First round not completed yet
  333. txt += "<h3>Please wait for the first round to complete!</h3><h3>Current state: " + *status + "</h3>\n";
  334. }
  335. else {
  336. txt += "<h3>Value</h3>";
  337. }
  338. httpd_resp_sendstr_chunk(req, txt.c_str());
  339. }
  340. zw = flowctrl.getReadout(_rawValue, _noerror, 0);
  341. if (zw.length() > 0)
  342. httpd_resp_sendstr_chunk(req, zw.c_str());
  343. if (query.find("full") != std::string::npos)
  344. {
  345. string txt, zw;
  346. if ((countRounds <= 1) && (*status != std::string("Flow finished"))) { // First round not completed yet
  347. // Nothing to do
  348. }
  349. else {
  350. /* Digital ROIs */
  351. txt = "<body style=\"font-family: arial\">";
  352. txt += "<h3>Recognized Digit ROIs (previous round)</h3>\n";
  353. txt += "<table style=\"border-spacing: 5px\"><tr style=\"text-align: center; vertical-align: top;\">\n";
  354. std::vector<HTMLInfo*> htmlinfodig;
  355. htmlinfodig = flowctrl.GetAllDigital();
  356. for (int i = 0; i < htmlinfodig.size(); ++i)
  357. {
  358. if (flowctrl.GetTypeDigital() == Digital)
  359. {
  360. if (htmlinfodig[i]->val == 10)
  361. zw = "NaN";
  362. else
  363. zw = to_string((int) htmlinfodig[i]->val);
  364. txt += "<td style=\"width: 100px\"><h4>" + zw + "</h4><p><img src=\"/img_tmp/" + htmlinfodig[i]->filename + "\"></p></td>\n";
  365. }
  366. else
  367. {
  368. std::stringstream stream;
  369. stream << std::fixed << std::setprecision(1) << htmlinfodig[i]->val;
  370. zw = stream.str();
  371. txt += "<td style=\"width: 100px\"><h4>" + zw + "</h4><p><img src=\"/img_tmp/" + htmlinfodig[i]->filename + "\"></p></td>\n";
  372. }
  373. delete htmlinfodig[i];
  374. }
  375. htmlinfodig.clear();
  376. txt += "</tr></table>\n";
  377. httpd_resp_sendstr_chunk(req, txt.c_str());
  378. /* Analog ROIs */
  379. txt = "<h3>Recognized Analog ROIs (previous round)</h3>\n";
  380. txt += "<table style=\"border-spacing: 5px\"><tr style=\"text-align: center; vertical-align: top;\">\n";
  381. std::vector<HTMLInfo*> htmlinfoana;
  382. htmlinfoana = flowctrl.GetAllAnalog();
  383. for (int i = 0; i < htmlinfoana.size(); ++i)
  384. {
  385. std::stringstream stream;
  386. stream << std::fixed << std::setprecision(1) << htmlinfoana[i]->val;
  387. zw = stream.str();
  388. txt += "<td style=\"width: 150px;\"><h4>" + zw + "</h4><p><img src=\"/img_tmp/" + htmlinfoana[i]->filename + "\"></p></td>\n";
  389. delete htmlinfoana[i];
  390. }
  391. htmlinfoana.clear();
  392. txt += "</tr>\n</table>\n";
  393. httpd_resp_sendstr_chunk(req, txt.c_str());
  394. /* Full Image
  395. * Only show it after the image got taken and aligned */
  396. txt = "<h3>Aligned Image (current round)</h3>\n";
  397. if ((*status == std::string("Initialization")) ||
  398. (*status == std::string("Initialization (delayed)")) ||
  399. (*status == std::string("Take Image"))) {
  400. txt += "<p>Current state: " + *status + "</p>\n";
  401. }
  402. else {
  403. txt += "<img src=\"/img_tmp/alg_roi.jpg\">\n";
  404. }
  405. httpd_resp_sendstr_chunk(req, txt.c_str());
  406. }
  407. }
  408. /* Respond with an empty chunk to signal HTTP response completion */
  409. httpd_resp_sendstr_chunk(req, NULL);
  410. }
  411. else
  412. {
  413. httpd_resp_send_err(req, HTTPD_403_FORBIDDEN, "Flow not (yet) started: REST API /value not available!");
  414. return ESP_ERR_NOT_FOUND;
  415. }
  416. #ifdef DEBUG_DETAIL_ON
  417. LogFile.WriteHeapInfo("handler_wasserzaehler - Done");
  418. #endif
  419. return ESP_OK;
  420. }
  421. esp_err_t handler_editflow(httpd_req_t *req)
  422. {
  423. #ifdef DEBUG_DETAIL_ON
  424. LogFile.WriteHeapInfo("handler_editflow - Start");
  425. #endif
  426. ESP_LOGD(TAG, "handler_editflow uri: %s", req->uri);
  427. char _query[200];
  428. char _valuechar[30];
  429. string _task;
  430. if (httpd_req_get_url_query_str(req, _query, 200) == ESP_OK)
  431. {
  432. if (httpd_query_key_value(_query, "task", _valuechar, 30) == ESP_OK)
  433. {
  434. #ifdef DEBUG_DETAIL_ON
  435. ESP_LOGD(TAG, "task is found: %s", _valuechar);
  436. #endif
  437. _task = 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. if (_task.compare("data") == 0)
  446. {
  447. ESP_LOGD(TAG, "Get data list");
  448. return get_data_file_handler(req);
  449. }
  450. 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. string in, out, zw;
  458. httpd_query_key_value(_query, "in", _valuechar, 30);
  459. in = string(_valuechar);
  460. httpd_query_key_value(_query, "out", _valuechar, 30);
  461. out = string(_valuechar);
  462. #ifdef DEBUG_DETAIL_ON
  463. ESP_LOGD(TAG, "in: %s", in.c_str());
  464. ESP_LOGD(TAG, "out: %s", out.c_str());
  465. #endif
  466. in = "/sdcard" + in;
  467. out = "/sdcard" + out;
  468. CopyFile(in, out);
  469. zw = "Copy Done";
  470. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  471. httpd_resp_send(req, zw.c_str(), zw.length());
  472. }
  473. if (_task.compare("cutref") == 0)
  474. {
  475. string in, out, zw;
  476. int x, y, dx, dy;
  477. bool enhance = false;
  478. httpd_query_key_value(_query, "in", _valuechar, 30);
  479. in = string(_valuechar);
  480. httpd_query_key_value(_query, "out", _valuechar, 30);
  481. out = string(_valuechar);
  482. httpd_query_key_value(_query, "x", _valuechar, 30);
  483. zw = string(_valuechar);
  484. x = stoi(zw);
  485. httpd_query_key_value(_query, "y", _valuechar, 30);
  486. zw = string(_valuechar);
  487. y = stoi(zw);
  488. httpd_query_key_value(_query, "dx", _valuechar, 30);
  489. zw = string(_valuechar);
  490. dx = stoi(zw);
  491. httpd_query_key_value(_query, "dy", _valuechar, 30);
  492. zw = string(_valuechar);
  493. dy = stoi(zw);
  494. #ifdef DEBUG_DETAIL_ON
  495. ESP_LOGD(TAG, "in: %s", in.c_str());
  496. ESP_LOGD(TAG, "out: %s", out.c_str());
  497. ESP_LOGD(TAG, "x: %s", zw.c_str());
  498. ESP_LOGD(TAG, "y: %s", zw.c_str());
  499. ESP_LOGD(TAG, "dx: %s", zw.c_str());
  500. ESP_LOGD(TAG, "dy: %s", zw.c_str());
  501. #endif
  502. if (httpd_query_key_value(_query, "enhance", _valuechar, 10) == ESP_OK)
  503. {
  504. zw = string(_valuechar);
  505. if (zw.compare("true") == 0)
  506. {
  507. enhance = true;
  508. }
  509. }
  510. in = "/sdcard" + in;
  511. out = "/sdcard" + out;
  512. string out2 = out.substr(0, out.length() - 4) + "_org.jpg";
  513. CAlignAndCutImage *caic = new CAlignAndCutImage("cutref", in);
  514. caic->CutAndSave(out2, x, y, dx, dy);
  515. delete caic;
  516. CImageBasis *cim = new CImageBasis("cutref", out2);
  517. if (enhance)
  518. {
  519. cim->Contrast(90);
  520. }
  521. cim->SaveToFile(out);
  522. delete cim;
  523. zw = "CutImage Done";
  524. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  525. httpd_resp_send(req, zw.c_str(), zw.length());
  526. }
  527. if (_task.compare("test_take") == 0)
  528. {
  529. std::string _host = "";
  530. std::string _bri = "";
  531. std::string _con = "";
  532. std::string _sat = "";
  533. std::string _int = "";
  534. int bri = -100;
  535. int sat = -100;
  536. int con = -100;
  537. int intens = -100;
  538. if (httpd_query_key_value(_query, "host", _valuechar, 30) == ESP_OK) {
  539. _host = std::string(_valuechar);
  540. }
  541. if (httpd_query_key_value(_query, "int", _valuechar, 30) == ESP_OK) {
  542. _int = std::string(_valuechar);
  543. intens = stoi(_int);
  544. }
  545. if (httpd_query_key_value(_query, "bri", _valuechar, 30) == ESP_OK) {
  546. _bri = std::string(_valuechar);
  547. bri = stoi(_bri);
  548. }
  549. if (httpd_query_key_value(_query, "con", _valuechar, 30) == ESP_OK) {
  550. _con = std::string(_valuechar);
  551. con = stoi(_con);
  552. }
  553. if (httpd_query_key_value(_query, "sat", _valuechar, 30) == ESP_OK) {
  554. _sat = std::string(_valuechar);
  555. sat = stoi(_sat);
  556. }
  557. // ESP_LOGD(TAG, "Parameter host: %s", _host.c_str());
  558. // string zwzw = "Do " + _task + " start\n"; ESP_LOGD(TAG, zwzw.c_str());
  559. Camera.SetBrightnessContrastSaturation(bri, con, sat);
  560. Camera.SetLEDIntensity(intens);
  561. ESP_LOGD(TAG, "test_take - vor TakeImage");
  562. std::string zw = flowctrl.doSingleStep("[TakeImage]", _host);
  563. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  564. httpd_resp_send(req, zw.c_str(), zw.length());
  565. }
  566. if (_task.compare("test_align") == 0)
  567. {
  568. std::string _host = "";
  569. if (httpd_query_key_value(_query, "host", _valuechar, 30) == ESP_OK) {
  570. _host = std::string(_valuechar);
  571. }
  572. // ESP_LOGD(TAG, "Parameter host: %s", _host.c_str());
  573. // string zwzw = "Do " + _task + " start\n"; ESP_LOGD(TAG, zwzw.c_str());
  574. std::string zw = flowctrl.doSingleStep("[Alignment]", _host);
  575. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  576. httpd_resp_send(req, zw.c_str(), zw.length());
  577. }
  578. #ifdef DEBUG_DETAIL_ON
  579. LogFile.WriteHeapInfo("handler_editflow - Done");
  580. #endif
  581. return ESP_OK;
  582. }
  583. esp_err_t handler_statusflow(httpd_req_t *req)
  584. {
  585. #ifdef DEBUG_DETAIL_ON
  586. LogFile.WriteHeapInfo("handler_statusflow - Start");
  587. #endif
  588. const char* resp_str;
  589. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  590. if (bTaskAutoFlowCreated)
  591. {
  592. #ifdef DEBUG_DETAIL_ON
  593. ESP_LOGD(TAG, "handler_statusflow: %s", req->uri);
  594. #endif
  595. string* zw = flowctrl.getActStatusWithTime();
  596. resp_str = zw->c_str();
  597. httpd_resp_send(req, resp_str, HTTPD_RESP_USE_STRLEN);
  598. }
  599. else
  600. {
  601. resp_str = "Flow task not yet created";
  602. httpd_resp_send(req, resp_str, HTTPD_RESP_USE_STRLEN);
  603. }
  604. #ifdef DEBUG_DETAIL_ON
  605. LogFile.WriteHeapInfo("handler_statusflow - Done");
  606. #endif
  607. return ESP_OK;
  608. }
  609. esp_err_t handler_cputemp(httpd_req_t *req)
  610. {
  611. #ifdef DEBUG_DETAIL_ON
  612. LogFile.WriteHeapInfo("handler_cputemp - Start");
  613. #endif
  614. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  615. httpd_resp_send(req, std::to_string((int)temperatureRead()).c_str(), HTTPD_RESP_USE_STRLEN);
  616. #ifdef DEBUG_DETAIL_ON
  617. LogFile.WriteHeapInfo("handler_cputemp - End");
  618. #endif
  619. return ESP_OK;
  620. }
  621. esp_err_t handler_rssi(httpd_req_t *req)
  622. {
  623. #ifdef DEBUG_DETAIL_ON
  624. LogFile.WriteHeapInfo("handler_rssi - Start");
  625. #endif
  626. if (getWIFIisConnected())
  627. {
  628. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  629. httpd_resp_send(req, std::to_string(get_WIFI_RSSI()).c_str(), HTTPD_RESP_USE_STRLEN);
  630. }
  631. else
  632. {
  633. httpd_resp_send_err(req, HTTPD_403_FORBIDDEN, "WIFI not (yet) connected: REST API /rssi not available!");
  634. return ESP_ERR_NOT_FOUND;
  635. }
  636. #ifdef DEBUG_DETAIL_ON
  637. LogFile.WriteHeapInfo("handler_rssi - End");
  638. #endif
  639. return ESP_OK;
  640. }
  641. esp_err_t handler_uptime(httpd_req_t *req)
  642. {
  643. #ifdef DEBUG_DETAIL_ON
  644. LogFile.WriteHeapInfo("handler_uptime - Start");
  645. #endif
  646. std::string formatedUptime = getFormatedUptime(false);
  647. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  648. httpd_resp_send(req, formatedUptime.c_str(), formatedUptime.length());
  649. #ifdef DEBUG_DETAIL_ON
  650. LogFile.WriteHeapInfo("handler_uptime - End");
  651. #endif
  652. return ESP_OK;
  653. }
  654. esp_err_t handler_prevalue(httpd_req_t *req)
  655. {
  656. #ifdef DEBUG_DETAIL_ON
  657. LogFile.WriteHeapInfo("handler_prevalue - Start");
  658. ESP_LOGD(TAG, "handler_prevalue: %s", req->uri);
  659. #endif
  660. // Default usage message when handler gets called without any parameter
  661. const std::string RESTUsageInfo =
  662. "00: Handler usage:<br>"
  663. "- To retrieve actual PreValue, please provide only a numbersname, e.g. /setPreValue?numbers=main<br>"
  664. "- To set PreValue to a new value, please provide a numbersname and a value, e.g. /setPreValue?numbers=main&value=1234.5678<br>"
  665. "NOTE:<br>"
  666. "value >= 0.0: Set PreValue to provided value<br>"
  667. "value < 0.0: Set PreValue to actual RAW value (as long RAW value is a valid number, without N)";
  668. // Default return error message when no return is programmed
  669. std::string sReturnMessage = "E90: Uninitialized";
  670. char _query[100];
  671. char _numbersname[50] = "default";
  672. char _value[20] = "";
  673. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  674. if (httpd_req_get_url_query_str(req, _query, 100) == ESP_OK) {
  675. #ifdef DEBUG_DETAIL_ON
  676. ESP_LOGD(TAG, "Query: %s", _query);
  677. #endif
  678. if (httpd_query_key_value(_query, "numbers", _numbersname, 50) != ESP_OK) { // If request is incomplete
  679. sReturnMessage = "E91: Query parameter incomplete or not valid!<br> "
  680. "Call /setPreValue to show REST API usage info and/or check documentation";
  681. httpd_resp_send(req, sReturnMessage.c_str(), sReturnMessage.length());
  682. return ESP_FAIL;
  683. }
  684. if (httpd_query_key_value(_query, "value", _value, 20) == ESP_OK) {
  685. #ifdef DEBUG_DETAIL_ON
  686. ESP_LOGD(TAG, "Value: %s", _size);
  687. #endif
  688. }
  689. }
  690. else { // if no parameter is provided, print handler usage
  691. httpd_resp_send(req, RESTUsageInfo.c_str(), RESTUsageInfo.length());
  692. return ESP_OK;
  693. }
  694. if (strlen(_value) == 0) { // If no value is povided --> return actual PreValue
  695. sReturnMessage = flowctrl.GetPrevalue(std::string(_numbersname));
  696. if (sReturnMessage.empty()) {
  697. sReturnMessage = "E92: Numbers name not found";
  698. httpd_resp_send(req, sReturnMessage.c_str(), sReturnMessage.length());
  699. return ESP_FAIL;
  700. }
  701. }
  702. else {
  703. // New value is positive: Set PreValue to provided value and return value
  704. // New value is negative and actual RAW value is a valid number: Set PreValue to RAW value and return value
  705. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "REST API handler_prevalue called: numbersname: " + std::string(_numbersname) +
  706. ", value: " + std::string(_value));
  707. if (!flowctrl.UpdatePrevalue(_value, _numbersname, true)) {
  708. sReturnMessage = "E93: Update request rejected. Please check device logs for more details";
  709. httpd_resp_send(req, sReturnMessage.c_str(), sReturnMessage.length());
  710. return ESP_FAIL;
  711. }
  712. sReturnMessage = flowctrl.GetPrevalue(std::string(_numbersname));
  713. if (sReturnMessage.empty()) {
  714. sReturnMessage = "E94: Numbers name not found";
  715. httpd_resp_send(req, sReturnMessage.c_str(), sReturnMessage.length());
  716. return ESP_FAIL;
  717. }
  718. }
  719. httpd_resp_send(req, sReturnMessage.c_str(), sReturnMessage.length());
  720. #ifdef DEBUG_DETAIL_ON
  721. LogFile.WriteHeapInfo("handler_prevalue - End");
  722. #endif
  723. return ESP_OK;
  724. }
  725. void task_autodoFlow(void *pvParameter)
  726. {
  727. int64_t fr_start, fr_delta_ms;
  728. bTaskAutoFlowCreated = true;
  729. if (!isPlannedReboot && (esp_reset_reason() == ESP_RST_PANIC))
  730. {
  731. flowctrl.setActStatus("Initialization (delayed)");
  732. //#ifdef ENABLE_MQTT
  733. //MQTTPublish(mqttServer_getMainTopic() + "/" + "status", "Initialization (delayed)", false); // Right now, not possible -> MQTT Service is going to be started later
  734. //#endif //ENABLE_MQTT
  735. vTaskDelay(60*5000 / portTICK_PERIOD_MS); // Wait 5 minutes to give time to do an OTA update or fetch the log
  736. }
  737. ESP_LOGD(TAG, "task_autodoFlow: start");
  738. doInit();
  739. auto_isrunning = flowctrl.isAutoStart(auto_interval);
  740. if (isSetupModusActive())
  741. {
  742. auto_isrunning = false;
  743. std::string zw_time = getCurrentTimeString(LOGFILE_TIME_FORMAT);
  744. flowctrl.doFlowTakeImageOnly(zw_time);
  745. }
  746. while (auto_isrunning)
  747. {
  748. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "----------------------------------------------------------------"); // Clear separation between runs
  749. std::string _zw = "Round #" + std::to_string(++countRounds) + " started";
  750. time_t roundStartTime = getUpTime();
  751. LogFile.WriteToFile(ESP_LOG_INFO, TAG, _zw);
  752. fr_start = esp_timer_get_time();
  753. if (flowisrunning)
  754. {
  755. #ifdef DEBUG_DETAIL_ON
  756. ESP_LOGD(TAG, "Autoflow: doFlow is already running!");
  757. #endif
  758. }
  759. else
  760. {
  761. #ifdef DEBUG_DETAIL_ON
  762. ESP_LOGD(TAG, "Autoflow: doFlow is started");
  763. #endif
  764. flowisrunning = true;
  765. doflow();
  766. #ifdef DEBUG_DETAIL_ON
  767. ESP_LOGD(TAG, "Remove older log files");
  768. #endif
  769. LogFile.RemoveOldLogFile();
  770. LogFile.RemoveOldDataLog();
  771. }
  772. // Round finished -> Logfile
  773. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Round #" + std::to_string(countRounds) +
  774. " completed (" + std::to_string(getUpTime() - roundStartTime) + " seconds)");
  775. // CPU Temp -> Logfile
  776. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "CPU Temperature: " + std::to_string((int)temperatureRead()) + "°C");
  777. // WIFI Signal Strength (RSSI) -> Logfile
  778. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "WIFI Signal (RSSI): " + std::to_string(get_WIFI_RSSI()) + "dBm");
  779. // Check if time is synchronized (if NTP is configured)
  780. if (getUseNtp() && !getTimeIsSet()) {
  781. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Time server is configured, but time is not yet set!");
  782. StatusLED(TIME_CHECK, 1, false);
  783. }
  784. #if (defined WLAN_USE_MESH_ROAMING && defined WLAN_USE_MESH_ROAMING_ACTIVATE_CLIENT_TRIGGERED_QUERIES)
  785. wifiRoamingQuery();
  786. #endif
  787. // Scan channels and check if an AP with better RSSI is available, then disconnect and try to reconnect to AP with better RSSI
  788. // NOTE: Keep this direct before the following task delay, because scan is done in blocking mode and this takes ca. 1,5 - 2s.
  789. #ifdef WLAN_USE_ROAMING_BY_SCANNING
  790. wifiRoamByScanning();
  791. #endif
  792. fr_delta_ms = (esp_timer_get_time() - fr_start) / 1000;
  793. if (auto_interval > fr_delta_ms)
  794. {
  795. const TickType_t xDelay = (auto_interval - fr_delta_ms) / portTICK_PERIOD_MS;
  796. ESP_LOGD(TAG, "Autoflow: sleep for: %ldms", (long) xDelay);
  797. vTaskDelay( xDelay );
  798. }
  799. }
  800. while(1) // Keep flow task running to handle necessary sub tasks like reboot handler, etc..
  801. {
  802. vTaskDelay(2000 / portTICK_PERIOD_MS);
  803. }
  804. vTaskDelete(NULL); //Delete this task if it exits from the loop above
  805. xHandletask_autodoFlow = NULL;
  806. ESP_LOGD(TAG, "task_autodoFlow: end");
  807. }
  808. void StartMainFlowTask()
  809. {
  810. BaseType_t xReturned;
  811. ESP_LOGD(TAG, "getESPHeapInfo: %s", getESPHeapInfo().c_str());
  812. uint32_t stackSize = 16 * 1024;
  813. xReturned = xTaskCreatePinnedToCore(&task_autodoFlow, "task_autodoFlow", stackSize, NULL, tskIDLE_PRIORITY+2, &xHandletask_autodoFlow, 0);
  814. if( xReturned != pdPASS )
  815. {
  816. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Creation task_autodoFlow failed. Requested stack size:" + std::to_string(stackSize));
  817. LogFile.WriteHeapInfo("Creation task_autodoFlow failed");
  818. }
  819. ESP_LOGD(TAG, "getESPHeapInfo: %s", getESPHeapInfo().c_str());
  820. }
  821. void register_server_main_flow_task_uri(httpd_handle_t server)
  822. {
  823. ESP_LOGI(TAG, "server_main_flow_task - Registering URI handlers");
  824. httpd_uri_t camuri = { };
  825. camuri.method = HTTP_GET;
  826. camuri.uri = "/doinit";
  827. camuri.handler = handler_init;
  828. camuri.user_ctx = (void*) "Light On";
  829. httpd_register_uri_handler(server, &camuri);
  830. // Legacy API => New: "/setPreValue"
  831. camuri.uri = "/setPreValue.html";
  832. camuri.handler = handler_prevalue;
  833. camuri.user_ctx = (void*) "Prevalue";
  834. httpd_register_uri_handler(server, &camuri);
  835. camuri.uri = "/setPreValue";
  836. camuri.handler = handler_prevalue;
  837. camuri.user_ctx = (void*) "Prevalue";
  838. httpd_register_uri_handler(server, &camuri);
  839. camuri.uri = "/flow_start";
  840. camuri.handler = handler_flow_start;
  841. camuri.user_ctx = (void*) "Flow Start";
  842. httpd_register_uri_handler(server, &camuri);
  843. camuri.uri = "/statusflow.html";
  844. camuri.handler = handler_statusflow;
  845. camuri.user_ctx = (void*) "Light Off";
  846. httpd_register_uri_handler(server, &camuri);
  847. camuri.uri = "/statusflow";
  848. camuri.handler = handler_statusflow;
  849. camuri.user_ctx = (void*) "Light Off";
  850. httpd_register_uri_handler(server, &camuri);
  851. // Legacy API => New: "/cpu_temperature"
  852. camuri.uri = "/cputemp.html";
  853. camuri.handler = handler_cputemp;
  854. camuri.user_ctx = (void*) "Light Off";
  855. httpd_register_uri_handler(server, &camuri);
  856. camuri.uri = "/cpu_temperature";
  857. camuri.handler = handler_cputemp;
  858. camuri.user_ctx = (void*) "Light Off";
  859. httpd_register_uri_handler(server, &camuri);
  860. // Legacy API => New: "/rssi"
  861. camuri.uri = "/rssi.html";
  862. camuri.handler = handler_rssi;
  863. camuri.user_ctx = (void*) "Light Off";
  864. httpd_register_uri_handler(server, &camuri);
  865. camuri.uri = "/rssi";
  866. camuri.handler = handler_rssi;
  867. camuri.user_ctx = (void*) "Light Off";
  868. httpd_register_uri_handler(server, &camuri);
  869. camuri.uri = "/uptime";
  870. camuri.handler = handler_uptime;
  871. camuri.user_ctx = (void*) "Light Off";
  872. httpd_register_uri_handler(server, &camuri);
  873. camuri.uri = "/editflow";
  874. camuri.handler = handler_editflow;
  875. camuri.user_ctx = (void*) "EditFlow";
  876. httpd_register_uri_handler(server, &camuri);
  877. // Legacy API => New: "/value"
  878. camuri.uri = "/value.html";
  879. camuri.handler = handler_wasserzaehler;
  880. camuri.user_ctx = (void*) "Value";
  881. httpd_register_uri_handler(server, &camuri);
  882. camuri.uri = "/value";
  883. camuri.handler = handler_wasserzaehler;
  884. camuri.user_ctx = (void*) "Value";
  885. httpd_register_uri_handler(server, &camuri);
  886. // Legacy API => New: "/value"
  887. camuri.uri = "/wasserzaehler.html";
  888. camuri.handler = handler_wasserzaehler;
  889. camuri.user_ctx = (void*) "Wasserzaehler";
  890. httpd_register_uri_handler(server, &camuri);
  891. camuri.uri = "/json";
  892. camuri.handler = handler_json;
  893. camuri.user_ctx = (void*) "JSON";
  894. httpd_register_uri_handler(server, &camuri);
  895. camuri.uri = "/heap";
  896. camuri.handler = handler_get_heap;
  897. camuri.user_ctx = (void*) "Heap";
  898. httpd_register_uri_handler(server, &camuri);
  899. camuri.uri = "/stream";
  900. camuri.handler = handler_stream;
  901. camuri.user_ctx = (void*) "stream";
  902. httpd_register_uri_handler(server, &camuri);
  903. }