Helper.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  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. #ifdef __cplusplus
  8. extern "C" {
  9. #endif
  10. #include <dirent.h>
  11. #ifdef __cplusplus
  12. }
  13. #endif
  14. #include <string.h>
  15. #include <esp_log.h>
  16. #include "ClassLogFile.h"
  17. #include "esp_vfs_fat.h"
  18. //#define ISWINDOWS_TRUE
  19. #define PATH_MAX_STRING_SIZE 256
  20. using namespace std;
  21. sdmmc_cid_t SDCardCid;
  22. sdmmc_csd_t SDCardCsd;
  23. /////////////////////////////////////////////////////////////////////////////////////////////
  24. string getESPHeapInfo(){
  25. string espInfoResultStr = "";
  26. char aMsgBuf[80];
  27. multi_heap_info_t aMultiHead_info ;
  28. heap_caps_get_info (&aMultiHead_info,MALLOC_CAP_8BIT);
  29. size_t aFreeHeapSize = heap_caps_get_free_size(MALLOC_CAP_8BIT);
  30. size_t aMinFreeHeadSize = heap_caps_get_minimum_free_size(MALLOC_CAP_8BIT);
  31. size_t aMinFreeHeapSize = heap_caps_get_minimum_free_size(MALLOC_CAP_8BIT);
  32. size_t aHeapLargestFreeBlockSize = heap_caps_get_largest_free_block(MALLOC_CAP_8BIT);
  33. sprintf(aMsgBuf," Free Heap Size: %ld", (long) aFreeHeapSize);
  34. size_t aFreeSPIHeapSize = heap_caps_get_free_size(MALLOC_CAP_8BIT| MALLOC_CAP_SPIRAM);
  35. size_t aFreeInternalHeapSize = heap_caps_get_free_size(MALLOC_CAP_8BIT| MALLOC_CAP_INTERNAL);
  36. size_t aMinFreeInternalHeapSize = heap_caps_get_minimum_free_size(MALLOC_CAP_8BIT| MALLOC_CAP_INTERNAL);
  37. sprintf(aMsgBuf," Heap: %ld", (long) aFreeHeapSize);
  38. espInfoResultStr += string(aMsgBuf);
  39. sprintf(aMsgBuf," Min Free: %ld", (long) aMinFreeHeapSize);
  40. espInfoResultStr += string(aMsgBuf);
  41. sprintf(aMsgBuf," larg. Block: %ld", (long) aHeapLargestFreeBlockSize);
  42. espInfoResultStr += string(aMsgBuf);
  43. sprintf(aMsgBuf," SPI Heap: %ld", (long) aFreeSPIHeapSize);
  44. espInfoResultStr += string(aMsgBuf);
  45. sprintf(aMsgBuf," Min Free Heap Size: %ld", (long) aMinFreeHeadSize);
  46. sprintf(aMsgBuf," NOT_SPI Heap: %ld", (long) (aFreeHeapSize - aFreeSPIHeapSize));
  47. espInfoResultStr += string(aMsgBuf);
  48. sprintf(aMsgBuf," largest Block Size: %ld", (long) aHeapLargestFreeBlockSize);
  49. sprintf(aMsgBuf," Internal Heap: %ld", (long) (aFreeInternalHeapSize));
  50. espInfoResultStr += string(aMsgBuf);
  51. sprintf(aMsgBuf," Internal Min Heap free: %ld", (long) (aMinFreeInternalHeapSize));
  52. espInfoResultStr += string(aMsgBuf);
  53. return espInfoResultStr;
  54. }
  55. size_t getESPHeapSize(){
  56. size_t aFreeHeapSize = heap_caps_get_free_size(MALLOC_CAP_8BIT);
  57. return aFreeHeapSize;
  58. }
  59. size_t getInternalESPHeapSize() {
  60. size_t aFreeInternalHeapSize = heap_caps_get_free_size(MALLOC_CAP_8BIT| MALLOC_CAP_INTERNAL);
  61. return aFreeInternalHeapSize;
  62. }
  63. string getSDCardPartitionSize(){
  64. FATFS *fs;
  65. uint32_t fre_clust, tot_sect;
  66. /* Get volume information and free clusters of drive 0 */
  67. f_getfree("0:", (DWORD *)&fre_clust, &fs);
  68. 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
  69. printf("%d MB total drive space (Sector size [bytes]: %d)\n", (int)tot_sect, (int)fs->csize*512);
  70. return std::to_string(tot_sect);
  71. }
  72. string getSDCardFreePartitionSpace(){
  73. FATFS *fs;
  74. uint32_t fre_clust, fre_sect;
  75. /* Get volume information and free clusters of drive 0 */
  76. f_getfree("0:", (DWORD *)&fre_clust, &fs);
  77. fre_sect = (fre_clust * fs->csize) / 1024 /(1024/SDCardCsd.sector_size); //corrected by SD Card sector size (usually 512 bytes) and convert to MB
  78. printf("%d MB free drive space (Sector size [bytes]: %d)\n", (int)fre_sect, (int)fs->ssize);
  79. return std::to_string(fre_sect);
  80. }
  81. string getSDCardPartitionAllocationSize(){
  82. FATFS *fs;
  83. uint32_t fre_clust, allocation_size;
  84. /* Get volume information and free clusters of drive 0 */
  85. f_getfree("0:", (DWORD *)&fre_clust, &fs);
  86. allocation_size = fs->ssize;
  87. printf("SD Card Partition Allocation Size (bytes): %d)\n", allocation_size);
  88. return std::to_string(allocation_size);
  89. }
  90. void SaveSDCardInfo(sdmmc_card_t* card) {
  91. SDCardCid = card->cid;
  92. SDCardCsd = card->csd;
  93. }
  94. string getSDCardManufacturer(){
  95. string SDCardManufacturer = SDCardParseManufacturerIDs(SDCardCid.mfg_id);
  96. printf("SD Card Manufactuer: %s\n", SDCardManufacturer.c_str());
  97. return (SDCardManufacturer + " (ID: " + std::to_string(SDCardCid.mfg_id) + ")");
  98. }
  99. string getSDCardName(){
  100. char *SDCardName = SDCardCid.name;
  101. printf("SD Card Name: %s\n", SDCardName);
  102. return std::string(SDCardName);
  103. }
  104. string getSDCardCapacity(){
  105. int SDCardCapacity = SDCardCsd.capacity / (1024/SDCardCsd.sector_size) / 1024; // total sectors * sector size --> Byte to MB (1024*1024)
  106. printf("SD Card Capacity: %s\n", std::to_string(SDCardCapacity).c_str());
  107. return std::to_string(SDCardCapacity);
  108. }
  109. string getSDCardSectorSize(){
  110. int SDCardSectorSize = SDCardCsd.sector_size;
  111. printf("SD Card Sector Size: %s\n", std::to_string(SDCardSectorSize).c_str());
  112. return std::to_string(SDCardSectorSize);
  113. }
  114. ///////////////////////////////////////////////////////////////////////////////////////////////
  115. void memCopyGen(uint8_t* _source, uint8_t* _target, int _size)
  116. {
  117. for (int i = 0; i < _size; ++i)
  118. *(_target + i) = *(_source + i);
  119. }
  120. FILE* OpenFileAndWait(const char* nm, const char* _mode, int _waitsec)
  121. {
  122. FILE *pfile;
  123. printf("open file %s in mode %s\n", nm, _mode);
  124. if ((pfile = fopen(nm, _mode)) != NULL) {
  125. printf("File %s successfully opened\n", nm);
  126. }
  127. else {
  128. printf("Error: file %s does not exist!\n", nm);
  129. return NULL;
  130. }
  131. /*
  132. if (pfile == NULL)
  133. {
  134. TickType_t xDelay;
  135. xDelay = _waitsec * 1000 / portTICK_PERIOD_MS;
  136. std::string zw = "File is locked: " + std::string(nm) + " - wait for " + std::to_string(_waitsec) + " seconds";
  137. printf(zw.c_str());
  138. printf("\n");
  139. LogFile.WriteToFile(zw);
  140. vTaskDelay( xDelay );
  141. pfile = fopen(nm, _mode);
  142. }
  143. */
  144. return pfile;
  145. }
  146. std::string FormatFileName(std::string input)
  147. {
  148. #ifdef ISWINDOWS_TRUE
  149. input.erase(0, 1);
  150. std::string os = "/";
  151. std::string ns = "\\";
  152. FindReplace(input, os, ns);
  153. #endif
  154. return input;
  155. }
  156. void FindReplace(std::string& line, std::string& oldString, std::string& newString) {
  157. const size_t oldSize = oldString.length();
  158. // do nothing if line is shorter than the string to find
  159. if (oldSize > line.length()) return;
  160. const size_t newSize = newString.length();
  161. for (size_t pos = 0; ; pos += newSize) {
  162. // Locate the substring to replace
  163. pos = line.find(oldString, pos);
  164. if (pos == std::string::npos) return;
  165. if (oldSize == newSize) {
  166. // if they're same size, use std::string::replace
  167. line.replace(pos, oldSize, newString);
  168. }
  169. else {
  170. // if not same size, replace by erasing and inserting
  171. line.erase(pos, oldSize);
  172. line.insert(pos, newString);
  173. }
  174. }
  175. }
  176. void MakeDir(std::string _what)
  177. {
  178. // chdir(_where.c_str());
  179. if (mkdir(_what.c_str(), S_IRWXU|S_IRWXG|S_IROTH))
  180. printf("Problem with MakeDir: %s \n", _what.c_str());
  181. }
  182. bool ctype_space(const char c, string adddelimiter)
  183. {
  184. if (c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == 11)
  185. {
  186. return true;
  187. }
  188. if (adddelimiter.find(c) != string::npos)
  189. return true;
  190. return false;
  191. }
  192. string trim(string istring, string adddelimiter)
  193. {
  194. bool trimmed = false;
  195. if (ctype_space(istring[istring.length() - 1], adddelimiter))
  196. {
  197. istring.erase(istring.length() - 1);
  198. trimmed = true;
  199. }
  200. if (ctype_space(istring[0], adddelimiter))
  201. {
  202. istring.erase(0, 1);
  203. trimmed = true;
  204. }
  205. if ((trimmed == false) || (istring.size() == 0))
  206. {
  207. return istring;
  208. }
  209. else
  210. {
  211. return trim(istring, adddelimiter);
  212. }
  213. }
  214. size_t findDelimiterPos(string input, string delimiter)
  215. {
  216. size_t pos = std::string::npos;
  217. size_t zw;
  218. string akt_del;
  219. for (int anz = 0; anz < delimiter.length(); ++anz)
  220. {
  221. akt_del = delimiter[anz];
  222. if ((zw = input.find(akt_del)) != std::string::npos)
  223. {
  224. if (pos != std::string::npos)
  225. {
  226. if (zw < pos)
  227. pos = zw;
  228. }
  229. else
  230. pos = zw;
  231. }
  232. }
  233. return pos;
  234. }
  235. void RenameFile(string from, string to)
  236. {
  237. // ESP_LOGI(logTag, "Deleting file : %s", fn.c_str());
  238. /* Delete file */
  239. FILE* fpSourceFile = OpenFileAndWait(from.c_str(), "rb");
  240. if (!fpSourceFile) // Sourcefile existiert nicht sonst gibt es einen Fehler beim Kopierversuch!
  241. {
  242. printf("DeleteFile: File %s existiert nicht!\n", from.c_str());
  243. return;
  244. }
  245. fclose(fpSourceFile);
  246. rename(from.c_str(), to.c_str());
  247. }
  248. void DeleteFile(string fn)
  249. {
  250. // ESP_LOGI(logTag, "Deleting file : %s", fn.c_str());
  251. /* Delete file */
  252. FILE* fpSourceFile = OpenFileAndWait(fn.c_str(), "rb");
  253. if (!fpSourceFile) // Sourcefile existiert nicht sonst gibt es einen Fehler beim Kopierversuch!
  254. {
  255. printf("DeleteFile: File %s existiert nicht!\n", fn.c_str());
  256. return;
  257. }
  258. fclose(fpSourceFile);
  259. unlink(fn.c_str());
  260. }
  261. void CopyFile(string input, string output)
  262. {
  263. input = FormatFileName(input);
  264. output = FormatFileName(output);
  265. if (toUpper(input).compare("/SDCARD/WLAN.INI") == 0)
  266. {
  267. printf("wlan.ini kann nicht kopiert werden!\n");
  268. return;
  269. }
  270. char cTemp;
  271. FILE* fpSourceFile = OpenFileAndWait(input.c_str(), "rb");
  272. if (!fpSourceFile) // Sourcefile existiert nicht sonst gibt es einen Fehler beim Kopierversuch!
  273. {
  274. printf("File %s existiert nicht!\n", input.c_str());
  275. return;
  276. }
  277. FILE* fpTargetFile = OpenFileAndWait(output.c_str(), "wb");
  278. // Code Section
  279. // Read From The Source File - "Copy"
  280. while (fread(&cTemp, 1, 1, fpSourceFile) == 1)
  281. {
  282. // Write To The Target File - "Paste"
  283. fwrite(&cTemp, 1, 1, fpTargetFile);
  284. }
  285. // Close The Files
  286. fclose(fpSourceFile);
  287. fclose(fpTargetFile);
  288. printf("File copied: %s to %s", input.c_str(), output.c_str());
  289. }
  290. string getFileFullFileName(string filename)
  291. {
  292. size_t lastpos = filename.find_last_of('/');
  293. if (lastpos == string::npos)
  294. return "";
  295. // printf("Last position: %d\n", lastpos);
  296. string zw = filename.substr(lastpos + 1, filename.size() - lastpos);
  297. return zw;
  298. }
  299. string getDirectory(string filename)
  300. {
  301. size_t lastpos = filename.find('/');
  302. if (lastpos == string::npos)
  303. lastpos = filename.find('\\');
  304. if (lastpos == string::npos)
  305. return "";
  306. // printf("Directory: %d\n", lastpos);
  307. string zw = filename.substr(0, lastpos - 1);
  308. return zw;
  309. }
  310. string getFileType(string filename)
  311. {
  312. size_t lastpos = filename.rfind(".", filename.length());
  313. size_t neu_pos;
  314. while ((neu_pos = filename.find(".", lastpos + 1)) > -1)
  315. {
  316. lastpos = neu_pos;
  317. }
  318. if (lastpos == string::npos)
  319. return "";
  320. string zw = filename.substr(lastpos + 1, filename.size() - lastpos);
  321. zw = toUpper(zw);
  322. return zw;
  323. }
  324. /* recursive mkdir */
  325. int mkdir_r(const char *dir, const mode_t mode) {
  326. char tmp[PATH_MAX_STRING_SIZE];
  327. char *p = NULL;
  328. struct stat sb;
  329. size_t len;
  330. /* copy path */
  331. len = strnlen (dir, PATH_MAX_STRING_SIZE);
  332. if (len == 0 || len == PATH_MAX_STRING_SIZE) {
  333. return -1;
  334. }
  335. memcpy (tmp, dir, len);
  336. tmp[len] = '\0';
  337. /* remove trailing slash */
  338. if(tmp[len - 1] == '/') {
  339. tmp[len - 1] = '\0';
  340. }
  341. /* check if path exists and is a directory */
  342. if (stat (tmp, &sb) == 0) {
  343. if (S_ISDIR (sb.st_mode)) {
  344. return 0;
  345. }
  346. }
  347. /* recursive mkdir */
  348. for(p = tmp + 1; *p; p++) {
  349. if(*p == '/') {
  350. *p = 0;
  351. /* test path */
  352. if (stat(tmp, &sb) != 0) {
  353. /* path does not exist - create directory */
  354. if (mkdir(tmp, mode) < 0) {
  355. return -1;
  356. }
  357. } else if (!S_ISDIR(sb.st_mode)) {
  358. /* not a directory */
  359. return -1;
  360. }
  361. *p = '/';
  362. }
  363. }
  364. /* test path */
  365. if (stat(tmp, &sb) != 0) {
  366. /* path does not exist - create directory */
  367. if (mkdir(tmp, mode) < 0) {
  368. return -1;
  369. }
  370. } else if (!S_ISDIR(sb.st_mode)) {
  371. /* not a directory */
  372. return -1;
  373. }
  374. return 0;
  375. }
  376. string toUpper(string in)
  377. {
  378. for (int i = 0; i < in.length(); ++i)
  379. in[i] = toupper(in[i]);
  380. return in;
  381. }
  382. string toLower(string in)
  383. {
  384. for (int i = 0; i < in.length(); ++i)
  385. in[i] = tolower(in[i]);
  386. return in;
  387. }
  388. // CPU Temp
  389. extern "C" uint8_t temprature_sens_read();
  390. float temperatureRead()
  391. {
  392. return (temprature_sens_read() - 32) / 1.8;
  393. }
  394. time_t addDays(time_t startTime, int days) {
  395. struct tm* tm = localtime(&startTime);
  396. tm->tm_mday += days;
  397. return mktime(tm);
  398. }
  399. int removeFolder(const char* folderPath, const char* logTag) {
  400. ESP_LOGI(logTag, "Delete folder %s", folderPath);
  401. DIR *dir = opendir(folderPath);
  402. if (!dir) {
  403. ESP_LOGI(logTag, "Failed to stat dir : %s", folderPath);
  404. return -1;
  405. }
  406. struct dirent *entry;
  407. int deleted = 0;
  408. while ((entry = readdir(dir)) != NULL) {
  409. std::string path = string(folderPath) + "/" + entry->d_name;
  410. if (entry->d_type == DT_REG) {
  411. if (unlink(path.c_str()) == 0) {
  412. deleted ++;
  413. } else {
  414. ESP_LOGE(logTag, "can't delete file : %s", path.c_str());
  415. }
  416. } else if (entry->d_type == DT_DIR) {
  417. deleted += removeFolder(path.c_str(), logTag);
  418. }
  419. }
  420. closedir(dir);
  421. if (rmdir(folderPath) != 0) {
  422. ESP_LOGE(logTag, "can't delete file : %s", folderPath);
  423. }
  424. ESP_LOGI(logTag, "%d older log files in folder %s deleted.", deleted, folderPath);
  425. return deleted;
  426. }
  427. std::vector<string> HelperZerlegeZeile(std::string input, std::string _delimiter = "")
  428. {
  429. std::vector<string> Output;
  430. std::string delimiter = " =,";
  431. if (_delimiter.length() > 0){
  432. delimiter = _delimiter;
  433. }
  434. input = trim(input, delimiter);
  435. size_t pos = findDelimiterPos(input, delimiter);
  436. std::string token;
  437. while (pos != std::string::npos) {
  438. token = input.substr(0, pos);
  439. token = trim(token, delimiter);
  440. Output.push_back(token);
  441. input.erase(0, pos + 1);
  442. input = trim(input, delimiter);
  443. pos = findDelimiterPos(input, delimiter);
  444. }
  445. Output.push_back(input);
  446. return Output;
  447. }
  448. /* Source: https://git.kernel.org/pub/scm/utils/mmc/mmc-utils.git/tree/lsmmc.c */
  449. /* SD Card Manufacturer Database */
  450. struct SDCard_Manufacturer_database {
  451. string type;
  452. int id;
  453. string manufacturer;
  454. };
  455. /* Source: https://git.kernel.org/pub/scm/utils/mmc/mmc-utils.git/tree/lsmmc.c */
  456. /* SD Card Manufacturer Database */
  457. struct SDCard_Manufacturer_database database[] = {
  458. {
  459. .type = "sd",
  460. .id = 0x01,
  461. .manufacturer = "Panasonic",
  462. },
  463. {
  464. .type = "sd",
  465. .id = 0x02,
  466. .manufacturer = "Toshiba/Kingston/Viking",
  467. },
  468. {
  469. .type = "sd",
  470. .id = 0x03,
  471. .manufacturer = "SanDisk",
  472. },
  473. {
  474. .type = "sd",
  475. .id = 0x08,
  476. .manufacturer = "Silicon Power",
  477. },
  478. {
  479. .type = "sd",
  480. .id = 0x18,
  481. .manufacturer = "Infineon",
  482. },
  483. {
  484. .type = "sd",
  485. .id = 0x1b,
  486. .manufacturer = "Transcend/Samsung",
  487. },
  488. {
  489. .type = "sd",
  490. .id = 0x1c,
  491. .manufacturer = "Transcend",
  492. },
  493. {
  494. .type = "sd",
  495. .id = 0x1d,
  496. .manufacturer = "Corsair/AData",
  497. },
  498. {
  499. .type = "sd",
  500. .id = 0x1e,
  501. .manufacturer = "Transcend",
  502. },
  503. {
  504. .type = "sd",
  505. .id = 0x1f,
  506. .manufacturer = "Kingston",
  507. },
  508. {
  509. .type = "sd",
  510. .id = 0x27,
  511. .manufacturer = "Delkin/Phison",
  512. },
  513. {
  514. .type = "sd",
  515. .id = 0x28,
  516. .manufacturer = "Lexar",
  517. },
  518. {
  519. .type = "sd",
  520. .id = 0x30,
  521. .manufacturer = "SanDisk",
  522. },
  523. {
  524. .type = "sd",
  525. .id = 0x31,
  526. .manufacturer = "Silicon Power",
  527. },
  528. {
  529. .type = "sd",
  530. .id = 0x33,
  531. .manufacturer = "STMicroelectronics",
  532. },
  533. {
  534. .type = "sd",
  535. .id = 0x41,
  536. .manufacturer = "Kingston",
  537. },
  538. {
  539. .type = "sd",
  540. .id = 0x6f,
  541. .manufacturer = "STMicroelectronics",
  542. },
  543. {
  544. .type = "sd",
  545. .id = 0x74,
  546. .manufacturer = "Transcend",
  547. },
  548. {
  549. .type = "sd",
  550. .id = 0x76,
  551. .manufacturer = "Patriot",
  552. },
  553. {
  554. .type = "sd",
  555. .id = 0x82,
  556. .manufacturer = "Gobe/Sony",
  557. },
  558. {
  559. .type = "sd",
  560. .id = 0x89,
  561. .manufacturer = "Unknown",
  562. }
  563. };
  564. /* Parse SD Card Manufacturer Database */
  565. string SDCardParseManufacturerIDs(int id)
  566. {
  567. unsigned int id_cnt = sizeof(database) / sizeof(struct SDCard_Manufacturer_database);
  568. string ret_val = "";
  569. for (int i = 0; i < id_cnt; i++) {
  570. if (database[i].id == id) {
  571. return database[i].manufacturer;
  572. }
  573. else {
  574. ret_val = "ID unknown (not in DB)";
  575. }
  576. }
  577. return ret_val;
  578. }