Helper.cpp 26 KB

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