Helper.cpp 27 KB

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