Helper.cpp 24 KB

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