ClassFlowControll.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993
  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. ClassFlowControll::ClassFlowControll()
  167. {
  168. SetInitialParameter();
  169. }
  170. ClassFlowControll::~ClassFlowControll()
  171. {
  172. // Destroy dependants before the flows they reference (PostProcessing, CNN,
  173. // Alignment, then TakeImage), so borrowed image pointers remain valid.
  174. for (auto it = FlowControll.rbegin(); it != FlowControll.rend(); ++it) {
  175. delete *it;
  176. }
  177. FlowControll.clear();
  178. flowpostprocessing = NULL;
  179. flowdigit = NULL;
  180. flowanalog = NULL;
  181. flowalignment = NULL;
  182. flowtakeimage = NULL;
  183. }
  184. void ClassFlowControll::SetInitialParameter(void)
  185. {
  186. AutoStart = true;
  187. SetupModeActive = false;
  188. AutoInterval = 10;
  189. flowdigit = NULL;
  190. flowanalog = NULL;
  191. flowpostprocessing = NULL;
  192. flowalignment = NULL;
  193. flowtakeimage = NULL;
  194. disabled = false;
  195. aktRunNr = 0;
  196. setStatus("Flow task not yet created", "Flow task not yet created");
  197. }
  198. bool ClassFlowControll::getIsAutoStart(void)
  199. {
  200. //return AutoStart;
  201. return true; // Flow must always be enabled, else the manual trigger (REST, MQTT) will not work!
  202. }
  203. void ClassFlowControll::setAutoStartInterval(long &_interval)
  204. {
  205. _interval = AutoInterval * 60 * 1000; // AutoInterval: minutes -> ms
  206. }
  207. ClassFlow* ClassFlowControll::CreateClassFlow(std::string _type)
  208. {
  209. ClassFlow* cfc = NULL;
  210. _type = trim(_type);
  211. if (toUpper(_type).compare("[TAKEIMAGE]") == 0) {
  212. cfc = new (std::nothrow) ClassFlowTakeImage(&FlowControll);
  213. flowtakeimage = (ClassFlowTakeImage*) cfc;
  214. }
  215. if (toUpper(_type).compare("[ALIGNMENT]") == 0) {
  216. cfc = new (std::nothrow) ClassFlowAlignment(&FlowControll);
  217. flowalignment = (ClassFlowAlignment*) cfc;
  218. }
  219. if (toUpper(_type).compare("[ANALOG]") == 0) {
  220. cfc = new (std::nothrow) ClassFlowCNNGeneral(flowalignment);
  221. flowanalog = (ClassFlowCNNGeneral*) cfc;
  222. }
  223. if (toUpper(_type).compare(0, 7, "[DIGITS") == 0) {
  224. cfc = new (std::nothrow) ClassFlowCNNGeneral(flowalignment);
  225. flowdigit = (ClassFlowCNNGeneral*) cfc;
  226. }
  227. #ifdef ENABLE_MQTT
  228. if (toUpper(_type).compare("[MQTT]") == 0) {
  229. cfc = new (std::nothrow) ClassFlowMQTT(&FlowControll);
  230. }
  231. #endif //ENABLE_MQTT
  232. #ifdef ENABLE_INFLUXDB
  233. if (toUpper(_type).compare("[INFLUXDB]") == 0) {
  234. cfc = new (std::nothrow) ClassFlowInfluxDB(&FlowControll);
  235. }
  236. if (toUpper(_type).compare("[INFLUXDBV2]") == 0) {
  237. cfc = new (std::nothrow) ClassFlowInfluxDBv2(&FlowControll);
  238. }
  239. #endif //ENABLE_INFLUXDB
  240. #ifdef ENABLE_WEBHOOK
  241. if (toUpper(_type).compare("[WEBHOOK]") == 0) {
  242. cfc = new (std::nothrow) ClassFlowWebhook(&FlowControll);
  243. }
  244. #endif //ENABLE_WEBHOOK
  245. if (toUpper(_type).compare("[POSTPROCESSING]") == 0) {
  246. cfc = new (std::nothrow) ClassFlowPostProcessing(&FlowControll, flowanalog, flowdigit);
  247. flowpostprocessing = (ClassFlowPostProcessing*) cfc;
  248. }
  249. const std::string normalizedType = toUpper(_type);
  250. const bool disabledSection = !_type.empty() && (_type[0] == ';');
  251. if (cfc) {
  252. FlowControll.push_back(cfc);
  253. } else if (!disabledSection &&
  254. normalizedType != "[AUTOTIMER]" && normalizedType != "[DATALOGGING]" &&
  255. normalizedType != "[DEBUG]" && normalizedType != "[SYSTEM]") {
  256. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to allocate flow component " + _type);
  257. }
  258. if (toUpper(_type).compare("[AUTOTIMER]") == 0) {
  259. cfc = this;
  260. }
  261. if (toUpper(_type).compare("[DATALOGGING]") == 0) {
  262. cfc = this;
  263. }
  264. if (toUpper(_type).compare("[DEBUG]") == 0) {
  265. cfc = this;
  266. }
  267. if (toUpper(_type).compare("[SYSTEM]") == 0) {
  268. cfc = this;
  269. }
  270. return cfc;
  271. }
  272. void ClassFlowControll::InitFlow(std::string config)
  273. {
  274. setStatus("Initialization", "Initialization");
  275. //#ifdef ENABLE_MQTT
  276. //MQTTPublish(mqttServer_getMainTopic() + "/" + "status", "Initialization", 1, false); // Right now, not possible -> MQTT Service is going to be started later
  277. //#endif //ENABLE_MQTT
  278. string line;
  279. flowpostprocessing = NULL;
  280. ClassFlow* cfc;
  281. FILE* pFile;
  282. config = FormatFileName(config);
  283. pFile = fopen(config.c_str(), "r");
  284. line = "";
  285. char zw[1024];
  286. if (pFile != NULL) {
  287. fgets(zw, 1024, pFile);
  288. ESP_LOGD(TAG, "%s", zw);
  289. line = std::string(zw);
  290. }
  291. while ((line.size() > 0) && !(feof(pFile))) {
  292. cfc = CreateClassFlow(line);
  293. // printf("Name: %s\n", cfc->name().c_str());
  294. if (cfc) {
  295. ESP_LOGI(TAG, "Start ReadParameter (%s)", line.c_str());
  296. cfc->ReadParameter(pFile, line);
  297. }
  298. else {
  299. // This controller only instantiates flow steps. Other or disabled
  300. // config sections (for example GPIO and commented-out integrations)
  301. // are handled elsewhere or intentionally inactive. Skip their whole
  302. // paragraph instead of treating each key/value line as a flow name.
  303. if (!this->GetNextParagraph(pFile, line)) {
  304. line.clear();
  305. }
  306. }
  307. }
  308. fclose(pFile);
  309. }
  310. std::string ClassFlowControll::getActStatusWithTime()
  311. {
  312. std::lock_guard<std::mutex> lock(statusMutex);
  313. return aktstatusWithTime;
  314. }
  315. std::string ClassFlowControll::getActStatus()
  316. {
  317. std::lock_guard<std::mutex> lock(statusMutex);
  318. return aktstatus;
  319. }
  320. void ClassFlowControll::setStatus(const std::string &_status, const std::string &_statusWithTime)
  321. {
  322. std::lock_guard<std::mutex> lock(statusMutex);
  323. aktstatus = _status;
  324. aktstatusWithTime = _statusWithTime;
  325. }
  326. void ClassFlowControll::setActStatus(std::string _aktstatus)
  327. {
  328. setStatus(_aktstatus, _aktstatus);
  329. }
  330. void ClassFlowControll::doFlowTakeImageOnly(string time)
  331. {
  332. std::string zw_time;
  333. for (int i = 0; i < FlowControll.size(); ++i) {
  334. if (FlowControll[i]->name() == "ClassFlowTakeImage") {
  335. zw_time = getCurrentTimeString("%H:%M:%S");
  336. std::string status = TranslateAktstatus(FlowControll[i]->name());
  337. setStatus(status, status + " (" + zw_time + ")");
  338. #ifdef ENABLE_MQTT
  339. MQTTPublish(mqttServer_getMainTopic() + "/" + "status", aktstatus, 1, false);
  340. #endif //ENABLE_MQTT
  341. FlowControll[i]->doFlow(time);
  342. }
  343. }
  344. }
  345. bool ClassFlowControll::doFlow(string time)
  346. {
  347. bool result = true;
  348. std::string zw_time;
  349. int repeat = 0;
  350. int qos = 1;
  351. #ifdef DEBUG_DETAIL_ON
  352. LogFile.WriteHeapInfo("ClassFlowControll::doFlow - Start");
  353. #endif
  354. /* Check if we have a valid date/time and if not restart the NTP client */
  355. /* if (! getTimeIsSet()) {
  356. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Time not set, restarting NTP Client!");
  357. restartNtpClient();
  358. }*/
  359. //checkNtpStatus(0);
  360. for (int i = 0; i < FlowControll.size(); ++i) {
  361. zw_time = getCurrentTimeString("%H:%M:%S");
  362. std::string status = TranslateAktstatus(FlowControll[i]->name());
  363. setStatus(status, status + " (" + zw_time + ")");
  364. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Status: " + aktstatusWithTime);
  365. #ifdef ENABLE_MQTT
  366. MQTTPublish(mqttServer_getMainTopic() + "/" + "status", aktstatus, qos, false);
  367. #endif //ENABLE_MQTT
  368. #ifdef DEBUG_DETAIL_ON
  369. string zw = "FlowControll.doFlow - " + FlowControll[i]->name();
  370. LogFile.WriteHeapInfo(zw);
  371. #endif
  372. if (!FlowControll[i]->doFlow(time)) {
  373. repeat++;
  374. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Fehler im vorheriger Schritt - wird zum " + to_string(repeat) + ". Mal wiederholt");
  375. if (i) { i -= 1; } // vPrevious step must be repeated (probably take pictures)
  376. result = false;
  377. if (repeat > 5) {
  378. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Wiederholung 5x nicht erfolgreich --> reboot");
  379. doReboot();
  380. //Step was repeated 5x --> reboot
  381. }
  382. }
  383. else {
  384. result = true;
  385. }
  386. #ifdef DEBUG_DETAIL_ON
  387. LogFile.WriteHeapInfo("ClassFlowControll::doFlow");
  388. #endif
  389. }
  390. zw_time = getCurrentTimeString("%H:%M:%S");
  391. setStatus("Flow finished", std::string("Flow finished (") + zw_time + ")");
  392. //LogFile.WriteToFile(ESP_LOG_INFO, TAG, aktstatusWithTime);
  393. #ifdef ENABLE_MQTT
  394. MQTTPublish(mqttServer_getMainTopic() + "/" + "status", aktstatus, qos, false);
  395. #endif //ENABLE_MQTT
  396. return result;
  397. }
  398. string ClassFlowControll::getReadoutAll(int _type)
  399. {
  400. std::string out = "";
  401. if (flowpostprocessing) {
  402. std::vector<NumberPost*> *numbers = flowpostprocessing->GetNumbers();
  403. for (int i = 0; i < (*numbers).size(); ++i) {
  404. out = out + (*numbers)[i]->name + "\t";
  405. switch (_type) {
  406. case READOUT_TYPE_VALUE:
  407. out = out + (*numbers)[i]->ReturnValue;
  408. break;
  409. case READOUT_TYPE_PREVALUE:
  410. if (flowpostprocessing->PreValueUse) {
  411. if ((*numbers)[i]->PreValueOkay) {
  412. out = out + (*numbers)[i]->ReturnPreValue;
  413. }
  414. else {
  415. out = out + "PreValue too old";
  416. }
  417. }
  418. else {
  419. out = out + "PreValue deactivated";
  420. }
  421. break;
  422. case READOUT_TYPE_RAWVALUE:
  423. out = out + (*numbers)[i]->ReturnRawValue;
  424. break;
  425. case READOUT_TYPE_ERROR:
  426. out = out + (*numbers)[i]->ErrorMessageText;
  427. break;
  428. }
  429. if (i < (*numbers).size()-1) {
  430. out = out + "\r\n";
  431. }
  432. }
  433. // ESP_LOGD(TAG, "OUT: %s", out.c_str());
  434. }
  435. return out;
  436. }
  437. string ClassFlowControll::getReadout(bool _rawvalue = false, bool _noerror = false, int _number = 0)
  438. {
  439. if (flowpostprocessing) {
  440. return flowpostprocessing->getReadoutParam(_rawvalue, _noerror, _number);
  441. }
  442. return std::string("");
  443. }
  444. string ClassFlowControll::GetPrevalue(std::string _number)
  445. {
  446. if (flowpostprocessing) {
  447. return flowpostprocessing->GetPreValue(_number);
  448. }
  449. return std::string("");
  450. }
  451. bool ClassFlowControll::UpdatePrevalue(std::string _newvalue, std::string _numbers, bool _extern)
  452. {
  453. double newvalueAsDouble;
  454. char* p;
  455. _newvalue = trim(_newvalue);
  456. // ESP_LOGD(TAG, "Input UpdatePreValue: %s", _newvalue.c_str());
  457. if (_newvalue.substr(0,8).compare("0.000000") == 0 || _newvalue.compare("0.0") == 0 || _newvalue.compare("0") == 0) {
  458. newvalueAsDouble = 0; // preset to value = 0
  459. }
  460. else {
  461. newvalueAsDouble = strtod(_newvalue.c_str(), &p);
  462. if (newvalueAsDouble == 0) {
  463. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "UpdatePrevalue: No valid value for processing: " + _newvalue);
  464. return false;
  465. }
  466. }
  467. if (flowpostprocessing) {
  468. if (flowpostprocessing->SetPreValue(newvalueAsDouble, _numbers, _extern)) {
  469. return true;
  470. }
  471. else {
  472. return false;
  473. }
  474. }
  475. else {
  476. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "UpdatePrevalue: ERROR - Class Post-Processing not initialized");
  477. return false;
  478. }
  479. }
  480. bool ClassFlowControll::ReadParameter(FILE* pfile, string& aktparamgraph)
  481. {
  482. std::vector<string> splitted;
  483. aktparamgraph = trim(aktparamgraph);
  484. if (aktparamgraph.size() == 0) {
  485. if (!this->GetNextParagraph(pfile, aktparamgraph)) {
  486. return false;
  487. }
  488. }
  489. if ((toUpper(aktparamgraph).compare("[AUTOTIMER]") != 0) && (toUpper(aktparamgraph).compare("[DEBUG]") != 0) &&
  490. (toUpper(aktparamgraph).compare("[SYSTEM]") != 0 && (toUpper(aktparamgraph).compare("[DATALOGGING]") != 0))) {
  491. // Paragraph passt nicht zu Debug oder DataLogging
  492. return false;
  493. }
  494. while (this->getNextLine(pfile, &aktparamgraph) && !this->isNewParagraph(aktparamgraph)) {
  495. splitted = ZerlegeZeile(aktparamgraph, " =");
  496. if ((toUpper(splitted[0]) == "INTERVAL") && (splitted.size() > 1)) {
  497. if (isStringNumeric(splitted[1])) {
  498. AutoInterval = std::stof(splitted[1]);
  499. }
  500. }
  501. if ((toUpper(splitted[0]) == "DATALOGACTIVE") && (splitted.size() > 1)) {
  502. LogFile.SetDataLogToSD(alphanumericToBoolean(splitted[1]));
  503. }
  504. if ((toUpper(splitted[0]) == "DATAFILESRETENTION") && (splitted.size() > 1)) {
  505. if (isStringNumeric(splitted[1])) {
  506. LogFile.SetDataLogRetention(std::stoi(splitted[1]));
  507. }
  508. }
  509. if ((toUpper(splitted[0]) == "LOGLEVEL") && (splitted.size() > 1)) {
  510. /* matches esp_log_level_t */
  511. if ((toUpper(splitted[1]) == "TRUE") || (toUpper(splitted[1]) == "2")) {
  512. LogFile.setLogLevel(ESP_LOG_WARN);
  513. }
  514. else if ((toUpper(splitted[1]) == "FALSE") || (toUpper(splitted[1]) == "0") || (toUpper(splitted[1]) == "1")) {
  515. LogFile.setLogLevel(ESP_LOG_ERROR);
  516. }
  517. else if (toUpper(splitted[1]) == "3") {
  518. LogFile.setLogLevel(ESP_LOG_INFO);
  519. }
  520. else if (toUpper(splitted[1]) == "4") {
  521. LogFile.setLogLevel(ESP_LOG_DEBUG);
  522. }
  523. /* If system reboot was not triggered by user and reboot was caused by execption -> keep log level to DEBUG */
  524. if (!getIsPlannedReboot() && (esp_reset_reason() == ESP_RST_PANIC)) {
  525. LogFile.setLogLevel(ESP_LOG_DEBUG);
  526. }
  527. }
  528. if ((toUpper(splitted[0]) == "LOGFILESRETENTION") && (splitted.size() > 1)) {
  529. if (isStringNumeric(splitted[1])) {
  530. LogFile.SetLogFileRetention(std::stoi(splitted[1]));
  531. }
  532. }
  533. /* TimeServer and TimeZone got already read from the config, see setupTime () */
  534. #if (defined WLAN_USE_ROAMING_BY_SCANNING || (defined WLAN_USE_MESH_ROAMING && defined WLAN_USE_MESH_ROAMING_ACTIVATE_CLIENT_TRIGGERED_QUERIES))
  535. if ((toUpper(splitted[0]) == "RSSITHRESHOLD") && (splitted.size() > 1)) {
  536. int RSSIThresholdTMP = atoi(splitted[1].c_str());
  537. RSSIThresholdTMP = min(0, max(-100, RSSIThresholdTMP)); // Verify input limits (-100 - 0)
  538. if (ChangeRSSIThreshold(WLAN_CONFIG_FILE, RSSIThresholdTMP)) {
  539. // reboot necessary so that the new wlan.ini is also used !!!
  540. fclose(pfile);
  541. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Rebooting to activate new RSSITHRESHOLD ...");
  542. doReboot();
  543. }
  544. }
  545. #endif
  546. if ((toUpper(splitted[0]) == "HOSTNAME") && (splitted.size() > 1)) {
  547. if (ChangeHostName(WLAN_CONFIG_FILE, splitted[1])) {
  548. // reboot necessary so that the new wlan.ini is also used !!!
  549. fclose(pfile);
  550. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Rebooting to activate new HOSTNAME...");
  551. doReboot();
  552. }
  553. }
  554. if ((toUpper(splitted[0]) == "SETUPMODE") && (splitted.size() > 1)) {
  555. SetupModeActive = alphanumericToBoolean(splitted[1]);
  556. }
  557. }
  558. return true;
  559. }
  560. int ClassFlowControll::CleanTempFolder() {
  561. const char* folderPath = "/sdcard/img_tmp";
  562. ESP_LOGD(TAG, "Clean up temporary folder to avoid damage of sdcard sectors: %s", folderPath);
  563. DIR *dir = opendir(folderPath);
  564. if (!dir) {
  565. ESP_LOGE(TAG, "Failed to stat dir: %s", folderPath);
  566. return -1;
  567. }
  568. struct dirent *entry;
  569. int deleted = 0;
  570. while ((entry = readdir(dir)) != NULL) {
  571. std::string path = string(folderPath) + "/" + entry->d_name;
  572. if (entry->d_type == DT_REG) {
  573. if (unlink(path.c_str()) == 0) {
  574. deleted ++;
  575. }
  576. else {
  577. ESP_LOGE(TAG, "can't delete file: %s", path.c_str());
  578. }
  579. }
  580. else if (entry->d_type == DT_DIR) {
  581. deleted += removeFolder(path.c_str(), TAG);
  582. }
  583. }
  584. closedir(dir);
  585. ESP_LOGD(TAG, "%d files deleted", deleted);
  586. return 0;
  587. }
  588. esp_err_t ClassFlowControll::SendRawJPG(httpd_req_t *req, bool previewCapture)
  589. {
  590. return flowtakeimage != NULL ? flowtakeimage->SendRawJPG(req, previewCapture) : ESP_FAIL;
  591. }
  592. esp_err_t ClassFlowControll::GetJPGStream(std::string _fn, httpd_req_t *req)
  593. {
  594. ESP_LOGD(TAG, "ClassFlowControll::GetJPGStream %s", _fn.c_str());
  595. #ifdef DEBUG_DETAIL_ON
  596. LogFile.WriteHeapInfo("ClassFlowControll::GetJPGStream - Start");
  597. #endif
  598. CImageBasis *_send = NULL;
  599. esp_err_t result = ESP_FAIL;
  600. bool _sendDelete = false;
  601. if (_fn == "alg.jpg") {
  602. if (flowalignment && flowalignment->ImageBasis && flowalignment->ImageBasis->ImageOkay()) {
  603. _send = flowalignment->ImageBasis;
  604. }
  605. else {
  606. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "ClassFlowControll::GetJPGStream: alg.jpg cannot be served");
  607. return ESP_FAIL;
  608. }
  609. }
  610. else if (_fn == "alg_roi.jpg") {
  611. std::string status = getActStatus(); // copy: the flow task changes it while this handler runs
  612. #ifdef ALGROI_LOAD_FROM_MEM_AS_JPG // no CImageBasis needed to create alg_roi.jpg (ca. 790kB less RAM)
  613. if (status.find("Initialization (delayed)") != -1) {
  614. std::string filename = "/sdcard/html/Flowstate_initialization_delayed.jpg";
  615. result = send_file(req, filename);
  616. /*
  617. FILE* file = fopen("/sdcard/html/Flowstate_initialization_delayed.jpg", "rb");
  618. if (!file) {
  619. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "File /sdcard/html/Flowstate_initialization_delayed.jpg not found");
  620. return ESP_FAIL;
  621. }
  622. fseek(file, 0, SEEK_END);
  623. long fileSize = ftell(file); // how long is the file ?
  624. fseek(file, 0, SEEK_SET); // reset
  625. unsigned char* fileBuffer = (unsigned char*) malloc(fileSize);
  626. if (!fileBuffer) {
  627. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "ClassFlowControll::GetJPGStream: Not enough memory to create fileBuffer: " + std::to_string(fileSize));
  628. fclose(file);
  629. return ESP_FAIL;
  630. }
  631. fread(fileBuffer, fileSize, 1, file);
  632. fclose(file);
  633. httpd_resp_set_type(req, "image/jpeg");
  634. result = httpd_resp_send(req, (const char *)fileBuffer, fileSize);
  635. free(fileBuffer);
  636. */
  637. }
  638. else if (status.find("Initialization") != -1) {
  639. std::string filename = "/sdcard/html/Flowstate_initialization.jpg";
  640. result = send_file(req, filename);
  641. /*
  642. FILE* file = fopen("/sdcard/html/Flowstate_initialization.jpg", "rb");
  643. if (!file) {
  644. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "File /sdcard/html/Flowstate_initialization.jpg not found");
  645. return ESP_FAIL;
  646. }
  647. fseek(file, 0, SEEK_END);
  648. long fileSize = ftell(file); // how long is the file ?
  649. fseek(file, 0, SEEK_SET); // reset
  650. unsigned char* fileBuffer = (unsigned char*) malloc(fileSize);
  651. if (!fileBuffer) {
  652. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "ClassFlowControll::GetJPGStream: Not enough memory to create fileBuffer: " + std::to_string(fileSize));
  653. fclose(file);
  654. return ESP_FAIL;
  655. }
  656. fread(fileBuffer, fileSize, 1, file);
  657. fclose(file);
  658. httpd_resp_set_type(req, "image/jpeg");
  659. result = httpd_resp_send(req, (const char *)fileBuffer, fileSize);
  660. free(fileBuffer);
  661. */
  662. }
  663. else if (status.find("Take Image") != -1) {
  664. if (flowalignment != NULL) {
  665. std::string filename = "/sdcard/html/Flowstate_take_image.jpg";
  666. result = send_file(req, filename);
  667. /*
  668. FILE* file = fopen("/sdcard/html/Flowstate_take_image.jpg", "rb");
  669. if (!file) {
  670. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "File /sdcard/html/Flowstate_take_image.jpg not found");
  671. return ESP_FAIL;
  672. }
  673. fseek(file, 0, SEEK_END);
  674. flowalignment->AlgROI->size = ftell(file); // how long is the file ?
  675. fseek(file, 0, SEEK_SET); // reset
  676. if (flowalignment->AlgROI->size > MAX_JPG_SIZE) {
  677. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "File /sdcard/html/Flowstate_take_image.jpg (" + std::to_string(flowalignment->AlgROI->size) +
  678. ") > allocated buffer (" + std::to_string(MAX_JPG_SIZE) + ")");
  679. fclose(file);
  680. return ESP_FAIL;
  681. }
  682. fread(flowalignment->AlgROI->data, flowalignment->AlgROI->size, 1, file);
  683. fclose(file);
  684. httpd_resp_set_type(req, "image/jpeg");
  685. result = httpd_resp_send(req, (const char *)flowalignment->AlgROI->data, flowalignment->AlgROI->size);
  686. */
  687. }
  688. else {
  689. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "ClassFlowControll::GetJPGStream: alg_roi.jpg cannot be served -> alg.jpg is going to be served!");
  690. if (flowalignment && flowalignment->ImageBasis && flowalignment->ImageBasis->ImageOkay()) {
  691. _send = flowalignment->ImageBasis;
  692. }
  693. else {
  694. httpd_resp_send(req, NULL, 0);
  695. return ESP_OK;
  696. }
  697. }
  698. }
  699. else {
  700. if (flowalignment != NULL) {
  701. result = flowalignment->SendAlgROIToHTTP(req);
  702. if (result != ESP_ERR_NOT_FOUND && result != ESP_ERR_TIMEOUT) {
  703. return result;
  704. }
  705. }
  706. // A missing preview must not fall back to ImageBasis: that would
  707. // make the single HTTP server task wait on the global image lock.
  708. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "ClassFlowControll::GetJPGStream: ROI preview is not ready");
  709. httpd_resp_set_status(req, "503 Service Unavailable");
  710. httpd_resp_set_type(req, "text/plain");
  711. return httpd_resp_send(req, "ROI preview not ready", HTTPD_RESP_USE_STRLEN);
  712. }
  713. #else
  714. if (!flowalignment) {
  715. ESP_LOGD(TAG, "ClassFloDControll::GetJPGStream: FlowAlignment is not (yet) initialized. Interrupt serving!");
  716. httpd_resp_send(req, NULL, 0);
  717. return ESP_FAIL;
  718. }
  719. if (flowalignment->ImageBasis == NULL || !flowalignment->ImageBasis->ImageOkay()) {
  720. httpd_resp_send(req, NULL, 0);
  721. return ESP_FAIL;
  722. }
  723. _send = new (std::nothrow) CImageBasis("alg_roi", flowalignment->ImageBasis);
  724. if (_send != NULL && _send->ImageOkay()) {
  725. flowalignment->DrawRef(_send);
  726. if (flowdigit) flowdigit->DrawROI(_send);
  727. if (flowanalog) flowanalog->DrawROI(_send);
  728. _sendDelete = true;
  729. } else {
  730. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "ClassFlowControll::GetJPGStream: Not enough memory to create alg_roi.jpg -> alg.jpg is going to be served!");
  731. delete _send;
  732. _send = flowalignment->ImageBasis;
  733. _sendDelete = false;
  734. }
  735. #endif
  736. }
  737. else {
  738. std::vector<HTMLInfo*> htmlinfo;
  739. htmlinfo = GetAllDigit();
  740. ESP_LOGD(TAG, "After getClassFlowControll::GetAllDigit");
  741. for (int i = 0; i < htmlinfo.size(); ++i) {
  742. if (_fn == htmlinfo[i]->filename) {
  743. if (htmlinfo[i]->image) {
  744. _send = htmlinfo[i]->image;
  745. }
  746. }
  747. if (_fn == htmlinfo[i]->filename_org) {
  748. if (htmlinfo[i]->image_org) {
  749. _send = htmlinfo[i]->image_org;
  750. }
  751. }
  752. delete htmlinfo[i];
  753. }
  754. htmlinfo.clear();
  755. if (!_send) {
  756. htmlinfo = GetAllAnalog();
  757. ESP_LOGD(TAG, "After getClassFlowControll::GetAllAnalog");
  758. for (int i = 0; i < htmlinfo.size(); ++i) {
  759. if (_fn == htmlinfo[i]->filename) {
  760. if (htmlinfo[i]->image) {
  761. _send = htmlinfo[i]->image;
  762. }
  763. }
  764. if (_fn == htmlinfo[i]->filename_org) {
  765. if (htmlinfo[i]->image_org) {
  766. _send = htmlinfo[i]->image_org;
  767. }
  768. }
  769. delete htmlinfo[i];
  770. }
  771. htmlinfo.clear();
  772. }
  773. }
  774. #ifdef DEBUG_DETAIL_ON
  775. LogFile.WriteHeapInfo("ClassFlowControll::GetJPGStream - before send");
  776. #endif
  777. if (_send) {
  778. ESP_LOGD(TAG, "Sending file: %s ...", _fn.c_str());
  779. set_content_type_from_file(req, _fn.c_str());
  780. result = _send->SendJPGtoHTTP(req);
  781. /* Respond with an empty chunk to signal HTTP response completion */
  782. httpd_resp_send_chunk(req, NULL, 0);
  783. ESP_LOGD(TAG, "File sending complete");
  784. if (_sendDelete) {
  785. delete _send;
  786. }
  787. _send = NULL;
  788. }
  789. #ifdef DEBUG_DETAIL_ON
  790. LogFile.WriteHeapInfo("ClassFlowControll::GetJPGStream - done");
  791. #endif
  792. return result;
  793. }
  794. // flowpostprocessing is NULL until InitFlow() has parsed the config, and InitFlow() resets it to NULL
  795. // whenever the flow is rebuilt; REST handlers can call these at any time.
  796. string ClassFlowControll::getNumbersName()
  797. {
  798. if (flowpostprocessing) {
  799. return flowpostprocessing->getNumbersName();
  800. }
  801. return "";
  802. }
  803. string ClassFlowControll::getJSON()
  804. {
  805. if (flowpostprocessing) {
  806. return flowpostprocessing->GetJSON();
  807. }
  808. return "";
  809. }
  810. /**
  811. * @returns a vector of all current sequences (empty while the flow is not initialized)
  812. **/
  813. const std::vector<NumberPost*> &ClassFlowControll::getNumbers()
  814. {
  815. static const std::vector<NumberPost*> noNumbers;
  816. if (flowpostprocessing) {
  817. return *flowpostprocessing->GetNumbers();
  818. }
  819. return noNumbers;
  820. }