Helper.cpp 25 KB

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