Helper.cpp 28 KB

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