Helper.cpp 25 KB

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