Helper.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377
  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, "Renaming File: %s", from.c_str());
  293. FILE *fpSourceFile = fopen(from.c_str(), "rb");
  294. // Sourcefile does not exist otherwise there is a mistake when renaming!
  295. if (!fpSourceFile)
  296. {
  297. ESP_LOGE(TAG, "RenameFile: File %s does not exist!", from.c_str());
  298. return false;
  299. }
  300. fclose(fpSourceFile);
  301. rename(from.c_str(), to.c_str());
  302. return true;
  303. }
  304. bool RenameFolder(string from, string to)
  305. {
  306. // ESP_LOGI(logTag, "Renaming Folder: %s", from.c_str());
  307. DIR *fpSourceFolder = opendir(from.c_str());
  308. // Sourcefolder does not exist otherwise there is a mistake when renaming!
  309. if (!fpSourceFolder)
  310. {
  311. ESP_LOGE(TAG, "RenameFolder: Folder %s does not exist!", from.c_str());
  312. return false;
  313. }
  314. closedir(fpSourceFolder);
  315. rename(from.c_str(), to.c_str());
  316. return true;
  317. }
  318. bool FileExists(string filename)
  319. {
  320. FILE *fpSourceFile = fopen(filename.c_str(), "rb");
  321. // Sourcefile does not exist
  322. if (!fpSourceFile)
  323. {
  324. return false;
  325. }
  326. fclose(fpSourceFile);
  327. return true;
  328. }
  329. bool FolderExists(string foldername)
  330. {
  331. DIR *fpSourceFolder = opendir(foldername.c_str());
  332. // Sourcefolder does not exist
  333. if (!fpSourceFolder)
  334. {
  335. return false;
  336. }
  337. closedir(fpSourceFolder);
  338. return true;
  339. }
  340. bool DeleteFile(string filename)
  341. {
  342. // ESP_LOGI(logTag, "Deleting file: %s", filename.c_str());
  343. /* Delete file */
  344. FILE *fpSourceFile = fopen(filename.c_str(), "rb");
  345. // Sourcefile does not exist otherwise there is a mistake in copying!
  346. if (!fpSourceFile)
  347. {
  348. ESP_LOGD(TAG, "DeleteFile: File %s existiert nicht!", filename.c_str());
  349. return false;
  350. }
  351. fclose(fpSourceFile);
  352. unlink(filename.c_str());
  353. return true;
  354. }
  355. bool CopyFile(string input, string output)
  356. {
  357. input = FormatFileName(input);
  358. output = FormatFileName(output);
  359. if (toUpper(input).compare(WLAN_CONFIG_FILE) == 0)
  360. {
  361. ESP_LOGD(TAG, "wlan.ini kann nicht kopiert werden!");
  362. return false;
  363. }
  364. char cTemp;
  365. FILE *fpSourceFile = fopen(input.c_str(), "rb");
  366. // Sourcefile existiert nicht sonst gibt es einen Fehler beim Kopierversuch!
  367. if (!fpSourceFile)
  368. {
  369. ESP_LOGD(TAG, "File %s existiert nicht!", input.c_str());
  370. return false;
  371. }
  372. FILE *fpTargetFile = fopen(output.c_str(), "wb");
  373. // Code Section
  374. // Read From The Source File - "Copy"
  375. while (fread(&cTemp, 1, 1, fpSourceFile) == 1)
  376. {
  377. // Write To The Target File - "Paste"
  378. fwrite(&cTemp, 1, 1, fpTargetFile);
  379. }
  380. // Close The Files
  381. fclose(fpSourceFile);
  382. fclose(fpTargetFile);
  383. ESP_LOGD(TAG, "File copied: %s to %s", input.c_str(), output.c_str());
  384. return true;
  385. }
  386. string getFileFullFileName(string filename)
  387. {
  388. size_t lastpos = filename.find_last_of('/');
  389. if (lastpos == string::npos)
  390. {
  391. return "";
  392. }
  393. // ESP_LOGD(TAG, "Last position: %d", lastpos);
  394. string zw = filename.substr(lastpos + 1, filename.size() - lastpos);
  395. return zw;
  396. }
  397. string getDirectory(string filename)
  398. {
  399. size_t lastpos = filename.find('/');
  400. if (lastpos == string::npos)
  401. {
  402. lastpos = filename.find('\\');
  403. }
  404. if (lastpos == string::npos)
  405. {
  406. return "";
  407. }
  408. // ESP_LOGD(TAG, "Directory: %d", lastpos);
  409. string zw = filename.substr(0, lastpos - 1);
  410. return zw;
  411. }
  412. string getFileType(string filename)
  413. {
  414. size_t lastpos = filename.rfind(".", filename.length());
  415. size_t neu_pos;
  416. while ((neu_pos = filename.find(".", lastpos + 1)) > -1)
  417. {
  418. lastpos = neu_pos;
  419. }
  420. if (lastpos == string::npos)
  421. {
  422. return "";
  423. }
  424. string zw = filename.substr(lastpos + 1, filename.size() - lastpos);
  425. zw = toUpper(zw);
  426. return zw;
  427. }
  428. /* recursive mkdir */
  429. int mkdir_r(const char *dir, const mode_t mode)
  430. {
  431. char tmp[FILE_PATH_MAX];
  432. char *p = NULL;
  433. struct stat sb;
  434. size_t len;
  435. /* copy path */
  436. len = strnlen(dir, FILE_PATH_MAX);
  437. if (len == 0 || len == FILE_PATH_MAX)
  438. {
  439. return -1;
  440. }
  441. memcpy(tmp, dir, len);
  442. tmp[len] = '\0';
  443. /* remove trailing slash */
  444. if (tmp[len - 1] == '/')
  445. {
  446. tmp[len - 1] = '\0';
  447. }
  448. /* check if path exists and is a directory */
  449. if (stat(tmp, &sb) == 0)
  450. {
  451. if (S_ISDIR(sb.st_mode))
  452. {
  453. return 0;
  454. }
  455. }
  456. /* recursive mkdir */
  457. for (p = tmp + 1; *p; p++)
  458. {
  459. if (*p == '/')
  460. {
  461. *p = 0;
  462. /* test path */
  463. if (stat(tmp, &sb) != 0)
  464. {
  465. /* path does not exist - create directory */
  466. if (mkdir(tmp, mode) < 0)
  467. {
  468. return -1;
  469. }
  470. }
  471. else if (!S_ISDIR(sb.st_mode))
  472. {
  473. /* not a directory */
  474. return -1;
  475. }
  476. *p = '/';
  477. }
  478. }
  479. /* test path */
  480. if (stat(tmp, &sb) != 0)
  481. {
  482. /* path does not exist - create directory */
  483. if (mkdir(tmp, mode) < 0)
  484. {
  485. return -1;
  486. }
  487. }
  488. else if (!S_ISDIR(sb.st_mode))
  489. {
  490. /* not a directory */
  491. return -1;
  492. }
  493. return 0;
  494. }
  495. string toUpper(string in)
  496. {
  497. for (int i = 0; i < in.length(); ++i)
  498. {
  499. in[i] = toupper(in[i]);
  500. }
  501. return in;
  502. }
  503. string toLower(string in)
  504. {
  505. for (int i = 0; i < in.length(); ++i)
  506. {
  507. in[i] = tolower(in[i]);
  508. }
  509. return in;
  510. }
  511. // CPU Temp
  512. extern "C" uint8_t temprature_sens_read();
  513. float temperatureRead()
  514. {
  515. return (temprature_sens_read() - 32) / 1.8;
  516. }
  517. time_t addDays(time_t startTime, int days)
  518. {
  519. struct tm *tm = localtime(&startTime);
  520. tm->tm_mday += days;
  521. return mktime(tm);
  522. }
  523. int removeFolder(const char *folderPath, const char *logTag)
  524. {
  525. // ESP_LOGD(logTag, "Delete content in path %s", folderPath);
  526. DIR *dir = opendir(folderPath);
  527. if (!dir)
  528. {
  529. ESP_LOGE(logTag, "Failed to stat dir: %s", folderPath);
  530. return -1;
  531. }
  532. struct dirent *entry;
  533. int deleted = 0;
  534. while ((entry = readdir(dir)) != NULL)
  535. {
  536. std::string path = string(folderPath) + "/" + entry->d_name;
  537. if (entry->d_type == DT_REG)
  538. {
  539. // ESP_LOGD(logTag, "Delete file %s", path.c_str());
  540. if (unlink(path.c_str()) == 0)
  541. {
  542. deleted++;
  543. }
  544. else
  545. {
  546. ESP_LOGE(logTag, "can't delete file: %s", path.c_str());
  547. }
  548. }
  549. else if (entry->d_type == DT_DIR)
  550. {
  551. deleted += removeFolder(path.c_str(), logTag);
  552. }
  553. }
  554. closedir(dir);
  555. if (rmdir(folderPath) != 0)
  556. {
  557. ESP_LOGE(logTag, "can't delete folder: %s", folderPath);
  558. }
  559. ESP_LOGD(logTag, "%d files in folder %s deleted.", deleted, folderPath);
  560. return deleted;
  561. }
  562. std::vector<string> HelperZerlegeZeile(std::string input, std::string _delimiter = "")
  563. {
  564. std::vector<string> Output;
  565. std::string delimiter = " =,";
  566. if (_delimiter.length() > 0)
  567. {
  568. delimiter = _delimiter;
  569. }
  570. return ZerlegeZeile(input, delimiter);
  571. }
  572. std::vector<string> ZerlegeZeile(std::string input, std::string delimiter)
  573. {
  574. std::vector<string> Output;
  575. /* The input can have multiple formats:
  576. * - key = value
  577. * - key = value1 value2 value3 ...
  578. * - key value1 value2 value3 ...
  579. *
  580. * Examples:
  581. * - ImageSize = VGA
  582. * - IO0 = input disabled 10 false false
  583. * - main.dig1 28 144 55 100 false
  584. *
  585. * This causes issues eg. if a password key has a whitespace or equal sign in its value.
  586. * As a workaround and to not break any legacy usage, we enforce to only use the
  587. * equal sign, if the key is "password"
  588. */
  589. if ((input.find("password") != string::npos) || (input.find("Token") != string::npos))
  590. {
  591. // Line contains a password, use the equal sign as the only delimiter and only split on first occurrence
  592. size_t pos = input.find("=");
  593. Output.push_back(trim(input.substr(0, pos), ""));
  594. Output.push_back(trim(input.substr(pos + 1, string::npos), ""));
  595. }
  596. else
  597. {
  598. // Legacy Mode
  599. input = trim(input, delimiter); // sonst werden delimiter am Ende (z.B. == im Token) gelöscht)
  600. size_t pos = findDelimiterPos(input, delimiter);
  601. std::string token;
  602. while (pos != std::string::npos)
  603. {
  604. token = input.substr(0, pos);
  605. token = trim(token, delimiter);
  606. Output.push_back(token);
  607. input.erase(0, pos + 1);
  608. input = trim(input, delimiter);
  609. pos = findDelimiterPos(input, delimiter);
  610. }
  611. Output.push_back(input);
  612. }
  613. return Output;
  614. }
  615. std::string ReplaceString(std::string subject, const std::string &search, const std::string &replace)
  616. {
  617. size_t pos = 0;
  618. while ((pos = subject.find(search, pos)) != std::string::npos)
  619. {
  620. subject.replace(pos, search.length(), replace);
  621. pos += replace.length();
  622. }
  623. return subject;
  624. }
  625. /* Source: https://git.kernel.org/pub/scm/utils/mmc/mmc-utils.git/tree/lsmmc.c */
  626. /* SD Card Manufacturer Database */
  627. struct SDCard_Manufacturer_database
  628. {
  629. string type;
  630. int id;
  631. string manufacturer;
  632. };
  633. /* Source: https://git.kernel.org/pub/scm/utils/mmc/mmc-utils.git/tree/lsmmc.c */
  634. /* SD Card Manufacturer Database */
  635. struct SDCard_Manufacturer_database sd_database[] = {
  636. {
  637. .type = "sd",
  638. .id = 0x01,
  639. .manufacturer = "Panasonic",
  640. },
  641. {
  642. .type = "sd",
  643. .id = 0x02,
  644. .manufacturer = "Toshiba/Kingston/Viking",
  645. },
  646. {
  647. .type = "sd",
  648. .id = 0x03,
  649. .manufacturer = "SanDisk",
  650. },
  651. {
  652. .type = "sd",
  653. .id = 0x05,
  654. .manufacturer = "Lenovo",
  655. },
  656. {
  657. .type = "sd",
  658. .id = 0x08,
  659. .manufacturer = "Silicon Power",
  660. },
  661. {
  662. .type = "sd",
  663. .id = 0x09,
  664. .manufacturer = "ATP",
  665. },
  666. {
  667. .type = "sd",
  668. .id = 0x18,
  669. .manufacturer = "Infineon",
  670. },
  671. {
  672. .type = "sd",
  673. .id = 0x1b,
  674. .manufacturer = "Transcend/Samsung",
  675. },
  676. {
  677. .type = "sd",
  678. .id = 0x1c,
  679. .manufacturer = "Transcend",
  680. },
  681. {
  682. .type = "sd",
  683. .id = 0x1d,
  684. .manufacturer = "Corsair/AData",
  685. },
  686. {
  687. .type = "sd",
  688. .id = 0x1e,
  689. .manufacturer = "Transcend",
  690. },
  691. {
  692. .type = "sd",
  693. .id = 0x1f,
  694. .manufacturer = "Kingston",
  695. },
  696. {
  697. .type = "sd",
  698. .id = 0x27,
  699. .manufacturer = "Delkin/Phison",
  700. },
  701. {
  702. .type = "sd",
  703. .id = 0x28,
  704. .manufacturer = "Lexar",
  705. },
  706. {
  707. .type = "sd",
  708. .id = 0x30,
  709. .manufacturer = "SanDisk",
  710. },
  711. {
  712. .type = "sd",
  713. .id = 0x31,
  714. .manufacturer = "Silicon Power",
  715. },
  716. {
  717. .type = "sd",
  718. .id = 0x33,
  719. .manufacturer = "STMicroelectronics",
  720. },
  721. {
  722. .type = "sd",
  723. .id = 0x41,
  724. .manufacturer = "Kingston",
  725. },
  726. {
  727. .type = "sd",
  728. .id = 0x6f,
  729. .manufacturer = "STMicroelectronics",
  730. },
  731. {
  732. .type = "sd",
  733. .id = 0x74,
  734. .manufacturer = "Transcend",
  735. },
  736. {
  737. .type = "sd",
  738. .id = 0x76,
  739. .manufacturer = "Patriot",
  740. },
  741. {
  742. .type = "sd",
  743. .id = 0x82,
  744. .manufacturer = "Gobe/Sony",
  745. },
  746. {
  747. .type = "sd",
  748. .id = 0x89,
  749. .manufacturer = "Netac",
  750. },
  751. {
  752. .type = "sd",
  753. .id = 0x9f,
  754. .manufacturer = "Kingston/Kodak/Silicon Power",
  755. },
  756. {
  757. .type = "sd",
  758. .id = 0xad,
  759. .manufacturer = "Amazon Basics/Lexar/OV",
  760. },
  761. {
  762. .type = "sd",
  763. .id = 0xdf,
  764. .manufacturer = "Lenovo",
  765. },
  766. {
  767. .type = "sd",
  768. .id = 0xfe,
  769. .manufacturer = "Bekit/Cloudisk/HP/Reletech",
  770. },
  771. };
  772. struct SDCard_Manufacturer_database mmc_database[] = {
  773. {
  774. .type = "mmc",
  775. .id = 0x00,
  776. .manufacturer = "SanDisk",
  777. },
  778. {
  779. .type = "mmc",
  780. .id = 0x02,
  781. .manufacturer = "Kingston/SanDisk",
  782. },
  783. {
  784. .type = "mmc",
  785. .id = 0x03,
  786. .manufacturer = "Toshiba",
  787. },
  788. {
  789. .type = "mmc",
  790. .id = 0x05,
  791. .manufacturer = "Unknown",
  792. },
  793. {
  794. .type = "mmc",
  795. .id = 0x06,
  796. .manufacturer = "Unknown",
  797. },
  798. {
  799. .type = "mmc",
  800. .id = 0x11,
  801. .manufacturer = "Toshiba",
  802. },
  803. {
  804. .type = "mmc",
  805. .id = 0x13,
  806. .manufacturer = "Micron",
  807. },
  808. {
  809. .type = "mmc",
  810. .id = 0x15,
  811. .manufacturer = "Samsung/SanDisk/LG",
  812. },
  813. {
  814. .type = "mmc",
  815. .id = 0x37,
  816. .manufacturer = "KingMax",
  817. },
  818. {
  819. .type = "mmc",
  820. .id = 0x44,
  821. .manufacturer = "ATP",
  822. },
  823. {
  824. .type = "mmc",
  825. .id = 0x45,
  826. .manufacturer = "SanDisk Corporation",
  827. },
  828. {
  829. .type = "mmc",
  830. .id = 0x2c,
  831. .manufacturer = "Kingston",
  832. },
  833. {
  834. .type = "mmc",
  835. .id = 0x70,
  836. .manufacturer = "Kingston",
  837. },
  838. {
  839. .type = "mmc",
  840. .id = 0xfe,
  841. .manufacturer = "Micron",
  842. },
  843. };
  844. /* Parse SD Card Manufacturer Database */
  845. string SDCardParseManufacturerIDs(int id)
  846. {
  847. if (SDCardIsMMC)
  848. {
  849. unsigned int id_cnt = sizeof(mmc_database) / sizeof(struct SDCard_Manufacturer_database);
  850. string ret_val = "";
  851. for (int i = 0; i < id_cnt; i++)
  852. {
  853. if (mmc_database[i].id == id)
  854. {
  855. return mmc_database[i].manufacturer;
  856. }
  857. else
  858. {
  859. ret_val = "ID unknown (not in DB)";
  860. }
  861. }
  862. return ret_val;
  863. }
  864. else
  865. {
  866. unsigned int id_cnt = sizeof(sd_database) / sizeof(struct SDCard_Manufacturer_database);
  867. string ret_val = "";
  868. for (int i = 0; i < id_cnt; i++)
  869. {
  870. if (sd_database[i].id == id)
  871. {
  872. return sd_database[i].manufacturer;
  873. }
  874. else
  875. {
  876. ret_val = "ID unknown (not in DB)";
  877. }
  878. }
  879. return ret_val;
  880. }
  881. }
  882. string RundeOutput(double _in, int _anzNachkomma)
  883. {
  884. std::stringstream stream;
  885. int _zw = _in;
  886. // ESP_LOGD(TAG, "AnzNachkomma: %d", _anzNachkomma);
  887. if (_anzNachkomma > 0)
  888. {
  889. stream << std::fixed << std::setprecision(_anzNachkomma) << _in;
  890. }
  891. else
  892. {
  893. stream << _zw;
  894. }
  895. return stream.str();
  896. }
  897. string getMac(void)
  898. {
  899. uint8_t macInt[6];
  900. char macFormated[6 * 2 + 5 + 1]; // AA:BB:CC:DD:EE:FF
  901. esp_read_mac(macInt, ESP_MAC_WIFI_STA);
  902. sprintf(macFormated, "%02X:%02X:%02X:%02X:%02X:%02X", macInt[0], macInt[1], macInt[2], macInt[3], macInt[4], macInt[5]);
  903. return macFormated;
  904. }
  905. void setSystemStatusFlag(SystemStatusFlag_t flag)
  906. {
  907. systemStatus = systemStatus | flag; // set bit
  908. char buf[20];
  909. snprintf(buf, sizeof(buf), "0x%08X", getSystemStatus());
  910. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "New System Status: " + std::string(buf));
  911. }
  912. void clearSystemStatusFlag(SystemStatusFlag_t flag)
  913. {
  914. systemStatus = systemStatus | ~flag; // clear bit
  915. char buf[20];
  916. snprintf(buf, sizeof(buf), "0x%08X", getSystemStatus());
  917. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "New System Status: " + std::string(buf));
  918. }
  919. int getSystemStatus(void)
  920. {
  921. return systemStatus;
  922. }
  923. bool isSetSystemStatusFlag(SystemStatusFlag_t flag)
  924. {
  925. // ESP_LOGE(TAG, "Flag (0x%08X) is set (0x%08X): %d", flag, systemStatus , ((systemStatus & flag) == flag));
  926. if ((systemStatus & flag) == flag)
  927. {
  928. return true;
  929. }
  930. else
  931. {
  932. return false;
  933. }
  934. }
  935. time_t getUpTime(void)
  936. {
  937. return (uint32_t)(esp_timer_get_time() / 1000 / 1000); // in seconds
  938. }
  939. string getResetReason(void)
  940. {
  941. std::string reasonText;
  942. switch (esp_reset_reason())
  943. {
  944. case ESP_RST_POWERON:
  945. reasonText = "Power-on event (or reset button)";
  946. break; //!< Reset due to power-on event
  947. case ESP_RST_EXT:
  948. reasonText = "External pin";
  949. break; //!< Reset by external pin (not applicable for ESP32)
  950. case ESP_RST_SW:
  951. reasonText = "Via esp_restart";
  952. break; //!< Software reset via esp_restart
  953. case ESP_RST_PANIC:
  954. reasonText = "Exception/panic";
  955. break; //!< Software reset due to exception/panic
  956. case ESP_RST_INT_WDT:
  957. reasonText = "Interrupt watchdog";
  958. break; //!< Reset (software or hardware) due to interrupt watchdog
  959. case ESP_RST_TASK_WDT:
  960. reasonText = "Task watchdog";
  961. break; //!< Reset due to task watchdog
  962. case ESP_RST_WDT:
  963. reasonText = "Other watchdogs";
  964. break; //!< Reset due to other watchdogs
  965. case ESP_RST_DEEPSLEEP:
  966. reasonText = "Exiting deep sleep mode";
  967. break; //!< Reset after exiting deep sleep mode
  968. case ESP_RST_BROWNOUT:
  969. reasonText = "Brownout";
  970. break; //!< Brownout reset (software or hardware)
  971. case ESP_RST_SDIO:
  972. reasonText = "SDIO";
  973. break; //!< Reset over SDIO
  974. case ESP_RST_UNKNOWN: //!< Reset reason can not be determined
  975. default:
  976. reasonText = "Unknown";
  977. }
  978. return reasonText;
  979. }
  980. /**
  981. * Returns the current uptime formated ad xxf xxh xxm [xxs]
  982. */
  983. std::string getFormatedUptime(bool compact)
  984. {
  985. char buf[20];
  986. #pragma GCC diagnostic ignored "-Wformat-truncation"
  987. int uptime = getUpTime(); // in seconds
  988. int days = int(floor(uptime / (3600 * 24)));
  989. int hours = int(floor((uptime - days * 3600 * 24) / (3600)));
  990. int minutes = int(floor((uptime - days * 3600 * 24 - hours * 3600) / (60)));
  991. int seconds = uptime - days * 3600 * 24 - hours * 3600 - minutes * 60;
  992. if (compact)
  993. {
  994. snprintf(buf, sizeof(buf), "%dd%02dh%02dm%02ds", days, hours, minutes, seconds);
  995. }
  996. else
  997. {
  998. snprintf(buf, sizeof(buf), "%3dd %02dh %02dm %02ds", days, hours, minutes, seconds);
  999. }
  1000. return std::string(buf);
  1001. }
  1002. const char *get404(void)
  1003. {
  1004. return "<pre>\n\n\n\n"
  1005. " _\n"
  1006. " .__(.)< ( oh oh! This page does not exist! )\n"
  1007. " \\___)\n"
  1008. "\n\n"
  1009. " You could try your <a href=index.html target=_parent>luck</a> here!</pre>\n"
  1010. "<script>document.cookie = \"page=overview.html\"</script>"; // Make sure we load the overview page
  1011. }
  1012. std::string UrlDecode(const std::string &value)
  1013. {
  1014. std::string result;
  1015. result.reserve(value.size());
  1016. for (std::size_t i = 0; i < value.size(); ++i)
  1017. {
  1018. auto ch = value[i];
  1019. if (ch == '%' && (i + 2) < value.size())
  1020. {
  1021. auto hex = value.substr(i + 1, 2);
  1022. auto dec = static_cast<char>(std::strtol(hex.c_str(), nullptr, 16));
  1023. result.push_back(dec);
  1024. i += 2;
  1025. }
  1026. else if (ch == '+')
  1027. {
  1028. result.push_back(' ');
  1029. }
  1030. else
  1031. {
  1032. result.push_back(ch);
  1033. }
  1034. }
  1035. return result;
  1036. }
  1037. bool replaceString(std::string &s, std::string const &toReplace, std::string const &replaceWith)
  1038. {
  1039. return replaceString(s, toReplace, replaceWith, true);
  1040. }
  1041. bool replaceString(std::string &s, std::string const &toReplace, std::string const &replaceWith, bool logIt)
  1042. {
  1043. std::size_t pos = s.find(toReplace);
  1044. if (pos == std::string::npos)
  1045. {
  1046. // Not found
  1047. return false;
  1048. }
  1049. std::string old = s;
  1050. s.replace(pos, toReplace.length(), replaceWith);
  1051. if (logIt)
  1052. {
  1053. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Migrated Configfile line '" + old + "' to '" + s + "'");
  1054. }
  1055. return true;
  1056. }
  1057. bool isInString(std::string &s, std::string const &toFind)
  1058. {
  1059. std::size_t pos = s.find(toFind);
  1060. if (pos == std::string::npos)
  1061. {
  1062. // Not found
  1063. return false;
  1064. }
  1065. return true;
  1066. }
  1067. // from https://stackoverflow.com/a/14678800
  1068. void replaceAll(std::string& s, const std::string& toReplace, const std::string& replaceWith)
  1069. {
  1070. size_t pos = 0;
  1071. while ((pos = s.find(toReplace, pos)) != std::string::npos)
  1072. {
  1073. s.replace(pos, toReplace.length(), replaceWith);
  1074. pos += replaceWith.length();
  1075. }
  1076. }
  1077. bool isStringNumeric(std::string &input)
  1078. {
  1079. if (input.size() <= 0)
  1080. {
  1081. return false;
  1082. }
  1083. // Replace comma with a dot
  1084. replaceString(input, ",", ".", false);
  1085. int start = 0;
  1086. int punkt_existiert_schon = 0;
  1087. if (input[0] == '-')
  1088. {
  1089. start = 1;
  1090. }
  1091. for (int i = start; i < input.size(); i++)
  1092. {
  1093. if ((input[i] == '.') && (i > 0) && (punkt_existiert_schon == 0))
  1094. {
  1095. punkt_existiert_schon = 1;
  1096. i++;
  1097. }
  1098. else if (!isdigit(input[i]))
  1099. {
  1100. return false;
  1101. }
  1102. }
  1103. return true;
  1104. }
  1105. bool isStringAlphabetic(std::string &input)
  1106. {
  1107. for (int i = 0; i < input.size(); i++)
  1108. {
  1109. if (!isalpha(input[i]))
  1110. {
  1111. return false;
  1112. }
  1113. }
  1114. return true;
  1115. }
  1116. bool isStringAlphanumeric(std::string &input)
  1117. {
  1118. for (int i = 0; i < input.size(); i++)
  1119. {
  1120. if (!isalnum(input[i]))
  1121. {
  1122. return false;
  1123. }
  1124. }
  1125. return true;
  1126. }
  1127. bool alphanumericToBoolean(std::string &input)
  1128. {
  1129. if (isStringAlphabetic(input))
  1130. {
  1131. return stringToBoolean(toUpper(input));
  1132. }
  1133. else if (isStringNumeric(input))
  1134. {
  1135. return numericStrToBool(input);
  1136. }
  1137. return false;
  1138. }
  1139. int clipInt(int input, int high, int low)
  1140. {
  1141. if (input < low)
  1142. {
  1143. input = low;
  1144. }
  1145. else if (input > high)
  1146. {
  1147. input = high;
  1148. }
  1149. return input;
  1150. }
  1151. bool numericStrToBool(std::string input)
  1152. {
  1153. return (std::stoi(input) != 0);
  1154. }
  1155. bool stringToBoolean(std::string input)
  1156. {
  1157. return (input == "TRUE");
  1158. }