Helper.cpp 16 KB

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