Helper.cpp 24 KB

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