Helper.cpp 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508
  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. {
  15. #endif
  16. #include <dirent.h>
  17. #ifdef __cplusplus
  18. }
  19. #endif
  20. #include <string.h>
  21. #include <esp_log.h>
  22. #include <esp_mac.h>
  23. #include <esp_timer.h>
  24. #include "../../include/defines.h"
  25. #include "ClassLogFile.h"
  26. #include "esp_vfs_fat.h"
  27. #if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 4, 0))
  28. #include <esp_private/sdmmc_common.h>
  29. #else
  30. #include <../sdmmc_common.h>
  31. #endif
  32. static const char *TAG = "HELPER";
  33. using namespace std;
  34. unsigned int systemStatus = 0;
  35. sdmmc_cid_t SDCardCid;
  36. sdmmc_csd_t SDCardCsd;
  37. bool SDCardIsMMC;
  38. // #define DEBUG_DETAIL_ON
  39. /////////////////////////////////////////////////////////////////////////////////////////////
  40. string getESPHeapInfo()
  41. {
  42. string espInfoResultStr = "";
  43. char aMsgBuf[80];
  44. size_t aFreeHeapSize = heap_caps_get_free_size(MALLOC_CAP_8BIT);
  45. size_t aFreeSPIHeapSize = heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM);
  46. size_t aFreeInternalHeapSize = heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL);
  47. size_t aHeapLargestFreeBlockSize = heap_caps_get_largest_free_block(MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM);
  48. size_t aHeapIntLargestFreeBlockSize = heap_caps_get_largest_free_block(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL);
  49. size_t aMinFreeHeapSize = heap_caps_get_minimum_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM);
  50. size_t aMinFreeInternalHeapSize = heap_caps_get_minimum_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL);
  51. sprintf(aMsgBuf, "Heap Total: %ld", (long)aFreeHeapSize);
  52. espInfoResultStr += string(aMsgBuf);
  53. sprintf(aMsgBuf, " | SPI Free: %ld", (long)aFreeSPIHeapSize);
  54. espInfoResultStr += string(aMsgBuf);
  55. sprintf(aMsgBuf, " | SPI Large Block: %ld", (long)aHeapLargestFreeBlockSize);
  56. espInfoResultStr += string(aMsgBuf);
  57. sprintf(aMsgBuf, " | SPI Min Free: %ld", (long)aMinFreeHeapSize);
  58. espInfoResultStr += string(aMsgBuf);
  59. sprintf(aMsgBuf, " | Int Free: %ld", (long)(aFreeInternalHeapSize));
  60. espInfoResultStr += string(aMsgBuf);
  61. sprintf(aMsgBuf, " | Int Large Block: %ld", (long)aHeapIntLargestFreeBlockSize);
  62. espInfoResultStr += string(aMsgBuf);
  63. sprintf(aMsgBuf, " | Int Min Free: %ld", (long)(aMinFreeInternalHeapSize));
  64. espInfoResultStr += string(aMsgBuf);
  65. return espInfoResultStr;
  66. }
  67. size_t getESPHeapSize()
  68. {
  69. return heap_caps_get_free_size(MALLOC_CAP_8BIT);
  70. }
  71. size_t getInternalESPHeapSize()
  72. {
  73. return heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL);
  74. }
  75. string getSDCardPartitionSize()
  76. {
  77. FATFS *fs;
  78. uint32_t fre_clust, tot_sect;
  79. /* Get volume information and free clusters of drive 0 */
  80. f_getfree("0:", (DWORD *)&fre_clust, &fs);
  81. 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
  82. // ESP_LOGD(TAG, "%d MB total drive space (Sector size [bytes]: %d)", (int)tot_sect, (int)fs->ssize);
  83. return std::to_string(tot_sect);
  84. }
  85. string getSDCardFreePartitionSpace()
  86. {
  87. FATFS *fs;
  88. uint32_t fre_clust, fre_sect;
  89. /* Get volume information and free clusters of drive 0 */
  90. f_getfree("0:", (DWORD *)&fre_clust, &fs);
  91. fre_sect = (fre_clust * fs->csize) / 1024 / (1024 / SDCardCsd.sector_size); // corrected by SD Card sector size (usually 512 bytes) and convert to MB
  92. // ESP_LOGD(TAG, "%d MB free drive space (Sector size [bytes]: %d)", (int)fre_sect, (int)fs->ssize);
  93. return std::to_string(fre_sect);
  94. }
  95. string getSDCardPartitionAllocationSize()
  96. {
  97. FATFS *fs;
  98. uint32_t fre_clust, allocation_size;
  99. /* Get volume information and free clusters of drive 0 */
  100. f_getfree("0:", (DWORD *)&fre_clust, &fs);
  101. allocation_size = fs->ssize;
  102. // ESP_LOGD(TAG, "SD Card Partition Allocation Size: %d bytes", allocation_size);
  103. return std::to_string(allocation_size);
  104. }
  105. void SaveSDCardInfo(sdmmc_card_t *card)
  106. {
  107. SDCardCid = card->cid;
  108. SDCardCsd = card->csd;
  109. SDCardIsMMC = card->is_mmc;
  110. }
  111. string getSDCardManufacturer()
  112. {
  113. string SDCardManufacturer = SDCardParseManufacturerIDs(SDCardCid.mfg_id);
  114. // ESP_LOGD(TAG, "SD Card Manufacturer: %s", SDCardManufacturer.c_str());
  115. return (SDCardManufacturer + " (ID: " + std::to_string(SDCardCid.mfg_id) + ")");
  116. }
  117. string getSDCardName()
  118. {
  119. char *SDCardName = SDCardCid.name;
  120. // ESP_LOGD(TAG, "SD Card Name: %s", SDCardName);
  121. return std::string(SDCardName);
  122. }
  123. string getSDCardCapacity()
  124. {
  125. int SDCardCapacity = SDCardCsd.capacity / (1024 / SDCardCsd.sector_size) / 1024; // total sectors * sector size --> Byte to MB (1024*1024)
  126. // ESP_LOGD(TAG, "SD Card Capacity: %s", std::to_string(SDCardCapacity).c_str());
  127. return std::to_string(SDCardCapacity);
  128. }
  129. string getSDCardSectorSize()
  130. {
  131. int SDCardSectorSize = SDCardCsd.sector_size;
  132. // ESP_LOGD(TAG, "SD Card Sector Size: %s bytes", std::to_string(SDCardSectorSize).c_str());
  133. return std::to_string(SDCardSectorSize);
  134. }
  135. ///////////////////////////////////////////////////////////////////////////////////////////////
  136. bool copy_string(char *dst, size_t dst_size, const char *src)
  137. {
  138. if (dst == nullptr || src == nullptr || dst_size == 0)
  139. {
  140. return false;
  141. }
  142. size_t len = strlen(src);
  143. if (len >= dst_size)
  144. {
  145. dst[0] = '\0';
  146. return false; // Target too small
  147. }
  148. memcpy(dst, src, len + 1);
  149. return true;
  150. }
  151. void mem_copy(uint8_t *_target, uint8_t *_source, int _size)
  152. {
  153. if ((_target != nullptr) && (_source != nullptr) && (_size > 0))
  154. {
  155. uint8_t *dst = _target;
  156. uint8_t *src = _source;
  157. for (int i = 0; i < _size; ++i)
  158. {
  159. *dst++ = *src++;
  160. }
  161. }
  162. }
  163. void mem_copy32(void *_target, const void *_source, size_t _size)
  164. {
  165. if ((_target != nullptr) && (_source != nullptr) && (_size > 0))
  166. {
  167. uint32_t *d32 = (uint32_t *)_target;
  168. const uint32_t *s32 = (const uint32_t *)_source;
  169. size_t words = _size / 4;
  170. for (size_t i = 0; i < words; i++)
  171. {
  172. d32[i] = s32[i];
  173. }
  174. // Copy remaining bytes
  175. uint8_t *d8 = (uint8_t *)(d32 + words);
  176. const uint8_t *s8 = (const uint8_t *)(s32 + words);
  177. for (size_t i = 0; i < (_size % 4); i++)
  178. {
  179. d8[i] = s8[i];
  180. }
  181. }
  182. }
  183. float fast_atan2(float y, float x)
  184. {
  185. float abs_y = fabs(y) + 1e-10;
  186. float r = (x - abs_y) / (x + abs_y);
  187. float angle = 0.78539816339 - 0.78539816339 * r;
  188. return (y < 0) ? -angle : angle;
  189. }
  190. double pow10_double(int pot)
  191. {
  192. static const double pow10_table[] = {
  193. 1.0,
  194. 10.0,
  195. 100.0,
  196. 1000.0,
  197. 10000.0,
  198. 100000.0,
  199. 1000000.0,
  200. 10000000.0,
  201. 100000000.0,
  202. 1000000000.0};
  203. if (pot >= 0 && pot < (int)(sizeof(pow10_table) / sizeof(pow10_table[0])))
  204. {
  205. return pow10_table[pot];
  206. }
  207. // Fallback if pot is larger
  208. double result = 1.0;
  209. for (int i = 0; i < pot; ++i)
  210. {
  211. result *= 10.0;
  212. }
  213. return result;
  214. }
  215. uint32_t pow10_int(int pot)
  216. {
  217. // Lookup table for small exponents 0-9
  218. static const uint32_t table[] = {
  219. 1, // 10^0
  220. 10, // 10^1
  221. 100, // 10^2
  222. 1000, // 10^3
  223. 10000, // 10^4
  224. 100000, // 10^5
  225. 1000000, // 10^6
  226. 10000000, // 10^7
  227. 100000000, // 10^8
  228. 1000000000 // 10^9
  229. };
  230. if (pot >= 0 && pot < (int)(sizeof(table) / sizeof(table[0])))
  231. {
  232. return table[pot];
  233. }
  234. // Fallback for larger pot
  235. uint32_t result = 1;
  236. for (int i = 0; i < pot; ++i)
  237. {
  238. result *= 10;
  239. }
  240. return result;
  241. }
  242. void memCopyGen(uint8_t *_source, uint8_t *_target, int _size)
  243. {
  244. for (int i = 0; i < _size; ++i)
  245. {
  246. *(_target + i) = *(_source + i);
  247. }
  248. }
  249. std::string FormatFileName(std::string input)
  250. {
  251. #ifdef ISWINDOWS_TRUE
  252. input.erase(0, 1);
  253. std::string os = "/";
  254. std::string ns = "\\";
  255. FindReplace(input, os, ns);
  256. #endif
  257. return input;
  258. }
  259. std::size_t file_size(const std::string &file_name)
  260. {
  261. std::ifstream file(file_name.c_str(), std::ios::in | std::ios::binary);
  262. if (!file)
  263. {
  264. return 0;
  265. }
  266. file.seekg(0, std::ios::end);
  267. return static_cast<std::size_t>(file.tellg());
  268. }
  269. void FindReplace(std::string &line, std::string &oldString, std::string &newString)
  270. {
  271. const size_t oldSize = oldString.length();
  272. // do nothing if line is shorter than the string to find
  273. if (oldSize > line.length())
  274. {
  275. return;
  276. }
  277. const size_t newSize = newString.length();
  278. for (size_t pos = 0;; pos += newSize)
  279. {
  280. // Locate the substring to replace
  281. pos = line.find(oldString, pos);
  282. if (pos == std::string::npos)
  283. {
  284. return;
  285. }
  286. if (oldSize == newSize)
  287. {
  288. // if they're same size, use std::string::replace
  289. line.replace(pos, oldSize, newString);
  290. }
  291. else
  292. {
  293. // if not same size, replace by erasing and inserting
  294. line.erase(pos, oldSize);
  295. line.insert(pos, newString);
  296. }
  297. }
  298. }
  299. /**
  300. * Create a folder and its parent folders as needed
  301. */
  302. bool MakeDir(std::string path)
  303. {
  304. std::string parent;
  305. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Creating folder " + path + "...");
  306. bool bSuccess = false;
  307. int nRC = ::mkdir(path.c_str(), 0775);
  308. if (nRC == -1)
  309. {
  310. switch (errno)
  311. {
  312. case ENOENT:
  313. // parent didn't exist, try to create it
  314. parent = path.substr(0, path.find_last_of('/'));
  315. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Need to create parent folder first: " + parent);
  316. if (MakeDir(parent))
  317. {
  318. // Now, try to create again.
  319. bSuccess = 0 == ::mkdir(path.c_str(), 0775);
  320. }
  321. else
  322. {
  323. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to create parent folder: " + parent);
  324. bSuccess = false;
  325. }
  326. break;
  327. case EEXIST:
  328. // Done!
  329. bSuccess = true;
  330. break;
  331. default:
  332. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to create folder: " + path + " (errno: " + std::to_string(errno) + ")");
  333. bSuccess = false;
  334. break;
  335. }
  336. }
  337. else
  338. {
  339. bSuccess = true;
  340. }
  341. return bSuccess;
  342. }
  343. bool ctype_space(const char c, string adddelimiter)
  344. {
  345. if (c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == 11)
  346. {
  347. return true;
  348. }
  349. if (adddelimiter.find(c) != string::npos)
  350. {
  351. return true;
  352. }
  353. return false;
  354. }
  355. string trim(string istring, string adddelimiter)
  356. {
  357. bool trimmed = false;
  358. if (ctype_space(istring[istring.length() - 1], adddelimiter))
  359. {
  360. istring.erase(istring.length() - 1);
  361. trimmed = true;
  362. }
  363. if (ctype_space(istring[0], adddelimiter))
  364. {
  365. istring.erase(0, 1);
  366. trimmed = true;
  367. }
  368. if ((trimmed == false) || (istring.size() == 0))
  369. {
  370. return istring;
  371. }
  372. else
  373. {
  374. return trim(istring, adddelimiter);
  375. }
  376. }
  377. size_t findDelimiterPos(string input, string delimiter)
  378. {
  379. size_t pos = std::string::npos;
  380. // size_t zw;
  381. string akt_del;
  382. for (int anz = 0; anz < delimiter.length(); ++anz)
  383. {
  384. akt_del = delimiter[anz];
  385. size_t zw = input.find(akt_del);
  386. if (zw != std::string::npos)
  387. {
  388. if ((pos != std::string::npos) && (zw < pos))
  389. {
  390. pos = zw;
  391. }
  392. else
  393. {
  394. pos = zw;
  395. }
  396. }
  397. }
  398. return pos;
  399. }
  400. bool RenameFile(string from, string to)
  401. {
  402. // ESP_LOGI(logTag, "Renaming File: %s", from.c_str());
  403. FILE *fpSourceFile = fopen(from.c_str(), "rb");
  404. // Sourcefile does not exist otherwise there is a mistake when renaming!
  405. if (!fpSourceFile)
  406. {
  407. ESP_LOGE(TAG, "RenameFile: File %s does not exist!", from.c_str());
  408. return false;
  409. }
  410. fclose(fpSourceFile);
  411. rename(from.c_str(), to.c_str());
  412. return true;
  413. }
  414. bool RenameFolder(string from, string to)
  415. {
  416. // ESP_LOGI(logTag, "Renaming Folder: %s", from.c_str());
  417. DIR *fpSourceFolder = opendir(from.c_str());
  418. // Sourcefolder does not exist otherwise there is a mistake when renaming!
  419. if (!fpSourceFolder)
  420. {
  421. ESP_LOGE(TAG, "RenameFolder: Folder %s does not exist!", from.c_str());
  422. return false;
  423. }
  424. closedir(fpSourceFolder);
  425. rename(from.c_str(), to.c_str());
  426. return true;
  427. }
  428. bool FileExists(string filename)
  429. {
  430. FILE *fpSourceFile = fopen(filename.c_str(), "rb");
  431. // Sourcefile does not exist
  432. if (!fpSourceFile)
  433. {
  434. return false;
  435. }
  436. fclose(fpSourceFile);
  437. return true;
  438. }
  439. bool FolderExists(string foldername)
  440. {
  441. DIR *fpSourceFolder = opendir(foldername.c_str());
  442. // Sourcefolder does not exist
  443. if (!fpSourceFolder)
  444. {
  445. return false;
  446. }
  447. closedir(fpSourceFolder);
  448. return true;
  449. }
  450. bool DeleteFile(string filename)
  451. {
  452. // ESP_LOGI(logTag, "Deleting file: %s", filename.c_str());
  453. /* Delete file */
  454. FILE *fpSourceFile = fopen(filename.c_str(), "rb");
  455. // Sourcefile does not exist otherwise there is a mistake in copying!
  456. if (!fpSourceFile)
  457. {
  458. ESP_LOGD(TAG, "DeleteFile: File %s existiert nicht!", filename.c_str());
  459. return false;
  460. }
  461. fclose(fpSourceFile);
  462. unlink(filename.c_str());
  463. return true;
  464. }
  465. bool CopyFile(string input, string output)
  466. {
  467. input = FormatFileName(input);
  468. output = FormatFileName(output);
  469. if (toUpper(input).compare(WLAN_CONFIG_FILE) == 0)
  470. {
  471. ESP_LOGD(TAG, "wlan.ini kann nicht kopiert werden!");
  472. return false;
  473. }
  474. char cTemp;
  475. FILE *fpSourceFile = fopen(input.c_str(), "rb");
  476. // Sourcefile existiert nicht sonst gibt es einen Fehler beim Kopierversuch!
  477. if (!fpSourceFile)
  478. {
  479. ESP_LOGD(TAG, "File %s existiert nicht!", input.c_str());
  480. return false;
  481. }
  482. FILE *fpTargetFile = fopen(output.c_str(), "wb");
  483. // Code Section
  484. // Read From The Source File - "Copy"
  485. while (fread(&cTemp, 1, 1, fpSourceFile) == 1)
  486. {
  487. // Write To The Target File - "Paste"
  488. fwrite(&cTemp, 1, 1, fpTargetFile);
  489. }
  490. // Close The Files
  491. fclose(fpSourceFile);
  492. fclose(fpTargetFile);
  493. ESP_LOGD(TAG, "File copied: %s to %s", input.c_str(), output.c_str());
  494. return true;
  495. }
  496. string getFileFullFileName(string filename)
  497. {
  498. size_t lastpos = filename.find_last_of('/');
  499. if (lastpos == string::npos)
  500. {
  501. return "";
  502. }
  503. // ESP_LOGD(TAG, "Last position: %d", lastpos);
  504. string zw = filename.substr(lastpos + 1, filename.size() - lastpos);
  505. return zw;
  506. }
  507. string getDirectory(string filename)
  508. {
  509. size_t lastpos = filename.find('/');
  510. if (lastpos == string::npos)
  511. {
  512. lastpos = filename.find('\\');
  513. }
  514. if (lastpos == string::npos)
  515. {
  516. return "";
  517. }
  518. // ESP_LOGD(TAG, "Directory: %d", lastpos);
  519. string zw = filename.substr(0, lastpos - 1);
  520. return zw;
  521. }
  522. string getFileType(string filename)
  523. {
  524. size_t lastpos = filename.rfind(".", filename.length());
  525. size_t neu_pos;
  526. while ((neu_pos = filename.find(".", lastpos + 1)) > -1)
  527. {
  528. lastpos = neu_pos;
  529. }
  530. if (lastpos == string::npos)
  531. {
  532. return "";
  533. }
  534. string zw = filename.substr(lastpos + 1, filename.size() - lastpos);
  535. zw = toUpper(zw);
  536. return zw;
  537. }
  538. /* recursive mkdir */
  539. int mkdir_r(const char *dir, const mode_t mode)
  540. {
  541. char tmp[FILE_PATH_MAX];
  542. char *p = NULL;
  543. struct stat sb;
  544. size_t len;
  545. /* copy path */
  546. len = strnlen(dir, FILE_PATH_MAX);
  547. if (len == 0 || len == FILE_PATH_MAX)
  548. {
  549. return -1;
  550. }
  551. memcpy(tmp, dir, len);
  552. tmp[len] = '\0';
  553. /* remove trailing slash */
  554. if (tmp[len - 1] == '/')
  555. {
  556. tmp[len - 1] = '\0';
  557. }
  558. /* check if path exists and is a directory */
  559. if (stat(tmp, &sb) == 0)
  560. {
  561. if (S_ISDIR(sb.st_mode))
  562. {
  563. return 0;
  564. }
  565. }
  566. /* recursive mkdir */
  567. for (p = tmp + 1; *p; p++)
  568. {
  569. if (*p == '/')
  570. {
  571. *p = 0;
  572. /* test path */
  573. if (stat(tmp, &sb) != 0)
  574. {
  575. /* path does not exist - create directory */
  576. if (mkdir(tmp, mode) < 0)
  577. {
  578. return -1;
  579. }
  580. }
  581. else if (!S_ISDIR(sb.st_mode))
  582. {
  583. /* not a directory */
  584. return -1;
  585. }
  586. *p = '/';
  587. }
  588. }
  589. /* test path */
  590. if (stat(tmp, &sb) != 0)
  591. {
  592. /* path does not exist - create directory */
  593. if (mkdir(tmp, mode) < 0)
  594. {
  595. return -1;
  596. }
  597. }
  598. else if (!S_ISDIR(sb.st_mode))
  599. {
  600. /* not a directory */
  601. return -1;
  602. }
  603. return 0;
  604. }
  605. string toUpper(string in)
  606. {
  607. for (int i = 0; i < in.length(); ++i)
  608. {
  609. in[i] = toupper(in[i]);
  610. }
  611. return in;
  612. }
  613. string toLower(string in)
  614. {
  615. for (int i = 0; i < in.length(); ++i)
  616. {
  617. in[i] = tolower(in[i]);
  618. }
  619. return in;
  620. }
  621. // CPU Temp
  622. extern "C" uint8_t temprature_sens_read();
  623. float temperatureRead()
  624. {
  625. return (temprature_sens_read() - 32) / 1.8;
  626. }
  627. time_t addDays(time_t startTime, int days)
  628. {
  629. struct tm *tm = localtime(&startTime);
  630. tm->tm_mday += days;
  631. return mktime(tm);
  632. }
  633. int removeFolder(const char *folderPath, const char *logTag)
  634. {
  635. // ESP_LOGD(logTag, "Delete content in path %s", folderPath);
  636. DIR *dir = opendir(folderPath);
  637. if (!dir)
  638. {
  639. ESP_LOGE(logTag, "Failed to stat dir: %s", folderPath);
  640. return -1;
  641. }
  642. struct dirent *entry;
  643. int deleted = 0;
  644. while ((entry = readdir(dir)) != NULL)
  645. {
  646. std::string path = string(folderPath) + "/" + entry->d_name;
  647. if (entry->d_type == DT_REG)
  648. {
  649. // ESP_LOGD(logTag, "Delete file %s", path.c_str());
  650. if (unlink(path.c_str()) == 0)
  651. {
  652. deleted++;
  653. }
  654. else
  655. {
  656. ESP_LOGE(logTag, "can't delete file: %s", path.c_str());
  657. }
  658. }
  659. else if (entry->d_type == DT_DIR)
  660. {
  661. deleted += removeFolder(path.c_str(), logTag);
  662. }
  663. }
  664. closedir(dir);
  665. if (rmdir(folderPath) != 0)
  666. {
  667. ESP_LOGE(logTag, "can't delete folder: %s", folderPath);
  668. }
  669. ESP_LOGD(logTag, "%d files in folder %s deleted.", deleted, folderPath);
  670. return deleted;
  671. }
  672. std::vector<string> HelperZerlegeZeile(std::string input, std::string _delimiter = "")
  673. {
  674. std::vector<string> Output;
  675. std::string delimiter = " =,";
  676. if (_delimiter.length() > 0)
  677. {
  678. delimiter = _delimiter;
  679. }
  680. return ZerlegeZeile(input, delimiter);
  681. }
  682. std::vector<string> ZerlegeZeile(std::string input, std::string delimiter)
  683. {
  684. std::vector<string> Output;
  685. /* The input can have multiple formats:
  686. * - key = value
  687. * - key = value1 value2 value3 ...
  688. * - key value1 value2 value3 ...
  689. *
  690. * Examples:
  691. * - ImageSize = VGA
  692. * - IO0 = input disabled 10 false false
  693. * - main.dig1 28 144 55 100 false
  694. *
  695. * This causes issues eg. if a password key has a whitespace or equal sign in its value.
  696. * As a workaround and to not break any legacy usage, we enforce to only use the
  697. * equal sign, if the key is "password"
  698. */
  699. if ((input.find("password") != string::npos) || (input.find("Token") != string::npos))
  700. {
  701. // Line contains a password, use the equal sign as the only delimiter and only split on first occurrence
  702. size_t pos = input.find("=");
  703. Output.push_back(trim(input.substr(0, pos), ""));
  704. Output.push_back(trim(input.substr(pos + 1, string::npos), ""));
  705. }
  706. else
  707. {
  708. // Legacy Mode
  709. input = trim(input, delimiter); // sonst werden delimiter am Ende (z.B. == im Token) gelöscht)
  710. size_t pos = findDelimiterPos(input, delimiter);
  711. std::string token;
  712. while (pos != std::string::npos)
  713. {
  714. token = input.substr(0, pos);
  715. token = trim(token, delimiter);
  716. Output.push_back(token);
  717. input.erase(0, pos + 1);
  718. input = trim(input, delimiter);
  719. pos = findDelimiterPos(input, delimiter);
  720. }
  721. Output.push_back(input);
  722. }
  723. return Output;
  724. }
  725. std::string ReplaceString(std::string subject, const std::string &search, const std::string &replace)
  726. {
  727. size_t pos = 0;
  728. while ((pos = subject.find(search, pos)) != std::string::npos)
  729. {
  730. subject.replace(pos, search.length(), replace);
  731. pos += replace.length();
  732. }
  733. return subject;
  734. }
  735. /* Source: https://git.kernel.org/pub/scm/utils/mmc/mmc-utils.git/tree/lsmmc.c */
  736. /* SD Card Manufacturer Database */
  737. struct SDCard_Manufacturer_database
  738. {
  739. string type;
  740. int id;
  741. string manufacturer;
  742. };
  743. /* Source: https://git.kernel.org/pub/scm/utils/mmc/mmc-utils.git/tree/lsmmc.c */
  744. /* SD Card Manufacturer Database */
  745. struct SDCard_Manufacturer_database sd_database[] = {
  746. {
  747. .type = "sd",
  748. .id = 0x01,
  749. .manufacturer = "Panasonic",
  750. },
  751. {
  752. .type = "sd",
  753. .id = 0x02,
  754. .manufacturer = "Toshiba/Kingston/Viking",
  755. },
  756. {
  757. .type = "sd",
  758. .id = 0x03,
  759. .manufacturer = "SanDisk",
  760. },
  761. {
  762. .type = "sd",
  763. .id = 0x05,
  764. .manufacturer = "Lenovo",
  765. },
  766. {
  767. .type = "sd",
  768. .id = 0x08,
  769. .manufacturer = "Silicon Power",
  770. },
  771. {
  772. .type = "sd",
  773. .id = 0x09,
  774. .manufacturer = "ATP",
  775. },
  776. {
  777. .type = "sd",
  778. .id = 0x18,
  779. .manufacturer = "Infineon",
  780. },
  781. {
  782. .type = "sd",
  783. .id = 0x1b,
  784. .manufacturer = "Transcend/Samsung",
  785. },
  786. {
  787. .type = "sd",
  788. .id = 0x1c,
  789. .manufacturer = "Transcend",
  790. },
  791. {
  792. .type = "sd",
  793. .id = 0x1d,
  794. .manufacturer = "Corsair/AData",
  795. },
  796. {
  797. .type = "sd",
  798. .id = 0x1e,
  799. .manufacturer = "Transcend",
  800. },
  801. {
  802. .type = "sd",
  803. .id = 0x1f,
  804. .manufacturer = "Kingston",
  805. },
  806. {
  807. .type = "sd",
  808. .id = 0x27,
  809. .manufacturer = "Delkin/Phison",
  810. },
  811. {
  812. .type = "sd",
  813. .id = 0x28,
  814. .manufacturer = "Lexar",
  815. },
  816. {
  817. .type = "sd",
  818. .id = 0x30,
  819. .manufacturer = "SanDisk",
  820. },
  821. {
  822. .type = "sd",
  823. .id = 0x31,
  824. .manufacturer = "Silicon Power",
  825. },
  826. {
  827. .type = "sd",
  828. .id = 0x33,
  829. .manufacturer = "STMicroelectronics",
  830. },
  831. {
  832. .type = "sd",
  833. .id = 0x41,
  834. .manufacturer = "Kingston",
  835. },
  836. {
  837. .type = "sd",
  838. .id = 0x6f,
  839. .manufacturer = "STMicroelectronics",
  840. },
  841. {
  842. .type = "sd",
  843. .id = 0x74,
  844. .manufacturer = "Transcend",
  845. },
  846. {
  847. .type = "sd",
  848. .id = 0x76,
  849. .manufacturer = "Patriot",
  850. },
  851. {
  852. .type = "sd",
  853. .id = 0x82,
  854. .manufacturer = "Gobe/Sony",
  855. },
  856. {
  857. .type = "sd",
  858. .id = 0x89,
  859. .manufacturer = "Netac",
  860. },
  861. {
  862. .type = "sd",
  863. .id = 0x9f,
  864. .manufacturer = "Kingston/Kodak/Silicon Power",
  865. },
  866. {
  867. .type = "sd",
  868. .id = 0xad,
  869. .manufacturer = "Amazon Basics/Lexar/OV",
  870. },
  871. {
  872. .type = "sd",
  873. .id = 0xdf,
  874. .manufacturer = "Lenovo",
  875. },
  876. {
  877. .type = "sd",
  878. .id = 0xfe,
  879. .manufacturer = "Bekit/Cloudisk/HP/Reletech",
  880. },
  881. };
  882. struct SDCard_Manufacturer_database mmc_database[] = {
  883. {
  884. .type = "mmc",
  885. .id = 0x00,
  886. .manufacturer = "SanDisk",
  887. },
  888. {
  889. .type = "mmc",
  890. .id = 0x02,
  891. .manufacturer = "Kingston/SanDisk",
  892. },
  893. {
  894. .type = "mmc",
  895. .id = 0x03,
  896. .manufacturer = "Toshiba",
  897. },
  898. {
  899. .type = "mmc",
  900. .id = 0x05,
  901. .manufacturer = "Unknown",
  902. },
  903. {
  904. .type = "mmc",
  905. .id = 0x06,
  906. .manufacturer = "Unknown",
  907. },
  908. {
  909. .type = "mmc",
  910. .id = 0x11,
  911. .manufacturer = "Toshiba",
  912. },
  913. {
  914. .type = "mmc",
  915. .id = 0x13,
  916. .manufacturer = "Micron",
  917. },
  918. {
  919. .type = "mmc",
  920. .id = 0x15,
  921. .manufacturer = "Samsung/SanDisk/LG",
  922. },
  923. {
  924. .type = "mmc",
  925. .id = 0x37,
  926. .manufacturer = "KingMax",
  927. },
  928. {
  929. .type = "mmc",
  930. .id = 0x44,
  931. .manufacturer = "ATP",
  932. },
  933. {
  934. .type = "mmc",
  935. .id = 0x45,
  936. .manufacturer = "SanDisk Corporation",
  937. },
  938. {
  939. .type = "mmc",
  940. .id = 0x2c,
  941. .manufacturer = "Kingston",
  942. },
  943. {
  944. .type = "mmc",
  945. .id = 0x70,
  946. .manufacturer = "Kingston",
  947. },
  948. {
  949. .type = "mmc",
  950. .id = 0xfe,
  951. .manufacturer = "Micron",
  952. },
  953. };
  954. /* Parse SD Card Manufacturer Database */
  955. string SDCardParseManufacturerIDs(int id)
  956. {
  957. if (SDCardIsMMC)
  958. {
  959. unsigned int id_cnt = sizeof(mmc_database) / sizeof(struct SDCard_Manufacturer_database);
  960. string ret_val = "";
  961. for (int i = 0; i < id_cnt; i++)
  962. {
  963. if (mmc_database[i].id == id)
  964. {
  965. return mmc_database[i].manufacturer;
  966. }
  967. else
  968. {
  969. ret_val = "ID unknown (not in DB)";
  970. }
  971. }
  972. return ret_val;
  973. }
  974. else
  975. {
  976. unsigned int id_cnt = sizeof(sd_database) / sizeof(struct SDCard_Manufacturer_database);
  977. string ret_val = "";
  978. for (int i = 0; i < id_cnt; i++)
  979. {
  980. if (sd_database[i].id == id)
  981. {
  982. return sd_database[i].manufacturer;
  983. }
  984. else
  985. {
  986. ret_val = "ID unknown (not in DB)";
  987. }
  988. }
  989. return ret_val;
  990. }
  991. }
  992. string RundeOutput(double _in, int _anzNachkomma)
  993. {
  994. std::stringstream stream;
  995. int _zw = _in;
  996. // ESP_LOGD(TAG, "AnzNachkomma: %d", _anzNachkomma);
  997. if (_anzNachkomma > 0)
  998. {
  999. stream << std::fixed << std::setprecision(_anzNachkomma) << _in;
  1000. }
  1001. else
  1002. {
  1003. stream << _zw;
  1004. }
  1005. return stream.str();
  1006. }
  1007. string getMac(void)
  1008. {
  1009. uint8_t macInt[6];
  1010. char macFormated[6 * 2 + 5 + 1]; // AA:BB:CC:DD:EE:FF
  1011. esp_read_mac(macInt, ESP_MAC_WIFI_STA);
  1012. sprintf(macFormated, "%02X:%02X:%02X:%02X:%02X:%02X", macInt[0], macInt[1], macInt[2], macInt[3], macInt[4], macInt[5]);
  1013. return macFormated;
  1014. }
  1015. void setSystemStatusFlag(SystemStatusFlag_t flag)
  1016. {
  1017. systemStatus = systemStatus | flag; // set bit
  1018. char buf[20];
  1019. snprintf(buf, sizeof(buf), "0x%08X", getSystemStatus());
  1020. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "New System Status: " + std::string(buf));
  1021. }
  1022. void clearSystemStatusFlag(SystemStatusFlag_t flag)
  1023. {
  1024. systemStatus = systemStatus | ~flag; // clear bit
  1025. char buf[20];
  1026. snprintf(buf, sizeof(buf), "0x%08X", getSystemStatus());
  1027. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "New System Status: " + std::string(buf));
  1028. }
  1029. int getSystemStatus(void)
  1030. {
  1031. return systemStatus;
  1032. }
  1033. bool isSetSystemStatusFlag(SystemStatusFlag_t flag)
  1034. {
  1035. // ESP_LOGE(TAG, "Flag (0x%08X) is set (0x%08X): %d", flag, systemStatus , ((systemStatus & flag) == flag));
  1036. if ((systemStatus & flag) == flag)
  1037. {
  1038. return true;
  1039. }
  1040. else
  1041. {
  1042. return false;
  1043. }
  1044. }
  1045. time_t getUpTime(void)
  1046. {
  1047. return (uint32_t)(esp_timer_get_time() / 1000 / 1000); // in seconds
  1048. }
  1049. string getResetReason(void)
  1050. {
  1051. std::string reasonText;
  1052. switch (esp_reset_reason())
  1053. {
  1054. case ESP_RST_POWERON:
  1055. reasonText = "Power-on event (or reset button)";
  1056. break; //!< Reset due to power-on event
  1057. case ESP_RST_EXT:
  1058. reasonText = "External pin";
  1059. break; //!< Reset by external pin (not applicable for ESP32)
  1060. case ESP_RST_SW:
  1061. reasonText = "Via esp_restart";
  1062. break; //!< Software reset via esp_restart
  1063. case ESP_RST_PANIC:
  1064. reasonText = "Exception/panic";
  1065. break; //!< Software reset due to exception/panic
  1066. case ESP_RST_INT_WDT:
  1067. reasonText = "Interrupt watchdog";
  1068. break; //!< Reset (software or hardware) due to interrupt watchdog
  1069. case ESP_RST_TASK_WDT:
  1070. reasonText = "Task watchdog";
  1071. break; //!< Reset due to task watchdog
  1072. case ESP_RST_WDT:
  1073. reasonText = "Other watchdogs";
  1074. break; //!< Reset due to other watchdogs
  1075. case ESP_RST_DEEPSLEEP:
  1076. reasonText = "Exiting deep sleep mode";
  1077. break; //!< Reset after exiting deep sleep mode
  1078. case ESP_RST_BROWNOUT:
  1079. reasonText = "Brownout";
  1080. break; //!< Brownout reset (software or hardware)
  1081. case ESP_RST_SDIO:
  1082. reasonText = "SDIO";
  1083. break; //!< Reset over SDIO
  1084. case ESP_RST_UNKNOWN: //!< Reset reason can not be determined
  1085. default:
  1086. reasonText = "Unknown";
  1087. }
  1088. return reasonText;
  1089. }
  1090. /**
  1091. * Returns the current uptime formated ad xxf xxh xxm [xxs]
  1092. */
  1093. std::string getFormatedUptime(bool compact)
  1094. {
  1095. char buf[20];
  1096. #pragma GCC diagnostic ignored "-Wformat-truncation"
  1097. int uptime = getUpTime(); // in seconds
  1098. int days = int(floor(uptime / (3600 * 24)));
  1099. int hours = int(floor((uptime - days * 3600 * 24) / (3600)));
  1100. int minutes = int(floor((uptime - days * 3600 * 24 - hours * 3600) / (60)));
  1101. int seconds = uptime - days * 3600 * 24 - hours * 3600 - minutes * 60;
  1102. if (compact)
  1103. {
  1104. snprintf(buf, sizeof(buf), "%dd%02dh%02dm%02ds", days, hours, minutes, seconds);
  1105. }
  1106. else
  1107. {
  1108. snprintf(buf, sizeof(buf), "%3dd %02dh %02dm %02ds", days, hours, minutes, seconds);
  1109. }
  1110. return std::string(buf);
  1111. }
  1112. const char *get404(void)
  1113. {
  1114. return "<pre>\n\n\n\n"
  1115. " _\n"
  1116. " .__(.)< ( oh oh! This page does not exist! )\n"
  1117. " \\___)\n"
  1118. "\n\n"
  1119. " You could try your <a href=index.html target=_parent>luck</a> here!</pre>\n"
  1120. "<script>document.cookie = \"page=overview.html\"</script>"; // Make sure we load the overview page
  1121. }
  1122. std::string UrlDecode(const std::string &value)
  1123. {
  1124. std::string result;
  1125. result.reserve(value.size());
  1126. for (std::size_t i = 0; i < value.size(); ++i)
  1127. {
  1128. auto ch = value[i];
  1129. if (ch == '%' && (i + 2) < value.size())
  1130. {
  1131. auto hex = value.substr(i + 1, 2);
  1132. auto dec = static_cast<char>(std::strtol(hex.c_str(), nullptr, 16));
  1133. result.push_back(dec);
  1134. i += 2;
  1135. }
  1136. else if (ch == '+')
  1137. {
  1138. result.push_back(' ');
  1139. }
  1140. else
  1141. {
  1142. result.push_back(ch);
  1143. }
  1144. }
  1145. return result;
  1146. }
  1147. bool replaceString(std::string &s, std::string const &toReplace, std::string const &replaceWith)
  1148. {
  1149. return replaceString(s, toReplace, replaceWith, true);
  1150. }
  1151. bool replaceString(std::string &s, std::string const &toReplace, std::string const &replaceWith, bool logIt)
  1152. {
  1153. std::size_t pos = s.find(toReplace);
  1154. if (pos == std::string::npos)
  1155. {
  1156. // Not found
  1157. return false;
  1158. }
  1159. std::string old = s;
  1160. s.replace(pos, toReplace.length(), replaceWith);
  1161. if (logIt)
  1162. {
  1163. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Migrated Configfile line '" + old + "' to '" + s + "'");
  1164. }
  1165. return true;
  1166. }
  1167. bool isInString(std::string &s, std::string const &toFind)
  1168. {
  1169. std::size_t pos = s.find(toFind);
  1170. if (pos == std::string::npos)
  1171. {
  1172. // Not found
  1173. return false;
  1174. }
  1175. return true;
  1176. }
  1177. // from https://stackoverflow.com/a/14678800
  1178. void replaceAll(std::string& s, const std::string& toReplace, const std::string& replaceWith)
  1179. {
  1180. size_t pos = 0;
  1181. while ((pos = s.find(toReplace, pos)) != std::string::npos)
  1182. {
  1183. s.replace(pos, toReplace.length(), replaceWith);
  1184. pos += replaceWith.length();
  1185. }
  1186. }
  1187. bool isStringNumeric(std::string &input)
  1188. {
  1189. if (input.size() <= 0)
  1190. {
  1191. return false;
  1192. }
  1193. // Replace comma with a dot
  1194. replaceString(input, ",", ".", false);
  1195. int start = 0;
  1196. int punkt_existiert_schon = 0;
  1197. if (input[0] == '-')
  1198. {
  1199. start = 1;
  1200. }
  1201. for (int i = start; i < input.size(); i++)
  1202. {
  1203. if ((input[i] == '.') && (i > 0) && (punkt_existiert_schon == 0))
  1204. {
  1205. punkt_existiert_schon = 1;
  1206. i++;
  1207. }
  1208. else if (!isdigit(input[i]))
  1209. {
  1210. return false;
  1211. }
  1212. }
  1213. return true;
  1214. }
  1215. bool isStringAlphabetic(std::string &input)
  1216. {
  1217. for (int i = 0; i < input.size(); i++)
  1218. {
  1219. if (!isalpha(input[i]))
  1220. {
  1221. return false;
  1222. }
  1223. }
  1224. return true;
  1225. }
  1226. bool isStringAlphanumeric(std::string &input)
  1227. {
  1228. for (int i = 0; i < input.size(); i++)
  1229. {
  1230. if (!isalnum(input[i]))
  1231. {
  1232. return false;
  1233. }
  1234. }
  1235. return true;
  1236. }
  1237. bool alphanumericToBoolean(std::string &input)
  1238. {
  1239. if (isStringAlphabetic(input))
  1240. {
  1241. return stringToBoolean(toUpper(input));
  1242. }
  1243. else if (isStringNumeric(input))
  1244. {
  1245. return numericStrToBool(input);
  1246. }
  1247. return false;
  1248. }
  1249. int clipInt(int input, int high, int low)
  1250. {
  1251. if (input < low)
  1252. {
  1253. input = low;
  1254. }
  1255. else if (input > high)
  1256. {
  1257. input = high;
  1258. }
  1259. return input;
  1260. }
  1261. bool numericStrToBool(std::string input)
  1262. {
  1263. return (std::stoi(input) != 0);
  1264. }
  1265. bool stringToBoolean(std::string input)
  1266. {
  1267. return (input == "TRUE");
  1268. }