ClassFlowControll.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965
  1. #include "ClassFlowControll.h"
  2. #include "connect_wlan.h"
  3. #include "read_wlanini.h"
  4. #include "freertos/task.h"
  5. #include <sys/stat.h>
  6. #include <new>
  7. #ifdef __cplusplus
  8. extern "C" {
  9. #endif
  10. #include <dirent.h>
  11. #ifdef __cplusplus
  12. }
  13. #endif
  14. #include "ClassLogFile.h"
  15. #include "time_sntp.h"
  16. #include "Helper.h"
  17. #include "server_ota.h"
  18. #ifdef ENABLE_MQTT
  19. #include "interface_mqtt.h"
  20. #include "server_mqtt.h"
  21. #endif //ENABLE_MQTT
  22. #include "server_help.h"
  23. #include "MainFlowControl.h"
  24. #include "basic_auth.h"
  25. #include "../../include/defines.h"
  26. static const char* TAG = "FLOWCTRL";
  27. //#define DEBUG_DETAIL_ON
  28. std::string ClassFlowControll::doSingleStep(std::string _stepname, std::string _host)
  29. {
  30. std::string _classname = "";
  31. std::string result = "";
  32. ESP_LOGD(TAG, "Step %s start", _stepname.c_str());
  33. if ((_stepname.compare("[TakeImage]") == 0) || (_stepname.compare(";[TakeImage]") == 0)) {
  34. _classname = "ClassFlowTakeImage";
  35. }
  36. if ((_stepname.compare("[Alignment]") == 0) || (_stepname.compare(";[Alignment]") == 0)) {
  37. _classname = "ClassFlowAlignment";
  38. }
  39. if ((_stepname.compare(0, 7, "[Digits") == 0) || (_stepname.compare(0, 8, ";[Digits") == 0)) {
  40. _classname = "ClassFlowCNNGeneral";
  41. }
  42. if ((_stepname.compare("[Analog]") == 0) || (_stepname.compare(";[Analog]") == 0)) {
  43. _classname = "ClassFlowCNNGeneral";
  44. }
  45. #ifdef ENABLE_MQTT
  46. if ((_stepname.compare("[MQTT]") == 0) || (_stepname.compare(";[MQTT]") == 0)) {
  47. _classname = "ClassFlowMQTT";
  48. }
  49. #endif //ENABLE_MQTT
  50. #ifdef ENABLE_INFLUXDB
  51. if ((_stepname.compare("[InfluxDB]") == 0) || (_stepname.compare(";[InfluxDB]") == 0)) {
  52. _classname = "ClassFlowInfluxDB";
  53. }
  54. if ((_stepname.compare("[InfluxDBv2]") == 0) || (_stepname.compare(";[InfluxDBv2]") == 0)) {
  55. _classname = "ClassFlowInfluxDBv2";
  56. }
  57. #endif //ENABLE_INFLUXDB
  58. #ifdef ENABLE_WEBHOOK
  59. if ((_stepname.compare("[Webhook]") == 0) || (_stepname.compare(";[Webhook]") == 0)) {
  60. _classname = "ClassFlowWebhook";
  61. }
  62. #endif //ENABLE_WEBHOOK
  63. for (int i = 0; i < FlowControll.size(); ++i) {
  64. if (FlowControll[i]->name().compare(_classname) == 0) {
  65. if (!(FlowControll[i]->name().compare("ClassFlowTakeImage") == 0)) {
  66. // if it is a TakeImage, the image does not need to be included, this happens automatically with the html query.
  67. FlowControll[i]->doFlow("");
  68. }
  69. result = FlowControll[i]->getHTMLSingleStep(_host);
  70. }
  71. }
  72. ESP_LOGD(TAG, "Step %s end", _stepname.c_str());
  73. return result;
  74. }
  75. std::string ClassFlowControll::TranslateAktstatus(std::string _input)
  76. {
  77. if (_input.compare("ClassFlowTakeImage") == 0) {
  78. return ("Take Image");
  79. }
  80. if (_input.compare("ClassFlowAlignment") == 0) {
  81. return ("Aligning");
  82. }
  83. if (_input.compare("ClassFlowCNNGeneral") == 0) {
  84. return ("Digitization of ROIs");
  85. }
  86. #ifdef ENABLE_MQTT
  87. if (_input.compare("ClassFlowMQTT") == 0) {
  88. return ("Sending MQTT");
  89. }
  90. #endif //ENABLE_MQTT
  91. #ifdef ENABLE_INFLUXDB
  92. if (_input.compare("ClassFlowInfluxDB") == 0) {
  93. return ("Sending InfluxDB");
  94. }
  95. if (_input.compare("ClassFlowInfluxDBv2") == 0) {
  96. return ("Sending InfluxDBv2");
  97. }
  98. #endif //ENABLE_INFLUXDB
  99. #ifdef ENABLE_WEBHOOK
  100. if (_input.compare("ClassFlowWebhook") == 0) {
  101. return ("Sending Webhook");
  102. }
  103. #endif //ENABLE_WEBHOOK
  104. if (_input.compare("ClassFlowPostProcessing") == 0) {
  105. return ("Post-Processing");
  106. }
  107. return "Unkown Status";
  108. }
  109. std::vector<HTMLInfo*> ClassFlowControll::GetAllDigit()
  110. {
  111. if (flowdigit) {
  112. ESP_LOGD(TAG, "ClassFlowControll::GetAllDigit - flowdigit != NULL");
  113. return flowdigit->GetHTMLInfo();
  114. }
  115. std::vector<HTMLInfo*> empty;
  116. return empty;
  117. }
  118. std::vector<HTMLInfo*> ClassFlowControll::GetAllAnalog()
  119. {
  120. if (flowanalog) {
  121. return flowanalog->GetHTMLInfo();
  122. }
  123. std::vector<HTMLInfo*> empty;
  124. return empty;
  125. }
  126. t_CNNType ClassFlowControll::GetTypeDigit()
  127. {
  128. if (flowdigit) {
  129. return flowdigit->getCNNType();
  130. }
  131. return t_CNNType::None;
  132. }
  133. t_CNNType ClassFlowControll::GetTypeAnalog()
  134. {
  135. if (flowanalog) {
  136. return flowanalog->getCNNType();
  137. }
  138. return t_CNNType::None;
  139. }
  140. #ifdef ALGROI_LOAD_FROM_MEM_AS_JPG
  141. void ClassFlowControll::DigitDrawROI(CImageBasis *_zw)
  142. {
  143. if (flowdigit) {
  144. flowdigit->DrawROI(_zw);
  145. }
  146. }
  147. void ClassFlowControll::AnalogDrawROI(CImageBasis *_zw)
  148. {
  149. if (flowanalog) {
  150. flowanalog->DrawROI(_zw);
  151. }
  152. }
  153. #endif
  154. #ifdef ENABLE_MQTT
  155. bool ClassFlowControll::StartMQTTService()
  156. {
  157. /* Start the MQTT service */
  158. for (int i = 0; i < FlowControll.size(); ++i) {
  159. if (FlowControll[i]->name().compare("ClassFlowMQTT") == 0) {
  160. return ((ClassFlowMQTT*) (FlowControll[i]))->Start(AutoInterval);
  161. }
  162. }
  163. return false;
  164. }
  165. #endif //ENABLE_MQTT
  166. void ClassFlowControll::SetInitialParameter(void)
  167. {
  168. AutoStart = true;
  169. SetupModeActive = false;
  170. AutoInterval = 10; // Minutes
  171. flowdigit = NULL;
  172. flowanalog = NULL;
  173. flowpostprocessing = NULL;
  174. disabled = false;
  175. aktRunNr = 0;
  176. setStatus("Flow task not yet created", "Flow task not yet created");
  177. }
  178. bool ClassFlowControll::getIsAutoStart(void)
  179. {
  180. //return AutoStart;
  181. return true; // Flow must always be enabled, else the manual trigger (REST, MQTT) will not work!
  182. }
  183. void ClassFlowControll::setAutoStartInterval(long &_interval)
  184. {
  185. _interval = AutoInterval * 60 * 1000; // AutoInterval: minutes -> ms
  186. }
  187. ClassFlow* ClassFlowControll::CreateClassFlow(std::string _type)
  188. {
  189. ClassFlow* cfc = NULL;
  190. _type = trim(_type);
  191. if (toUpper(_type).compare("[TAKEIMAGE]") == 0) {
  192. cfc = new ClassFlowTakeImage(&FlowControll);
  193. flowtakeimage = (ClassFlowTakeImage*) cfc;
  194. }
  195. if (toUpper(_type).compare("[ALIGNMENT]") == 0) {
  196. cfc = new ClassFlowAlignment(&FlowControll);
  197. flowalignment = (ClassFlowAlignment*) cfc;
  198. }
  199. if (toUpper(_type).compare("[ANALOG]") == 0) {
  200. cfc = new ClassFlowCNNGeneral(flowalignment);
  201. flowanalog = (ClassFlowCNNGeneral*) cfc;
  202. }
  203. if (toUpper(_type).compare(0, 7, "[DIGITS") == 0) {
  204. cfc = new ClassFlowCNNGeneral(flowalignment);
  205. flowdigit = (ClassFlowCNNGeneral*) cfc;
  206. }
  207. #ifdef ENABLE_MQTT
  208. if (toUpper(_type).compare("[MQTT]") == 0) {
  209. cfc = new ClassFlowMQTT(&FlowControll);
  210. }
  211. #endif //ENABLE_MQTT
  212. #ifdef ENABLE_INFLUXDB
  213. if (toUpper(_type).compare("[INFLUXDB]") == 0) {
  214. cfc = new ClassFlowInfluxDB(&FlowControll);
  215. }
  216. if (toUpper(_type).compare("[INFLUXDBV2]") == 0) {
  217. cfc = new ClassFlowInfluxDBv2(&FlowControll);
  218. }
  219. #endif //ENABLE_INFLUXDB
  220. #ifdef ENABLE_WEBHOOK
  221. if (toUpper(_type).compare("[WEBHOOK]") == 0) {
  222. cfc = new ClassFlowWebhook(&FlowControll);
  223. }
  224. #endif //ENABLE_WEBHOOK
  225. if (toUpper(_type).compare("[POSTPROCESSING]") == 0) {
  226. cfc = new ClassFlowPostProcessing(&FlowControll, flowanalog, flowdigit);
  227. flowpostprocessing = (ClassFlowPostProcessing*) cfc;
  228. }
  229. if (cfc) {
  230. // Attached only if it is not [AutoTimer], because this is for FlowControll
  231. FlowControll.push_back(cfc);
  232. }
  233. if (toUpper(_type).compare("[AUTOTIMER]") == 0) {
  234. cfc = this;
  235. }
  236. if (toUpper(_type).compare("[DATALOGGING]") == 0) {
  237. cfc = this;
  238. }
  239. if (toUpper(_type).compare("[DEBUG]") == 0) {
  240. cfc = this;
  241. }
  242. if (toUpper(_type).compare("[SYSTEM]") == 0) {
  243. cfc = this;
  244. }
  245. return cfc;
  246. }
  247. void ClassFlowControll::InitFlow(std::string config)
  248. {
  249. setStatus("Initialization", "Initialization");
  250. //#ifdef ENABLE_MQTT
  251. //MQTTPublish(mqttServer_getMainTopic() + "/" + "status", "Initialization", 1, false); // Right now, not possible -> MQTT Service is going to be started later
  252. //#endif //ENABLE_MQTT
  253. string line;
  254. flowpostprocessing = NULL;
  255. ClassFlow* cfc;
  256. FILE* pFile;
  257. config = FormatFileName(config);
  258. pFile = fopen(config.c_str(), "r");
  259. line = "";
  260. char zw[1024];
  261. if (pFile != NULL) {
  262. fgets(zw, 1024, pFile);
  263. ESP_LOGD(TAG, "%s", zw);
  264. line = std::string(zw);
  265. }
  266. while ((line.size() > 0) && !(feof(pFile))) {
  267. cfc = CreateClassFlow(line);
  268. // printf("Name: %s\n", cfc->name().c_str());
  269. if (cfc) {
  270. ESP_LOGE(TAG, "Start ReadParameter (%s)", line.c_str());
  271. cfc->ReadParameter(pFile, line);
  272. }
  273. else {
  274. line = "";
  275. if (fgets(zw, 1024, pFile) && !feof(pFile)) {
  276. ESP_LOGD(TAG, "Read: %s", zw);
  277. line = std::string(zw);
  278. }
  279. }
  280. }
  281. fclose(pFile);
  282. }
  283. std::string ClassFlowControll::getActStatusWithTime()
  284. {
  285. std::lock_guard<std::mutex> lock(statusMutex);
  286. return aktstatusWithTime;
  287. }
  288. std::string ClassFlowControll::getActStatus()
  289. {
  290. std::lock_guard<std::mutex> lock(statusMutex);
  291. return aktstatus;
  292. }
  293. void ClassFlowControll::setStatus(const std::string &_status, const std::string &_statusWithTime)
  294. {
  295. std::lock_guard<std::mutex> lock(statusMutex);
  296. aktstatus = _status;
  297. aktstatusWithTime = _statusWithTime;
  298. }
  299. void ClassFlowControll::setActStatus(std::string _aktstatus)
  300. {
  301. setStatus(_aktstatus, _aktstatus);
  302. }
  303. void ClassFlowControll::doFlowTakeImageOnly(string time)
  304. {
  305. std::string zw_time;
  306. for (int i = 0; i < FlowControll.size(); ++i) {
  307. if (FlowControll[i]->name() == "ClassFlowTakeImage") {
  308. zw_time = getCurrentTimeString("%H:%M:%S");
  309. std::string status = TranslateAktstatus(FlowControll[i]->name());
  310. setStatus(status, status + " (" + zw_time + ")");
  311. #ifdef ENABLE_MQTT
  312. MQTTPublish(mqttServer_getMainTopic() + "/" + "status", aktstatus, 1, false);
  313. #endif //ENABLE_MQTT
  314. FlowControll[i]->doFlow(time);
  315. }
  316. }
  317. }
  318. bool ClassFlowControll::doFlow(string time)
  319. {
  320. bool result = true;
  321. std::string zw_time;
  322. int repeat = 0;
  323. int qos = 1;
  324. #ifdef DEBUG_DETAIL_ON
  325. LogFile.WriteHeapInfo("ClassFlowControll::doFlow - Start");
  326. #endif
  327. /* Check if we have a valid date/time and if not restart the NTP client */
  328. /* if (! getTimeIsSet()) {
  329. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Time not set, restarting NTP Client!");
  330. restartNtpClient();
  331. }*/
  332. //checkNtpStatus(0);
  333. for (int i = 0; i < FlowControll.size(); ++i) {
  334. zw_time = getCurrentTimeString("%H:%M:%S");
  335. std::string status = TranslateAktstatus(FlowControll[i]->name());
  336. setStatus(status, status + " (" + zw_time + ")");
  337. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Status: " + aktstatusWithTime);
  338. #ifdef ENABLE_MQTT
  339. MQTTPublish(mqttServer_getMainTopic() + "/" + "status", aktstatus, qos, false);
  340. #endif //ENABLE_MQTT
  341. #ifdef DEBUG_DETAIL_ON
  342. string zw = "FlowControll.doFlow - " + FlowControll[i]->name();
  343. LogFile.WriteHeapInfo(zw);
  344. #endif
  345. if (!FlowControll[i]->doFlow(time)) {
  346. repeat++;
  347. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Fehler im vorheriger Schritt - wird zum " + to_string(repeat) + ". Mal wiederholt");
  348. if (i) { i -= 1; } // vPrevious step must be repeated (probably take pictures)
  349. result = false;
  350. if (repeat > 5) {
  351. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Wiederholung 5x nicht erfolgreich --> reboot");
  352. doReboot();
  353. //Step was repeated 5x --> reboot
  354. }
  355. }
  356. else {
  357. result = true;
  358. }
  359. #ifdef DEBUG_DETAIL_ON
  360. LogFile.WriteHeapInfo("ClassFlowControll::doFlow");
  361. #endif
  362. }
  363. zw_time = getCurrentTimeString("%H:%M:%S");
  364. setStatus("Flow finished", std::string("Flow finished (") + zw_time + ")");
  365. //LogFile.WriteToFile(ESP_LOG_INFO, TAG, aktstatusWithTime);
  366. #ifdef ENABLE_MQTT
  367. MQTTPublish(mqttServer_getMainTopic() + "/" + "status", aktstatus, qos, false);
  368. #endif //ENABLE_MQTT
  369. return result;
  370. }
  371. string ClassFlowControll::getReadoutAll(int _type)
  372. {
  373. std::string out = "";
  374. if (flowpostprocessing) {
  375. std::vector<NumberPost*> *numbers = flowpostprocessing->GetNumbers();
  376. for (int i = 0; i < (*numbers).size(); ++i) {
  377. out = out + (*numbers)[i]->name + "\t";
  378. switch (_type) {
  379. case READOUT_TYPE_VALUE:
  380. out = out + (*numbers)[i]->ReturnValue;
  381. break;
  382. case READOUT_TYPE_PREVALUE:
  383. if (flowpostprocessing->PreValueUse) {
  384. if ((*numbers)[i]->PreValueOkay) {
  385. out = out + (*numbers)[i]->ReturnPreValue;
  386. }
  387. else {
  388. out = out + "PreValue too old";
  389. }
  390. }
  391. else {
  392. out = out + "PreValue deactivated";
  393. }
  394. break;
  395. case READOUT_TYPE_RAWVALUE:
  396. out = out + (*numbers)[i]->ReturnRawValue;
  397. break;
  398. case READOUT_TYPE_ERROR:
  399. out = out + (*numbers)[i]->ErrorMessageText;
  400. break;
  401. }
  402. if (i < (*numbers).size()-1) {
  403. out = out + "\r\n";
  404. }
  405. }
  406. // ESP_LOGD(TAG, "OUT: %s", out.c_str());
  407. }
  408. return out;
  409. }
  410. string ClassFlowControll::getReadout(bool _rawvalue = false, bool _noerror = false, int _number = 0)
  411. {
  412. if (flowpostprocessing) {
  413. return flowpostprocessing->getReadoutParam(_rawvalue, _noerror, _number);
  414. }
  415. return std::string("");
  416. }
  417. string ClassFlowControll::GetPrevalue(std::string _number)
  418. {
  419. if (flowpostprocessing) {
  420. return flowpostprocessing->GetPreValue(_number);
  421. }
  422. return std::string("");
  423. }
  424. bool ClassFlowControll::UpdatePrevalue(std::string _newvalue, std::string _numbers, bool _extern)
  425. {
  426. double newvalueAsDouble;
  427. char* p;
  428. _newvalue = trim(_newvalue);
  429. // ESP_LOGD(TAG, "Input UpdatePreValue: %s", _newvalue.c_str());
  430. if (_newvalue.substr(0,8).compare("0.000000") == 0 || _newvalue.compare("0.0") == 0 || _newvalue.compare("0") == 0) {
  431. newvalueAsDouble = 0; // preset to value = 0
  432. }
  433. else {
  434. newvalueAsDouble = strtod(_newvalue.c_str(), &p);
  435. if (newvalueAsDouble == 0) {
  436. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "UpdatePrevalue: No valid value for processing: " + _newvalue);
  437. return false;
  438. }
  439. }
  440. if (flowpostprocessing) {
  441. if (flowpostprocessing->SetPreValue(newvalueAsDouble, _numbers, _extern)) {
  442. return true;
  443. }
  444. else {
  445. return false;
  446. }
  447. }
  448. else {
  449. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "UpdatePrevalue: ERROR - Class Post-Processing not initialized");
  450. return false;
  451. }
  452. }
  453. bool ClassFlowControll::ReadParameter(FILE* pfile, string& aktparamgraph)
  454. {
  455. std::vector<string> splitted;
  456. aktparamgraph = trim(aktparamgraph);
  457. if (aktparamgraph.size() == 0) {
  458. if (!this->GetNextParagraph(pfile, aktparamgraph)) {
  459. return false;
  460. }
  461. }
  462. if ((toUpper(aktparamgraph).compare("[AUTOTIMER]") != 0) && (toUpper(aktparamgraph).compare("[DEBUG]") != 0) &&
  463. (toUpper(aktparamgraph).compare("[SYSTEM]") != 0 && (toUpper(aktparamgraph).compare("[DATALOGGING]") != 0))) {
  464. // Paragraph passt nicht zu Debug oder DataLogging
  465. return false;
  466. }
  467. while (this->getNextLine(pfile, &aktparamgraph) && !this->isNewParagraph(aktparamgraph)) {
  468. splitted = ZerlegeZeile(aktparamgraph, " =");
  469. if ((toUpper(splitted[0]) == "INTERVAL") && (splitted.size() > 1)) {
  470. if (isStringNumeric(splitted[1])) {
  471. AutoInterval = std::stof(splitted[1]);
  472. }
  473. }
  474. if ((toUpper(splitted[0]) == "DATALOGACTIVE") && (splitted.size() > 1)) {
  475. LogFile.SetDataLogToSD(alphanumericToBoolean(splitted[1]));
  476. }
  477. if ((toUpper(splitted[0]) == "DATAFILESRETENTION") && (splitted.size() > 1)) {
  478. if (isStringNumeric(splitted[1])) {
  479. LogFile.SetDataLogRetention(std::stoi(splitted[1]));
  480. }
  481. }
  482. if ((toUpper(splitted[0]) == "LOGLEVEL") && (splitted.size() > 1)) {
  483. /* matches esp_log_level_t */
  484. if ((toUpper(splitted[1]) == "TRUE") || (toUpper(splitted[1]) == "2")) {
  485. LogFile.setLogLevel(ESP_LOG_WARN);
  486. }
  487. else if ((toUpper(splitted[1]) == "FALSE") || (toUpper(splitted[1]) == "0") || (toUpper(splitted[1]) == "1")) {
  488. LogFile.setLogLevel(ESP_LOG_ERROR);
  489. }
  490. else if (toUpper(splitted[1]) == "3") {
  491. LogFile.setLogLevel(ESP_LOG_INFO);
  492. }
  493. else if (toUpper(splitted[1]) == "4") {
  494. LogFile.setLogLevel(ESP_LOG_DEBUG);
  495. }
  496. /* If system reboot was not triggered by user and reboot was caused by execption -> keep log level to DEBUG */
  497. if (!getIsPlannedReboot() && (esp_reset_reason() == ESP_RST_PANIC)) {
  498. LogFile.setLogLevel(ESP_LOG_DEBUG);
  499. }
  500. }
  501. if ((toUpper(splitted[0]) == "LOGFILESRETENTION") && (splitted.size() > 1)) {
  502. if (isStringNumeric(splitted[1])) {
  503. LogFile.SetLogFileRetention(std::stoi(splitted[1]));
  504. }
  505. }
  506. /* TimeServer and TimeZone got already read from the config, see setupTime () */
  507. #if (defined WLAN_USE_ROAMING_BY_SCANNING || (defined WLAN_USE_MESH_ROAMING && defined WLAN_USE_MESH_ROAMING_ACTIVATE_CLIENT_TRIGGERED_QUERIES))
  508. if ((toUpper(splitted[0]) == "RSSITHRESHOLD") && (splitted.size() > 1)) {
  509. int RSSIThresholdTMP = atoi(splitted[1].c_str());
  510. RSSIThresholdTMP = min(0, max(-100, RSSIThresholdTMP)); // Verify input limits (-100 - 0)
  511. if (ChangeRSSIThreshold(WLAN_CONFIG_FILE, RSSIThresholdTMP)) {
  512. // reboot necessary so that the new wlan.ini is also used !!!
  513. fclose(pfile);
  514. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Rebooting to activate new RSSITHRESHOLD ...");
  515. doReboot();
  516. }
  517. }
  518. #endif
  519. if ((toUpper(splitted[0]) == "HOSTNAME") && (splitted.size() > 1)) {
  520. if (ChangeHostName(WLAN_CONFIG_FILE, splitted[1])) {
  521. // reboot necessary so that the new wlan.ini is also used !!!
  522. fclose(pfile);
  523. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Rebooting to activate new HOSTNAME...");
  524. doReboot();
  525. }
  526. }
  527. if ((toUpper(splitted[0]) == "SETUPMODE") && (splitted.size() > 1)) {
  528. SetupModeActive = alphanumericToBoolean(splitted[1]);
  529. }
  530. }
  531. return true;
  532. }
  533. int ClassFlowControll::CleanTempFolder() {
  534. const char* folderPath = "/sdcard/img_tmp";
  535. ESP_LOGD(TAG, "Clean up temporary folder to avoid damage of sdcard sectors: %s", folderPath);
  536. DIR *dir = opendir(folderPath);
  537. if (!dir) {
  538. ESP_LOGE(TAG, "Failed to stat dir: %s", folderPath);
  539. return -1;
  540. }
  541. struct dirent *entry;
  542. int deleted = 0;
  543. while ((entry = readdir(dir)) != NULL) {
  544. std::string path = string(folderPath) + "/" + entry->d_name;
  545. if (entry->d_type == DT_REG) {
  546. if (unlink(path.c_str()) == 0) {
  547. deleted ++;
  548. }
  549. else {
  550. ESP_LOGE(TAG, "can't delete file: %s", path.c_str());
  551. }
  552. }
  553. else if (entry->d_type == DT_DIR) {
  554. deleted += removeFolder(path.c_str(), TAG);
  555. }
  556. }
  557. closedir(dir);
  558. ESP_LOGD(TAG, "%d files deleted", deleted);
  559. return 0;
  560. }
  561. esp_err_t ClassFlowControll::SendRawJPG(httpd_req_t *req)
  562. {
  563. return flowtakeimage != NULL ? flowtakeimage->SendRawJPG(req) : ESP_FAIL;
  564. }
  565. esp_err_t ClassFlowControll::GetJPGStream(std::string _fn, httpd_req_t *req)
  566. {
  567. ESP_LOGD(TAG, "ClassFlowControll::GetJPGStream %s", _fn.c_str());
  568. #ifdef DEBUG_DETAIL_ON
  569. LogFile.WriteHeapInfo("ClassFlowControll::GetJPGStream - Start");
  570. #endif
  571. CImageBasis *_send = NULL;
  572. esp_err_t result = ESP_FAIL;
  573. bool _sendDelete = false;
  574. if (_fn == "alg.jpg") {
  575. if (flowalignment && flowalignment->ImageBasis->ImageOkay()) {
  576. _send = flowalignment->ImageBasis;
  577. }
  578. else {
  579. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "ClassFlowControll::GetJPGStream: alg.jpg cannot be served");
  580. return ESP_FAIL;
  581. }
  582. }
  583. else if (_fn == "alg_roi.jpg") {
  584. std::string status = getActStatus(); // copy: the flow task changes it while this handler runs
  585. #ifdef ALGROI_LOAD_FROM_MEM_AS_JPG // no CImageBasis needed to create alg_roi.jpg (ca. 790kB less RAM)
  586. if (status.find("Initialization (delayed)") != -1) {
  587. std::string filename = "/sdcard/html/Flowstate_initialization_delayed.jpg";
  588. result = send_file(req, filename);
  589. /*
  590. FILE* file = fopen("/sdcard/html/Flowstate_initialization_delayed.jpg", "rb");
  591. if (!file) {
  592. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "File /sdcard/html/Flowstate_initialization_delayed.jpg not found");
  593. return ESP_FAIL;
  594. }
  595. fseek(file, 0, SEEK_END);
  596. long fileSize = ftell(file); // how long is the file ?
  597. fseek(file, 0, SEEK_SET); // reset
  598. unsigned char* fileBuffer = (unsigned char*) malloc(fileSize);
  599. if (!fileBuffer) {
  600. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "ClassFlowControll::GetJPGStream: Not enough memory to create fileBuffer: " + std::to_string(fileSize));
  601. fclose(file);
  602. return ESP_FAIL;
  603. }
  604. fread(fileBuffer, fileSize, 1, file);
  605. fclose(file);
  606. httpd_resp_set_type(req, "image/jpeg");
  607. result = httpd_resp_send(req, (const char *)fileBuffer, fileSize);
  608. free(fileBuffer);
  609. */
  610. }
  611. else if (status.find("Initialization") != -1) {
  612. std::string filename = "/sdcard/html/Flowstate_initialization.jpg";
  613. result = send_file(req, filename);
  614. /*
  615. FILE* file = fopen("/sdcard/html/Flowstate_initialization.jpg", "rb");
  616. if (!file) {
  617. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "File /sdcard/html/Flowstate_initialization.jpg not found");
  618. return ESP_FAIL;
  619. }
  620. fseek(file, 0, SEEK_END);
  621. long fileSize = ftell(file); // how long is the file ?
  622. fseek(file, 0, SEEK_SET); // reset
  623. unsigned char* fileBuffer = (unsigned char*) malloc(fileSize);
  624. if (!fileBuffer) {
  625. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "ClassFlowControll::GetJPGStream: Not enough memory to create fileBuffer: " + std::to_string(fileSize));
  626. fclose(file);
  627. return ESP_FAIL;
  628. }
  629. fread(fileBuffer, fileSize, 1, file);
  630. fclose(file);
  631. httpd_resp_set_type(req, "image/jpeg");
  632. result = httpd_resp_send(req, (const char *)fileBuffer, fileSize);
  633. free(fileBuffer);
  634. */
  635. }
  636. else if (status.find("Take Image") != -1) {
  637. if (flowalignment && flowalignment->AlgROI) {
  638. std::string filename = "/sdcard/html/Flowstate_take_image.jpg";
  639. result = send_file(req, filename);
  640. /*
  641. FILE* file = fopen("/sdcard/html/Flowstate_take_image.jpg", "rb");
  642. if (!file) {
  643. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "File /sdcard/html/Flowstate_take_image.jpg not found");
  644. return ESP_FAIL;
  645. }
  646. fseek(file, 0, SEEK_END);
  647. flowalignment->AlgROI->size = ftell(file); // how long is the file ?
  648. fseek(file, 0, SEEK_SET); // reset
  649. if (flowalignment->AlgROI->size > MAX_JPG_SIZE) {
  650. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "File /sdcard/html/Flowstate_take_image.jpg (" + std::to_string(flowalignment->AlgROI->size) +
  651. ") > allocated buffer (" + std::to_string(MAX_JPG_SIZE) + ")");
  652. fclose(file);
  653. return ESP_FAIL;
  654. }
  655. fread(flowalignment->AlgROI->data, flowalignment->AlgROI->size, 1, file);
  656. fclose(file);
  657. httpd_resp_set_type(req, "image/jpeg");
  658. result = httpd_resp_send(req, (const char *)flowalignment->AlgROI->data, flowalignment->AlgROI->size);
  659. */
  660. }
  661. else {
  662. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "ClassFlowControll::GetJPGStream: alg_roi.jpg cannot be served -> alg.jpg is going to be served!");
  663. if (flowalignment && flowalignment->ImageBasis->ImageOkay()) {
  664. _send = flowalignment->ImageBasis;
  665. }
  666. else {
  667. httpd_resp_send(req, NULL, 0);
  668. return ESP_OK;
  669. }
  670. }
  671. }
  672. else {
  673. if (flowalignment && flowalignment->AlgROI) {
  674. httpd_resp_set_type(req, "image/jpeg");
  675. result = httpd_resp_send(req, (const char *)flowalignment->AlgROI->data, flowalignment->AlgROI->size);
  676. }
  677. else {
  678. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "ClassFlowControll::GetJPGStream: alg_roi.jpg cannot be served -> alg.jpg is going to be served!");
  679. if (flowalignment && flowalignment->ImageBasis->ImageOkay()) {
  680. _send = flowalignment->ImageBasis;
  681. }
  682. else {
  683. httpd_resp_send(req, NULL, 0);
  684. return ESP_OK;
  685. }
  686. }
  687. }
  688. #else
  689. if (!flowalignment) {
  690. ESP_LOGD(TAG, "ClassFloDControll::GetJPGStream: FlowAlignment is not (yet) initialized. Interrupt serving!");
  691. httpd_resp_send(req, NULL, 0);
  692. return ESP_FAIL;
  693. }
  694. if (flowalignment->ImageBasis == NULL || !flowalignment->ImageBasis->ImageOkay()) {
  695. httpd_resp_send(req, NULL, 0);
  696. return ESP_FAIL;
  697. }
  698. _send = new (std::nothrow) CImageBasis("alg_roi", flowalignment->ImageBasis);
  699. if (_send != NULL && _send->ImageOkay()) {
  700. flowalignment->DrawRef(_send);
  701. if (flowdigit) flowdigit->DrawROI(_send);
  702. if (flowanalog) flowanalog->DrawROI(_send);
  703. _sendDelete = true;
  704. } else {
  705. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "ClassFlowControll::GetJPGStream: Not enough memory to create alg_roi.jpg -> alg.jpg is going to be served!");
  706. delete _send;
  707. _send = flowalignment->ImageBasis;
  708. _sendDelete = false;
  709. }
  710. #endif
  711. }
  712. else {
  713. std::vector<HTMLInfo*> htmlinfo;
  714. htmlinfo = GetAllDigit();
  715. ESP_LOGD(TAG, "After getClassFlowControll::GetAllDigit");
  716. for (int i = 0; i < htmlinfo.size(); ++i) {
  717. if (_fn == htmlinfo[i]->filename) {
  718. if (htmlinfo[i]->image) {
  719. _send = htmlinfo[i]->image;
  720. }
  721. }
  722. if (_fn == htmlinfo[i]->filename_org) {
  723. if (htmlinfo[i]->image_org) {
  724. _send = htmlinfo[i]->image_org;
  725. }
  726. }
  727. delete htmlinfo[i];
  728. }
  729. htmlinfo.clear();
  730. if (!_send) {
  731. htmlinfo = GetAllAnalog();
  732. ESP_LOGD(TAG, "After getClassFlowControll::GetAllAnalog");
  733. for (int i = 0; i < htmlinfo.size(); ++i) {
  734. if (_fn == htmlinfo[i]->filename) {
  735. if (htmlinfo[i]->image) {
  736. _send = htmlinfo[i]->image;
  737. }
  738. }
  739. if (_fn == htmlinfo[i]->filename_org) {
  740. if (htmlinfo[i]->image_org) {
  741. _send = htmlinfo[i]->image_org;
  742. }
  743. }
  744. delete htmlinfo[i];
  745. }
  746. htmlinfo.clear();
  747. }
  748. }
  749. #ifdef DEBUG_DETAIL_ON
  750. LogFile.WriteHeapInfo("ClassFlowControll::GetJPGStream - before send");
  751. #endif
  752. if (_send) {
  753. ESP_LOGD(TAG, "Sending file: %s ...", _fn.c_str());
  754. set_content_type_from_file(req, _fn.c_str());
  755. result = _send->SendJPGtoHTTP(req);
  756. /* Respond with an empty chunk to signal HTTP response completion */
  757. httpd_resp_send_chunk(req, NULL, 0);
  758. ESP_LOGD(TAG, "File sending complete");
  759. if (_sendDelete) {
  760. delete _send;
  761. }
  762. _send = NULL;
  763. }
  764. #ifdef DEBUG_DETAIL_ON
  765. LogFile.WriteHeapInfo("ClassFlowControll::GetJPGStream - done");
  766. #endif
  767. return result;
  768. }
  769. // flowpostprocessing is NULL until InitFlow() has parsed the config, and InitFlow() resets it to NULL
  770. // whenever the flow is rebuilt; REST handlers can call these at any time.
  771. string ClassFlowControll::getNumbersName()
  772. {
  773. if (flowpostprocessing) {
  774. return flowpostprocessing->getNumbersName();
  775. }
  776. return "";
  777. }
  778. string ClassFlowControll::getJSON()
  779. {
  780. if (flowpostprocessing) {
  781. return flowpostprocessing->GetJSON();
  782. }
  783. return "";
  784. }
  785. /**
  786. * @returns a vector of all current sequences (empty while the flow is not initialized)
  787. **/
  788. const std::vector<NumberPost*> &ClassFlowControll::getNumbers()
  789. {
  790. static const std::vector<NumberPost*> noNumbers;
  791. if (flowpostprocessing) {
  792. return *flowpostprocessing->GetNumbers();
  793. }
  794. return noNumbers;
  795. }