MainFlowControl.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185
  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 autostartIsEnabled = 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 (autostartIsEnabled) {
  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 (autostartIsEnabled)
  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. std::string state = *flowctrl.getActStatus();
  515. /* To be able to provide the image, several conditions must be met due to the shared PSRAM usage:
  516. - Ether the round most be completed or not started yet
  517. - Or we must be in Setup Mode
  518. - Additionally, the initialization of the shared PSRAM must be successful */
  519. if (((state == "Flow finished") || (state == "Initialization") || (state == "Initialization (delayed)") || isSetupModusActive()) &&
  520. psram_init_shared_memory_for_take_image_step()) {
  521. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Taking image for Alignment Mark Update...");
  522. CAlignAndCutImage *caic = new CAlignAndCutImage("cutref", in);
  523. caic->CutAndSave(out2, x, y, dx, dy);
  524. delete caic;
  525. CImageBasis *cim = new CImageBasis("cutref", out2);
  526. if (enhance)
  527. {
  528. cim->Contrast(90);
  529. }
  530. cim->SaveToFile(out);
  531. delete cim;
  532. psram_deinit_shared_memory_for_take_image_step();
  533. zw = "CutImage Done";
  534. }
  535. else {
  536. LogFile.WriteToFile(ESP_LOG_WARN, TAG, std::string("Taking image for Alignment Mark not possible while device") +
  537. " is busy with a round (Current State: '" + state + "')!");
  538. zw = "Device Busy";
  539. }
  540. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  541. httpd_resp_send(req, zw.c_str(), zw.length());
  542. }
  543. if (_task.compare("test_take") == 0)
  544. {
  545. std::string _host = "";
  546. std::string _bri = "";
  547. std::string _con = "";
  548. std::string _sat = "";
  549. std::string _int = "";
  550. int bri = -100;
  551. int sat = -100;
  552. int con = -100;
  553. int intens = -100;
  554. if (httpd_query_key_value(_query, "host", _valuechar, 30) == ESP_OK) {
  555. _host = std::string(_valuechar);
  556. }
  557. if (httpd_query_key_value(_query, "int", _valuechar, 30) == ESP_OK) {
  558. _int = std::string(_valuechar);
  559. intens = stoi(_int);
  560. }
  561. if (httpd_query_key_value(_query, "bri", _valuechar, 30) == ESP_OK) {
  562. _bri = std::string(_valuechar);
  563. bri = stoi(_bri);
  564. }
  565. if (httpd_query_key_value(_query, "con", _valuechar, 30) == ESP_OK) {
  566. _con = std::string(_valuechar);
  567. con = stoi(_con);
  568. }
  569. if (httpd_query_key_value(_query, "sat", _valuechar, 30) == ESP_OK) {
  570. _sat = std::string(_valuechar);
  571. sat = stoi(_sat);
  572. }
  573. // ESP_LOGD(TAG, "Parameter host: %s", _host.c_str());
  574. // string zwzw = "Do " + _task + " start\n"; ESP_LOGD(TAG, zwzw.c_str());
  575. Camera.SetBrightnessContrastSaturation(bri, con, sat);
  576. Camera.SetLEDIntensity(intens);
  577. ESP_LOGD(TAG, "test_take - vor TakeImage");
  578. std::string zw = flowctrl.doSingleStep("[TakeImage]", _host);
  579. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  580. httpd_resp_send(req, zw.c_str(), zw.length());
  581. }
  582. if (_task.compare("test_align") == 0)
  583. {
  584. std::string _host = "";
  585. if (httpd_query_key_value(_query, "host", _valuechar, 30) == ESP_OK) {
  586. _host = std::string(_valuechar);
  587. }
  588. // ESP_LOGD(TAG, "Parameter host: %s", _host.c_str());
  589. // string zwzw = "Do " + _task + " start\n"; ESP_LOGD(TAG, zwzw.c_str());
  590. std::string zw = flowctrl.doSingleStep("[Alignment]", _host);
  591. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  592. httpd_resp_send(req, zw.c_str(), zw.length());
  593. }
  594. #ifdef DEBUG_DETAIL_ON
  595. LogFile.WriteHeapInfo("handler_editflow - Done");
  596. #endif
  597. return ESP_OK;
  598. }
  599. esp_err_t handler_statusflow(httpd_req_t *req)
  600. {
  601. #ifdef DEBUG_DETAIL_ON
  602. LogFile.WriteHeapInfo("handler_statusflow - Start");
  603. #endif
  604. const char* resp_str;
  605. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  606. if (bTaskAutoFlowCreated)
  607. {
  608. #ifdef DEBUG_DETAIL_ON
  609. ESP_LOGD(TAG, "handler_statusflow: %s", req->uri);
  610. #endif
  611. string* zw = flowctrl.getActStatusWithTime();
  612. resp_str = zw->c_str();
  613. httpd_resp_send(req, resp_str, HTTPD_RESP_USE_STRLEN);
  614. }
  615. else
  616. {
  617. resp_str = "Flow task not yet created";
  618. httpd_resp_send(req, resp_str, HTTPD_RESP_USE_STRLEN);
  619. }
  620. #ifdef DEBUG_DETAIL_ON
  621. LogFile.WriteHeapInfo("handler_statusflow - Done");
  622. #endif
  623. return ESP_OK;
  624. }
  625. esp_err_t handler_cputemp(httpd_req_t *req)
  626. {
  627. #ifdef DEBUG_DETAIL_ON
  628. LogFile.WriteHeapInfo("handler_cputemp - Start");
  629. #endif
  630. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  631. httpd_resp_send(req, std::to_string((int)temperatureRead()).c_str(), HTTPD_RESP_USE_STRLEN);
  632. #ifdef DEBUG_DETAIL_ON
  633. LogFile.WriteHeapInfo("handler_cputemp - End");
  634. #endif
  635. return ESP_OK;
  636. }
  637. esp_err_t handler_rssi(httpd_req_t *req)
  638. {
  639. #ifdef DEBUG_DETAIL_ON
  640. LogFile.WriteHeapInfo("handler_rssi - Start");
  641. #endif
  642. if (getWIFIisConnected())
  643. {
  644. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  645. httpd_resp_send(req, std::to_string(get_WIFI_RSSI()).c_str(), HTTPD_RESP_USE_STRLEN);
  646. }
  647. else
  648. {
  649. httpd_resp_send_err(req, HTTPD_403_FORBIDDEN, "WIFI not (yet) connected: REST API /rssi not available!");
  650. return ESP_ERR_NOT_FOUND;
  651. }
  652. #ifdef DEBUG_DETAIL_ON
  653. LogFile.WriteHeapInfo("handler_rssi - End");
  654. #endif
  655. return ESP_OK;
  656. }
  657. esp_err_t handler_uptime(httpd_req_t *req)
  658. {
  659. #ifdef DEBUG_DETAIL_ON
  660. LogFile.WriteHeapInfo("handler_uptime - Start");
  661. #endif
  662. std::string formatedUptime = getFormatedUptime(false);
  663. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  664. httpd_resp_send(req, formatedUptime.c_str(), formatedUptime.length());
  665. #ifdef DEBUG_DETAIL_ON
  666. LogFile.WriteHeapInfo("handler_uptime - End");
  667. #endif
  668. return ESP_OK;
  669. }
  670. esp_err_t handler_prevalue(httpd_req_t *req)
  671. {
  672. #ifdef DEBUG_DETAIL_ON
  673. LogFile.WriteHeapInfo("handler_prevalue - Start");
  674. ESP_LOGD(TAG, "handler_prevalue: %s", req->uri);
  675. #endif
  676. // Default usage message when handler gets called without any parameter
  677. const std::string RESTUsageInfo =
  678. "00: Handler usage:<br>"
  679. "- To retrieve actual PreValue, please provide only a numbersname, e.g. /setPreValue?numbers=main<br>"
  680. "- To set PreValue to a new value, please provide a numbersname and a value, e.g. /setPreValue?numbers=main&value=1234.5678<br>"
  681. "NOTE:<br>"
  682. "value >= 0.0: Set PreValue to provided value<br>"
  683. "value < 0.0: Set PreValue to actual RAW value (as long RAW value is a valid number, without N)";
  684. // Default return error message when no return is programmed
  685. std::string sReturnMessage = "E90: Uninitialized";
  686. char _query[100];
  687. char _numbersname[50] = "default";
  688. char _value[20] = "";
  689. httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
  690. if (httpd_req_get_url_query_str(req, _query, 100) == ESP_OK) {
  691. #ifdef DEBUG_DETAIL_ON
  692. ESP_LOGD(TAG, "Query: %s", _query);
  693. #endif
  694. if (httpd_query_key_value(_query, "numbers", _numbersname, 50) != ESP_OK) { // If request is incomplete
  695. sReturnMessage = "E91: Query parameter incomplete or not valid!<br> "
  696. "Call /setPreValue to show REST API usage info and/or check documentation";
  697. httpd_resp_send(req, sReturnMessage.c_str(), sReturnMessage.length());
  698. return ESP_FAIL;
  699. }
  700. if (httpd_query_key_value(_query, "value", _value, 20) == ESP_OK) {
  701. #ifdef DEBUG_DETAIL_ON
  702. ESP_LOGD(TAG, "Value: %s", _size);
  703. #endif
  704. }
  705. }
  706. else { // if no parameter is provided, print handler usage
  707. httpd_resp_send(req, RESTUsageInfo.c_str(), RESTUsageInfo.length());
  708. return ESP_OK;
  709. }
  710. if (strlen(_value) == 0) { // If no value is povided --> return actual PreValue
  711. sReturnMessage = flowctrl.GetPrevalue(std::string(_numbersname));
  712. if (sReturnMessage.empty()) {
  713. sReturnMessage = "E92: Numbers name not found";
  714. httpd_resp_send(req, sReturnMessage.c_str(), sReturnMessage.length());
  715. return ESP_FAIL;
  716. }
  717. }
  718. else {
  719. // New value is positive: Set PreValue to provided value and return value
  720. // New value is negative and actual RAW value is a valid number: Set PreValue to RAW value and return value
  721. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "REST API handler_prevalue called: numbersname: " + std::string(_numbersname) +
  722. ", value: " + std::string(_value));
  723. if (!flowctrl.UpdatePrevalue(_value, _numbersname, true)) {
  724. sReturnMessage = "E93: Update request rejected. Please check device logs for more details";
  725. httpd_resp_send(req, sReturnMessage.c_str(), sReturnMessage.length());
  726. return ESP_FAIL;
  727. }
  728. sReturnMessage = flowctrl.GetPrevalue(std::string(_numbersname));
  729. if (sReturnMessage.empty()) {
  730. sReturnMessage = "E94: Numbers name not found";
  731. httpd_resp_send(req, sReturnMessage.c_str(), sReturnMessage.length());
  732. return ESP_FAIL;
  733. }
  734. }
  735. httpd_resp_send(req, sReturnMessage.c_str(), sReturnMessage.length());
  736. #ifdef DEBUG_DETAIL_ON
  737. LogFile.WriteHeapInfo("handler_prevalue - End");
  738. #endif
  739. return ESP_OK;
  740. }
  741. void task_autodoFlow(void *pvParameter)
  742. {
  743. int64_t fr_start, fr_delta_ms;
  744. bTaskAutoFlowCreated = true;
  745. if (!isPlannedReboot && (esp_reset_reason() == ESP_RST_PANIC))
  746. {
  747. flowctrl.setActStatus("Initialization (delayed)");
  748. //#ifdef ENABLE_MQTT
  749. //MQTTPublish(mqttServer_getMainTopic() + "/" + "status", "Initialization (delayed)", false); // Right now, not possible -> MQTT Service is going to be started later
  750. //#endif //ENABLE_MQTT
  751. vTaskDelay(60*5000 / portTICK_PERIOD_MS); // Wait 5 minutes to give time to do an OTA update or fetch the log
  752. }
  753. ESP_LOGD(TAG, "task_autodoFlow: start");
  754. doInit();
  755. flowctrl.setAutoStartInterval(auto_interval);
  756. autostartIsEnabled = flowctrl.getIsAutoStart();
  757. if (isSetupModusActive())
  758. {
  759. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "We are in Setup Mode -> Not starting Auto Flow!");
  760. autostartIsEnabled = false;
  761. std::string zw_time = getCurrentTimeString(LOGFILE_TIME_FORMAT);
  762. flowctrl.doFlowTakeImageOnly(zw_time);
  763. }
  764. if (autostartIsEnabled) {
  765. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Starting Flow...");
  766. }
  767. else {
  768. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Autostart is not enabled -> Not starting Flow");
  769. }
  770. while (autostartIsEnabled)
  771. {
  772. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "----------------------------------------------------------------"); // Clear separation between runs
  773. std::string _zw = "Round #" + std::to_string(++countRounds) + " started";
  774. schedule_websocket_message("{\"round\": \"" + std::to_string(countRounds) + "\"}");
  775. schedule_websocket_message("{\"uptime\": \"" + std::to_string(getUpTime()) + "\"}");
  776. time_t roundStartTime = getUpTime();
  777. LogFile.WriteToFile(ESP_LOG_INFO, TAG, _zw);
  778. fr_start = esp_timer_get_time();
  779. if (flowisrunning)
  780. {
  781. #ifdef DEBUG_DETAIL_ON
  782. ESP_LOGD(TAG, "Autoflow: doFlow is already running!");
  783. #endif
  784. }
  785. else
  786. {
  787. #ifdef DEBUG_DETAIL_ON
  788. ESP_LOGD(TAG, "Autoflow: doFlow is started");
  789. #endif
  790. flowisrunning = true;
  791. doflow();
  792. #ifdef DEBUG_DETAIL_ON
  793. ESP_LOGD(TAG, "Remove older log files");
  794. #endif
  795. LogFile.RemoveOldLogFile();
  796. LogFile.RemoveOldDataLog();
  797. }
  798. // Round finished -> Logfile
  799. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Round #" + std::to_string(countRounds) +
  800. " completed (" + std::to_string(getUpTime() - roundStartTime) + " seconds)");
  801. schedule_websocket_message("{\"round duration\": \"" + std::to_string(getUpTime() - roundStartTime) + "\"}");
  802. // CPU Temp -> Logfile
  803. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "CPU Temperature: " + std::to_string((int)temperatureRead()) + "°C");
  804. schedule_websocket_message("{\"cpu temperature\": \"" + std::to_string(temperatureRead()) + "\"}");
  805. // WIFI Signal Strength (RSSI) -> Logfile
  806. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "WIFI Signal (RSSI): " + std::to_string(get_WIFI_RSSI()) + "dBm");
  807. schedule_websocket_message("{\"wifi rssi\": \"" + std::to_string(get_WIFI_RSSI()) + "\"}");
  808. // Check if time is synchronized (if NTP is configured)
  809. if (getUseNtp() && !getTimeIsSet()) {
  810. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Time server is configured, but time is not yet set!");
  811. StatusLED(TIME_CHECK, 1, false);
  812. }
  813. #if (defined WLAN_USE_MESH_ROAMING && defined WLAN_USE_MESH_ROAMING_ACTIVATE_CLIENT_TRIGGERED_QUERIES)
  814. wifiRoamingQuery();
  815. #endif
  816. // Scan channels and check if an AP with better RSSI is available, then disconnect and try to reconnect to AP with better RSSI
  817. // NOTE: Keep this direct before the following task delay, because scan is done in blocking mode and this takes ca. 1,5 - 2s.
  818. #ifdef WLAN_USE_ROAMING_BY_SCANNING
  819. wifiRoamByScanning();
  820. #endif
  821. fr_delta_ms = (esp_timer_get_time() - fr_start) / 1000;
  822. if (auto_interval > fr_delta_ms)
  823. {
  824. const TickType_t xDelay = (auto_interval - fr_delta_ms) / portTICK_PERIOD_MS;
  825. ESP_LOGD(TAG, "Autoflow: sleep for: %ldms", (long) xDelay);
  826. vTaskDelay( xDelay );
  827. }
  828. }
  829. while(1) // Keep flow task running to handle necessary sub tasks like reboot handler, etc..
  830. {
  831. vTaskDelay(2000 / portTICK_PERIOD_MS);
  832. }
  833. vTaskDelete(NULL); //Delete this task if it exits from the loop above
  834. xHandletask_autodoFlow = NULL;
  835. ESP_LOGD(TAG, "task_autodoFlow: end");
  836. }
  837. void InitializeFlowTask()
  838. {
  839. BaseType_t xReturned;
  840. ESP_LOGD(TAG, "getESPHeapInfo: %s", getESPHeapInfo().c_str());
  841. uint32_t stackSize = 16 * 1024;
  842. xReturned = xTaskCreatePinnedToCore(&task_autodoFlow, "task_autodoFlow", stackSize, NULL, tskIDLE_PRIORITY+2, &xHandletask_autodoFlow, 0);
  843. if( xReturned != pdPASS )
  844. {
  845. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Creation task_autodoFlow failed. Requested stack size:" + std::to_string(stackSize));
  846. LogFile.WriteHeapInfo("Creation task_autodoFlow failed");
  847. }
  848. ESP_LOGD(TAG, "getESPHeapInfo: %s", getESPHeapInfo().c_str());
  849. }
  850. void register_server_main_flow_task_uri(httpd_handle_t server)
  851. {
  852. ESP_LOGI(TAG, "server_main_flow_task - Registering URI handlers");
  853. httpd_uri_t camuri = { };
  854. camuri.method = HTTP_GET;
  855. camuri.uri = "/doinit";
  856. camuri.handler = handler_init;
  857. camuri.user_ctx = (void*) "Light On";
  858. httpd_register_uri_handler(server, &camuri);
  859. // Legacy API => New: "/setPreValue"
  860. camuri.uri = "/setPreValue.html";
  861. camuri.handler = handler_prevalue;
  862. camuri.user_ctx = (void*) "Prevalue";
  863. httpd_register_uri_handler(server, &camuri);
  864. camuri.uri = "/setPreValue";
  865. camuri.handler = handler_prevalue;
  866. camuri.user_ctx = (void*) "Prevalue";
  867. httpd_register_uri_handler(server, &camuri);
  868. camuri.uri = "/flow_start";
  869. camuri.handler = handler_flow_start;
  870. camuri.user_ctx = (void*) "Flow Start";
  871. httpd_register_uri_handler(server, &camuri);
  872. camuri.uri = "/statusflow.html";
  873. camuri.handler = handler_statusflow;
  874. camuri.user_ctx = (void*) "Light Off";
  875. httpd_register_uri_handler(server, &camuri);
  876. camuri.uri = "/statusflow";
  877. camuri.handler = handler_statusflow;
  878. camuri.user_ctx = (void*) "Light Off";
  879. httpd_register_uri_handler(server, &camuri);
  880. // Legacy API => New: "/cpu_temperature"
  881. camuri.uri = "/cputemp.html";
  882. camuri.handler = handler_cputemp;
  883. camuri.user_ctx = (void*) "Light Off";
  884. httpd_register_uri_handler(server, &camuri);
  885. camuri.uri = "/cpu_temperature";
  886. camuri.handler = handler_cputemp;
  887. camuri.user_ctx = (void*) "Light Off";
  888. httpd_register_uri_handler(server, &camuri);
  889. // Legacy API => New: "/rssi"
  890. camuri.uri = "/rssi.html";
  891. camuri.handler = handler_rssi;
  892. camuri.user_ctx = (void*) "Light Off";
  893. httpd_register_uri_handler(server, &camuri);
  894. camuri.uri = "/rssi";
  895. camuri.handler = handler_rssi;
  896. camuri.user_ctx = (void*) "Light Off";
  897. httpd_register_uri_handler(server, &camuri);
  898. camuri.uri = "/uptime";
  899. camuri.handler = handler_uptime;
  900. camuri.user_ctx = (void*) "Light Off";
  901. httpd_register_uri_handler(server, &camuri);
  902. camuri.uri = "/editflow";
  903. camuri.handler = handler_editflow;
  904. camuri.user_ctx = (void*) "EditFlow";
  905. httpd_register_uri_handler(server, &camuri);
  906. // Legacy API => New: "/value"
  907. camuri.uri = "/value.html";
  908. camuri.handler = handler_wasserzaehler;
  909. camuri.user_ctx = (void*) "Value";
  910. httpd_register_uri_handler(server, &camuri);
  911. camuri.uri = "/value";
  912. camuri.handler = handler_wasserzaehler;
  913. camuri.user_ctx = (void*) "Value";
  914. httpd_register_uri_handler(server, &camuri);
  915. // Legacy API => New: "/value"
  916. camuri.uri = "/wasserzaehler.html";
  917. camuri.handler = handler_wasserzaehler;
  918. camuri.user_ctx = (void*) "Wasserzaehler";
  919. httpd_register_uri_handler(server, &camuri);
  920. camuri.uri = "/json";
  921. camuri.handler = handler_json;
  922. camuri.user_ctx = (void*) "JSON";
  923. httpd_register_uri_handler(server, &camuri);
  924. camuri.uri = "/heap";
  925. camuri.handler = handler_get_heap;
  926. camuri.user_ctx = (void*) "Heap";
  927. httpd_register_uri_handler(server, &camuri);
  928. camuri.uri = "/stream";
  929. camuri.handler = handler_stream;
  930. camuri.user_ctx = (void*) "stream";
  931. httpd_register_uri_handler(server, &camuri);
  932. }