MainFlowControl.cpp 34 KB

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