Helper.cpp 27 KB

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