Helper.cpp 24 KB

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