Helper.cpp 26 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355
  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. #if defined(BOARD_ESP32_S3_ALEKSEI) // ESP32s3 hat die Funktion nicht
  513. float temperatureRead()
  514. {
  515. return 0.0;
  516. }
  517. #elif
  518. extern "C" uint8_t temprature_sens_read();
  519. float temperatureRead()
  520. {
  521. return (temprature_sens_read() - 32) / 1.8;
  522. }
  523. #endif
  524. time_t addDays(time_t startTime, int days)
  525. {
  526. struct tm *tm = localtime(&startTime);
  527. tm->tm_mday += days;
  528. return mktime(tm);
  529. }
  530. int removeFolder(const char *folderPath, const char *logTag)
  531. {
  532. // ESP_LOGD(logTag, "Delete content in path %s", folderPath);
  533. DIR *dir = opendir(folderPath);
  534. if (!dir)
  535. {
  536. ESP_LOGE(logTag, "Failed to stat dir: %s", folderPath);
  537. return -1;
  538. }
  539. struct dirent *entry;
  540. int deleted = 0;
  541. while ((entry = readdir(dir)) != NULL)
  542. {
  543. std::string path = string(folderPath) + "/" + entry->d_name;
  544. if (entry->d_type == DT_REG)
  545. {
  546. // ESP_LOGD(logTag, "Delete file %s", path.c_str());
  547. if (unlink(path.c_str()) == 0)
  548. {
  549. deleted++;
  550. }
  551. else
  552. {
  553. ESP_LOGE(logTag, "can't delete file: %s", path.c_str());
  554. }
  555. }
  556. else if (entry->d_type == DT_DIR)
  557. {
  558. deleted += removeFolder(path.c_str(), logTag);
  559. }
  560. }
  561. closedir(dir);
  562. if (rmdir(folderPath) != 0)
  563. {
  564. ESP_LOGE(logTag, "can't delete folder: %s", folderPath);
  565. }
  566. ESP_LOGD(logTag, "%d files in folder %s deleted.", deleted, folderPath);
  567. return deleted;
  568. }
  569. std::vector<string> HelperZerlegeZeile(std::string input, std::string _delimiter = "")
  570. {
  571. std::vector<string> Output;
  572. std::string delimiter = " =,";
  573. if (_delimiter.length() > 0)
  574. {
  575. delimiter = _delimiter;
  576. }
  577. return ZerlegeZeile(input, delimiter);
  578. }
  579. std::vector<string> ZerlegeZeile(std::string input, std::string delimiter)
  580. {
  581. std::vector<string> Output;
  582. /* The input can have multiple formats:
  583. * - key = value
  584. * - key = value1 value2 value3 ...
  585. * - key value1 value2 value3 ...
  586. *
  587. * Examples:
  588. * - ImageSize = VGA
  589. * - IO0 = input disabled 10 false false
  590. * - main.dig1 28 144 55 100 false
  591. *
  592. * This causes issues eg. if a password key has a whitespace or equal sign in its value.
  593. * As a workaround and to not break any legacy usage, we enforce to only use the
  594. * equal sign, if the key is "password"
  595. */
  596. if ((input.find("password") != string::npos) || (input.find("Token") != string::npos))
  597. {
  598. // Line contains a password, use the equal sign as the only delimiter and only split on first occurrence
  599. size_t pos = input.find("=");
  600. Output.push_back(trim(input.substr(0, pos), ""));
  601. Output.push_back(trim(input.substr(pos + 1, string::npos), ""));
  602. }
  603. else
  604. {
  605. // Legacy Mode
  606. input = trim(input, delimiter); // sonst werden delimiter am Ende (z.B. == im Token) gelöscht)
  607. size_t pos = findDelimiterPos(input, delimiter);
  608. std::string token;
  609. while (pos != std::string::npos)
  610. {
  611. token = input.substr(0, pos);
  612. token = trim(token, delimiter);
  613. Output.push_back(token);
  614. input.erase(0, pos + 1);
  615. input = trim(input, delimiter);
  616. pos = findDelimiterPos(input, delimiter);
  617. }
  618. Output.push_back(input);
  619. }
  620. return Output;
  621. }
  622. std::string ReplaceString(std::string subject, const std::string &search, const std::string &replace)
  623. {
  624. size_t pos = 0;
  625. while ((pos = subject.find(search, pos)) != std::string::npos)
  626. {
  627. subject.replace(pos, search.length(), replace);
  628. pos += replace.length();
  629. }
  630. return subject;
  631. }
  632. /* Source: https://git.kernel.org/pub/scm/utils/mmc/mmc-utils.git/tree/lsmmc.c */
  633. /* SD Card Manufacturer Database */
  634. struct SDCard_Manufacturer_database
  635. {
  636. string type;
  637. int id;
  638. string manufacturer;
  639. };
  640. /* Source: https://git.kernel.org/pub/scm/utils/mmc/mmc-utils.git/tree/lsmmc.c */
  641. /* SD Card Manufacturer Database */
  642. struct SDCard_Manufacturer_database sd_database[] = {
  643. {
  644. .type = "sd",
  645. .id = 0x01,
  646. .manufacturer = "Panasonic",
  647. },
  648. {
  649. .type = "sd",
  650. .id = 0x02,
  651. .manufacturer = "Toshiba/Kingston/Viking",
  652. },
  653. {
  654. .type = "sd",
  655. .id = 0x03,
  656. .manufacturer = "SanDisk",
  657. },
  658. {
  659. .type = "sd",
  660. .id = 0x08,
  661. .manufacturer = "Silicon Power",
  662. },
  663. {
  664. .type = "sd",
  665. .id = 0x18,
  666. .manufacturer = "Infineon",
  667. },
  668. {
  669. .type = "sd",
  670. .id = 0x1b,
  671. .manufacturer = "Transcend/Samsung",
  672. },
  673. {
  674. .type = "sd",
  675. .id = 0x1c,
  676. .manufacturer = "Transcend",
  677. },
  678. {
  679. .type = "sd",
  680. .id = 0x1d,
  681. .manufacturer = "Corsair/AData",
  682. },
  683. {
  684. .type = "sd",
  685. .id = 0x1e,
  686. .manufacturer = "Transcend",
  687. },
  688. {
  689. .type = "sd",
  690. .id = 0x1f,
  691. .manufacturer = "Kingston",
  692. },
  693. {
  694. .type = "sd",
  695. .id = 0x27,
  696. .manufacturer = "Delkin/Phison",
  697. },
  698. {
  699. .type = "sd",
  700. .id = 0x28,
  701. .manufacturer = "Lexar",
  702. },
  703. {
  704. .type = "sd",
  705. .id = 0x30,
  706. .manufacturer = "SanDisk",
  707. },
  708. {
  709. .type = "sd",
  710. .id = 0x31,
  711. .manufacturer = "Silicon Power",
  712. },
  713. {
  714. .type = "sd",
  715. .id = 0x33,
  716. .manufacturer = "STMicroelectronics",
  717. },
  718. {
  719. .type = "sd",
  720. .id = 0x41,
  721. .manufacturer = "Kingston",
  722. },
  723. {
  724. .type = "sd",
  725. .id = 0x6f,
  726. .manufacturer = "STMicroelectronics",
  727. },
  728. {
  729. .type = "sd",
  730. .id = 0x74,
  731. .manufacturer = "Transcend",
  732. },
  733. {
  734. .type = "sd",
  735. .id = 0x76,
  736. .manufacturer = "Patriot",
  737. },
  738. {
  739. .type = "sd",
  740. .id = 0x82,
  741. .manufacturer = "Gobe/Sony",
  742. },
  743. {
  744. .type = "sd",
  745. .id = 0x89,
  746. .manufacturer = "Unknown",
  747. },
  748. };
  749. struct SDCard_Manufacturer_database mmc_database[] = {
  750. {
  751. .type = "mmc",
  752. .id = 0x00,
  753. .manufacturer = "SanDisk",
  754. },
  755. {
  756. .type = "mmc",
  757. .id = 0x02,
  758. .manufacturer = "Kingston/SanDisk",
  759. },
  760. {
  761. .type = "mmc",
  762. .id = 0x03,
  763. .manufacturer = "Toshiba",
  764. },
  765. {
  766. .type = "mmc",
  767. .id = 0x05,
  768. .manufacturer = "Unknown",
  769. },
  770. {
  771. .type = "mmc",
  772. .id = 0x06,
  773. .manufacturer = "Unknown",
  774. },
  775. {
  776. .type = "mmc",
  777. .id = 0x11,
  778. .manufacturer = "Toshiba",
  779. },
  780. {
  781. .type = "mmc",
  782. .id = 0x13,
  783. .manufacturer = "Micron",
  784. },
  785. {
  786. .type = "mmc",
  787. .id = 0x15,
  788. .manufacturer = "Samsung/SanDisk/LG",
  789. },
  790. {
  791. .type = "mmc",
  792. .id = 0x37,
  793. .manufacturer = "KingMax",
  794. },
  795. {
  796. .type = "mmc",
  797. .id = 0x44,
  798. .manufacturer = "ATP",
  799. },
  800. {
  801. .type = "mmc",
  802. .id = 0x45,
  803. .manufacturer = "SanDisk Corporation",
  804. },
  805. {
  806. .type = "mmc",
  807. .id = 0x2c,
  808. .manufacturer = "Kingston",
  809. },
  810. {
  811. .type = "mmc",
  812. .id = 0x70,
  813. .manufacturer = "Kingston",
  814. },
  815. {
  816. .type = "mmc",
  817. .id = 0xfe,
  818. .manufacturer = "Micron",
  819. },
  820. };
  821. /* Parse SD Card Manufacturer Database */
  822. string SDCardParseManufacturerIDs(int id)
  823. {
  824. if (SDCardIsMMC)
  825. {
  826. unsigned int id_cnt = sizeof(mmc_database) / sizeof(struct SDCard_Manufacturer_database);
  827. string ret_val = "";
  828. for (int i = 0; i < id_cnt; i++)
  829. {
  830. if (mmc_database[i].id == id)
  831. {
  832. return mmc_database[i].manufacturer;
  833. }
  834. else
  835. {
  836. ret_val = "ID unknown (not in DB)";
  837. }
  838. }
  839. return ret_val;
  840. }
  841. else
  842. {
  843. unsigned int id_cnt = sizeof(sd_database) / sizeof(struct SDCard_Manufacturer_database);
  844. string ret_val = "";
  845. for (int i = 0; i < id_cnt; i++)
  846. {
  847. if (sd_database[i].id == id)
  848. {
  849. return sd_database[i].manufacturer;
  850. }
  851. else
  852. {
  853. ret_val = "ID unknown (not in DB)";
  854. }
  855. }
  856. return ret_val;
  857. }
  858. }
  859. string RundeOutput(double _in, int _anzNachkomma)
  860. {
  861. std::stringstream stream;
  862. int _zw = _in;
  863. // ESP_LOGD(TAG, "AnzNachkomma: %d", _anzNachkomma);
  864. if (_anzNachkomma > 0)
  865. {
  866. stream << std::fixed << std::setprecision(_anzNachkomma) << _in;
  867. }
  868. else
  869. {
  870. stream << _zw;
  871. }
  872. return stream.str();
  873. }
  874. string getMac(void)
  875. {
  876. uint8_t macInt[6];
  877. char macFormated[6 * 2 + 5 + 1]; // AA:BB:CC:DD:EE:FF
  878. esp_read_mac(macInt, ESP_MAC_WIFI_STA);
  879. sprintf(macFormated, "%02X:%02X:%02X:%02X:%02X:%02X", macInt[0], macInt[1], macInt[2], macInt[3], macInt[4], macInt[5]);
  880. return macFormated;
  881. }
  882. void setSystemStatusFlag(SystemStatusFlag_t flag)
  883. {
  884. systemStatus = systemStatus | flag; // set bit
  885. char buf[20];
  886. snprintf(buf, sizeof(buf), "0x%08X", getSystemStatus());
  887. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "New System Status: " + std::string(buf));
  888. }
  889. void clearSystemStatusFlag(SystemStatusFlag_t flag)
  890. {
  891. systemStatus = systemStatus | ~flag; // clear bit
  892. char buf[20];
  893. snprintf(buf, sizeof(buf), "0x%08X", getSystemStatus());
  894. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "New System Status: " + std::string(buf));
  895. }
  896. int getSystemStatus(void)
  897. {
  898. return systemStatus;
  899. }
  900. bool isSetSystemStatusFlag(SystemStatusFlag_t flag)
  901. {
  902. // ESP_LOGE(TAG, "Flag (0x%08X) is set (0x%08X): %d", flag, systemStatus , ((systemStatus & flag) == flag));
  903. if ((systemStatus & flag) == flag)
  904. {
  905. return true;
  906. }
  907. else
  908. {
  909. return false;
  910. }
  911. }
  912. time_t getUpTime(void)
  913. {
  914. return (uint32_t)(esp_timer_get_time() / 1000 / 1000); // in seconds
  915. }
  916. string getResetReason(void)
  917. {
  918. std::string reasonText;
  919. switch (esp_reset_reason())
  920. {
  921. case ESP_RST_POWERON:
  922. reasonText = "Power-on event (or reset button)";
  923. break; //!< Reset due to power-on event
  924. case ESP_RST_EXT:
  925. reasonText = "External pin";
  926. break; //!< Reset by external pin (not applicable for ESP32)
  927. case ESP_RST_SW:
  928. reasonText = "Via esp_restart";
  929. break; //!< Software reset via esp_restart
  930. case ESP_RST_PANIC:
  931. reasonText = "Exception/panic";
  932. break; //!< Software reset due to exception/panic
  933. case ESP_RST_INT_WDT:
  934. reasonText = "Interrupt watchdog";
  935. break; //!< Reset (software or hardware) due to interrupt watchdog
  936. case ESP_RST_TASK_WDT:
  937. reasonText = "Task watchdog";
  938. break; //!< Reset due to task watchdog
  939. case ESP_RST_WDT:
  940. reasonText = "Other watchdogs";
  941. break; //!< Reset due to other watchdogs
  942. case ESP_RST_DEEPSLEEP:
  943. reasonText = "Exiting deep sleep mode";
  944. break; //!< Reset after exiting deep sleep mode
  945. case ESP_RST_BROWNOUT:
  946. reasonText = "Brownout";
  947. break; //!< Brownout reset (software or hardware)
  948. case ESP_RST_SDIO:
  949. reasonText = "SDIO";
  950. break; //!< Reset over SDIO
  951. case ESP_RST_UNKNOWN: //!< Reset reason can not be determined
  952. default:
  953. reasonText = "Unknown";
  954. }
  955. return reasonText;
  956. }
  957. /**
  958. * Returns the current uptime formated ad xxf xxh xxm [xxs]
  959. */
  960. std::string getFormatedUptime(bool compact)
  961. {
  962. char buf[20];
  963. #pragma GCC diagnostic ignored "-Wformat-truncation"
  964. int uptime = getUpTime(); // in seconds
  965. int days = int(floor(uptime / (3600 * 24)));
  966. int hours = int(floor((uptime - days * 3600 * 24) / (3600)));
  967. int minutes = int(floor((uptime - days * 3600 * 24 - hours * 3600) / (60)));
  968. int seconds = uptime - days * 3600 * 24 - hours * 3600 - minutes * 60;
  969. if (compact)
  970. {
  971. snprintf(buf, sizeof(buf), "%dd%02dh%02dm%02ds", days, hours, minutes, seconds);
  972. }
  973. else
  974. {
  975. snprintf(buf, sizeof(buf), "%3dd %02dh %02dm %02ds", days, hours, minutes, seconds);
  976. }
  977. return std::string(buf);
  978. }
  979. const char *get404(void)
  980. {
  981. return "<pre>\n\n\n\n"
  982. " _\n"
  983. " .__(.)< ( oh oh! This page does not exist! )\n"
  984. " \\___)\n"
  985. "\n\n"
  986. " You could try your <a href=index.html target=_parent>luck</a> here!</pre>\n"
  987. "<script>document.cookie = \"page=overview.html\"</script>"; // Make sure we load the overview page
  988. }
  989. std::string UrlDecode(const std::string &value)
  990. {
  991. std::string result;
  992. result.reserve(value.size());
  993. for (std::size_t i = 0; i < value.size(); ++i)
  994. {
  995. auto ch = value[i];
  996. if (ch == '%' && (i + 2) < value.size())
  997. {
  998. auto hex = value.substr(i + 1, 2);
  999. auto dec = static_cast<char>(std::strtol(hex.c_str(), nullptr, 16));
  1000. result.push_back(dec);
  1001. i += 2;
  1002. }
  1003. else if (ch == '+')
  1004. {
  1005. result.push_back(' ');
  1006. }
  1007. else
  1008. {
  1009. result.push_back(ch);
  1010. }
  1011. }
  1012. return result;
  1013. }
  1014. bool replaceString(std::string &s, std::string const &toReplace, std::string const &replaceWith)
  1015. {
  1016. return replaceString(s, toReplace, replaceWith, true);
  1017. }
  1018. bool replaceString(std::string &s, std::string const &toReplace, std::string const &replaceWith, bool logIt)
  1019. {
  1020. std::size_t pos = s.find(toReplace);
  1021. if (pos == std::string::npos)
  1022. {
  1023. // Not found
  1024. return false;
  1025. }
  1026. std::string old = s;
  1027. s.replace(pos, toReplace.length(), replaceWith);
  1028. if (logIt)
  1029. {
  1030. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Migrated Configfile line '" + old + "' to '" + s + "'");
  1031. }
  1032. return true;
  1033. }
  1034. bool isInString(std::string &s, std::string const &toFind)
  1035. {
  1036. std::size_t pos = s.find(toFind);
  1037. if (pos == std::string::npos)
  1038. {
  1039. // Not found
  1040. return false;
  1041. }
  1042. return true;
  1043. }
  1044. // from https://stackoverflow.com/a/14678800
  1045. void replaceAll(std::string& s, const std::string& toReplace, const std::string& replaceWith)
  1046. {
  1047. size_t pos = 0;
  1048. while ((pos = s.find(toReplace, pos)) != std::string::npos)
  1049. {
  1050. s.replace(pos, toReplace.length(), replaceWith);
  1051. pos += replaceWith.length();
  1052. }
  1053. }
  1054. bool isStringNumeric(std::string &input)
  1055. {
  1056. if (input.size() <= 0)
  1057. {
  1058. return false;
  1059. }
  1060. // Replace comma with a dot
  1061. replaceString(input, ",", ".", false);
  1062. int start = 0;
  1063. int punkt_existiert_schon = 0;
  1064. if (input[0] == '-')
  1065. {
  1066. start = 1;
  1067. }
  1068. for (int i = start; i < input.size(); i++)
  1069. {
  1070. if ((input[i] == '.') && (i > 0) && (punkt_existiert_schon == 0))
  1071. {
  1072. punkt_existiert_schon = 1;
  1073. i++;
  1074. }
  1075. else if (!isdigit(input[i]))
  1076. {
  1077. return false;
  1078. }
  1079. }
  1080. return true;
  1081. }
  1082. bool isStringAlphabetic(std::string &input)
  1083. {
  1084. for (int i = 0; i < input.size(); i++)
  1085. {
  1086. if (!isalpha(input[i]))
  1087. {
  1088. return false;
  1089. }
  1090. }
  1091. return true;
  1092. }
  1093. bool isStringAlphanumeric(std::string &input)
  1094. {
  1095. for (int i = 0; i < input.size(); i++)
  1096. {
  1097. if (!isalnum(input[i]))
  1098. {
  1099. return false;
  1100. }
  1101. }
  1102. return true;
  1103. }
  1104. bool alphanumericToBoolean(std::string &input)
  1105. {
  1106. if (isStringAlphabetic(input))
  1107. {
  1108. return stringToBoolean(toUpper(input));
  1109. }
  1110. else if (isStringNumeric(input))
  1111. {
  1112. return numericStrToBool(input);
  1113. }
  1114. return false;
  1115. }
  1116. int clipInt(int input, int high, int low)
  1117. {
  1118. if (input < low)
  1119. {
  1120. input = low;
  1121. }
  1122. else if (input > high)
  1123. {
  1124. input = high;
  1125. }
  1126. return input;
  1127. }
  1128. bool numericStrToBool(std::string input)
  1129. {
  1130. return (std::stoi(input) != 0);
  1131. }
  1132. bool stringToBoolean(std::string input)
  1133. {
  1134. return (input == "TRUE");
  1135. }