MainFlowControl.cpp 36 KB

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