Helper.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353
  1. // #pragma warning(disable : 4996)
  2. #include "freertos/FreeRTOS.h"
  3. #include "freertos/task.h"
  4. #include "Helper.h"
  5. #include <sys/types.h>
  6. #include <sys/stat.h>
  7. #include <iomanip>
  8. #include <sstream>
  9. #include <fstream>
  10. #include <iostream>
  11. #include <math.h>
  12. #ifdef __cplusplus
  13. extern "C"
  14. {
  15. #endif
  16. #include <dirent.h>
  17. #ifdef __cplusplus
  18. }
  19. #endif
  20. #include <string.h>
  21. #include <esp_log.h>
  22. #include <esp_mac.h>
  23. #include <esp_timer.h>
  24. #include "../../include/defines.h"
  25. #include "ClassLogFile.h"
  26. #include "esp_vfs_fat.h"
  27. #if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 4, 0))
  28. #include <esp_private/sdmmc_common.h>
  29. #else
  30. #include <../sdmmc_common.h>
  31. #endif
  32. static const char *TAG = "HELPER";
  33. using namespace std;
  34. unsigned int systemStatus = 0;
  35. sdmmc_cid_t SDCardCid;
  36. sdmmc_csd_t SDCardCsd;
  37. bool SDCardIsMMC;
  38. // #define DEBUG_DETAIL_ON
  39. /////////////////////////////////////////////////////////////////////////////////////////////
  40. string getESPHeapInfo()
  41. {
  42. string espInfoResultStr = "";
  43. char aMsgBuf[80];
  44. size_t aFreeHeapSize = heap_caps_get_free_size(MALLOC_CAP_8BIT);
  45. size_t aFreeSPIHeapSize = heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM);
  46. size_t aFreeInternalHeapSize = heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL);
  47. size_t aHeapLargestFreeBlockSize = heap_caps_get_largest_free_block(MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM);
  48. size_t aHeapIntLargestFreeBlockSize = heap_caps_get_largest_free_block(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL);
  49. size_t aMinFreeHeapSize = heap_caps_get_minimum_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM);
  50. size_t aMinFreeInternalHeapSize = heap_caps_get_minimum_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL);
  51. sprintf(aMsgBuf, "Heap Total: %ld", (long)aFreeHeapSize);
  52. espInfoResultStr += string(aMsgBuf);
  53. sprintf(aMsgBuf, " | SPI Free: %ld", (long)aFreeSPIHeapSize);
  54. espInfoResultStr += string(aMsgBuf);
  55. sprintf(aMsgBuf, " | SPI Large Block: %ld", (long)aHeapLargestFreeBlockSize);
  56. espInfoResultStr += string(aMsgBuf);
  57. sprintf(aMsgBuf, " | SPI Min Free: %ld", (long)aMinFreeHeapSize);
  58. espInfoResultStr += string(aMsgBuf);
  59. sprintf(aMsgBuf, " | Int Free: %ld", (long)(aFreeInternalHeapSize));
  60. espInfoResultStr += string(aMsgBuf);
  61. sprintf(aMsgBuf, " | Int Large Block: %ld", (long)aHeapIntLargestFreeBlockSize);
  62. espInfoResultStr += string(aMsgBuf);
  63. sprintf(aMsgBuf, " | Int Min Free: %ld", (long)(aMinFreeInternalHeapSize));
  64. espInfoResultStr += string(aMsgBuf);
  65. return espInfoResultStr;
  66. }
  67. size_t getESPHeapSize()
  68. {
  69. return heap_caps_get_free_size(MALLOC_CAP_8BIT);
  70. }
  71. string getSDCardPartitionSize()
  72. {
  73. FATFS *fs;
  74. uint32_t fre_clust, tot_sect;
  75. /* Get volume information and free clusters of drive 0 */
  76. f_getfree("0:", (DWORD *)&fre_clust, &fs);
  77. tot_sect = ((fs->n_fatent - 2) * fs->csize) / 1024 / (1024 / SDCardCsd.sector_size); // corrected by SD Card sector size (usually 512 bytes) and convert to MB
  78. // ESP_LOGD(TAG, "%d MB total drive space (Sector size [bytes]: %d)", (int)tot_sect, (int)fs->ssize);
  79. return std::to_string(tot_sect);
  80. }
  81. string getSDCardFreePartitionSpace()
  82. {
  83. FATFS *fs;
  84. uint32_t fre_clust, fre_sect;
  85. /* Get volume information and free clusters of drive 0 */
  86. f_getfree("0:", (DWORD *)&fre_clust, &fs);
  87. fre_sect = (fre_clust * fs->csize) / 1024 / (1024 / SDCardCsd.sector_size); // corrected by SD Card sector size (usually 512 bytes) and convert to MB
  88. // ESP_LOGD(TAG, "%d MB free drive space (Sector size [bytes]: %d)", (int)fre_sect, (int)fs->ssize);
  89. return std::to_string(fre_sect);
  90. }
  91. string getSDCardPartitionAllocationSize()
  92. {
  93. FATFS *fs;
  94. uint32_t fre_clust, allocation_size;
  95. /* Get volume information and free clusters of drive 0 */
  96. f_getfree("0:", (DWORD *)&fre_clust, &fs);
  97. allocation_size = fs->ssize;
  98. // ESP_LOGD(TAG, "SD Card Partition Allocation Size: %d bytes", allocation_size);
  99. return std::to_string(allocation_size);
  100. }
  101. void SaveSDCardInfo(sdmmc_card_t *card)
  102. {
  103. SDCardCid = card->cid;
  104. SDCardCsd = card->csd;
  105. SDCardIsMMC = card->is_mmc;
  106. }
  107. string getSDCardManufacturer()
  108. {
  109. string SDCardManufacturer = SDCardParseManufacturerIDs(SDCardCid.mfg_id);
  110. // ESP_LOGD(TAG, "SD Card Manufacturer: %s", SDCardManufacturer.c_str());
  111. return (SDCardManufacturer + " (ID: " + std::to_string(SDCardCid.mfg_id) + ")");
  112. }
  113. string getSDCardName()
  114. {
  115. char *SDCardName = SDCardCid.name;
  116. // ESP_LOGD(TAG, "SD Card Name: %s", SDCardName);
  117. return std::string(SDCardName);
  118. }
  119. string getSDCardCapacity()
  120. {
  121. int SDCardCapacity = SDCardCsd.capacity / (1024 / SDCardCsd.sector_size) / 1024; // total sectors * sector size --> Byte to MB (1024*1024)
  122. // ESP_LOGD(TAG, "SD Card Capacity: %s", std::to_string(SDCardCapacity).c_str());
  123. return std::to_string(SDCardCapacity);
  124. }
  125. string getSDCardSectorSize()
  126. {
  127. int SDCardSectorSize = SDCardCsd.sector_size;
  128. // ESP_LOGD(TAG, "SD Card Sector Size: %s bytes", std::to_string(SDCardSectorSize).c_str());
  129. return std::to_string(SDCardSectorSize);
  130. }
  131. ///////////////////////////////////////////////////////////////////////////////////////////////
  132. std::string FormatFileName(std::string input)
  133. {
  134. #ifdef ISWINDOWS_TRUE
  135. input.erase(0, 1);
  136. std::string os = "/";
  137. std::string ns = "\\";
  138. FindReplace(input, os, ns);
  139. #endif
  140. return input;
  141. }
  142. std::size_t file_size(const std::string &file_name)
  143. {
  144. std::ifstream file(file_name.c_str(), std::ios::in | std::ios::binary);
  145. if (!file)
  146. {
  147. return 0;
  148. }
  149. file.seekg(0, std::ios::end);
  150. return static_cast<std::size_t>(file.tellg());
  151. }
  152. void FindReplace(std::string &line, std::string &oldString, std::string &newString)
  153. {
  154. const size_t oldSize = oldString.length();
  155. // do nothing if line is shorter than the string to find
  156. if (oldSize > line.length())
  157. {
  158. return;
  159. }
  160. const size_t newSize = newString.length();
  161. for (size_t pos = 0;; pos += newSize)
  162. {
  163. // Locate the substring to replace
  164. pos = line.find(oldString, pos);
  165. if (pos == std::string::npos)
  166. {
  167. return;
  168. }
  169. if (oldSize == newSize)
  170. {
  171. // if they're same size, use std::string::replace
  172. line.replace(pos, oldSize, newString);
  173. }
  174. else
  175. {
  176. // if not same size, replace by erasing and inserting
  177. line.erase(pos, oldSize);
  178. line.insert(pos, newString);
  179. }
  180. }
  181. }
  182. /**
  183. * Create a folder and its parent folders as needed
  184. */
  185. bool MakeDir(std::string path)
  186. {
  187. std::string parent;
  188. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Creating folder " + path + "...");
  189. bool bSuccess = false;
  190. int nRC = ::mkdir(path.c_str(), 0775);
  191. if (nRC == -1)
  192. {
  193. switch (errno)
  194. {
  195. case ENOENT:
  196. // parent didn't exist, try to create it
  197. parent = path.substr(0, path.find_last_of('/'));
  198. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Need to create parent folder first: " + parent);
  199. if (MakeDir(parent))
  200. {
  201. // Now, try to create again.
  202. bSuccess = 0 == ::mkdir(path.c_str(), 0775);
  203. }
  204. else
  205. {
  206. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to create parent folder: " + parent);
  207. bSuccess = false;
  208. }
  209. break;
  210. case EEXIST:
  211. // Done!
  212. bSuccess = true;
  213. break;
  214. default:
  215. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to create folder: " + path + " (errno: " + std::to_string(errno) + ")");
  216. bSuccess = false;
  217. break;
  218. }
  219. }
  220. else
  221. {
  222. bSuccess = true;
  223. }
  224. return bSuccess;
  225. }
  226. bool ctype_space(const char c, string adddelimiter)
  227. {
  228. if (c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == 11)
  229. {
  230. return true;
  231. }
  232. if (adddelimiter.find(c) != string::npos)
  233. {
  234. return true;
  235. }
  236. return false;
  237. }
  238. string trim(string istring, string adddelimiter)
  239. {
  240. bool trimmed = false;
  241. if (ctype_space(istring[istring.length() - 1], adddelimiter))
  242. {
  243. istring.erase(istring.length() - 1);
  244. trimmed = true;
  245. }
  246. if (ctype_space(istring[0], adddelimiter))
  247. {
  248. istring.erase(0, 1);
  249. trimmed = true;
  250. }
  251. if ((trimmed == false) || (istring.size() == 0))
  252. {
  253. return istring;
  254. }
  255. else
  256. {
  257. return trim(istring, adddelimiter);
  258. }
  259. }
  260. size_t findDelimiterPos(string input, string delimiter)
  261. {
  262. size_t pos = std::string::npos;
  263. // size_t zw;
  264. string akt_del;
  265. for (int anz = 0; anz < delimiter.length(); ++anz)
  266. {
  267. akt_del = delimiter[anz];
  268. size_t zw = input.find(akt_del);
  269. if (zw != std::string::npos)
  270. {
  271. if ((pos != std::string::npos) && (zw < pos))
  272. {
  273. pos = zw;
  274. }
  275. else
  276. {
  277. pos = zw;
  278. }
  279. }
  280. }
  281. return pos;
  282. }
  283. bool RenameFile(string from, string to)
  284. {
  285. // ESP_LOGI(logTag, "Renaming File: %s", from.c_str());
  286. FILE *fpSourceFile = fopen(from.c_str(), "rb");
  287. // Sourcefile does not exist otherwise there is a mistake when renaming!
  288. if (!fpSourceFile)
  289. {
  290. ESP_LOGE(TAG, "RenameFile: File %s does not exist!", from.c_str());
  291. return false;
  292. }
  293. fclose(fpSourceFile);
  294. rename(from.c_str(), to.c_str());
  295. return true;
  296. }
  297. bool RenameFolder(string from, string to)
  298. {
  299. // ESP_LOGI(logTag, "Renaming Folder: %s", from.c_str());
  300. DIR *fpSourceFolder = opendir(from.c_str());
  301. // Sourcefolder does not exist otherwise there is a mistake when renaming!
  302. if (!fpSourceFolder)
  303. {
  304. ESP_LOGE(TAG, "RenameFolder: Folder %s does not exist!", from.c_str());
  305. return false;
  306. }
  307. closedir(fpSourceFolder);
  308. rename(from.c_str(), to.c_str());
  309. return true;
  310. }
  311. bool FileExists(string filename)
  312. {
  313. FILE *fpSourceFile = fopen(filename.c_str(), "rb");
  314. // Sourcefile does not exist
  315. if (!fpSourceFile)
  316. {
  317. return false;
  318. }
  319. fclose(fpSourceFile);
  320. return true;
  321. }
  322. bool DeleteFile(string filename)
  323. {
  324. // ESP_LOGI(logTag, "Deleting file: %s", filename.c_str());
  325. /* Delete file */
  326. FILE *fpSourceFile = fopen(filename.c_str(), "rb");
  327. // Sourcefile does not exist otherwise there is a mistake in copying!
  328. if (!fpSourceFile)
  329. {
  330. ESP_LOGD(TAG, "DeleteFile: File %s existiert nicht!", filename.c_str());
  331. return false;
  332. }
  333. fclose(fpSourceFile);
  334. unlink(filename.c_str());
  335. return true;
  336. }
  337. bool CopyFile(string input, string output)
  338. {
  339. input = FormatFileName(input);
  340. output = FormatFileName(output);
  341. if (toUpper(input).compare(WLAN_CONFIG_FILE) == 0)
  342. {
  343. ESP_LOGD(TAG, "wlan.ini kann nicht kopiert werden!");
  344. return false;
  345. }
  346. char cTemp;
  347. FILE *fpSourceFile = fopen(input.c_str(), "rb");
  348. // Sourcefile existiert nicht sonst gibt es einen Fehler beim Kopierversuch!
  349. if (!fpSourceFile)
  350. {
  351. ESP_LOGD(TAG, "File %s existiert nicht!", input.c_str());
  352. return false;
  353. }
  354. FILE *fpTargetFile = fopen(output.c_str(), "wb");
  355. // Code Section
  356. // Read From The Source File - "Copy"
  357. while (fread(&cTemp, 1, 1, fpSourceFile) == 1)
  358. {
  359. // Write To The Target File - "Paste"
  360. fwrite(&cTemp, 1, 1, fpTargetFile);
  361. }
  362. // Close The Files
  363. fclose(fpSourceFile);
  364. fclose(fpTargetFile);
  365. ESP_LOGD(TAG, "File copied: %s to %s", input.c_str(), output.c_str());
  366. return true;
  367. }
  368. string getFileFullFileName(string filename)
  369. {
  370. size_t lastpos = filename.find_last_of('/');
  371. if (lastpos == string::npos)
  372. {
  373. return "";
  374. }
  375. // ESP_LOGD(TAG, "Last position: %d", lastpos);
  376. string zw = filename.substr(lastpos + 1, filename.size() - lastpos);
  377. return zw;
  378. }
  379. string getDirectory(string filename)
  380. {
  381. size_t lastpos = filename.find('/');
  382. if (lastpos == string::npos)
  383. {
  384. lastpos = filename.find('\\');
  385. }
  386. if (lastpos == string::npos)
  387. {
  388. return "";
  389. }
  390. // ESP_LOGD(TAG, "Directory: %d", lastpos);
  391. string zw = filename.substr(0, lastpos - 1);
  392. return zw;
  393. }
  394. string getFileType(string filename)
  395. {
  396. size_t lastpos = filename.rfind(".", filename.length());
  397. size_t neu_pos;
  398. while ((neu_pos = filename.find(".", lastpos + 1)) > -1)
  399. {
  400. lastpos = neu_pos;
  401. }
  402. if (lastpos == string::npos)
  403. {
  404. return "";
  405. }
  406. string zw = filename.substr(lastpos + 1, filename.size() - lastpos);
  407. zw = toUpper(zw);
  408. return zw;
  409. }
  410. /* recursive mkdir */
  411. int mkdir_r(const char *dir, const mode_t mode)
  412. {
  413. char tmp[FILE_PATH_MAX];
  414. char *p = NULL;
  415. struct stat sb;
  416. size_t len;
  417. /* copy path */
  418. len = strnlen(dir, FILE_PATH_MAX);
  419. if (len == 0 || len == FILE_PATH_MAX)
  420. {
  421. return -1;
  422. }
  423. memcpy(tmp, dir, len);
  424. tmp[len] = '\0';
  425. /* remove trailing slash */
  426. if (tmp[len - 1] == '/')
  427. {
  428. tmp[len - 1] = '\0';
  429. }
  430. /* check if path exists and is a directory */
  431. if (stat(tmp, &sb) == 0)
  432. {
  433. if (S_ISDIR(sb.st_mode))
  434. {
  435. return 0;
  436. }
  437. }
  438. /* recursive mkdir */
  439. for (p = tmp + 1; *p; p++)
  440. {
  441. if (*p == '/')
  442. {
  443. *p = 0;
  444. /* test path */
  445. if (stat(tmp, &sb) != 0)
  446. {
  447. /* path does not exist - create directory */
  448. if (mkdir(tmp, mode) < 0)
  449. {
  450. return -1;
  451. }
  452. }
  453. else if (!S_ISDIR(sb.st_mode))
  454. {
  455. /* not a directory */
  456. return -1;
  457. }
  458. *p = '/';
  459. }
  460. }
  461. /* test path */
  462. if (stat(tmp, &sb) != 0)
  463. {
  464. /* path does not exist - create directory */
  465. if (mkdir(tmp, mode) < 0)
  466. {
  467. return -1;
  468. }
  469. }
  470. else if (!S_ISDIR(sb.st_mode))
  471. {
  472. /* not a directory */
  473. return -1;
  474. }
  475. return 0;
  476. }
  477. string toUpper(string in)
  478. {
  479. for (int i = 0; i < in.length(); ++i)
  480. {
  481. in[i] = toupper(in[i]);
  482. }
  483. return in;
  484. }
  485. string toLower(string in)
  486. {
  487. for (int i = 0; i < in.length(); ++i)
  488. {
  489. in[i] = tolower(in[i]);
  490. }
  491. return in;
  492. }
  493. // CPU Temp
  494. extern "C" uint8_t temprature_sens_read();
  495. float temperatureRead()
  496. {
  497. return (temprature_sens_read() - 32) / 1.8;
  498. }
  499. time_t addDays(time_t startTime, int days)
  500. {
  501. struct tm *tm = localtime(&startTime);
  502. tm->tm_mday += days;
  503. return mktime(tm);
  504. }
  505. int removeFolder(const char *folderPath, const char *logTag)
  506. {
  507. // ESP_LOGD(logTag, "Delete content in path %s", folderPath);
  508. DIR *dir = opendir(folderPath);
  509. if (!dir)
  510. {
  511. ESP_LOGE(logTag, "Failed to stat dir: %s", folderPath);
  512. return -1;
  513. }
  514. struct dirent *entry;
  515. int deleted = 0;
  516. while ((entry = readdir(dir)) != NULL)
  517. {
  518. std::string path = string(folderPath) + "/" + entry->d_name;
  519. if (entry->d_type == DT_REG)
  520. {
  521. // ESP_LOGD(logTag, "Delete file %s", path.c_str());
  522. if (unlink(path.c_str()) == 0)
  523. {
  524. deleted++;
  525. }
  526. else
  527. {
  528. ESP_LOGE(logTag, "can't delete file: %s", path.c_str());
  529. }
  530. }
  531. else if (entry->d_type == DT_DIR)
  532. {
  533. deleted += removeFolder(path.c_str(), logTag);
  534. }
  535. }
  536. closedir(dir);
  537. if (rmdir(folderPath) != 0)
  538. {
  539. ESP_LOGE(logTag, "can't delete folder: %s", folderPath);
  540. }
  541. ESP_LOGD(logTag, "%d files in folder %s deleted.", deleted, folderPath);
  542. return deleted;
  543. }
  544. std::vector<string> HelperZerlegeZeile(std::string input, std::string _delimiter = "")
  545. {
  546. std::vector<string> Output;
  547. std::string delimiter = " =,";
  548. if (_delimiter.length() > 0)
  549. {
  550. delimiter = _delimiter;
  551. }
  552. return ZerlegeZeile(input, delimiter);
  553. }
  554. std::vector<string> ZerlegeZeile(std::string input, std::string delimiter)
  555. {
  556. std::vector<string> Output;
  557. /* The input can have multiple formats:
  558. * - key = value
  559. * - key = value1 value2 value3 ...
  560. * - key value1 value2 value3 ...
  561. *
  562. * Examples:
  563. * - ImageSize = VGA
  564. * - IO0 = input disabled 10 false false
  565. * - main.dig1 28 144 55 100 false
  566. *
  567. * This causes issues eg. if a password key has a whitespace or equal sign in its value.
  568. * As a workaround and to not break any legacy usage, we enforce to only use the
  569. * equal sign, if the key is "password"
  570. */
  571. if ((input.find("password") != string::npos) || (input.find("Token") != string::npos))
  572. {
  573. // Line contains a password, use the equal sign as the only delimiter and only split on first occurrence
  574. size_t pos = input.find("=");
  575. Output.push_back(trim(input.substr(0, pos), ""));
  576. Output.push_back(trim(input.substr(pos + 1, string::npos), ""));
  577. }
  578. else
  579. {
  580. // Legacy Mode
  581. input = trim(input, delimiter); // sonst werden delimiter am Ende (z.B. == im Token) gelöscht)
  582. size_t pos = findDelimiterPos(input, delimiter);
  583. std::string token;
  584. while (pos != std::string::npos)
  585. {
  586. token = input.substr(0, pos);
  587. token = trim(token, delimiter);
  588. Output.push_back(token);
  589. input.erase(0, pos + 1);
  590. input = trim(input, delimiter);
  591. pos = findDelimiterPos(input, delimiter);
  592. }
  593. Output.push_back(input);
  594. }
  595. return Output;
  596. }
  597. std::string ReplaceString(std::string subject, const std::string &search, const std::string &replace)
  598. {
  599. size_t pos = 0;
  600. while ((pos = subject.find(search, pos)) != std::string::npos)
  601. {
  602. subject.replace(pos, search.length(), replace);
  603. pos += replace.length();
  604. }
  605. return subject;
  606. }
  607. /* Source: https://git.kernel.org/pub/scm/utils/mmc/mmc-utils.git/tree/lsmmc.c */
  608. /* SD Card Manufacturer Database */
  609. struct SDCard_Manufacturer_database
  610. {
  611. string type;
  612. int id;
  613. string manufacturer;
  614. };
  615. /* Source: https://git.kernel.org/pub/scm/utils/mmc/mmc-utils.git/tree/lsmmc.c */
  616. /* SD Card Manufacturer Database */
  617. struct SDCard_Manufacturer_database sd_database[] = {
  618. {
  619. .type = "sd",
  620. .id = 0x01,
  621. .manufacturer = "Panasonic",
  622. },
  623. {
  624. .type = "sd",
  625. .id = 0x02,
  626. .manufacturer = "Toshiba/Kingston/Viking",
  627. },
  628. {
  629. .type = "sd",
  630. .id = 0x03,
  631. .manufacturer = "SanDisk",
  632. },
  633. {
  634. .type = "sd",
  635. .id = 0x05,
  636. .manufacturer = "Lenovo",
  637. },
  638. {
  639. .type = "sd",
  640. .id = 0x08,
  641. .manufacturer = "Silicon Power",
  642. },
  643. {
  644. .type = "sd",
  645. .id = 0x09,
  646. .manufacturer = "ATP",
  647. },
  648. {
  649. .type = "sd",
  650. .id = 0x18,
  651. .manufacturer = "Infineon",
  652. },
  653. {
  654. .type = "sd",
  655. .id = 0x1b,
  656. .manufacturer = "Transcend/Samsung",
  657. },
  658. {
  659. .type = "sd",
  660. .id = 0x1c,
  661. .manufacturer = "Transcend",
  662. },
  663. {
  664. .type = "sd",
  665. .id = 0x1d,
  666. .manufacturer = "Corsair/AData",
  667. },
  668. {
  669. .type = "sd",
  670. .id = 0x1e,
  671. .manufacturer = "Transcend",
  672. },
  673. {
  674. .type = "sd",
  675. .id = 0x1f,
  676. .manufacturer = "Kingston",
  677. },
  678. {
  679. .type = "sd",
  680. .id = 0x27,
  681. .manufacturer = "Delkin/Phison",
  682. },
  683. {
  684. .type = "sd",
  685. .id = 0x28,
  686. .manufacturer = "Lexar",
  687. },
  688. {
  689. .type = "sd",
  690. .id = 0x30,
  691. .manufacturer = "SanDisk",
  692. },
  693. {
  694. .type = "sd",
  695. .id = 0x31,
  696. .manufacturer = "Silicon Power",
  697. },
  698. {
  699. .type = "sd",
  700. .id = 0x33,
  701. .manufacturer = "STMicroelectronics",
  702. },
  703. {
  704. .type = "sd",
  705. .id = 0x41,
  706. .manufacturer = "Kingston",
  707. },
  708. {
  709. .type = "sd",
  710. .id = 0x6f,
  711. .manufacturer = "STMicroelectronics",
  712. },
  713. {
  714. .type = "sd",
  715. .id = 0x74,
  716. .manufacturer = "Transcend",
  717. },
  718. {
  719. .type = "sd",
  720. .id = 0x76,
  721. .manufacturer = "Patriot",
  722. },
  723. {
  724. .type = "sd",
  725. .id = 0x82,
  726. .manufacturer = "Gobe/Sony",
  727. },
  728. {
  729. .type = "sd",
  730. .id = 0x89,
  731. .manufacturer = "Netac",
  732. },
  733. {
  734. .type = "sd",
  735. .id = 0x9f,
  736. .manufacturer = "Kingston/Kodak/Silicon Power",
  737. },
  738. {
  739. .type = "sd",
  740. .id = 0xad,
  741. .manufacturer = "Amazon Basics/Lexar/OV",
  742. },
  743. {
  744. .type = "sd",
  745. .id = 0xdf,
  746. .manufacturer = "Lenovo",
  747. },
  748. {
  749. .type = "sd",
  750. .id = 0xfe,
  751. .manufacturer = "Bekit/Cloudisk/HP/Reletech",
  752. },
  753. };
  754. struct SDCard_Manufacturer_database mmc_database[] = {
  755. {
  756. .type = "mmc",
  757. .id = 0x00,
  758. .manufacturer = "SanDisk",
  759. },
  760. {
  761. .type = "mmc",
  762. .id = 0x02,
  763. .manufacturer = "Kingston/SanDisk",
  764. },
  765. {
  766. .type = "mmc",
  767. .id = 0x03,
  768. .manufacturer = "Toshiba",
  769. },
  770. {
  771. .type = "mmc",
  772. .id = 0x05,
  773. .manufacturer = "Unknown",
  774. },
  775. {
  776. .type = "mmc",
  777. .id = 0x06,
  778. .manufacturer = "Unknown",
  779. },
  780. {
  781. .type = "mmc",
  782. .id = 0x11,
  783. .manufacturer = "Toshiba",
  784. },
  785. {
  786. .type = "mmc",
  787. .id = 0x13,
  788. .manufacturer = "Micron",
  789. },
  790. {
  791. .type = "mmc",
  792. .id = 0x15,
  793. .manufacturer = "Samsung/SanDisk/LG",
  794. },
  795. {
  796. .type = "mmc",
  797. .id = 0x37,
  798. .manufacturer = "KingMax",
  799. },
  800. {
  801. .type = "mmc",
  802. .id = 0x44,
  803. .manufacturer = "ATP",
  804. },
  805. {
  806. .type = "mmc",
  807. .id = 0x45,
  808. .manufacturer = "SanDisk Corporation",
  809. },
  810. {
  811. .type = "mmc",
  812. .id = 0x2c,
  813. .manufacturer = "Kingston",
  814. },
  815. {
  816. .type = "mmc",
  817. .id = 0x70,
  818. .manufacturer = "Kingston",
  819. },
  820. {
  821. .type = "mmc",
  822. .id = 0xfe,
  823. .manufacturer = "Micron",
  824. },
  825. };
  826. /* Parse SD Card Manufacturer Database */
  827. string SDCardParseManufacturerIDs(int id)
  828. {
  829. if (SDCardIsMMC)
  830. {
  831. unsigned int id_cnt = sizeof(mmc_database) / sizeof(struct SDCard_Manufacturer_database);
  832. string ret_val = "";
  833. for (int i = 0; i < id_cnt; i++)
  834. {
  835. if (mmc_database[i].id == id)
  836. {
  837. return mmc_database[i].manufacturer;
  838. }
  839. else
  840. {
  841. ret_val = "ID unknown (not in DB)";
  842. }
  843. }
  844. return ret_val;
  845. }
  846. else
  847. {
  848. unsigned int id_cnt = sizeof(sd_database) / sizeof(struct SDCard_Manufacturer_database);
  849. string ret_val = "";
  850. for (int i = 0; i < id_cnt; i++)
  851. {
  852. if (sd_database[i].id == id)
  853. {
  854. return sd_database[i].manufacturer;
  855. }
  856. else
  857. {
  858. ret_val = "ID unknown (not in DB)";
  859. }
  860. }
  861. return ret_val;
  862. }
  863. }
  864. string RundeOutput(double _in, int _anzNachkomma)
  865. {
  866. std::stringstream stream;
  867. int _zw = _in;
  868. // ESP_LOGD(TAG, "AnzNachkomma: %d", _anzNachkomma);
  869. if (_anzNachkomma > 0)
  870. {
  871. stream << std::fixed << std::setprecision(_anzNachkomma) << _in;
  872. }
  873. else
  874. {
  875. stream << _zw;
  876. }
  877. return stream.str();
  878. }
  879. void setSystemStatusFlag(SystemStatusFlag_t flag)
  880. {
  881. systemStatus = systemStatus | flag; // set bit
  882. char buf[20];
  883. snprintf(buf, sizeof(buf), "0x%08X", getSystemStatus());
  884. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "New System Status: " + std::string(buf));
  885. }
  886. void clearSystemStatusFlag(SystemStatusFlag_t flag)
  887. {
  888. systemStatus = systemStatus | ~flag; // clear bit
  889. char buf[20];
  890. snprintf(buf, sizeof(buf), "0x%08X", getSystemStatus());
  891. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "New System Status: " + std::string(buf));
  892. }
  893. int getSystemStatus(void)
  894. {
  895. return systemStatus;
  896. }
  897. bool isSetSystemStatusFlag(SystemStatusFlag_t flag)
  898. {
  899. // ESP_LOGE(TAG, "Flag (0x%08X) is set (0x%08X): %d", flag, systemStatus , ((systemStatus & flag) == flag));
  900. if ((systemStatus & flag) == flag)
  901. {
  902. return true;
  903. }
  904. else
  905. {
  906. return false;
  907. }
  908. }
  909. time_t getUpTime(void)
  910. {
  911. return (uint32_t)(esp_timer_get_time() / 1000 / 1000); // in seconds
  912. }
  913. string getResetReason(void)
  914. {
  915. std::string reasonText;
  916. switch (esp_reset_reason())
  917. {
  918. case ESP_RST_POWERON:
  919. reasonText = "Power-on event (or reset button)";
  920. break; //!< Reset due to power-on event
  921. case ESP_RST_EXT:
  922. reasonText = "External pin";
  923. break; //!< Reset by external pin (not applicable for ESP32)
  924. case ESP_RST_SW:
  925. reasonText = "Via esp_restart";
  926. break; //!< Software reset via esp_restart
  927. case ESP_RST_PANIC:
  928. reasonText = "Exception/panic";
  929. break; //!< Software reset due to exception/panic
  930. case ESP_RST_INT_WDT:
  931. reasonText = "Interrupt watchdog";
  932. break; //!< Reset (software or hardware) due to interrupt watchdog
  933. case ESP_RST_TASK_WDT:
  934. reasonText = "Task watchdog";
  935. break; //!< Reset due to task watchdog
  936. case ESP_RST_WDT:
  937. reasonText = "Other watchdogs";
  938. break; //!< Reset due to other watchdogs
  939. case ESP_RST_DEEPSLEEP:
  940. reasonText = "Exiting deep sleep mode";
  941. break; //!< Reset after exiting deep sleep mode
  942. case ESP_RST_BROWNOUT:
  943. reasonText = "Brownout";
  944. break; //!< Brownout reset (software or hardware)
  945. case ESP_RST_SDIO:
  946. reasonText = "SDIO";
  947. break; //!< Reset over SDIO
  948. case ESP_RST_UNKNOWN: //!< Reset reason can not be determined
  949. default:
  950. reasonText = "Unknown";
  951. }
  952. return reasonText;
  953. }
  954. /**
  955. * Returns the current uptime formated ad xxf xxh xxm [xxs]
  956. */
  957. std::string getFormatedUptime(bool compact)
  958. {
  959. char buf[20];
  960. #pragma GCC diagnostic ignored "-Wformat-truncation"
  961. int uptime = getUpTime(); // in seconds
  962. int days = int(floor(uptime / (3600 * 24)));
  963. int hours = int(floor((uptime - days * 3600 * 24) / (3600)));
  964. int minutes = int(floor((uptime - days * 3600 * 24 - hours * 3600) / (60)));
  965. int seconds = uptime - days * 3600 * 24 - hours * 3600 - minutes * 60;
  966. if (compact)
  967. {
  968. snprintf(buf, sizeof(buf), "%dd%02dh%02dm%02ds", days, hours, minutes, seconds);
  969. }
  970. else
  971. {
  972. snprintf(buf, sizeof(buf), "%3dd %02dh %02dm %02ds", days, hours, minutes, seconds);
  973. }
  974. return std::string(buf);
  975. }
  976. const char *get404(void)
  977. {
  978. return "<pre>\n\n\n\n"
  979. " _\n"
  980. " .__(.)< ( oh oh! This page does not exist! )\n"
  981. " \\___)\n"
  982. "\n\n"
  983. " You could try your <a href=index.html target=_parent>luck</a> here!</pre>\n"
  984. "<script>document.cookie = \"page=overview.html\"</script>"; // Make sure we load the overview page
  985. }
  986. std::string UrlDecode(const std::string &value)
  987. {
  988. std::string result;
  989. result.reserve(value.size());
  990. for (std::size_t i = 0; i < value.size(); ++i)
  991. {
  992. auto ch = value[i];
  993. if (ch == '%' && (i + 2) < value.size())
  994. {
  995. auto hex = value.substr(i + 1, 2);
  996. auto dec = static_cast<char>(std::strtol(hex.c_str(), nullptr, 16));
  997. result.push_back(dec);
  998. i += 2;
  999. }
  1000. else if (ch == '+')
  1001. {
  1002. result.push_back(' ');
  1003. }
  1004. else
  1005. {
  1006. result.push_back(ch);
  1007. }
  1008. }
  1009. return result;
  1010. }
  1011. bool replaceString(std::string &s, std::string const &toReplace, std::string const &replaceWith)
  1012. {
  1013. return replaceString(s, toReplace, replaceWith, true);
  1014. }
  1015. bool replaceString(std::string &s, std::string const &toReplace, std::string const &replaceWith, bool logIt)
  1016. {
  1017. std::size_t pos = s.find(toReplace);
  1018. if (pos == std::string::npos)
  1019. {
  1020. // Not found
  1021. return false;
  1022. }
  1023. std::string old = s;
  1024. s.replace(pos, toReplace.length(), replaceWith);
  1025. if (logIt)
  1026. {
  1027. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Migrated Configfile line '" + old + "' to '" + s + "'");
  1028. }
  1029. return true;
  1030. }
  1031. bool isInString(std::string &s, std::string const &toFind)
  1032. {
  1033. std::size_t pos = s.find(toFind);
  1034. if (pos == std::string::npos)
  1035. {
  1036. // Not found
  1037. return false;
  1038. }
  1039. return true;
  1040. }
  1041. // from https://stackoverflow.com/a/14678800
  1042. void replaceAll(std::string& s, const std::string& toReplace, const std::string& replaceWith)
  1043. {
  1044. size_t pos = 0;
  1045. while ((pos = s.find(toReplace, pos)) != std::string::npos)
  1046. {
  1047. s.replace(pos, toReplace.length(), replaceWith);
  1048. pos += replaceWith.length();
  1049. }
  1050. }
  1051. bool isStringNumeric(std::string &input)
  1052. {
  1053. if (input.size() <= 0)
  1054. {
  1055. return false;
  1056. }
  1057. // Replace comma with a dot
  1058. replaceString(input, ",", ".", false);
  1059. int start = 0;
  1060. int punkt_existiert_schon = 0;
  1061. if (input[0] == '-')
  1062. {
  1063. start = 1;
  1064. }
  1065. for (int i = start; i < input.size(); i++)
  1066. {
  1067. if ((input[i] == '.') && (i > 0) && (punkt_existiert_schon == 0))
  1068. {
  1069. punkt_existiert_schon = 1;
  1070. i++;
  1071. }
  1072. else if (!isdigit(input[i]))
  1073. {
  1074. return false;
  1075. }
  1076. }
  1077. return true;
  1078. }
  1079. bool isStringAlphabetic(std::string &input)
  1080. {
  1081. for (int i = 0; i < input.size(); i++)
  1082. {
  1083. if (!isalpha(input[i]))
  1084. {
  1085. return false;
  1086. }
  1087. }
  1088. return true;
  1089. }
  1090. bool isStringAlphanumeric(std::string &input)
  1091. {
  1092. for (int i = 0; i < input.size(); i++)
  1093. {
  1094. if (!isalnum(input[i]))
  1095. {
  1096. return false;
  1097. }
  1098. }
  1099. return true;
  1100. }
  1101. bool alphanumericToBoolean(std::string &input)
  1102. {
  1103. if (isStringAlphabetic(input))
  1104. {
  1105. return stringToBoolean(toUpper(input));
  1106. }
  1107. else if (isStringNumeric(input))
  1108. {
  1109. return numericStrToBool(input);
  1110. }
  1111. return false;
  1112. }
  1113. int clipInt(int input, int high, int low)
  1114. {
  1115. if (input < low)
  1116. {
  1117. input = low;
  1118. }
  1119. else if (input > high)
  1120. {
  1121. input = high;
  1122. }
  1123. return input;
  1124. }
  1125. bool numericStrToBool(std::string input)
  1126. {
  1127. return (std::stoi(input) != 0);
  1128. }
  1129. bool stringToBoolean(std::string input)
  1130. {
  1131. return (input == "TRUE");
  1132. }