From 43cbaf75cb992260a620a6d67c6a5885eaf85c5c Mon Sep 17 00:00:00 2001 From: George Alexandre Silva Date: Mon, 18 Sep 2023 22:43:54 -0300 Subject: [PATCH 1/4] Touch, Sprites fix to small heap, Suffix adj. --- platformio.ini | 11 +- src/drivers/displays/esp23_2432s028r.cpp | 337 +++++++++++++++-------- src/monitor.cpp | 21 +- src/monitor.h | 2 +- 4 files changed, 241 insertions(+), 130 deletions(-) diff --git a/platformio.ini b/platformio.ini index aad639e..b039650 100644 --- a/platformio.ini +++ b/platformio.ini @@ -170,8 +170,8 @@ upload_speed = 921600 ;build_type = debug board_build.partitions = huge_app.csv build_flags = - -D ESP32_2432S028R=1 - -DCORE_DEBUG_LEVEL=ARDUHAL_LOG_LEVEL_DEBUG + ;-DDEBUG_MEMORY=1 + -D ESP32_2432S028R=1 -DUSER_SETUP_LOADED=1 -DILI9341_2_DRIVER=1 -DTFT_WIDTH=240 @@ -183,7 +183,11 @@ build_flags = -DTFT_DC=2 -DTFT_RST=12 -DTFT_BL=21 - -DTOUCH_CS=33 + -DETOUCH_CS=33 + -DTOUCH_CLK=25 + -DTOUCH_MISO=39 + -DTOUCH_MOSI=32 + -DTOUCH_IRQ=36 -DLOAD_GLCD=1 -DLOAD_FONT2=1 -DLOAD_GFXFF=1 @@ -198,6 +202,7 @@ lib_deps = mathertel/OneButton @ ^2.0.3 arduino-libraries/NTPClient bodmer/TFT_eSPI @ ^2.5.31 + https://github.com/achillhasler/TFT_eTouch [env:NerdminerV2-T-Display_V1] platform = espressif32 diff --git a/src/drivers/displays/esp23_2432s028r.cpp b/src/drivers/displays/esp23_2432s028r.cpp index 1221b72..e87a279 100644 --- a/src/drivers/displays/esp23_2432s028r.cpp +++ b/src/drivers/displays/esp23_2432s028r.cpp @@ -3,6 +3,7 @@ #ifdef ESP32_2432S028R #include +#include #include "media/images_320_170.h" #include "media/images_bottom_320_70.h" #include "media/myFonts.h" @@ -10,39 +11,52 @@ #include "version.h" #include "monitor.h" #include "OpenFontRender.h" +#include -#define WIDTH 340 -#define HEIGHT 240 +#define WIDTH 130 //320 +#define HEIGHT 170 OpenFontRender render; -TFT_eSPI tft = TFT_eSPI(); // Invoke library, pins defined in User_Setup.h +TFT_eSPI tft = TFT_eSPI(); // Invoke library, pins defined in platformio.ini TFT_eSprite background = TFT_eSprite(&tft); // Invoke library sprite +SPIClass hSPI(HSPI); +TFT_eTouch touch(tft, ETOUCH_CS, 0xFF, hSPI); extern monitor_data mMonitor; extern pool_data pData; +extern DisplayDriver *currentDisplayDriver; + +bool hasChangedScreen = true; void esp32_2432S028R_Init(void) -{ +{ tft.init(); tft.setRotation(1); - tft.setSwapBytes(true); // Swap the colour byte order when rendering + tft.setSwapBytes(true); // Swap the colour byte order when rendering + hSPI.begin(TOUCH_CLK, TOUCH_MISO, TOUCH_MOSI, ETOUCH_CS); + touch.init(); + + TFT_eTouchBase::Calibation calibation = { 233, 3785, 3731, 120, 2 }; + touch.setCalibration(calibation); + //background.createSprite(WIDTH, HEIGHT); // Background Sprite background.setSwapBytes(true); render.setDrawer(background); // Link drawing object to background instance (so font will be rendered on background) render.setLineSpaceRatio(0.9); // Espaciado entre texto // Load the font and check it can be read OK - // if (render.loadFont(NotoSans_Bold, sizeof(NotoSans_Bold))) { + // if (render.loadFont(NotoSans_Bold, sizeof(NotoSans_Bold))) if (render.loadFont(DigitalNumbers, sizeof(DigitalNumbers))) { Serial.println("Initialise error"); return; } + pinMode(LED_PIN, OUTPUT); pData.bestDifficulty = "0"; pData.workersHash = "0"; pData.workersCount = 0; - + //Serial.println("=========== Fim Display ==============") ; } void esp32_2432S028R_AlternateScreenState(void) @@ -55,15 +69,21 @@ void esp32_2432S028R_AlternateScreenState(void) void esp32_2432S028R_AlternateRotation(void) { tft.getRotation() == 1 ? tft.setRotation(3) : tft.setRotation(1); + hasChangedScreen = true; } +bool bottomScreenBlue = true; + void printPoolData(){ - pData = updatePoolData(); + pData = getPoolData(); background.createSprite(320,70); //Background Sprite background.setSwapBytes(true); - background.pushImage(0, 0, 320, 70, bottonPoolScreen); - + if (bottomScreenBlue) { + background.pushImage(0, 0, 320, 70, bottonPoolScreen); + } else { + background.pushImage(0, 0, 320, 70, bottonPoolScreen_g); + } //background.setTextDatum(MC_DATUM); render.setDrawer(background); // Link drawing object to background instance (so font will be rendered on background) render.setLineSpaceRatio(1); @@ -80,118 +100,150 @@ void printPoolData(){ background.deleteSprite(); } -void esp32_2432S028R_MinerScreen(unsigned long mElapsed) -{ - mining_data data = getMiningData(mElapsed); - - // Create background sprite to print data at once - background.createSprite(initWidth,initHeight); //Background Sprite +void printheap(){ + //Serial.print("============ Free Heap:"); + //Serial.println(ESP.getFreeHeap()); +} + +void createBackgroundSprite(int16_t wdt, int16_t hgt){ // Set the background and link the render, used multiple times to fit in heap + background.createSprite(wdt, hgt) ; //Background Sprite + printheap(); background.setColorDepth(16); background.setSwapBytes(true); render.setDrawer(background); // Link drawing object to background instance (so font will be rendered on background) render.setLineSpaceRatio(0.9); - +} + +void esp32_2432S028R_MinerScreen(unsigned long mElapsed) +{ + if (hasChangedScreen) tft.pushImage(0, 0, initWidth, initHeight, MinerScreen); + hasChangedScreen = false; + + mining_data data = getMiningData(mElapsed); + + //Serial.println("Proximo sprite..."); + int wdtOffset = 190; + // Recreate sprite to the right side of the screen + createBackgroundSprite(WIDTH-5, HEIGHT-7); //Print background screen - background.pushImage(0, 0, MinerWidth, MinerHeight, MinerScreen); + background.pushImage(-190, 0, MinerWidth, MinerHeight, MinerScreen); + + // Total hashes + render.setFontSize(18); + render.rdrawString(data.totalMHashes.c_str(), 268-wdtOffset, 138, TFT_BLACK); + // Block templates + render.setFontSize(18); + render.drawString(data.templates.c_str(), 189-wdtOffset, 20, 0xDEDB); + // Best diff + render.drawString(data.bestDiff.c_str(), 189-wdtOffset, 48, 0xDEDB); + // 32Bit shares + render.setFontSize(18); + render.drawString(data.completedShares.c_str(), 189-wdtOffset, 76, 0xDEDB); + // Hores + render.setFontSize(14); + render.rdrawString(data.timeMining.c_str(), 315-wdtOffset, 104, 0xDEDB); + + // Valid Blocks + render.setFontSize(24); + render.drawString(data.valids.c_str(), 285-wdtOffset, 56, 0xDEDB); + + // Print Temp + render.setFontSize(10); + render.rdrawString(data.temp.c_str(), 239-wdtOffset, 1, TFT_BLACK); + + render.setFontSize(4); + render.rdrawString(String(0).c_str(), 244-wdtOffset, 3, TFT_BLACK); + + // Print Hour + render.setFontSize(10); + render.rdrawString(data.currentTime.c_str(), 286-wdtOffset, 1, TFT_BLACK); + + // Push prepared background to screen + background.pushSprite(190, 0); + + // Delete sprite to free the memory heap + background.deleteSprite(); + printheap(); + + //Serial.println("=========== Mining Display ==============") ; + // Create background sprite to print data at once + createBackgroundSprite(WIDTH-7, HEIGHT-100); // initHeight); //Background Sprite + //Print background screen + background.pushImage(0, -90, MinerWidth, MinerHeight, MinerScreen); Serial.printf(">>> Completed %s share(s), %s Khashes, avg. hashrate %s KH/s\n", data.completedShares.c_str(), data.totalKHashes.c_str(), data.currentHashRate.c_str()); - // Hashrate + // Hashrate render.setFontSize(35); render.setCursor(19, 118); render.setFontColor(TFT_BLACK); - - render.rdrawString(data.currentHashRate.c_str(), 118, 114, TFT_BLACK); - // Total hashes - render.setFontSize(18); - render.rdrawString(data.totalMHashes.c_str(), 268, 138, TFT_BLACK); - // Block templates - render.setFontSize(18); - render.drawString(data.templates.c_str(), 186, 20, 0xDEDB); - // Best diff - render.drawString(data.bestDiff.c_str(), 186, 48, 0xDEDB); - // 32Bit shares - render.setFontSize(18); - render.drawString(data.completedShares.c_str(), 186, 76, 0xDEDB); - // Hores - render.setFontSize(14); - render.rdrawString(data.timeMining.c_str(), 315, 104, 0xDEDB); - - // Valid Blocks - render.setFontSize(24); - render.drawString(data.valids.c_str(), 285, 56, 0xDEDB); - - // Print Temp - render.setFontSize(10); - render.rdrawString(data.temp.c_str(), 239, 1, TFT_BLACK); - - render.setFontSize(4); - render.rdrawString(String(0).c_str(), 244, 3, TFT_BLACK); - - // Print Hour - render.setFontSize(10); - render.rdrawString(data.currentTime.c_str(), 286, 1, TFT_BLACK); - + render.rdrawString(data.currentHashRate.c_str(), 118, 114-90, TFT_BLACK); + // Push prepared background to screen - background.pushSprite(0, 0); - + background.pushSprite(0, 90); + // Delete sprite to free the memory heap - background.deleteSprite(); - - #ifdef ESP32_2432S028R - printPoolData(); - #endif + background.deleteSprite(); + //delay(50); + + printPoolData(); #ifdef DEBUG_MEMORY - // Print heap - printheap(); + // Print heap + printheap(); #endif } void esp32_2432S028R_ClockScreen(unsigned long mElapsed) { + + if (hasChangedScreen) tft.pushImage(0, 0, minerClockWidth, minerClockHeight, minerClockScreen); + hasChangedScreen = false; + clock_data data = getClockData(mElapsed); - // Create background sprite to print data at once - background.createSprite(initWidth,initHeight); //Background Sprite - background.setColorDepth(16); - background.setSwapBytes(true); - render.setDrawer(background); // Link drawing object to background instance (so font will be rendered on background) - render.setLineSpaceRatio(0.9); - - // Print background screen - background.pushImage(0, 0, minerClockWidth, minerClockHeight, minerClockScreen); - Serial.printf(">>> Completed %s share(s), %s Khashes, avg. hashrate %s KH/s\n", data.completedShares.c_str(), data.totalKHashes.c_str(), data.currentHashRate.c_str()); + // Create background sprite to print data at once + createBackgroundSprite(270,36); + + // Print background screen + background.pushImage(0, -130, minerClockWidth, minerClockHeight, minerClockScreen); // Hashrate render.setFontSize(25); - render.setCursor(19, 122); render.setFontColor(TFT_BLACK); - render.rdrawString(data.currentHashRate.c_str(), 94, 129, TFT_BLACK); + render.rdrawString(data.currentHashRate.c_str(), 95, 0, TFT_BLACK); + // Print BlockHeight + render.setFontSize(18); + render.rdrawString(data.blockHeight.c_str(), 254, 9, TFT_BLACK); + + // Push prepared background to screen + background.pushSprite(0, 130); + // Delete sprite to free the memory heap + background.deleteSprite(); + + createBackgroundSprite(169,105); + // Print background screen + background.pushImage(-130, -3, minerClockWidth, minerClockHeight, minerClockScreen); + // Print BTC Price background.setFreeFont(FSSB9); background.setTextSize(1); background.setTextDatum(TL_DATUM); background.setTextColor(TFT_BLACK); - background.drawString(data.btcPrice.c_str(), 202, 3, GFXFF); - - // Print BlockHeight - render.setFontSize(18); - render.rdrawString(data.blockHeight.c_str(), 254, 140, TFT_BLACK); - + background.drawString(data.btcPrice.c_str(), 202-130, 0, GFXFF); + // Print Hour background.setFreeFont(FF23); background.setTextSize(2); background.setTextColor(0xDEDB, TFT_BLACK); - - background.drawString(data.currentTime.c_str(), 130, 50, GFXFF); - + background.drawString(data.currentTime.c_str(), 0, 50, GFXFF); + // Push prepared background to screen - background.pushSprite(0, 0); + background.pushSprite(130, 3); // Delete sprite to free the memory heap background.deleteSprite(); @@ -208,17 +260,15 @@ void esp32_2432S028R_ClockScreen(unsigned long mElapsed) void esp32_2432S028R_GlobalHashScreen(unsigned long mElapsed) { + if (hasChangedScreen) tft.pushImage(0, 0, globalHashWidth, globalHashHeight, globalHashScreen); + hasChangedScreen = false; coin_data data = getCoinData(mElapsed); // Create background sprite to print data at once - background.createSprite(initWidth,initHeight); //Background Sprite - background.setColorDepth(16); - background.setSwapBytes(true); - render.setDrawer(background); // Link drawing object to background instance (so font will be rendered on background) - render.setLineSpaceRatio(0.9); - + createBackgroundSprite(169,105); // Print background screen - background.pushImage(0, 0, globalHashWidth, globalHashHeight, globalHashScreen); + background.pushImage(-160, -3, minerClockWidth, minerClockHeight, globalHashScreen); + //background.fillScreen(TFT_BLUE); Serial.printf(">>> Completed %s share(s), %s Khashes, avg. hashrate %s KH/s\n", data.completedShares.c_str(), data.totalKHashes.c_str(), data.currentHashRate.c_str()); @@ -228,52 +278,68 @@ void esp32_2432S028R_GlobalHashScreen(unsigned long mElapsed) background.setTextSize(1); background.setTextDatum(TL_DATUM); background.setTextColor(TFT_BLACK); - background.drawString(data.btcPrice.c_str(), 198, 3, GFXFF); - + background.drawString(data.btcPrice.c_str(), 198-160, 0, GFXFF); // Print Hour background.setFreeFont(FSSB9); background.setTextSize(1); background.setTextDatum(TL_DATUM); background.setTextColor(TFT_BLACK); - background.drawString(data.currentTime.c_str(), 268, 3, GFXFF); + background.drawString(data.currentTime.c_str(), 268-160, 0, GFXFF); // Print Last Pool Block background.setFreeFont(FSS9); background.setTextDatum(TR_DATUM); background.setTextColor(0x9C92); - background.drawString(data.halfHourFee.c_str(), 302, 52, GFXFF); + background.drawString(data.halfHourFee.c_str(), 302-160, 49, GFXFF); // Print Difficulty background.setFreeFont(FSS9); background.setTextDatum(TR_DATUM); background.setTextColor(0x9C92); - background.drawString(data.netwrokDifficulty.c_str(), 302, 88, GFXFF); - - // Print Global Hashrate - render.setFontSize(17); - render.rdrawString(data.globalHashRate.c_str(), 274, 145, TFT_BLACK); - - // Print BlockHeight - render.setFontSize(28); - render.rdrawString(data.blockHeight.c_str(), 140, 104, 0xDEDB); - - // Draw percentage rectangle - int x2 = 2 + (138 * data.progressPercent / 100); - background.fillRect(2, 149, x2, 168, 0xDEDB); - - // Print Remaining BLocks - background.setTextFont(FONT2); - background.setTextSize(1); - background.setTextDatum(MC_DATUM); - background.setTextColor(TFT_BLACK); - background.drawString(data.remainingBlocks.c_str(), 72, 159, FONT2); - + background.drawString(data.netwrokDifficulty.c_str(), 302-160, 85, GFXFF); // Push prepared background to screen - background.pushSprite(0, 0); - + background.pushSprite(160, 3); // Delete sprite to free the memory heap background.deleteSprite(); + // Create background sprite to print data at once + createBackgroundSprite(280,30); + // Print background screen + background.pushImage(0, -139, minerClockWidth, minerClockHeight, globalHashScreen); + //background.fillSprite(TFT_CYAN); + // Print Global Hashrate + render.setFontSize(17); + render.rdrawString(data.globalHashRate.c_str(), 274, 145-139, TFT_BLACK); + + // Draw percentage rectangle + int x2 = 2 + (138 * data.progressPercent / 100); + background.fillRect(2, 149-139, x2, 168, 0xDEDB); + + // Print Remaining BLocks + background.setTextFont(FONT2); + background.setTextSize(1); + background.setTextDatum(MC_DATUM); + background.setTextColor(TFT_BLACK); + background.drawString(data.remainingBlocks.c_str(), 72, 159-139, FONT2); + + // Push prepared background to screen + background.pushSprite(0, 139); + // Delete sprite to free the memory heap + background.deleteSprite(); + + // Create background sprite to print data at once + createBackgroundSprite(140,40); + // Print background screen + background.pushImage(-5, -100, minerClockWidth, minerClockHeight, globalHashScreen); + //background.fillSprite(TFT_CYAN); + // Print BlockHeight + render.setFontSize(28); + render.rdrawString(data.blockHeight.c_str(), 140-5, 104-100, 0xDEDB); + + // Push prepared background to screen + background.pushSprite(5, 100); + // Delete sprite to free the memory heap + background.deleteSprite(); #ifdef ESP32_2432S028R printPoolData(); #endif @@ -292,6 +358,7 @@ void esp32_2432S028R_LoadingScreen(void) tft.drawString(CURRENT_VERSION, 24, 147, FONT2); delay(2000); tft.fillScreen(TFT_BLACK); + tft.pushImage(0, 0, initWidth, initHeight, MinerScreen); } void esp32_2432S028R_SetupScreen(void) @@ -305,10 +372,44 @@ void esp32_2432S028R_AnimateCurrentScreen(unsigned long frame) // Variables para controlar el parpadeo con millis() unsigned long previousMillis = 0; +unsigned long previousTouchMillis = 0; +char currentScreen = 0; void esp32_2432S028R_DoLedStuff(unsigned long frame) { - unsigned long currentMillis = millis(); + unsigned long currentMillis = millis(); + + // / Check the touch coordinates 110x185 210x240 + if (currentMillis - previousTouchMillis >= 500) + { + int16_t t_x , t_y; // To store the touch coordinates + bool pressed = touch.getXY(t_x, t_y); + if (pressed) { + if (((t_x > 109)&&(t_x < 211)) && ((t_y > 185)&&(t_y < 241))) bottomScreenBlue ^= true; + else + if (t_x > 160) { + // next screen + Serial.print(t_x); + Serial.print(":x Próxima Tela y:"); + Serial.println(t_y); + currentDisplayDriver->current_cyclic_screen = (currentDisplayDriver->current_cyclic_screen + 1) % currentDisplayDriver->num_cyclic_screens; + } else if (t_x < 160) + { + // Previus screen + Serial.print(t_x); + Serial.print(":x Tela anterior y:"); + Serial.println(t_y); + /* Serial.println(currentDisplayDriver->current_cyclic_screen); */ + currentDisplayDriver->current_cyclic_screen = currentDisplayDriver->current_cyclic_screen - 1; + if (currentDisplayDriver->current_cyclic_screen<0) currentDisplayDriver->current_cyclic_screen = currentDisplayDriver->num_cyclic_screens - 1; + Serial.println(currentDisplayDriver->current_cyclic_screen); + } + } + previousTouchMillis = currentMillis; + } + + if (currentScreen != currentDisplayDriver->current_cyclic_screen) hasChangedScreen ^= true; + currentScreen = currentDisplayDriver->current_cyclic_screen; switch (mMonitor.NerdStatus) { @@ -332,6 +433,8 @@ void esp32_2432S028R_DoLedStuff(unsigned long frame) } break; } + + } CyclicScreenFunction esp32_2432S028RCyclicScreens[] = {esp32_2432S028R_MinerScreen, esp32_2432S028R_ClockScreen, esp32_2432S028R_GlobalHashScreen}; diff --git a/src/monitor.cpp b/src/monitor.cpp index 34e6976..27753cd 100644 --- a/src/monitor.cpp +++ b/src/monitor.cpp @@ -287,7 +287,7 @@ coin_data getCoinData(unsigned long mElapsed) return data; } -pool_data updatePoolData(void){ +pool_data getPoolData(void){ //pool_data pData; if((mPoolUpdate == 0) || (millis() - mPoolUpdate > UPDATE_POOL_min * 60 * 1000)){ if (WiFi.status() != WL_CONNECTED) return pData; @@ -296,10 +296,12 @@ pool_data updatePoolData(void){ HTTPClient http; http.setReuse(true); try { - http.begin(String(getPublicPool)+btcString); + String btcWallet = btcString; + Serial.println(btcWallet); + if (btcWallet.indexOf(".")>0) btcWallet = btcWallet.substring(0,btcWallet.indexOf(".")); + http.begin(String(getPublicPool)+btcWallet); int httpCode = http.GET(); - - if (httpCode > 0) { + if (httpCode == HTTP_CODE_OK) { String payload = http.getString(); // Serial.println(payload); DynamicJsonDocument doc(1024); @@ -311,12 +313,13 @@ pool_data updatePoolData(void){ for (const JsonObject& worker : workers) { totalhashs += worker["hashRate"].as(); } - pData.workersHash = String(totalhashs/1000); - - String temp = ""; + pData.workersHash = String(totalhashs/1000); + double temp; if (doc.containsKey("bestDifficulty")) { - temp = doc["bestDifficulty"].as(); - pData.bestDifficulty = String(temp); + temp = doc["bestDifficulty"].as(); + char best_diff_string[16] = {0}; + suffix_string(temp, best_diff_string, 16, 0); + pData.bestDifficulty = String(best_diff_string); } doc.clear(); mPoolUpdate = millis(); diff --git a/src/monitor.h b/src/monitor.h index c8bd6e1..7331b3d 100644 --- a/src/monitor.h +++ b/src/monitor.h @@ -111,7 +111,7 @@ void setup_monitor(void); mining_data getMiningData(unsigned long mElapsed); clock_data getClockData(unsigned long mElapsed); coin_data getCoinData(unsigned long mElapsed); -pool_data updatePoolData(void); +pool_data getPoolData(void); clock_data_t getClockData_t(unsigned long mElapsed); From 56fc227c7c8b4afe47abff60b570de466c59c727 Mon Sep 17 00:00:00 2001 From: George Alexandre Silva Date: Tue, 19 Sep 2023 20:38:15 -0300 Subject: [PATCH 2/4] Revert "Merge branch 'dev' of https://github.com/BitMaker-hub/NerdMiner_v2 into dev" This reverts commit 16ffd47a671ebe0267bcf8960567832bfeda5b02, reversing changes made to 43cbaf75cb992260a620a6d67c6a5885eaf85c5c. --- .gitignore | 3 - README.md | 31 -- lib/TFT_eSPI/Processors/TFT_eSPI_ESP32_S3.h | 2 +- platformio.ini | 40 +- src/NerdMinerV2.ino.cpp | 14 +- src/drivers/devices/device.h | 27 -- src/drivers/devices/esp32CAM.h | 18 - src/drivers/{displays => }/display.cpp | 0 src/drivers/{displays => }/display.h | 2 +- src/drivers/displays/amoledDisplayDriver.cpp | 2 +- src/drivers/displays/dongleDisplayDriver.cpp | 8 +- src/drivers/displays/esp23_2432s028r.cpp | 2 +- src/drivers/displays/noDisplayDriver.cpp | 2 +- src/drivers/displays/tDisplayDriver.cpp | 2 +- src/drivers/displays/tDisplayV1Driver.cpp | 2 +- src/drivers/displays/t_qtDisplayDriver.cpp | 2 +- .../{displays/displayDriver.h => drivers.h} | 27 +- src/drivers/storage/SDCard.cpp | 157 ------- src/drivers/storage/SDCard.h | 38 -- src/drivers/storage/nvMemory.cpp | 148 ------ src/drivers/storage/nvMemory.h | 30 -- src/drivers/storage/storage.h | 35 -- src/mining.cpp | 28 +- src/monitor.cpp | 10 +- src/wManager.cpp | 431 +++++++++++------- src/wManager.h | 7 +- 26 files changed, 329 insertions(+), 739 deletions(-) delete mode 100644 src/drivers/devices/device.h delete mode 100644 src/drivers/devices/esp32CAM.h rename src/drivers/{displays => }/display.cpp (100%) rename src/drivers/{displays => }/display.h (94%) rename src/drivers/{displays/displayDriver.h => drivers.h} (73%) delete mode 100644 src/drivers/storage/SDCard.cpp delete mode 100644 src/drivers/storage/SDCard.h delete mode 100644 src/drivers/storage/nvMemory.cpp delete mode 100644 src/drivers/storage/nvMemory.h delete mode 100644 src/drivers/storage/storage.h diff --git a/.gitignore b/.gitignore index f7eadc5..bebd06e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,5 @@ .pio .vscode -.vs -*.sln -*.vcxproj* NerdMinerLog.txt bin/0x10000_firmware.bin logs diff --git a/README.md b/README.md index dd37a9c..e38bde5 100644 --- a/README.md +++ b/README.md @@ -44,7 +44,6 @@ Every time an stratum job notification is received miner update its current work - LILYGO T-Display S3 AMOLED ([Aliexpress link](https://s.click.aliexpress.com/e/_DmOIK6j)) - LILYGO T-Dongle S3 ([Aliexpress link](https://s.click.aliexpress.com/e/_DmQCPyj)) - ESP32-2432S028R 2,8" ([Aliexpress link](https://s.click.aliexpress.com/e/_DdXkvLv)) -- ESP32-cam [Board Info](https://lastminuteengineers.com/getting-started-with-esp32-cam/) ### Flash firmware #### microMiners Flashtool [Recommended] @@ -76,33 +75,12 @@ Update NerdMiner firmware following same flashing steps but only adding 0x10000_ ### NerdMiner configuration After programming, you will only need to setup your Wifi and BTC address. -#### Wifi Accesspoint - 1. Connect to NerdMinerAP - AP: NerdMinerAP - PASS: MineYourCoins 1. Setup your Wifi Network 1. Add your BTCaddress -#### SD card (if available) - -1. Format a SD card using Fat32. -1. Create a file named "config.json" in your card's root, containing the the following structure. Adjust the settings to your needs: -{ - "SSID": "myWifiSSID", - "PW": "myWifiPassword", - "PoolUrl": "public-pool.io", - "PoolPort": 21496, - "BtcWallet": "walletID", - "Timezone": 2, - "saveStats": false -} -1. Insert the SD card. -1. Hold down the "reset configurations" button as described below to reset the configurations and/or boot without settings in your nvmemory. -1. Power down to remove the SD card. It is not needed for mining. - -#### Pool selection - Recommended low difficulty share pools: | Pool URL | Port | Web URL | Status | @@ -121,15 +99,6 @@ Other standard pools not compatible with low difficulty share: | eu.stratum.slushpool.com | 3333 | https://braiins.com/pool | ### Buttons - -#### One button devices: - -- One click > change screen. -- Double click > change screen orientation. -- Tripple click > turn the screen off and on again. -- Hold 5 seconds > **reset the configurations and reboot** your NerdMiner. - -#### Two button devices: With the USB-C port to the right: **TOP BUTTON** diff --git a/lib/TFT_eSPI/Processors/TFT_eSPI_ESP32_S3.h b/lib/TFT_eSPI/Processors/TFT_eSPI_ESP32_S3.h index f090f24..4438fe9 100644 --- a/lib/TFT_eSPI/Processors/TFT_eSPI_ESP32_S3.h +++ b/lib/TFT_eSPI/Processors/TFT_eSPI_ESP32_S3.h @@ -375,7 +375,7 @@ SPI3_HOST = 2 if ( c & 0x20 ) xset_mask[c] |= (1 << (TFT_D5-MASK_OFFSET)); \ if ( c & 0x40 ) xset_mask[c] |= (1 << (TFT_D6-MASK_OFFSET)); \ if ( c & 0x80 ) xset_mask[c] |= (1 << (TFT_D7-MASK_OFFSET)); \ - } \ + } \ // Mask for the 8 data bits to set pin directions #define GPIO_DIR_MASK ((1 << (TFT_D0-MASK_OFFSET)) | (1 << (TFT_D1-MASK_OFFSET)) | (1 << (TFT_D2-MASK_OFFSET)) | (1 << (TFT_D3-MASK_OFFSET)) | (1 << (TFT_D4-MASK_OFFSET)) | (1 << (TFT_D5-MASK_OFFSET)) | (1 << (TFT_D6-MASK_OFFSET)) | (1 << (TFT_D7-MASK_OFFSET))) diff --git a/platformio.ini b/platformio.ini index ef7a08f..b039650 100644 --- a/platformio.ini +++ b/platformio.ini @@ -10,7 +10,7 @@ [platformio] globallib_dir = lib -default_envs = esp32cam, ESP32-2432S028R, NerminerV2, ESP32-devKitv1, NerminerV2-S3-DONGLE, NerminerV2-S3-AMOLED, NerminerV2-T-QT, NerdminerV2-T-Display_V1, ESP32-2432S028R +default_envs = ESP32-2432S028R ;NerminerV2, ESP32-devKitv1, NerminerV2-S3-DONGLE, NerminerV2-S3-AMOLED, NerminerV2-T-QT, NerdminerV2-T-Display_V1, ESP32-2432S028R [env:NerminerV2] platform = espressif32 @@ -23,11 +23,13 @@ monitor_filters = board_build.arduino.memory_type = qio_opi monitor_speed = 115200 upload_speed = 115200 + # 2 x 4.5MB app, 6.875MB SPIFFS ;board_build.partitions = large_spiffs_16MB.csv ;board_build.partitions = default_8MB.csv board_build.partitions = huge_app.csv ;board_build.partitions = default.csv + build_flags = -D LV_LVGL_H_INCLUDE_SIMPLE -D BOARD_HAS_PSRAM @@ -43,6 +45,7 @@ lib_deps = arduino-libraries/NTPClient ;https://github.com/golden-guy/Arduino_wolfssl.git#v5.5.4 + [env:ESP32-devKitv1] platform = espressif32 board = esp32dev @@ -54,8 +57,10 @@ monitor_filters = ;board_build.arduino.memory_type = qio_opi monitor_speed = 115200 upload_speed = 115200 + # 2 x 4.5MB app, 6.875MB SPIFFS board_build.partitions = huge_app.csv + build_flags = -D DEVKITV1=1 ;-D DEBUG_MINING=1 @@ -66,6 +71,7 @@ lib_deps = mathertel/OneButton @ ^2.0.3 arduino-libraries/NTPClient + [env:TTGO-T-Display] platform = espressif32 board = esp32dev ;esp-wrover-kit @@ -77,8 +83,11 @@ monitor_filters = board_build.arduino.memory_type = qio_opi monitor_speed = 115200 upload_speed = 115200 + + # 2 x 4.5MB app, 6.875MB SPIFFS board_build.partitions = huge_app.csv + build_flags = ;-D DEBUG_MINING=1 -D TDISPLAY=1 @@ -94,7 +103,9 @@ lib_deps = platform = espressif32 board = lilygo-t-amoled framework = arduino + board_build.partitions = huge_app.csv + build_flags = -DNERMINER_S3_AMOLED -DBOARD_HAS_PSRAM @@ -111,7 +122,9 @@ lib_deps = platform = espressif32 board = esp32-s3-devkitc-1 framework = arduino + board_build.partitions = huge_app.csv + build_flags = -DNERMINER_S3_DONGLE -DBOARD_HAS_PSRAM @@ -122,31 +135,8 @@ lib_deps = https://github.com/tzapu/WiFiManager.git mathertel/OneButton @ ^2.0.3 arduino-libraries/NTPClient + https://github.com/golden-guy/Arduino_wolfssl.git#v5.5.4 https://github.com/FastLED/FastLED - ;https://github.com/golden-guy/Arduino_wolfssl.git#v5.5.4 - -[env:esp32cam] -platform = espressif32 ;(ESP32-D0WD-V3) -board = esp32cam -framework = arduino -monitor_filters = - esp32_exception_decoder - time - log2file -monitor_speed = 115200 -upload_speed = 921600 -board_build.partitions = huge_app.csv -build_flags = - -D ESP32_CAM - -D MONITOR_SPEED=${this.monitor_speed} -lib_deps = - ;https://github.com/takkaO/OpenFontRender - bblanchon/ArduinoJson@^6.21.2 - https://github.com/tzapu/WiFiManager.git - mathertel/OneButton @ ^2.0.3 - arduino-libraries/NTPClient -lib_ignore = - TFT_eSPI [env:NerminerV2-T-QT] platform = espressif32 diff --git a/src/NerdMinerV2.ino.cpp b/src/NerdMinerV2.ino.cpp index 9904d15..94e802f 100644 --- a/src/NerdMinerV2.ino.cpp +++ b/src/NerdMinerV2.ino.cpp @@ -10,7 +10,7 @@ #include "wManager.h" #include "mining.h" #include "monitor.h" -#include "drivers/displays/display.h" +#include "drivers/display.h" //3 seconds WDT #define WDT_TIMEOUT 3 @@ -38,12 +38,7 @@ const char* ntpServer = "pool.ntp.org"; /********* INIT *****/ void setup() { -#ifdef MONITOR_SPEED - Serial.begin(MONITOR_SPEED); -#else - Serial.begin(115200); -#endif //MONITOR_SPEED - + Serial.begin(115200); Serial.setTimeout(0); delay(100); @@ -57,8 +52,7 @@ void setup() button1.setPressTicks(5000); button1.attachClick(switchToNextScreen); button1.attachDoubleClick(alternateScreenRotation); - button1.attachLongPressStart(reset_configuration); - button1.attachMultiClick(alternateScreenState); + button1.attachLongPressStart(reset_configurations); #endif #if defined(PIN_BUTTON_1) && defined(PIN_BUTTON_2) //Button 1 of two button device @@ -70,7 +64,7 @@ void setup() #if defined(PIN_BUTTON_2) //Button 2 of two button device button2.setPressTicks(5000); button2.attachClick(switchToNextScreen); - button2.attachLongPressStart(reset_configuration); + button2.attachLongPressStart(reset_configurations); #endif /******** INIT NERDMINER ************/ diff --git a/src/drivers/devices/device.h b/src/drivers/devices/device.h deleted file mode 100644 index 7d8ba51..0000000 --- a/src/drivers/devices/device.h +++ /dev/null @@ -1,27 +0,0 @@ -#ifndef __DEVICE_H__ -#define __DEVICE_H__ - -#if defined(NERDMINERV2) -#include "nerdMinerV2.h" -#elif defined(DEVKITV1) -#include "esp32DevKit.h" -#elif defined(TDISPLAY) -#include "lilygoS3TDisplay.h" -#elif defined(NERMINER_S3_AMOLED) -#include "lilygoS3Amoled.h" -#elif defined(NERMINER_S3_DONGLE) -#include "lilygoS3Dongle.h" -#elif defined(ESP32_2432S028R) -#include "esp322432s028r.h" -#elif defined(NERMINER_T_QT) -#include "lilygoT_QT.h" -#elif defined(NERDMINER_T_DISPLAY_V1) -#include "lilygoV1TDisplay.h" -#elif defined(ESP32_CAM) -#include "esp32CAM.h" - -#else -#error "No device defined" -#endif - -#endif // __DEVICE_H__ \ No newline at end of file diff --git a/src/drivers/devices/esp32CAM.h b/src/drivers/devices/esp32CAM.h deleted file mode 100644 index 54d7460..0000000 --- a/src/drivers/devices/esp32CAM.h +++ /dev/null @@ -1,18 +0,0 @@ -#ifndef _ESP32CAM_H_ -#define _ESP32CAM_H_ - -#define PIN_BUTTON_1 0 -#define LED_PIN 33 - -#define NO_DISPLAY - -// SDMMC interface: 1-bit mode (might cause issues): -#define SDMMC_CLK 14 -#define SDMMC_CMD 15 -#define SDMMC_D0 2 -// additional defines to enable 4-bit mode -#define SDMMC_D1 4 -#define SDMMC_D2 12 -#define SDMMC_D3 13 - -#endif // _ESP32_CAM_H_ diff --git a/src/drivers/displays/display.cpp b/src/drivers/display.cpp similarity index 100% rename from src/drivers/displays/display.cpp rename to src/drivers/display.cpp diff --git a/src/drivers/displays/display.h b/src/drivers/display.h similarity index 94% rename from src/drivers/displays/display.h rename to src/drivers/display.h index 2a4a469..331ea95 100644 --- a/src/drivers/displays/display.h +++ b/src/drivers/display.h @@ -1,7 +1,7 @@ #ifndef DISPLAY_H #define DISPLAY_H -#include "DisplayDriver.h" +#include "drivers.h" extern DisplayDriver *currentDisplayDriver; diff --git a/src/drivers/displays/amoledDisplayDriver.cpp b/src/drivers/displays/amoledDisplayDriver.cpp index 4abc576..c0eae8b 100644 --- a/src/drivers/displays/amoledDisplayDriver.cpp +++ b/src/drivers/displays/amoledDisplayDriver.cpp @@ -1,4 +1,4 @@ -#include "DisplayDriver.h" +#include "../drivers.h" #ifdef AMOLED_DISPLAY diff --git a/src/drivers/displays/dongleDisplayDriver.cpp b/src/drivers/displays/dongleDisplayDriver.cpp index f6b4fe0..2ba6356 100644 --- a/src/drivers/displays/dongleDisplayDriver.cpp +++ b/src/drivers/displays/dongleDisplayDriver.cpp @@ -1,4 +1,4 @@ -#include "DisplayDriver.h" +#include "../drivers.h" #ifdef DONGLE_DISPLAY @@ -45,15 +45,15 @@ extern monitor_data mMonitor; int32_t x = 8, y = 8; \ background.setTextSize(1); \ background.setTextFont(FONT2); \ - \ + \ background.setTextColor(KEY_COLOR); \ - \ + \ render.setFontSize(18); #define CLEAR_SCREEN() \ RESET_SCREEN(); \ background.fillRect(0, 0, BUFFER_WIDTH, BUFFER_HEIGHT, BACK_COLOR); \ - \ + \ #define PRINT_STR(str) \ diff --git a/src/drivers/displays/esp23_2432s028r.cpp b/src/drivers/displays/esp23_2432s028r.cpp index 7c96258..e87a279 100644 --- a/src/drivers/displays/esp23_2432s028r.cpp +++ b/src/drivers/displays/esp23_2432s028r.cpp @@ -1,4 +1,4 @@ -#include "DisplayDriver.h" +#include "../drivers.h" #ifdef ESP32_2432S028R diff --git a/src/drivers/displays/noDisplayDriver.cpp b/src/drivers/displays/noDisplayDriver.cpp index 636cf81..23a74bd 100644 --- a/src/drivers/displays/noDisplayDriver.cpp +++ b/src/drivers/displays/noDisplayDriver.cpp @@ -1,4 +1,4 @@ -#include "DisplayDriver.h" +#include "../drivers.h" #ifdef NO_DISPLAY diff --git a/src/drivers/displays/tDisplayDriver.cpp b/src/drivers/displays/tDisplayDriver.cpp index 76eede4..6eb454b 100644 --- a/src/drivers/displays/tDisplayDriver.cpp +++ b/src/drivers/displays/tDisplayDriver.cpp @@ -1,4 +1,4 @@ -#include "DisplayDriver.h" +#include "../drivers.h" #ifdef T_DISPLAY diff --git a/src/drivers/displays/tDisplayV1Driver.cpp b/src/drivers/displays/tDisplayV1Driver.cpp index 93b8f76..ac05290 100644 --- a/src/drivers/displays/tDisplayV1Driver.cpp +++ b/src/drivers/displays/tDisplayV1Driver.cpp @@ -1,4 +1,4 @@ -#include "DisplayDriver.h" +#include "../drivers.h" #ifdef V1_DISPLAY diff --git a/src/drivers/displays/t_qtDisplayDriver.cpp b/src/drivers/displays/t_qtDisplayDriver.cpp index f632cae..c5ddadc 100644 --- a/src/drivers/displays/t_qtDisplayDriver.cpp +++ b/src/drivers/displays/t_qtDisplayDriver.cpp @@ -1,4 +1,4 @@ -#include "DisplayDriver.h" +#include "../drivers.h" #ifdef T_QT_DISPLAY diff --git a/src/drivers/displays/displayDriver.h b/src/drivers/drivers.h similarity index 73% rename from src/drivers/displays/displayDriver.h rename to src/drivers/drivers.h index 939b00c..9897db0 100644 --- a/src/drivers/displays/displayDriver.h +++ b/src/drivers/drivers.h @@ -1,7 +1,26 @@ -#ifndef DISPLAYDRIVER_H_ -#define DISPLAYDRIVER_H_ +#ifndef DRIVERS_H +#define DRIVERS_H -#include "..\devices\device.h" +#if defined(NERDMINERV2) +#include "devices/nerdMinerV2.h" +#elif defined(DEVKITV1) +#include "devices/esp32DevKit.h" +#elif defined(TDISPLAY) +#include "devices/lilygoS3TDisplay.h" +#elif defined(NERMINER_S3_AMOLED) +#include "devices/lilygoS3Amoled.h" +#elif defined(NERMINER_S3_DONGLE) +#include "devices/lilygoS3Dongle.h" +#elif defined(ESP32_2432S028R) +#include "devices/esp322432s028r.h" +#elif defined(NERMINER_T_QT) +#include "devices/lilygoT_QT.h" +#elif defined(NERDMINER_T_DISPLAY_V1) +#include "devices/lilygoV1TDisplay.h" + +#else +#error "No device defined" +#endif typedef void (*AlternateFunction)(void); typedef void (*DriverInitFunction)(void); @@ -38,4 +57,4 @@ extern DisplayDriver tDisplayV1Driver; #define SCREENS_ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0])) -#endif // DISPLAYDRIVER_H_ +#endif // DRIVERS_H diff --git a/src/drivers/storage/SDCard.cpp b/src/drivers/storage/SDCard.cpp deleted file mode 100644 index fe06bde..0000000 --- a/src/drivers/storage/SDCard.cpp +++ /dev/null @@ -1,157 +0,0 @@ - -#include -#include -#include - -#include "storage.h" -#include "nvMemory.h" -#include "..\devices\device.h" -#include "SDCard.h" - -#if defined (BUILD_SDMMC_1) || defined(BUILD_SDMMC_4) - -#include - -SDCard::SDCard() -{ -#if defined (BUILD_SDMMC_1) || defined(BUILD_SDMMC_4) - iSD_ = &SD_MMC; -#elif defined (BUILD_SDSPI) -#error You chose to run the sd card in SPI mode. This is not implemented yet. -#endif -} - -SDCard::~SDCard() -{ - unmount(); -} - -void SDCard::SD2nvMemory(nvMemory* nvMem) -{ - TSettings Settings; - if (loadConfigFile(&Settings)) - { - nvMem->saveConfig(&Settings); - WiFi.begin(Settings.WifiSSID, Settings.WifiPW); - Serial.println("SDCard: Settings transfered to internal memory. Restarting now."); - ESP.restart(); - } -} - -bool SDCard::loadConfigFile(TSettings* Settings) -{ - // Load existing configuration file - // Read configuration from FS json - - if (initSDcard()) - { - if (iSD_->exists(JSON_CONFIG_FILE)) - { - // The file exists, reading and loading - File configFile = iSD_->open(JSON_CONFIG_FILE, "r"); - if (configFile) - { - StaticJsonDocument<512> json; - DeserializationError error = deserializeJson(json, configFile); - configFile.close(); - Serial.println("SDCard: Loading config file"); - serializeJsonPretty(json, Serial); - Serial.print('\n'); - unmount(); - if (!error) - { - strcpy(Settings->WifiSSID, json[JSON_KEY_SSID] | Settings->WifiSSID); - strcpy(Settings->WifiPW, json[JSON_KEY_PASW] | Settings->WifiPW); - strcpy(Settings->PoolAddress, json[JSON_KEY_POOLURL] | Settings->PoolAddress); - strcpy(Settings->BtcWallet, json[JSON_KEY_WALLETID] | Settings->BtcWallet); - if (json.containsKey(JSON_KEY_POOLPORT)) - Settings->PoolPort = json[JSON_KEY_POOLPORT].as(); - if (json.containsKey(JSON_KEY_TIMEZONE)) - Settings->Timezone = json[JSON_KEY_TIMEZONE].as(); - if (json.containsKey(JSON_KEY_STATS2NV)) - Settings->saveStats = json[JSON_KEY_STATS2NV].as(); - return true; - } - else - { - // Error loading JSON data - Serial.println("SDCard: Error parsing config file!"); - } - } - else - { - Serial.println("SDCard: Error opening config file!"); - } - } - else - { - Serial.println("SDCard: No config file available!"); - } - unmount(); - } - return false; -} - -void SDCard::unmount() -{ - iSD_->end(); - Serial.println("SDCard: Unmounted"); -} - -bool SDCard::initSDcard() -{ - if (iSD_->cardType() != CARD_NONE) - { - Serial.println("SDCard: Already mounted."); - return true; - } - Serial.println("SDCard: Mounting card."); - - bool cardInitialized = false; -#if defined (BUILD_SDMMC_4) - if (iSD_->cardType() == CARD_NONE) - { - iSD_->setPins(SDMMC_CLK, SDMMC_CMD, SDMMC_D0, SDMMC_D1, SDMMC_D2, SDMMC_D3); - Serial.println("SDCard: 4-Bit Mode."); - cardInitialized = iSD_->begin("/sd", false); - } -#elif defined (BUILD_SDMMC_1) - #warning SDMMC : 1 - bit mode is not always working.If you experience issues, try other modes. - if (iSD_->cardType() == CARD_NONE) - { - iSD_->setPins(SDMMC_CLK, SDMMC_CMD, SDMMC_D0); - Serial.println("SDCard: 1-Bit Mode."); - cardInitialized = iSD_->begin("/sd", true); - } -#elif defined (BUILD_SDSPI) -#error You chose to run the sd card in SPI mode. This is not implemented yet. -#else - Serial.println("SDCard: interface not available."); - return false; -#endif // dataPinsDefined - if (cardInitialized) - { - if (iSD_->cardType() != CARD_NONE) - { - Serial.println("SDCard: Mounted."); - return true; - } - else - { - Serial.println("SDCard: Mounting failed."); - iSD_->end(); - } - } - return false; -} - -#else - -SDCard::SDCard() {} -SDCard::~SDCard() {} -void SDCard::SD2nvMemory(nvMemory* nvMem) {}; -bool SDCard::loadConfigFile(TSettings* Settings) { return false; } -bool SDCard::initSDcard() { return false; } -void unmount() {} - -#endif //BUILD_SDMMC \ No newline at end of file diff --git a/src/drivers/storage/SDCard.h b/src/drivers/storage/SDCard.h deleted file mode 100644 index b2e91f5..0000000 --- a/src/drivers/storage/SDCard.h +++ /dev/null @@ -1,38 +0,0 @@ -#ifndef _SDCARD_H_ -#define _SDCARD_H_ - -#include "storage.h" -#include "nvMemory.h" -#include "..\devices\device.h" - -#if defined (SDMMC_D0) && defined (SDMMC_D1) && defined (SDMMC_D2) && defined (SDMMC_D3) -#define BUILD_SDMMC_4 -#include -#elif defined (SDMMC_D0) && !(defined (SDMMC_D1) && defined (SDMMC_D2) && defined (SDMMC_D3)) -#define BUILD_SDMMC_1 -#include -#else -#warning SD card support disabled! -#endif - -// Handles the transfer of settings from sd card to nv memory (wifi credentials are handled by wifimanager) -class SDCard -{ -public: - SDCard(); - ~SDCard(); - void SD2nvMemory(nvMemory* nvMem); - bool loadConfigFile(TSettings* Settings); -private: - bool initSDcard(); - void unmount(); - -#if defined (BUILD_SDMMC_1) || defined(BUILD_SDMMC_4) - fs::SDMMCFS* iSD_; -#elif defined (BUILD_SDSPI) -#error You chose to run the SD card in SPI mode. This is not implemented yet. - fs::SDFS* iSD_; -#endif -}; - -#endif // _SDCARD_H_ diff --git a/src/drivers/storage/nvMemory.cpp b/src/drivers/storage/nvMemory.cpp deleted file mode 100644 index a686589..0000000 --- a/src/drivers/storage/nvMemory.cpp +++ /dev/null @@ -1,148 +0,0 @@ -#include "nvMemory.h" - -#ifdef NVMEM_SPIFFS - -#include -#include -#include - -#include "..\devices\device.h" -#include "storage.h" - -nvMemory::nvMemory() -{ - Initialized_ = false; -} - -nvMemory::~nvMemory() -{ - if (Initialized_) - SPIFFS.end(); -}; - -bool nvMemory::saveConfig(TSettings* Settings) -{ - if (init()) - { - // Save Config in JSON format - Serial.println(F("SPIFS: Saving configuration.")); - - // Create a JSON document - StaticJsonDocument<512> json; - json[JSON_KEY_POOLURL] = Settings->PoolAddress; - json[JSON_KEY_POOLPORT] = Settings->PoolPort; - json[JSON_KEY_WALLETID] = Settings->BtcWallet; - json[JSON_KEY_TIMEZONE] = Settings->Timezone; - json[JSON_KEY_STATS2NV] = Settings->saveStats; - - // Open config file - File configFile = SPIFFS.open(JSON_CONFIG_FILE, "w"); - if (!configFile) - { - // Error, file did not open - Serial.println("SPIFS: Failed to open config file for writing"); - return false; - } - - // Serialize JSON data to write to file - serializeJsonPretty(json, Serial); - Serial.print('\n'); - if (serializeJson(json, configFile) == 0) - { - // Error writing file - Serial.println(F("SPIFS: Failed to write to file")); - return false; - } - // Close file - configFile.close(); - return true; - }; - return false; -} - -bool nvMemory::loadConfig(TSettings* Settings) -{ - // Uncomment if we need to format filesystem - // SPIFFS.format(); - - // Load existing configuration file - // Read configuration from FS json - - if (init()) - { - if (SPIFFS.exists(JSON_CONFIG_FILE)) - { - // The file exists, reading and loading - File configFile = SPIFFS.open(JSON_CONFIG_FILE, "r"); - if (configFile) - { - Serial.println("SPIFS: Loading config file"); - StaticJsonDocument<512> json; - DeserializationError error = deserializeJson(json, configFile); - configFile.close(); - serializeJsonPretty(json, Serial); - Serial.print('\n'); - if (!error) - { - strcpy(Settings->PoolAddress, json[JSON_KEY_POOLURL] | Settings->PoolAddress); - strcpy(Settings->BtcWallet, json[JSON_KEY_WALLETID] | Settings->BtcWallet); - if (json.containsKey(JSON_KEY_POOLPORT)) - Settings->PoolPort = json[JSON_KEY_POOLPORT].as(); - if (json.containsKey(JSON_KEY_TIMEZONE)) - Settings->Timezone = json[JSON_KEY_TIMEZONE].as(); - if (json.containsKey(JSON_KEY_STATS2NV)) - Settings->saveStats = json[JSON_KEY_STATS2NV].as(); - return true; - } - else - { - // Error loading JSON data - Serial.println("SPIFS: Error parsing config file!"); - } - } - else - { - Serial.println("SPIFS: Error opening config file!"); - } - } - else - { - Serial.println("SPIFS: No config file available!"); - } - } - return false; -} - -bool nvMemory::deleteConfig() -{ - Serial.println("SPIFS: Erasing config file.."); - return SPIFFS.remove(JSON_CONFIG_FILE); //Borramos fichero -} - -bool nvMemory::init() -{ - if (!Initialized_) - { - Serial.println("SPIFS: Mounting File System..."); - // May need to make it begin(true) first time you are using SPIFFS - Initialized_ = SPIFFS.begin(false) || SPIFFS.begin(true); - Initialized_ ? Serial.println("SPIFS: Mounted") : Serial.println("SPIFS: Mounting failed."); - } - else - { - Serial.println("SPIFS: Already Mounted"); - } - return Initialized_; -}; - -#else - -nvMemory::nvMemory() {} -nvMemory::~nvMemory() {} -bool nvMemory::saveConfig(TSettings* Settings) { return false; } -bool nvMemory::loadConfig(TSettings* Settings) { return false; } -bool nvMemory::deleteConfig() { return false; } -bool nvMemory::init() { return false; } - - -#endif //NVMEM_TYPE \ No newline at end of file diff --git a/src/drivers/storage/nvMemory.h b/src/drivers/storage/nvMemory.h deleted file mode 100644 index 163431c..0000000 --- a/src/drivers/storage/nvMemory.h +++ /dev/null @@ -1,30 +0,0 @@ -#ifndef _NVMEMORY_H_ -#define _NVMEMORY_H_ - -// we only have one implementation right now and nothing to choose from. -#define NVMEM_SPIFFS - -#include "..\devices\device.h" -#include "storage.h" - -// Handles load and store of user settings, except wifi credentials. Those are managed by the wifimanager. -class nvMemory -{ -public: - nvMemory(); - ~nvMemory(); - bool saveConfig(TSettings* Settings); - bool loadConfig(TSettings* Settings); - bool deleteConfig(); -private: - bool init(); - bool Initialized_; -}; - -#ifdef NVMEM_SPIFFS -#define ESP_DRD_USE_SPIFFS true -#else -#error We need some kind of permanent storage implementation! -#endif //NVMEM_TYPE - -#endif // _NVMEMORY_H_ diff --git a/src/drivers/storage/storage.h b/src/drivers/storage/storage.h deleted file mode 100644 index 8aa0668..0000000 --- a/src/drivers/storage/storage.h +++ /dev/null @@ -1,35 +0,0 @@ -#ifndef _STORAGE_H_ -#define _STORAGE_H_ - -#include - -#define DEFAULT_SSID "NerdMinerAP" -#define DEFAULT_WIFIPW "MineYourCoins" -#define DEFAULT_POOLURL "public-pool.io" -#define DEFAULT_WALLETID "yourBtcAddress" -#define DEFAULT_POOLPORT 21496 -#define DEFAULT_TIMEZONE 2 -#define DEFAULT_SAVESTATS false - -// JSON config file -#define JSON_CONFIG_FILE "/config.json" -#define JSON_KEY_SSID "SSID" -#define JSON_KEY_PASW "PW" -#define JSON_KEY_POOLURL "PoolUrl" -#define JSON_KEY_WALLETID "BtcWallet" -#define JSON_KEY_POOLPORT "PoolPort" -#define JSON_KEY_TIMEZONE "Timezone" -#define JSON_KEY_STATS2NV "saveStats" - -struct TSettings -{ - char WifiSSID[80]{ DEFAULT_SSID }; - char WifiPW[80]{ DEFAULT_WIFIPW }; - char PoolAddress[80]{ DEFAULT_POOLURL }; - char BtcWallet[80]{ DEFAULT_WALLETID }; - uint32_t PoolPort{ DEFAULT_POOLPORT }; - uint32_t Timezone{ DEFAULT_TIMEZONE }; - bool saveStats{ DEFAULT_SAVESTATS }; -}; - -#endif // _STORAGE_H_ \ No newline at end of file diff --git a/src/mining.cpp b/src/mining.cpp index d6f5694..9bf3fce 100644 --- a/src/mining.cpp +++ b/src/mining.cpp @@ -10,8 +10,7 @@ #include "mining.h" #include "utils.h" #include "monitor.h" -#include "drivers/displays/display.h" -#include "drivers/storage/storage.h" +#include "drivers/display.h" nvs_handle_t stat_handle; @@ -29,10 +28,11 @@ uint32_t valids; // increased if blockhash <= target double best_diff = 0.0; // Variables to hold data from custom textboxes -//Track mining stats in non volatile memory -extern TSettings Settings; - +extern char poolString[80]; +extern int portNumber; +extern char btcString[80]; IPAddress serverIP(1, 1, 1, 1); //Temporally save poolIPaddres +extern bool saveStatsToNVS; //Track mining stats in non volatile memory //Global work data static WiFiClient client; @@ -59,14 +59,14 @@ bool checkPoolConnection(void) { //Resolve first time pool DNS and save IP if(serverIP == IPAddress(1,1,1,1)) { - WiFi.hostByName(Settings.PoolAddress, serverIP); + WiFi.hostByName(poolString, serverIP); Serial.printf("Resolved DNS and save ip (first time) got: %s\n", serverIP.toString()); } //Try connecting pool IP - if (!client.connect(serverIP, Settings.PoolPort)) { - Serial.println("Imposible to connect to : " + String(Settings.PoolAddress)); - WiFi.hostByName(Settings.PoolAddress, serverIP); + if (!client.connect(serverIP, portNumber)) { + Serial.println("Imposible to connect to : " + String(poolString)); + WiFi.hostByName(poolString, serverIP); Serial.printf("Resolved DNS got: %s\n", serverIP.toString()); vTaskDelay(1000 / portTICK_PERIOD_MS); return false; @@ -166,7 +166,7 @@ void runStratumWorker(void *name) { continue; } - strcpy(mWorker.wName, Settings.BtcWallet); + strcpy(mWorker.wName, btcString); strcpy(mWorker.wPass, "x"); // STEP 2: Pool authorize work (Block Info) tx_mining_auth(client, mWorker.wName, mWorker.wPass); //Don't verifies authoritzation, TODO @@ -386,7 +386,7 @@ void runMiner(void * task_id) { #define REDRAW_EVERY 10 void restoreStat() { - if(!Settings.saveStats) return; + if(!saveStatsToNVS) return; esp_err_t ret = nvs_flash_init(); if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) { Serial.printf("[MONITOR] NVS partition is full or has invalid version, erasing...\n"); @@ -405,7 +405,7 @@ void restoreStat() { } void saveStat() { - if(!Settings.saveStats) return; + if(!saveStatsToNVS) return; Serial.printf("[MONITOR] Saving stats\n"); nvs_set_blob(stat_handle, "best_diff", &best_diff, sizeof(double)); nvs_set_u32(stat_handle, "Mhashes", Mhashes); @@ -447,8 +447,8 @@ void runMonitor(void *name) if (elapsedKHs == 0) { Serial.printf(">>> [i] Miner: newJob>%s / inRun>%s) - Client: connected>%s / subscribed>%s / wificonnected>%s\n", - mMiner.newJob ? "true" : "false", mMiner.inRun ? "true" : "false", - client.connected() ? "true" : "false", isMinerSuscribed ? "true" : "false", WiFi.status() == WL_CONNECTED ? "true" : "false"); + mMiner.newJob ? "true" : "false", mMiner.inRun ? "true" : "false", + client.connected() ? "true" : "false", isMinerSuscribed ? "true" : "false", WiFi.status() == WL_CONNECTED ? "true" : "false"); } #ifdef DEBUG_MEMORY diff --git a/src/monitor.cpp b/src/monitor.cpp index 56f1368..27753cd 100644 --- a/src/monitor.cpp +++ b/src/monitor.cpp @@ -7,8 +7,8 @@ #include "mining.h" #include "utils.h" #include "monitor.h" -#include "drivers/storage/storage.h" +extern char poolString[80]; extern uint32_t templates; extern uint32_t hashes; extern uint32_t Mhashes; @@ -23,8 +23,7 @@ extern double best_diff; // track best diff extern monitor_data mMonitor; -//from saved config -extern TSettings Settings; +extern int GMTzone; //Gotten from saved config WiFiUDP ntpUDP; NTPClient timeClient(ntpUDP, "europe.pool.ntp.org", 3600, 60000); @@ -40,7 +39,7 @@ void setup_monitor(void){ // Adjust offset depending on your zone // GMT +2 in seconds (zona horaria de Europa Central) - timeClient.setTimeOffset(3600 * Settings.Timezone); + timeClient.setTimeOffset(3600 * GMTzone); Serial.println("TimeClient setup done"); } @@ -172,6 +171,7 @@ unsigned long mTriggerUpdate = 0; unsigned long initialMillis = millis(); unsigned long initialTime = 0; unsigned long mPoolUpdate = 0; +extern char btcString[80]; void getTime(unsigned long* currentHours, unsigned long* currentMinutes, unsigned long* currentSeconds){ @@ -296,7 +296,7 @@ pool_data getPoolData(void){ HTTPClient http; http.setReuse(true); try { - String btcWallet = Settings.BtcWallet; + String btcWallet = btcString; Serial.println(btcWallet); if (btcWallet.indexOf(".")>0) btcWallet = btcWallet.substring(0,btcWallet.indexOf(".")); http.begin(String(getPublicPool)+btcWallet); diff --git a/src/wManager.cpp b/src/wManager.cpp index 93afff4..1e94ae4 100644 --- a/src/wManager.cpp +++ b/src/wManager.cpp @@ -1,148 +1,221 @@ +#define ESP_DRD_USE_SPIFFS true // Include Libraries //#include ".h" #include +#include +#include #include - +#include #include "wManager.h" #include "monitor.h" -#include "drivers/displays/display.h" -#include "drivers/storage/SDCard.h" -#include "drivers/storage/nvMemory.h" -#include "drivers/storage/storage.h" +#include "drivers/display.h" +// JSON configuration file +#define JSON_CONFIG_FILE "/config.json" // Flag for saving data bool shouldSaveConfig = false; // Variables to hold data from custom textboxes -TSettings Settings; +char poolString[80] = "public-pool.io"; +int portNumber = 21496;//3333; +char btcString[80] = "yourBtcAddress"; +int GMTzone = 2; //Currently selected in spain +bool saveStatsToNVS = false; //Track mining stats in non volatile memory + // Define WiFiManager Object WiFiManager wm; extern monitor_data mMonitor; -nvMemory nvMem; +void saveConfigFile() +// Save Config in JSON format +{ + Serial.println(F("Saving configuration...")); + + // Create a JSON document + StaticJsonDocument<512> json; + json["poolString"] = poolString; + json["portNumber"] = portNumber; + json["btcString"] = btcString; + json["gmtZone"] = GMTzone; + json["saveStatsToNVS"] = String(saveStatsToNVS); + + // Open config file + File configFile = SPIFFS.open(JSON_CONFIG_FILE, "w"); + if (!configFile) + { + // Error, file did not open + Serial.println("failed to open config file for writing"); + } + + // Serialize JSON data to write to file + serializeJsonPretty(json, Serial); + if (serializeJson(json, configFile) == 0) + { + // Error writing file + Serial.println(F("Failed to write to file")); + } + // Close file + configFile.close(); +} + +bool loadConfigFile() +// Load existing configuration file +{ + // Uncomment if we need to format filesystem + // SPIFFS.format(); + + // Read configuration from FS json + Serial.println("Mounting File System..."); + + // May need to make it begin(true) first time you are using SPIFFS + if (SPIFFS.begin(false) || SPIFFS.begin(true)) + { + Serial.println("mounted file system"); + if (SPIFFS.exists(JSON_CONFIG_FILE)) + { + // The file exists, reading and loading + Serial.println("reading config file"); + File configFile = SPIFFS.open(JSON_CONFIG_FILE, "r"); + if (configFile) + { + Serial.println("Opened configuration file"); + StaticJsonDocument<512> json; + DeserializationError error = deserializeJson(json, configFile); + configFile.close(); + serializeJsonPretty(json, Serial); + if (!error) + { + Serial.println("Parsing JSON"); + + strcpy(poolString, json["poolString"]); + strcpy(btcString, json["btcString"]); + portNumber = json["portNumber"].as(); + GMTzone = json["gmtZone"].as(); + if(json.containsKey("saveStatsToNVS")) + saveStatsToNVS = json["saveStatsToNVS"].as(); + return true; + } + else + { + // Error loading JSON data + Serial.println("Failed to load json config"); + } + } + } + } + else + { + // Error mounting file system + Serial.println("Failed to mount FS"); + } + + return false; +} + void saveConfigCallback() // Callback notifying us of the need to save configuration { - Serial.println("Should save config"); - shouldSaveConfig = true; - //wm.setConfigPortalBlocking(false); + Serial.println("Should save config"); + shouldSaveConfig = true; + //wm.setConfigPortalBlocking(false); } -void configModeCallback(WiFiManager* myWiFiManager) +void configModeCallback(WiFiManager *myWiFiManager) // Called when config mode launched { - Serial.println("Entered Configuration Mode"); + Serial.println("Entered Configuration Mode"); - Serial.print("Config SSID: "); - Serial.println(myWiFiManager->getConfigPortalSSID()); + Serial.print("Config SSID: "); + Serial.println(myWiFiManager->getConfigPortalSSID()); - Serial.print("Config IP Address: "); - Serial.println(WiFi.softAPIP()); -} - -void reset_configuration() -{ - Serial.println("Erasing Config, restarting"); - nvMem.deleteConfig(); - wm.resetSettings(); - ESP.restart(); + Serial.print("Config IP Address: "); + Serial.println(WiFi.softAPIP()); } void init_WifiManager() { -#ifdef MONITOR_SPEED - Serial.begin(MONITOR_SPEED); -#else - Serial.begin(115200); -#endif //MONITOR_SPEED - //Serial.setTxTimeoutMs(10); + Serial.begin(115200); + //Serial.setTxTimeoutMs(10); - //Init pin 15 to eneble 5V external power (LilyGo bug) -#ifdef PIN_ENABLE5V + //Init pin 15 to eneble 5V external power (LilyGo bug) + #ifdef PIN_ENABLE5V pinMode(PIN_ENABLE5V, OUTPUT); digitalWrite(PIN_ENABLE5V, HIGH); -#endif + #endif - // Change to true when testing to force configuration every time we run - bool forceConfig = false; + // Change to true when testing to force configuration every time we run + bool forceConfig = false; -#if defined(PIN_BUTTON_2) + #if defined(PIN_BUTTON_2) // Check if button2 is pressed to enter configMode with actual configuration - if (!digitalRead(PIN_BUTTON_2)) { - Serial.println(F("Button pressed to force start config mode")); - forceConfig = true; - wm.setBreakAfterConfig(true); //Set to detect config edition and save + if(!digitalRead(PIN_BUTTON_2)){ + Serial.println(F("Button pressed to force start config mode")); + forceConfig = true; + wm.setBreakAfterConfig(true); //Set to detect config edition and save } -#endif - // Explicitly set WiFi mode - WiFi.mode(WIFI_STA); + #endif + + bool spiffsSetup = loadConfigFile(); + if (!spiffsSetup) + { + Serial.println(F("Forcing config mode as there is no saved config")); + forceConfig = true; + + } - if (!nvMem.loadConfig(&Settings)) - { - //No config file on internal flash. - SDCard SDCrd; - if (SDCrd.loadConfigFile(&Settings)) - { - //Config file on SD card. - SDCrd.SD2nvMemory(&nvMem); // reboot on success. - } - else - { - //No config file on SD card. Starting wifi config server. - forceConfig = true; - } - }; + // Explicitly set WiFi mode + WiFi.mode(WIFI_STA); - // Reset settings (only for development) - //wm.resetSettings(); + // Reset settings (only for development) + //wm.resetSettings(); - //Set dark theme - //wm.setClass("invert"); // dark theme + //Set dark theme + //wm.setClass("invert"); // dark theme + + // Set config save notify callback + wm.setSaveConfigCallback(saveConfigCallback); - // Set config save notify callback - wm.setSaveConfigCallback(saveConfigCallback); + // Set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode + wm.setAPCallback(configModeCallback); - // Set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode - wm.setAPCallback(configModeCallback); + //Advanced settings + wm.setConfigPortalBlocking(false); //Hacemos que el portal no bloquee el firmware + wm.setConnectTimeout(50); // how long to try to connect for before continuing + //wm.setConfigPortalTimeout(30); // auto close configportal after n seconds + // wm.setCaptivePortalEnable(false); // disable captive portal redirection + // wm.setAPClientCheck(true); // avoid timeout if client connected to softap + //wm.setTimeout(120); + //wm.setConfigPortalTimeout(120); //seconds + + // Custom elements - //Advanced settings - wm.setConfigPortalBlocking(false); //Hacemos que el portal no bloquee el firmware - wm.setConnectTimeout(50); // how long to try to connect for before continuing - //wm.setConfigPortalTimeout(30); // auto close configportal after n seconds - // wm.setCaptivePortalEnable(false); // disable captive portal redirection - // wm.setAPClientCheck(true); // avoid timeout if client connected to softap - //wm.setTimeout(120); - //wm.setConfigPortalTimeout(120); //seconds + // Text box (String) - 80 characters maximum + WiFiManagerParameter pool_text_box("Poolurl", "Pool url", poolString, 80); - // Custom elements + // Need to convert numerical input to string to display the default value. + char convertedValue[6]; + sprintf(convertedValue, "%d", portNumber); + + // Text box (Number) - 7 characters maximum + WiFiManagerParameter port_text_box_num("Poolport", "Pool port", convertedValue, 7); - // Text box (String) - 80 characters maximum - WiFiManagerParameter pool_text_box("Poolurl", "Pool url", Settings.PoolAddress, 80); - - // Need to convert numerical input to string to display the default value. - char convertedValue[6]; - sprintf(convertedValue, "%d", Settings.PoolPort); - - // Text box (Number) - 7 characters maximum - WiFiManagerParameter port_text_box_num("Poolport", "Pool port", convertedValue, 7); - - // Text box (String) - 80 characters maximum - WiFiManagerParameter addr_text_box("btcAddress", "Your BTC address", Settings.BtcWallet, 80); + // Text box (String) - 80 characters maximum + WiFiManagerParameter addr_text_box("btcAddress", "Your BTC address", btcString, 80); // Text box (Number) - 2 characters maximum char charZone[6]; - sprintf(charZone, "%d", Settings.Timezone); + sprintf(charZone, "%d", GMTzone); WiFiManagerParameter time_text_box_num("TimeZone", "TimeZone fromUTC (-12/+12)", charZone, 3); WiFiManagerParameter features_html("

"); char checkboxParams[24] = "type=\"checkbox\""; - if (Settings.saveStats) + if (saveStatsToNVS) { strcat(checkboxParams, " checked"); } @@ -156,103 +229,109 @@ void init_WifiManager() wm.addParameter(&features_html); wm.addParameter(&save_stats_to_nvs); - Serial.println("AllDone: "); - if (forceConfig) + Serial.println("AllDone: "); + if (forceConfig) + // Run if we need a configuration + { + //No configuramos timeout al modulo + wm.setConfigPortalBlocking(true); //Hacemos que el portal SI bloquee el firmware + drawSetupScreen(); + if (!wm.startConfigPortal("NerdMinerAP","MineYourCoins")) { - // Run if we need a configuration - //No configuramos timeout al modulo - wm.setConfigPortalBlocking(true); //Hacemos que el portal SI bloquee el firmware - drawSetupScreen(); - - if (wm.startConfigPortal(DEFAULT_SSID, DEFAULT_WIFIPW)) - { - //Could be break forced after edditing, so save new config - Serial.println("failed to connect and hit timeout"); - strncpy(Settings.PoolAddress, pool_text_box.getValue(), sizeof(Settings.PoolAddress)); - Settings.PoolPort = atoi(port_text_box_num.getValue()); - strncpy(Settings.BtcWallet, addr_text_box.getValue(), sizeof(Settings.BtcWallet)); - Settings.Timezone = atoi(time_text_box_num.getValue()); - Serial.println(save_stats_to_nvs.getValue()); - Settings.saveStats = (strncmp(save_stats_to_nvs.getValue(), "T", 1) == 0); - - nvMem.saveConfig(&Settings); - delay(3000); - //reset and try again, or maybe put it to deep sleep - ESP.restart(); - delay(5000); - }; + Serial.println("failed to connect and hit timeout"); + //Could be break forced after edditing, so save new config + strncpy(poolString, pool_text_box.getValue(), sizeof(poolString)); + portNumber = atoi(port_text_box_num.getValue()); + strncpy(btcString, addr_text_box.getValue(), sizeof(btcString)); + GMTzone = atoi(time_text_box_num.getValue()); + saveStatsToNVS = (strncmp(save_stats_to_nvs.getValue(), "T", 1) == 0); + saveConfigFile(); + delay(3000); + //reset and try again, or maybe put it to deep sleep + ESP.restart(); + delay(5000); } - else - { - //Tratamos de conectar con la configuración inicial ya almacenada - mMonitor.NerdStatus = NM_Connecting; - wm.setCaptivePortalEnable(false); // disable captive portal redirection - if (!wm.autoConnect(Settings.WifiSSID, Settings.WifiPW)) - { - Serial.println("Failed to connect and hit timeout"); - //delay(3000); - // if we still have not connected restart and try all over again - //ESP.restart(); - //delay(5000); - } - } - + } + else + { + //Tratamos de conectar con la configuración inicial ya almacenada mMonitor.NerdStatus = NM_Connecting; - - //Conectado a la red Wifi - if (WiFi.status() == WL_CONNECTED) { - //tft.pushImage(0, 0, MinerWidth, MinerHeight, MinerScreen); - Serial.println(""); - Serial.println("WiFi connected"); - Serial.print("IP address: "); - Serial.println(WiFi.localIP()); - - // Lets deal with the user config values - - // Copy the string value - strncpy(Settings.PoolAddress, pool_text_box.getValue(), sizeof(Settings.PoolAddress)); - Serial.print("PoolString: "); - Serial.println(Settings.PoolAddress); - - //Convert the number value - Settings.PoolPort = atoi(port_text_box_num.getValue()); - Serial.print("portNumber: "); - Serial.println(Settings.PoolPort); - - // Copy the string value - strncpy(Settings.BtcWallet, addr_text_box.getValue(), sizeof(Settings.BtcWallet)); - Serial.print("btcString: "); - Serial.println(Settings.BtcWallet); - - //Convert the number value - Settings.Timezone = atoi(time_text_box_num.getValue()); - Serial.print("TimeZone fromUTC: "); - Serial.println(Settings.Timezone); - - } - - // Save the custom parameters to FS - if (shouldSaveConfig) + wm.setCaptivePortalEnable(false); // disable captive portal redirection + if (!wm.autoConnect("NerdMinerAP","MineYourCoins")) { - nvMem.saveConfig(&Settings); + Serial.println("Failed to connect and hit timeout"); + //delay(3000); + // if we still have not connected restart and try all over again + //ESP.restart(); + //delay(5000); } + } + + mMonitor.NerdStatus = NM_Connecting; + + //Conectado a la red Wifi + if(WiFi.status() == WL_CONNECTED){ + //tft.pushImage(0, 0, MinerWidth, MinerHeight, MinerScreen); + Serial.println(""); + Serial.println("WiFi connected"); + Serial.print("IP address: "); + Serial.println(WiFi.localIP()); + + // Lets deal with the user config values + + // Copy the string value + strncpy(poolString, pool_text_box.getValue(), sizeof(poolString)); + Serial.print("PoolString: "); + Serial.println(poolString); + + //Convert the number value + portNumber = atoi(port_text_box_num.getValue()); + Serial.print("portNumber: "); + Serial.println(portNumber); + + // Copy the string value + strncpy(btcString, addr_text_box.getValue(), sizeof(btcString)); + Serial.print("btcString: "); + Serial.println(btcString); + + //Convert the number value + GMTzone = atoi(time_text_box_num.getValue()); + Serial.print("TimeZone fromUTC: "); + Serial.println(GMTzone); + } + + // Save the custom parameters to FS + if (shouldSaveConfig) + { + saveConfigFile(); + } } +void reset_configurations() { + Serial.println("Erasing Config, restarting"); + wm.resetSettings(); + SPIFFS.remove(JSON_CONFIG_FILE); //Borramos fichero + ESP.restart(); +} + + //----------------- MAIN PROCESS WIFI MANAGER -------------- int oldStatus = 0; void wifiManagerProcess() { - - wm.process(); // avoid delays() in loop when non-blocking and other long running code - - int newStatus = WiFi.status(); - if (newStatus != oldStatus) { - if (newStatus == WL_CONNECTED) { - Serial.println("CONNECTED - Current ip: " + WiFi.localIP().toString()); - } else { - Serial.print("[Error] - current status: "); - Serial.println(newStatus); - } - oldStatus = newStatus; + + wm.process(); // avoid delays() in loop when non-blocking and other long running code + + int newStatus = WiFi.status(); + if (newStatus != oldStatus) { + if (newStatus == WL_CONNECTED) { + Serial.println("CONNECTED - Current ip: " + WiFi.localIP().toString()); + } else { + Serial.print("[Error] - current status: "); + Serial.println(newStatus); } + oldStatus = newStatus; + } } + + diff --git a/src/wManager.h b/src/wManager.h index ef2bd37..870b435 100644 --- a/src/wManager.h +++ b/src/wManager.h @@ -1,8 +1,3 @@ -#ifndef _WMANAGER_H -#define _WMANAGER_H - void init_WifiManager(); void wifiManagerProcess(); -void reset_configuration(); - -#endif // _WMANAGER_H +void reset_configurations(); \ No newline at end of file From c803c3b78ca19bb7c805cad94a8336031d340736 Mon Sep 17 00:00:00 2001 From: George Alexandre Silva Date: Tue, 19 Sep 2023 21:38:11 -0300 Subject: [PATCH 3/4] minor adjusts. --- src/drivers/displays/esp23_2432s028r.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/drivers/displays/esp23_2432s028r.cpp b/src/drivers/displays/esp23_2432s028r.cpp index e87a279..7788014 100644 --- a/src/drivers/displays/esp23_2432s028r.cpp +++ b/src/drivers/displays/esp23_2432s028r.cpp @@ -377,8 +377,7 @@ char currentScreen = 0; void esp32_2432S028R_DoLedStuff(unsigned long frame) { - unsigned long currentMillis = millis(); - + unsigned long currentMillis = millis(); // / Check the touch coordinates 110x185 210x240 if (currentMillis - previousTouchMillis >= 500) { From 6105c57b9b514bfdaa88f86523b3c4b6ffa9e710 Mon Sep 17 00:00:00 2001 From: George Alexandre Silva Date: Tue, 19 Sep 2023 22:18:28 -0300 Subject: [PATCH 4/4] Revert "Revert "Merge branch 'dev' of https://github.com/BitMaker-hub/NerdMiner_v2 into dev"" This reverts commit 56fc227c7c8b4afe47abff60b570de466c59c727. --- .gitignore | 3 + README.md | 31 ++ lib/TFT_eSPI/Processors/TFT_eSPI_ESP32_S3.h | 2 +- platformio.ini | 40 +- src/NerdMinerV2.ino.cpp | 14 +- src/drivers/devices/device.h | 27 ++ src/drivers/devices/esp32CAM.h | 18 + src/drivers/displays/amoledDisplayDriver.cpp | 2 +- src/drivers/{ => displays}/display.cpp | 0 src/drivers/{ => displays}/display.h | 2 +- .../{drivers.h => displays/displayDriver.h} | 27 +- src/drivers/displays/dongleDisplayDriver.cpp | 8 +- src/drivers/displays/esp23_2432s028r.cpp | 2 +- src/drivers/displays/noDisplayDriver.cpp | 2 +- src/drivers/displays/tDisplayDriver.cpp | 2 +- src/drivers/displays/tDisplayV1Driver.cpp | 2 +- src/drivers/displays/t_qtDisplayDriver.cpp | 2 +- src/drivers/storage/SDCard.cpp | 157 +++++++ src/drivers/storage/SDCard.h | 38 ++ src/drivers/storage/nvMemory.cpp | 148 ++++++ src/drivers/storage/nvMemory.h | 30 ++ src/drivers/storage/storage.h | 35 ++ src/mining.cpp | 28 +- src/monitor.cpp | 10 +- src/wManager.cpp | 431 +++++++----------- src/wManager.h | 7 +- 26 files changed, 739 insertions(+), 329 deletions(-) create mode 100644 src/drivers/devices/device.h create mode 100644 src/drivers/devices/esp32CAM.h rename src/drivers/{ => displays}/display.cpp (100%) rename src/drivers/{ => displays}/display.h (94%) rename src/drivers/{drivers.h => displays/displayDriver.h} (73%) create mode 100644 src/drivers/storage/SDCard.cpp create mode 100644 src/drivers/storage/SDCard.h create mode 100644 src/drivers/storage/nvMemory.cpp create mode 100644 src/drivers/storage/nvMemory.h create mode 100644 src/drivers/storage/storage.h diff --git a/.gitignore b/.gitignore index bebd06e..f7eadc5 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,8 @@ .pio .vscode +.vs +*.sln +*.vcxproj* NerdMinerLog.txt bin/0x10000_firmware.bin logs diff --git a/README.md b/README.md index e38bde5..dd37a9c 100644 --- a/README.md +++ b/README.md @@ -44,6 +44,7 @@ Every time an stratum job notification is received miner update its current work - LILYGO T-Display S3 AMOLED ([Aliexpress link](https://s.click.aliexpress.com/e/_DmOIK6j)) - LILYGO T-Dongle S3 ([Aliexpress link](https://s.click.aliexpress.com/e/_DmQCPyj)) - ESP32-2432S028R 2,8" ([Aliexpress link](https://s.click.aliexpress.com/e/_DdXkvLv)) +- ESP32-cam [Board Info](https://lastminuteengineers.com/getting-started-with-esp32-cam/) ### Flash firmware #### microMiners Flashtool [Recommended] @@ -75,12 +76,33 @@ Update NerdMiner firmware following same flashing steps but only adding 0x10000_ ### NerdMiner configuration After programming, you will only need to setup your Wifi and BTC address. +#### Wifi Accesspoint + 1. Connect to NerdMinerAP - AP: NerdMinerAP - PASS: MineYourCoins 1. Setup your Wifi Network 1. Add your BTCaddress +#### SD card (if available) + +1. Format a SD card using Fat32. +1. Create a file named "config.json" in your card's root, containing the the following structure. Adjust the settings to your needs: +{ + "SSID": "myWifiSSID", + "PW": "myWifiPassword", + "PoolUrl": "public-pool.io", + "PoolPort": 21496, + "BtcWallet": "walletID", + "Timezone": 2, + "saveStats": false +} +1. Insert the SD card. +1. Hold down the "reset configurations" button as described below to reset the configurations and/or boot without settings in your nvmemory. +1. Power down to remove the SD card. It is not needed for mining. + +#### Pool selection + Recommended low difficulty share pools: | Pool URL | Port | Web URL | Status | @@ -99,6 +121,15 @@ Other standard pools not compatible with low difficulty share: | eu.stratum.slushpool.com | 3333 | https://braiins.com/pool | ### Buttons + +#### One button devices: + +- One click > change screen. +- Double click > change screen orientation. +- Tripple click > turn the screen off and on again. +- Hold 5 seconds > **reset the configurations and reboot** your NerdMiner. + +#### Two button devices: With the USB-C port to the right: **TOP BUTTON** diff --git a/lib/TFT_eSPI/Processors/TFT_eSPI_ESP32_S3.h b/lib/TFT_eSPI/Processors/TFT_eSPI_ESP32_S3.h index 4438fe9..f090f24 100644 --- a/lib/TFT_eSPI/Processors/TFT_eSPI_ESP32_S3.h +++ b/lib/TFT_eSPI/Processors/TFT_eSPI_ESP32_S3.h @@ -375,7 +375,7 @@ SPI3_HOST = 2 if ( c & 0x20 ) xset_mask[c] |= (1 << (TFT_D5-MASK_OFFSET)); \ if ( c & 0x40 ) xset_mask[c] |= (1 << (TFT_D6-MASK_OFFSET)); \ if ( c & 0x80 ) xset_mask[c] |= (1 << (TFT_D7-MASK_OFFSET)); \ - } \ + } \ // Mask for the 8 data bits to set pin directions #define GPIO_DIR_MASK ((1 << (TFT_D0-MASK_OFFSET)) | (1 << (TFT_D1-MASK_OFFSET)) | (1 << (TFT_D2-MASK_OFFSET)) | (1 << (TFT_D3-MASK_OFFSET)) | (1 << (TFT_D4-MASK_OFFSET)) | (1 << (TFT_D5-MASK_OFFSET)) | (1 << (TFT_D6-MASK_OFFSET)) | (1 << (TFT_D7-MASK_OFFSET))) diff --git a/platformio.ini b/platformio.ini index b039650..ef7a08f 100644 --- a/platformio.ini +++ b/platformio.ini @@ -10,7 +10,7 @@ [platformio] globallib_dir = lib -default_envs = ESP32-2432S028R ;NerminerV2, ESP32-devKitv1, NerminerV2-S3-DONGLE, NerminerV2-S3-AMOLED, NerminerV2-T-QT, NerdminerV2-T-Display_V1, ESP32-2432S028R +default_envs = esp32cam, ESP32-2432S028R, NerminerV2, ESP32-devKitv1, NerminerV2-S3-DONGLE, NerminerV2-S3-AMOLED, NerminerV2-T-QT, NerdminerV2-T-Display_V1, ESP32-2432S028R [env:NerminerV2] platform = espressif32 @@ -23,13 +23,11 @@ monitor_filters = board_build.arduino.memory_type = qio_opi monitor_speed = 115200 upload_speed = 115200 - # 2 x 4.5MB app, 6.875MB SPIFFS ;board_build.partitions = large_spiffs_16MB.csv ;board_build.partitions = default_8MB.csv board_build.partitions = huge_app.csv ;board_build.partitions = default.csv - build_flags = -D LV_LVGL_H_INCLUDE_SIMPLE -D BOARD_HAS_PSRAM @@ -45,7 +43,6 @@ lib_deps = arduino-libraries/NTPClient ;https://github.com/golden-guy/Arduino_wolfssl.git#v5.5.4 - [env:ESP32-devKitv1] platform = espressif32 board = esp32dev @@ -57,10 +54,8 @@ monitor_filters = ;board_build.arduino.memory_type = qio_opi monitor_speed = 115200 upload_speed = 115200 - # 2 x 4.5MB app, 6.875MB SPIFFS board_build.partitions = huge_app.csv - build_flags = -D DEVKITV1=1 ;-D DEBUG_MINING=1 @@ -71,7 +66,6 @@ lib_deps = mathertel/OneButton @ ^2.0.3 arduino-libraries/NTPClient - [env:TTGO-T-Display] platform = espressif32 board = esp32dev ;esp-wrover-kit @@ -83,11 +77,8 @@ monitor_filters = board_build.arduino.memory_type = qio_opi monitor_speed = 115200 upload_speed = 115200 - - # 2 x 4.5MB app, 6.875MB SPIFFS board_build.partitions = huge_app.csv - build_flags = ;-D DEBUG_MINING=1 -D TDISPLAY=1 @@ -103,9 +94,7 @@ lib_deps = platform = espressif32 board = lilygo-t-amoled framework = arduino - board_build.partitions = huge_app.csv - build_flags = -DNERMINER_S3_AMOLED -DBOARD_HAS_PSRAM @@ -122,9 +111,7 @@ lib_deps = platform = espressif32 board = esp32-s3-devkitc-1 framework = arduino - board_build.partitions = huge_app.csv - build_flags = -DNERMINER_S3_DONGLE -DBOARD_HAS_PSRAM @@ -135,8 +122,31 @@ lib_deps = https://github.com/tzapu/WiFiManager.git mathertel/OneButton @ ^2.0.3 arduino-libraries/NTPClient - https://github.com/golden-guy/Arduino_wolfssl.git#v5.5.4 https://github.com/FastLED/FastLED + ;https://github.com/golden-guy/Arduino_wolfssl.git#v5.5.4 + +[env:esp32cam] +platform = espressif32 ;(ESP32-D0WD-V3) +board = esp32cam +framework = arduino +monitor_filters = + esp32_exception_decoder + time + log2file +monitor_speed = 115200 +upload_speed = 921600 +board_build.partitions = huge_app.csv +build_flags = + -D ESP32_CAM + -D MONITOR_SPEED=${this.monitor_speed} +lib_deps = + ;https://github.com/takkaO/OpenFontRender + bblanchon/ArduinoJson@^6.21.2 + https://github.com/tzapu/WiFiManager.git + mathertel/OneButton @ ^2.0.3 + arduino-libraries/NTPClient +lib_ignore = + TFT_eSPI [env:NerminerV2-T-QT] platform = espressif32 diff --git a/src/NerdMinerV2.ino.cpp b/src/NerdMinerV2.ino.cpp index 94e802f..9904d15 100644 --- a/src/NerdMinerV2.ino.cpp +++ b/src/NerdMinerV2.ino.cpp @@ -10,7 +10,7 @@ #include "wManager.h" #include "mining.h" #include "monitor.h" -#include "drivers/display.h" +#include "drivers/displays/display.h" //3 seconds WDT #define WDT_TIMEOUT 3 @@ -38,7 +38,12 @@ const char* ntpServer = "pool.ntp.org"; /********* INIT *****/ void setup() { - Serial.begin(115200); +#ifdef MONITOR_SPEED + Serial.begin(MONITOR_SPEED); +#else + Serial.begin(115200); +#endif //MONITOR_SPEED + Serial.setTimeout(0); delay(100); @@ -52,7 +57,8 @@ void setup() button1.setPressTicks(5000); button1.attachClick(switchToNextScreen); button1.attachDoubleClick(alternateScreenRotation); - button1.attachLongPressStart(reset_configurations); + button1.attachLongPressStart(reset_configuration); + button1.attachMultiClick(alternateScreenState); #endif #if defined(PIN_BUTTON_1) && defined(PIN_BUTTON_2) //Button 1 of two button device @@ -64,7 +70,7 @@ void setup() #if defined(PIN_BUTTON_2) //Button 2 of two button device button2.setPressTicks(5000); button2.attachClick(switchToNextScreen); - button2.attachLongPressStart(reset_configurations); + button2.attachLongPressStart(reset_configuration); #endif /******** INIT NERDMINER ************/ diff --git a/src/drivers/devices/device.h b/src/drivers/devices/device.h new file mode 100644 index 0000000..7d8ba51 --- /dev/null +++ b/src/drivers/devices/device.h @@ -0,0 +1,27 @@ +#ifndef __DEVICE_H__ +#define __DEVICE_H__ + +#if defined(NERDMINERV2) +#include "nerdMinerV2.h" +#elif defined(DEVKITV1) +#include "esp32DevKit.h" +#elif defined(TDISPLAY) +#include "lilygoS3TDisplay.h" +#elif defined(NERMINER_S3_AMOLED) +#include "lilygoS3Amoled.h" +#elif defined(NERMINER_S3_DONGLE) +#include "lilygoS3Dongle.h" +#elif defined(ESP32_2432S028R) +#include "esp322432s028r.h" +#elif defined(NERMINER_T_QT) +#include "lilygoT_QT.h" +#elif defined(NERDMINER_T_DISPLAY_V1) +#include "lilygoV1TDisplay.h" +#elif defined(ESP32_CAM) +#include "esp32CAM.h" + +#else +#error "No device defined" +#endif + +#endif // __DEVICE_H__ \ No newline at end of file diff --git a/src/drivers/devices/esp32CAM.h b/src/drivers/devices/esp32CAM.h new file mode 100644 index 0000000..54d7460 --- /dev/null +++ b/src/drivers/devices/esp32CAM.h @@ -0,0 +1,18 @@ +#ifndef _ESP32CAM_H_ +#define _ESP32CAM_H_ + +#define PIN_BUTTON_1 0 +#define LED_PIN 33 + +#define NO_DISPLAY + +// SDMMC interface: 1-bit mode (might cause issues): +#define SDMMC_CLK 14 +#define SDMMC_CMD 15 +#define SDMMC_D0 2 +// additional defines to enable 4-bit mode +#define SDMMC_D1 4 +#define SDMMC_D2 12 +#define SDMMC_D3 13 + +#endif // _ESP32_CAM_H_ diff --git a/src/drivers/displays/amoledDisplayDriver.cpp b/src/drivers/displays/amoledDisplayDriver.cpp index c0eae8b..4abc576 100644 --- a/src/drivers/displays/amoledDisplayDriver.cpp +++ b/src/drivers/displays/amoledDisplayDriver.cpp @@ -1,4 +1,4 @@ -#include "../drivers.h" +#include "DisplayDriver.h" #ifdef AMOLED_DISPLAY diff --git a/src/drivers/display.cpp b/src/drivers/displays/display.cpp similarity index 100% rename from src/drivers/display.cpp rename to src/drivers/displays/display.cpp diff --git a/src/drivers/display.h b/src/drivers/displays/display.h similarity index 94% rename from src/drivers/display.h rename to src/drivers/displays/display.h index 331ea95..2a4a469 100644 --- a/src/drivers/display.h +++ b/src/drivers/displays/display.h @@ -1,7 +1,7 @@ #ifndef DISPLAY_H #define DISPLAY_H -#include "drivers.h" +#include "DisplayDriver.h" extern DisplayDriver *currentDisplayDriver; diff --git a/src/drivers/drivers.h b/src/drivers/displays/displayDriver.h similarity index 73% rename from src/drivers/drivers.h rename to src/drivers/displays/displayDriver.h index 9897db0..939b00c 100644 --- a/src/drivers/drivers.h +++ b/src/drivers/displays/displayDriver.h @@ -1,26 +1,7 @@ -#ifndef DRIVERS_H -#define DRIVERS_H +#ifndef DISPLAYDRIVER_H_ +#define DISPLAYDRIVER_H_ -#if defined(NERDMINERV2) -#include "devices/nerdMinerV2.h" -#elif defined(DEVKITV1) -#include "devices/esp32DevKit.h" -#elif defined(TDISPLAY) -#include "devices/lilygoS3TDisplay.h" -#elif defined(NERMINER_S3_AMOLED) -#include "devices/lilygoS3Amoled.h" -#elif defined(NERMINER_S3_DONGLE) -#include "devices/lilygoS3Dongle.h" -#elif defined(ESP32_2432S028R) -#include "devices/esp322432s028r.h" -#elif defined(NERMINER_T_QT) -#include "devices/lilygoT_QT.h" -#elif defined(NERDMINER_T_DISPLAY_V1) -#include "devices/lilygoV1TDisplay.h" - -#else -#error "No device defined" -#endif +#include "..\devices\device.h" typedef void (*AlternateFunction)(void); typedef void (*DriverInitFunction)(void); @@ -57,4 +38,4 @@ extern DisplayDriver tDisplayV1Driver; #define SCREENS_ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0])) -#endif // DRIVERS_H +#endif // DISPLAYDRIVER_H_ diff --git a/src/drivers/displays/dongleDisplayDriver.cpp b/src/drivers/displays/dongleDisplayDriver.cpp index 2ba6356..f6b4fe0 100644 --- a/src/drivers/displays/dongleDisplayDriver.cpp +++ b/src/drivers/displays/dongleDisplayDriver.cpp @@ -1,4 +1,4 @@ -#include "../drivers.h" +#include "DisplayDriver.h" #ifdef DONGLE_DISPLAY @@ -45,15 +45,15 @@ extern monitor_data mMonitor; int32_t x = 8, y = 8; \ background.setTextSize(1); \ background.setTextFont(FONT2); \ - \ + \ background.setTextColor(KEY_COLOR); \ - \ + \ render.setFontSize(18); #define CLEAR_SCREEN() \ RESET_SCREEN(); \ background.fillRect(0, 0, BUFFER_WIDTH, BUFFER_HEIGHT, BACK_COLOR); \ - \ + \ #define PRINT_STR(str) \ diff --git a/src/drivers/displays/esp23_2432s028r.cpp b/src/drivers/displays/esp23_2432s028r.cpp index 7788014..daef827 100644 --- a/src/drivers/displays/esp23_2432s028r.cpp +++ b/src/drivers/displays/esp23_2432s028r.cpp @@ -1,4 +1,4 @@ -#include "../drivers.h" +#include "DisplayDriver.h" #ifdef ESP32_2432S028R diff --git a/src/drivers/displays/noDisplayDriver.cpp b/src/drivers/displays/noDisplayDriver.cpp index 23a74bd..636cf81 100644 --- a/src/drivers/displays/noDisplayDriver.cpp +++ b/src/drivers/displays/noDisplayDriver.cpp @@ -1,4 +1,4 @@ -#include "../drivers.h" +#include "DisplayDriver.h" #ifdef NO_DISPLAY diff --git a/src/drivers/displays/tDisplayDriver.cpp b/src/drivers/displays/tDisplayDriver.cpp index 6eb454b..76eede4 100644 --- a/src/drivers/displays/tDisplayDriver.cpp +++ b/src/drivers/displays/tDisplayDriver.cpp @@ -1,4 +1,4 @@ -#include "../drivers.h" +#include "DisplayDriver.h" #ifdef T_DISPLAY diff --git a/src/drivers/displays/tDisplayV1Driver.cpp b/src/drivers/displays/tDisplayV1Driver.cpp index ac05290..93b8f76 100644 --- a/src/drivers/displays/tDisplayV1Driver.cpp +++ b/src/drivers/displays/tDisplayV1Driver.cpp @@ -1,4 +1,4 @@ -#include "../drivers.h" +#include "DisplayDriver.h" #ifdef V1_DISPLAY diff --git a/src/drivers/displays/t_qtDisplayDriver.cpp b/src/drivers/displays/t_qtDisplayDriver.cpp index c5ddadc..f632cae 100644 --- a/src/drivers/displays/t_qtDisplayDriver.cpp +++ b/src/drivers/displays/t_qtDisplayDriver.cpp @@ -1,4 +1,4 @@ -#include "../drivers.h" +#include "DisplayDriver.h" #ifdef T_QT_DISPLAY diff --git a/src/drivers/storage/SDCard.cpp b/src/drivers/storage/SDCard.cpp new file mode 100644 index 0000000..fe06bde --- /dev/null +++ b/src/drivers/storage/SDCard.cpp @@ -0,0 +1,157 @@ + +#include +#include +#include + +#include "storage.h" +#include "nvMemory.h" +#include "..\devices\device.h" +#include "SDCard.h" + +#if defined (BUILD_SDMMC_1) || defined(BUILD_SDMMC_4) + +#include + +SDCard::SDCard() +{ +#if defined (BUILD_SDMMC_1) || defined(BUILD_SDMMC_4) + iSD_ = &SD_MMC; +#elif defined (BUILD_SDSPI) +#error You chose to run the sd card in SPI mode. This is not implemented yet. +#endif +} + +SDCard::~SDCard() +{ + unmount(); +} + +void SDCard::SD2nvMemory(nvMemory* nvMem) +{ + TSettings Settings; + if (loadConfigFile(&Settings)) + { + nvMem->saveConfig(&Settings); + WiFi.begin(Settings.WifiSSID, Settings.WifiPW); + Serial.println("SDCard: Settings transfered to internal memory. Restarting now."); + ESP.restart(); + } +} + +bool SDCard::loadConfigFile(TSettings* Settings) +{ + // Load existing configuration file + // Read configuration from FS json + + if (initSDcard()) + { + if (iSD_->exists(JSON_CONFIG_FILE)) + { + // The file exists, reading and loading + File configFile = iSD_->open(JSON_CONFIG_FILE, "r"); + if (configFile) + { + StaticJsonDocument<512> json; + DeserializationError error = deserializeJson(json, configFile); + configFile.close(); + Serial.println("SDCard: Loading config file"); + serializeJsonPretty(json, Serial); + Serial.print('\n'); + unmount(); + if (!error) + { + strcpy(Settings->WifiSSID, json[JSON_KEY_SSID] | Settings->WifiSSID); + strcpy(Settings->WifiPW, json[JSON_KEY_PASW] | Settings->WifiPW); + strcpy(Settings->PoolAddress, json[JSON_KEY_POOLURL] | Settings->PoolAddress); + strcpy(Settings->BtcWallet, json[JSON_KEY_WALLETID] | Settings->BtcWallet); + if (json.containsKey(JSON_KEY_POOLPORT)) + Settings->PoolPort = json[JSON_KEY_POOLPORT].as(); + if (json.containsKey(JSON_KEY_TIMEZONE)) + Settings->Timezone = json[JSON_KEY_TIMEZONE].as(); + if (json.containsKey(JSON_KEY_STATS2NV)) + Settings->saveStats = json[JSON_KEY_STATS2NV].as(); + return true; + } + else + { + // Error loading JSON data + Serial.println("SDCard: Error parsing config file!"); + } + } + else + { + Serial.println("SDCard: Error opening config file!"); + } + } + else + { + Serial.println("SDCard: No config file available!"); + } + unmount(); + } + return false; +} + +void SDCard::unmount() +{ + iSD_->end(); + Serial.println("SDCard: Unmounted"); +} + +bool SDCard::initSDcard() +{ + if (iSD_->cardType() != CARD_NONE) + { + Serial.println("SDCard: Already mounted."); + return true; + } + Serial.println("SDCard: Mounting card."); + + bool cardInitialized = false; +#if defined (BUILD_SDMMC_4) + if (iSD_->cardType() == CARD_NONE) + { + iSD_->setPins(SDMMC_CLK, SDMMC_CMD, SDMMC_D0, SDMMC_D1, SDMMC_D2, SDMMC_D3); + Serial.println("SDCard: 4-Bit Mode."); + cardInitialized = iSD_->begin("/sd", false); + } +#elif defined (BUILD_SDMMC_1) + #warning SDMMC : 1 - bit mode is not always working.If you experience issues, try other modes. + if (iSD_->cardType() == CARD_NONE) + { + iSD_->setPins(SDMMC_CLK, SDMMC_CMD, SDMMC_D0); + Serial.println("SDCard: 1-Bit Mode."); + cardInitialized = iSD_->begin("/sd", true); + } +#elif defined (BUILD_SDSPI) +#error You chose to run the sd card in SPI mode. This is not implemented yet. +#else + Serial.println("SDCard: interface not available."); + return false; +#endif // dataPinsDefined + if (cardInitialized) + { + if (iSD_->cardType() != CARD_NONE) + { + Serial.println("SDCard: Mounted."); + return true; + } + else + { + Serial.println("SDCard: Mounting failed."); + iSD_->end(); + } + } + return false; +} + +#else + +SDCard::SDCard() {} +SDCard::~SDCard() {} +void SDCard::SD2nvMemory(nvMemory* nvMem) {}; +bool SDCard::loadConfigFile(TSettings* Settings) { return false; } +bool SDCard::initSDcard() { return false; } +void unmount() {} + +#endif //BUILD_SDMMC \ No newline at end of file diff --git a/src/drivers/storage/SDCard.h b/src/drivers/storage/SDCard.h new file mode 100644 index 0000000..b2e91f5 --- /dev/null +++ b/src/drivers/storage/SDCard.h @@ -0,0 +1,38 @@ +#ifndef _SDCARD_H_ +#define _SDCARD_H_ + +#include "storage.h" +#include "nvMemory.h" +#include "..\devices\device.h" + +#if defined (SDMMC_D0) && defined (SDMMC_D1) && defined (SDMMC_D2) && defined (SDMMC_D3) +#define BUILD_SDMMC_4 +#include +#elif defined (SDMMC_D0) && !(defined (SDMMC_D1) && defined (SDMMC_D2) && defined (SDMMC_D3)) +#define BUILD_SDMMC_1 +#include +#else +#warning SD card support disabled! +#endif + +// Handles the transfer of settings from sd card to nv memory (wifi credentials are handled by wifimanager) +class SDCard +{ +public: + SDCard(); + ~SDCard(); + void SD2nvMemory(nvMemory* nvMem); + bool loadConfigFile(TSettings* Settings); +private: + bool initSDcard(); + void unmount(); + +#if defined (BUILD_SDMMC_1) || defined(BUILD_SDMMC_4) + fs::SDMMCFS* iSD_; +#elif defined (BUILD_SDSPI) +#error You chose to run the SD card in SPI mode. This is not implemented yet. + fs::SDFS* iSD_; +#endif +}; + +#endif // _SDCARD_H_ diff --git a/src/drivers/storage/nvMemory.cpp b/src/drivers/storage/nvMemory.cpp new file mode 100644 index 0000000..a686589 --- /dev/null +++ b/src/drivers/storage/nvMemory.cpp @@ -0,0 +1,148 @@ +#include "nvMemory.h" + +#ifdef NVMEM_SPIFFS + +#include +#include +#include + +#include "..\devices\device.h" +#include "storage.h" + +nvMemory::nvMemory() +{ + Initialized_ = false; +} + +nvMemory::~nvMemory() +{ + if (Initialized_) + SPIFFS.end(); +}; + +bool nvMemory::saveConfig(TSettings* Settings) +{ + if (init()) + { + // Save Config in JSON format + Serial.println(F("SPIFS: Saving configuration.")); + + // Create a JSON document + StaticJsonDocument<512> json; + json[JSON_KEY_POOLURL] = Settings->PoolAddress; + json[JSON_KEY_POOLPORT] = Settings->PoolPort; + json[JSON_KEY_WALLETID] = Settings->BtcWallet; + json[JSON_KEY_TIMEZONE] = Settings->Timezone; + json[JSON_KEY_STATS2NV] = Settings->saveStats; + + // Open config file + File configFile = SPIFFS.open(JSON_CONFIG_FILE, "w"); + if (!configFile) + { + // Error, file did not open + Serial.println("SPIFS: Failed to open config file for writing"); + return false; + } + + // Serialize JSON data to write to file + serializeJsonPretty(json, Serial); + Serial.print('\n'); + if (serializeJson(json, configFile) == 0) + { + // Error writing file + Serial.println(F("SPIFS: Failed to write to file")); + return false; + } + // Close file + configFile.close(); + return true; + }; + return false; +} + +bool nvMemory::loadConfig(TSettings* Settings) +{ + // Uncomment if we need to format filesystem + // SPIFFS.format(); + + // Load existing configuration file + // Read configuration from FS json + + if (init()) + { + if (SPIFFS.exists(JSON_CONFIG_FILE)) + { + // The file exists, reading and loading + File configFile = SPIFFS.open(JSON_CONFIG_FILE, "r"); + if (configFile) + { + Serial.println("SPIFS: Loading config file"); + StaticJsonDocument<512> json; + DeserializationError error = deserializeJson(json, configFile); + configFile.close(); + serializeJsonPretty(json, Serial); + Serial.print('\n'); + if (!error) + { + strcpy(Settings->PoolAddress, json[JSON_KEY_POOLURL] | Settings->PoolAddress); + strcpy(Settings->BtcWallet, json[JSON_KEY_WALLETID] | Settings->BtcWallet); + if (json.containsKey(JSON_KEY_POOLPORT)) + Settings->PoolPort = json[JSON_KEY_POOLPORT].as(); + if (json.containsKey(JSON_KEY_TIMEZONE)) + Settings->Timezone = json[JSON_KEY_TIMEZONE].as(); + if (json.containsKey(JSON_KEY_STATS2NV)) + Settings->saveStats = json[JSON_KEY_STATS2NV].as(); + return true; + } + else + { + // Error loading JSON data + Serial.println("SPIFS: Error parsing config file!"); + } + } + else + { + Serial.println("SPIFS: Error opening config file!"); + } + } + else + { + Serial.println("SPIFS: No config file available!"); + } + } + return false; +} + +bool nvMemory::deleteConfig() +{ + Serial.println("SPIFS: Erasing config file.."); + return SPIFFS.remove(JSON_CONFIG_FILE); //Borramos fichero +} + +bool nvMemory::init() +{ + if (!Initialized_) + { + Serial.println("SPIFS: Mounting File System..."); + // May need to make it begin(true) first time you are using SPIFFS + Initialized_ = SPIFFS.begin(false) || SPIFFS.begin(true); + Initialized_ ? Serial.println("SPIFS: Mounted") : Serial.println("SPIFS: Mounting failed."); + } + else + { + Serial.println("SPIFS: Already Mounted"); + } + return Initialized_; +}; + +#else + +nvMemory::nvMemory() {} +nvMemory::~nvMemory() {} +bool nvMemory::saveConfig(TSettings* Settings) { return false; } +bool nvMemory::loadConfig(TSettings* Settings) { return false; } +bool nvMemory::deleteConfig() { return false; } +bool nvMemory::init() { return false; } + + +#endif //NVMEM_TYPE \ No newline at end of file diff --git a/src/drivers/storage/nvMemory.h b/src/drivers/storage/nvMemory.h new file mode 100644 index 0000000..163431c --- /dev/null +++ b/src/drivers/storage/nvMemory.h @@ -0,0 +1,30 @@ +#ifndef _NVMEMORY_H_ +#define _NVMEMORY_H_ + +// we only have one implementation right now and nothing to choose from. +#define NVMEM_SPIFFS + +#include "..\devices\device.h" +#include "storage.h" + +// Handles load and store of user settings, except wifi credentials. Those are managed by the wifimanager. +class nvMemory +{ +public: + nvMemory(); + ~nvMemory(); + bool saveConfig(TSettings* Settings); + bool loadConfig(TSettings* Settings); + bool deleteConfig(); +private: + bool init(); + bool Initialized_; +}; + +#ifdef NVMEM_SPIFFS +#define ESP_DRD_USE_SPIFFS true +#else +#error We need some kind of permanent storage implementation! +#endif //NVMEM_TYPE + +#endif // _NVMEMORY_H_ diff --git a/src/drivers/storage/storage.h b/src/drivers/storage/storage.h new file mode 100644 index 0000000..8aa0668 --- /dev/null +++ b/src/drivers/storage/storage.h @@ -0,0 +1,35 @@ +#ifndef _STORAGE_H_ +#define _STORAGE_H_ + +#include + +#define DEFAULT_SSID "NerdMinerAP" +#define DEFAULT_WIFIPW "MineYourCoins" +#define DEFAULT_POOLURL "public-pool.io" +#define DEFAULT_WALLETID "yourBtcAddress" +#define DEFAULT_POOLPORT 21496 +#define DEFAULT_TIMEZONE 2 +#define DEFAULT_SAVESTATS false + +// JSON config file +#define JSON_CONFIG_FILE "/config.json" +#define JSON_KEY_SSID "SSID" +#define JSON_KEY_PASW "PW" +#define JSON_KEY_POOLURL "PoolUrl" +#define JSON_KEY_WALLETID "BtcWallet" +#define JSON_KEY_POOLPORT "PoolPort" +#define JSON_KEY_TIMEZONE "Timezone" +#define JSON_KEY_STATS2NV "saveStats" + +struct TSettings +{ + char WifiSSID[80]{ DEFAULT_SSID }; + char WifiPW[80]{ DEFAULT_WIFIPW }; + char PoolAddress[80]{ DEFAULT_POOLURL }; + char BtcWallet[80]{ DEFAULT_WALLETID }; + uint32_t PoolPort{ DEFAULT_POOLPORT }; + uint32_t Timezone{ DEFAULT_TIMEZONE }; + bool saveStats{ DEFAULT_SAVESTATS }; +}; + +#endif // _STORAGE_H_ \ No newline at end of file diff --git a/src/mining.cpp b/src/mining.cpp index 9bf3fce..d6f5694 100644 --- a/src/mining.cpp +++ b/src/mining.cpp @@ -10,7 +10,8 @@ #include "mining.h" #include "utils.h" #include "monitor.h" -#include "drivers/display.h" +#include "drivers/displays/display.h" +#include "drivers/storage/storage.h" nvs_handle_t stat_handle; @@ -28,11 +29,10 @@ uint32_t valids; // increased if blockhash <= target double best_diff = 0.0; // Variables to hold data from custom textboxes -extern char poolString[80]; -extern int portNumber; -extern char btcString[80]; +//Track mining stats in non volatile memory +extern TSettings Settings; + IPAddress serverIP(1, 1, 1, 1); //Temporally save poolIPaddres -extern bool saveStatsToNVS; //Track mining stats in non volatile memory //Global work data static WiFiClient client; @@ -59,14 +59,14 @@ bool checkPoolConnection(void) { //Resolve first time pool DNS and save IP if(serverIP == IPAddress(1,1,1,1)) { - WiFi.hostByName(poolString, serverIP); + WiFi.hostByName(Settings.PoolAddress, serverIP); Serial.printf("Resolved DNS and save ip (first time) got: %s\n", serverIP.toString()); } //Try connecting pool IP - if (!client.connect(serverIP, portNumber)) { - Serial.println("Imposible to connect to : " + String(poolString)); - WiFi.hostByName(poolString, serverIP); + if (!client.connect(serverIP, Settings.PoolPort)) { + Serial.println("Imposible to connect to : " + String(Settings.PoolAddress)); + WiFi.hostByName(Settings.PoolAddress, serverIP); Serial.printf("Resolved DNS got: %s\n", serverIP.toString()); vTaskDelay(1000 / portTICK_PERIOD_MS); return false; @@ -166,7 +166,7 @@ void runStratumWorker(void *name) { continue; } - strcpy(mWorker.wName, btcString); + strcpy(mWorker.wName, Settings.BtcWallet); strcpy(mWorker.wPass, "x"); // STEP 2: Pool authorize work (Block Info) tx_mining_auth(client, mWorker.wName, mWorker.wPass); //Don't verifies authoritzation, TODO @@ -386,7 +386,7 @@ void runMiner(void * task_id) { #define REDRAW_EVERY 10 void restoreStat() { - if(!saveStatsToNVS) return; + if(!Settings.saveStats) return; esp_err_t ret = nvs_flash_init(); if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) { Serial.printf("[MONITOR] NVS partition is full or has invalid version, erasing...\n"); @@ -405,7 +405,7 @@ void restoreStat() { } void saveStat() { - if(!saveStatsToNVS) return; + if(!Settings.saveStats) return; Serial.printf("[MONITOR] Saving stats\n"); nvs_set_blob(stat_handle, "best_diff", &best_diff, sizeof(double)); nvs_set_u32(stat_handle, "Mhashes", Mhashes); @@ -447,8 +447,8 @@ void runMonitor(void *name) if (elapsedKHs == 0) { Serial.printf(">>> [i] Miner: newJob>%s / inRun>%s) - Client: connected>%s / subscribed>%s / wificonnected>%s\n", - mMiner.newJob ? "true" : "false", mMiner.inRun ? "true" : "false", - client.connected() ? "true" : "false", isMinerSuscribed ? "true" : "false", WiFi.status() == WL_CONNECTED ? "true" : "false"); + mMiner.newJob ? "true" : "false", mMiner.inRun ? "true" : "false", + client.connected() ? "true" : "false", isMinerSuscribed ? "true" : "false", WiFi.status() == WL_CONNECTED ? "true" : "false"); } #ifdef DEBUG_MEMORY diff --git a/src/monitor.cpp b/src/monitor.cpp index 27753cd..56f1368 100644 --- a/src/monitor.cpp +++ b/src/monitor.cpp @@ -7,8 +7,8 @@ #include "mining.h" #include "utils.h" #include "monitor.h" +#include "drivers/storage/storage.h" -extern char poolString[80]; extern uint32_t templates; extern uint32_t hashes; extern uint32_t Mhashes; @@ -23,7 +23,8 @@ extern double best_diff; // track best diff extern monitor_data mMonitor; -extern int GMTzone; //Gotten from saved config +//from saved config +extern TSettings Settings; WiFiUDP ntpUDP; NTPClient timeClient(ntpUDP, "europe.pool.ntp.org", 3600, 60000); @@ -39,7 +40,7 @@ void setup_monitor(void){ // Adjust offset depending on your zone // GMT +2 in seconds (zona horaria de Europa Central) - timeClient.setTimeOffset(3600 * GMTzone); + timeClient.setTimeOffset(3600 * Settings.Timezone); Serial.println("TimeClient setup done"); } @@ -171,7 +172,6 @@ unsigned long mTriggerUpdate = 0; unsigned long initialMillis = millis(); unsigned long initialTime = 0; unsigned long mPoolUpdate = 0; -extern char btcString[80]; void getTime(unsigned long* currentHours, unsigned long* currentMinutes, unsigned long* currentSeconds){ @@ -296,7 +296,7 @@ pool_data getPoolData(void){ HTTPClient http; http.setReuse(true); try { - String btcWallet = btcString; + String btcWallet = Settings.BtcWallet; Serial.println(btcWallet); if (btcWallet.indexOf(".")>0) btcWallet = btcWallet.substring(0,btcWallet.indexOf(".")); http.begin(String(getPublicPool)+btcWallet); diff --git a/src/wManager.cpp b/src/wManager.cpp index 1e94ae4..93afff4 100644 --- a/src/wManager.cpp +++ b/src/wManager.cpp @@ -1,221 +1,148 @@ -#define ESP_DRD_USE_SPIFFS true // Include Libraries //#include ".h" #include -#include -#include #include -#include + #include "wManager.h" #include "monitor.h" -#include "drivers/display.h" +#include "drivers/displays/display.h" +#include "drivers/storage/SDCard.h" +#include "drivers/storage/nvMemory.h" +#include "drivers/storage/storage.h" -// JSON configuration file -#define JSON_CONFIG_FILE "/config.json" // Flag for saving data bool shouldSaveConfig = false; // Variables to hold data from custom textboxes -char poolString[80] = "public-pool.io"; -int portNumber = 21496;//3333; -char btcString[80] = "yourBtcAddress"; -int GMTzone = 2; //Currently selected in spain -bool saveStatsToNVS = false; //Track mining stats in non volatile memory - +TSettings Settings; // Define WiFiManager Object WiFiManager wm; extern monitor_data mMonitor; -void saveConfigFile() -// Save Config in JSON format -{ - Serial.println(F("Saving configuration...")); - - // Create a JSON document - StaticJsonDocument<512> json; - json["poolString"] = poolString; - json["portNumber"] = portNumber; - json["btcString"] = btcString; - json["gmtZone"] = GMTzone; - json["saveStatsToNVS"] = String(saveStatsToNVS); - - // Open config file - File configFile = SPIFFS.open(JSON_CONFIG_FILE, "w"); - if (!configFile) - { - // Error, file did not open - Serial.println("failed to open config file for writing"); - } - - // Serialize JSON data to write to file - serializeJsonPretty(json, Serial); - if (serializeJson(json, configFile) == 0) - { - // Error writing file - Serial.println(F("Failed to write to file")); - } - // Close file - configFile.close(); -} - -bool loadConfigFile() -// Load existing configuration file -{ - // Uncomment if we need to format filesystem - // SPIFFS.format(); - - // Read configuration from FS json - Serial.println("Mounting File System..."); - - // May need to make it begin(true) first time you are using SPIFFS - if (SPIFFS.begin(false) || SPIFFS.begin(true)) - { - Serial.println("mounted file system"); - if (SPIFFS.exists(JSON_CONFIG_FILE)) - { - // The file exists, reading and loading - Serial.println("reading config file"); - File configFile = SPIFFS.open(JSON_CONFIG_FILE, "r"); - if (configFile) - { - Serial.println("Opened configuration file"); - StaticJsonDocument<512> json; - DeserializationError error = deserializeJson(json, configFile); - configFile.close(); - serializeJsonPretty(json, Serial); - if (!error) - { - Serial.println("Parsing JSON"); - - strcpy(poolString, json["poolString"]); - strcpy(btcString, json["btcString"]); - portNumber = json["portNumber"].as(); - GMTzone = json["gmtZone"].as(); - if(json.containsKey("saveStatsToNVS")) - saveStatsToNVS = json["saveStatsToNVS"].as(); - return true; - } - else - { - // Error loading JSON data - Serial.println("Failed to load json config"); - } - } - } - } - else - { - // Error mounting file system - Serial.println("Failed to mount FS"); - } - - return false; -} - +nvMemory nvMem; void saveConfigCallback() // Callback notifying us of the need to save configuration { - Serial.println("Should save config"); - shouldSaveConfig = true; - //wm.setConfigPortalBlocking(false); + Serial.println("Should save config"); + shouldSaveConfig = true; + //wm.setConfigPortalBlocking(false); } -void configModeCallback(WiFiManager *myWiFiManager) +void configModeCallback(WiFiManager* myWiFiManager) // Called when config mode launched { - Serial.println("Entered Configuration Mode"); + Serial.println("Entered Configuration Mode"); - Serial.print("Config SSID: "); - Serial.println(myWiFiManager->getConfigPortalSSID()); + Serial.print("Config SSID: "); + Serial.println(myWiFiManager->getConfigPortalSSID()); - Serial.print("Config IP Address: "); - Serial.println(WiFi.softAPIP()); + Serial.print("Config IP Address: "); + Serial.println(WiFi.softAPIP()); +} + +void reset_configuration() +{ + Serial.println("Erasing Config, restarting"); + nvMem.deleteConfig(); + wm.resetSettings(); + ESP.restart(); } void init_WifiManager() { - Serial.begin(115200); - //Serial.setTxTimeoutMs(10); +#ifdef MONITOR_SPEED + Serial.begin(MONITOR_SPEED); +#else + Serial.begin(115200); +#endif //MONITOR_SPEED + //Serial.setTxTimeoutMs(10); - //Init pin 15 to eneble 5V external power (LilyGo bug) - #ifdef PIN_ENABLE5V + //Init pin 15 to eneble 5V external power (LilyGo bug) +#ifdef PIN_ENABLE5V pinMode(PIN_ENABLE5V, OUTPUT); digitalWrite(PIN_ENABLE5V, HIGH); - #endif +#endif - // Change to true when testing to force configuration every time we run - bool forceConfig = false; + // Change to true when testing to force configuration every time we run + bool forceConfig = false; - #if defined(PIN_BUTTON_2) +#if defined(PIN_BUTTON_2) // Check if button2 is pressed to enter configMode with actual configuration - if(!digitalRead(PIN_BUTTON_2)){ - Serial.println(F("Button pressed to force start config mode")); - forceConfig = true; - wm.setBreakAfterConfig(true); //Set to detect config edition and save + if (!digitalRead(PIN_BUTTON_2)) { + Serial.println(F("Button pressed to force start config mode")); + forceConfig = true; + wm.setBreakAfterConfig(true); //Set to detect config edition and save } - #endif - - bool spiffsSetup = loadConfigFile(); - if (!spiffsSetup) - { - Serial.println(F("Forcing config mode as there is no saved config")); - forceConfig = true; - - } +#endif + // Explicitly set WiFi mode + WiFi.mode(WIFI_STA); - // Explicitly set WiFi mode - WiFi.mode(WIFI_STA); + if (!nvMem.loadConfig(&Settings)) + { + //No config file on internal flash. + SDCard SDCrd; + if (SDCrd.loadConfigFile(&Settings)) + { + //Config file on SD card. + SDCrd.SD2nvMemory(&nvMem); // reboot on success. + } + else + { + //No config file on SD card. Starting wifi config server. + forceConfig = true; + } + }; - // Reset settings (only for development) - //wm.resetSettings(); + // Reset settings (only for development) + //wm.resetSettings(); - //Set dark theme - //wm.setClass("invert"); // dark theme - - // Set config save notify callback - wm.setSaveConfigCallback(saveConfigCallback); + //Set dark theme + //wm.setClass("invert"); // dark theme - // Set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode - wm.setAPCallback(configModeCallback); + // Set config save notify callback + wm.setSaveConfigCallback(saveConfigCallback); - //Advanced settings - wm.setConfigPortalBlocking(false); //Hacemos que el portal no bloquee el firmware - wm.setConnectTimeout(50); // how long to try to connect for before continuing - //wm.setConfigPortalTimeout(30); // auto close configportal after n seconds - // wm.setCaptivePortalEnable(false); // disable captive portal redirection - // wm.setAPClientCheck(true); // avoid timeout if client connected to softap - //wm.setTimeout(120); - //wm.setConfigPortalTimeout(120); //seconds - - // Custom elements + // Set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode + wm.setAPCallback(configModeCallback); - // Text box (String) - 80 characters maximum - WiFiManagerParameter pool_text_box("Poolurl", "Pool url", poolString, 80); + //Advanced settings + wm.setConfigPortalBlocking(false); //Hacemos que el portal no bloquee el firmware + wm.setConnectTimeout(50); // how long to try to connect for before continuing + //wm.setConfigPortalTimeout(30); // auto close configportal after n seconds + // wm.setCaptivePortalEnable(false); // disable captive portal redirection + // wm.setAPClientCheck(true); // avoid timeout if client connected to softap + //wm.setTimeout(120); + //wm.setConfigPortalTimeout(120); //seconds - // Need to convert numerical input to string to display the default value. - char convertedValue[6]; - sprintf(convertedValue, "%d", portNumber); - - // Text box (Number) - 7 characters maximum - WiFiManagerParameter port_text_box_num("Poolport", "Pool port", convertedValue, 7); + // Custom elements - // Text box (String) - 80 characters maximum - WiFiManagerParameter addr_text_box("btcAddress", "Your BTC address", btcString, 80); + // Text box (String) - 80 characters maximum + WiFiManagerParameter pool_text_box("Poolurl", "Pool url", Settings.PoolAddress, 80); + + // Need to convert numerical input to string to display the default value. + char convertedValue[6]; + sprintf(convertedValue, "%d", Settings.PoolPort); + + // Text box (Number) - 7 characters maximum + WiFiManagerParameter port_text_box_num("Poolport", "Pool port", convertedValue, 7); + + // Text box (String) - 80 characters maximum + WiFiManagerParameter addr_text_box("btcAddress", "Your BTC address", Settings.BtcWallet, 80); // Text box (Number) - 2 characters maximum char charZone[6]; - sprintf(charZone, "%d", GMTzone); + sprintf(charZone, "%d", Settings.Timezone); WiFiManagerParameter time_text_box_num("TimeZone", "TimeZone fromUTC (-12/+12)", charZone, 3); WiFiManagerParameter features_html("

"); char checkboxParams[24] = "type=\"checkbox\""; - if (saveStatsToNVS) + if (Settings.saveStats) { strcat(checkboxParams, " checked"); } @@ -229,109 +156,103 @@ void init_WifiManager() wm.addParameter(&features_html); wm.addParameter(&save_stats_to_nvs); - Serial.println("AllDone: "); - if (forceConfig) - // Run if we need a configuration - { - //No configuramos timeout al modulo - wm.setConfigPortalBlocking(true); //Hacemos que el portal SI bloquee el firmware - drawSetupScreen(); - if (!wm.startConfigPortal("NerdMinerAP","MineYourCoins")) + Serial.println("AllDone: "); + if (forceConfig) { - Serial.println("failed to connect and hit timeout"); - //Could be break forced after edditing, so save new config - strncpy(poolString, pool_text_box.getValue(), sizeof(poolString)); - portNumber = atoi(port_text_box_num.getValue()); - strncpy(btcString, addr_text_box.getValue(), sizeof(btcString)); - GMTzone = atoi(time_text_box_num.getValue()); - saveStatsToNVS = (strncmp(save_stats_to_nvs.getValue(), "T", 1) == 0); - saveConfigFile(); - delay(3000); - //reset and try again, or maybe put it to deep sleep - ESP.restart(); - delay(5000); + // Run if we need a configuration + //No configuramos timeout al modulo + wm.setConfigPortalBlocking(true); //Hacemos que el portal SI bloquee el firmware + drawSetupScreen(); + + if (wm.startConfigPortal(DEFAULT_SSID, DEFAULT_WIFIPW)) + { + //Could be break forced after edditing, so save new config + Serial.println("failed to connect and hit timeout"); + strncpy(Settings.PoolAddress, pool_text_box.getValue(), sizeof(Settings.PoolAddress)); + Settings.PoolPort = atoi(port_text_box_num.getValue()); + strncpy(Settings.BtcWallet, addr_text_box.getValue(), sizeof(Settings.BtcWallet)); + Settings.Timezone = atoi(time_text_box_num.getValue()); + Serial.println(save_stats_to_nvs.getValue()); + Settings.saveStats = (strncmp(save_stats_to_nvs.getValue(), "T", 1) == 0); + + nvMem.saveConfig(&Settings); + delay(3000); + //reset and try again, or maybe put it to deep sleep + ESP.restart(); + delay(5000); + }; } - } - else - { - //Tratamos de conectar con la configuración inicial ya almacenada + else + { + //Tratamos de conectar con la configuración inicial ya almacenada + mMonitor.NerdStatus = NM_Connecting; + wm.setCaptivePortalEnable(false); // disable captive portal redirection + if (!wm.autoConnect(Settings.WifiSSID, Settings.WifiPW)) + { + Serial.println("Failed to connect and hit timeout"); + //delay(3000); + // if we still have not connected restart and try all over again + //ESP.restart(); + //delay(5000); + } + } + mMonitor.NerdStatus = NM_Connecting; - wm.setCaptivePortalEnable(false); // disable captive portal redirection - if (!wm.autoConnect("NerdMinerAP","MineYourCoins")) - { - Serial.println("Failed to connect and hit timeout"); - //delay(3000); - // if we still have not connected restart and try all over again - //ESP.restart(); - //delay(5000); + + //Conectado a la red Wifi + if (WiFi.status() == WL_CONNECTED) { + //tft.pushImage(0, 0, MinerWidth, MinerHeight, MinerScreen); + Serial.println(""); + Serial.println("WiFi connected"); + Serial.print("IP address: "); + Serial.println(WiFi.localIP()); + + // Lets deal with the user config values + + // Copy the string value + strncpy(Settings.PoolAddress, pool_text_box.getValue(), sizeof(Settings.PoolAddress)); + Serial.print("PoolString: "); + Serial.println(Settings.PoolAddress); + + //Convert the number value + Settings.PoolPort = atoi(port_text_box_num.getValue()); + Serial.print("portNumber: "); + Serial.println(Settings.PoolPort); + + // Copy the string value + strncpy(Settings.BtcWallet, addr_text_box.getValue(), sizeof(Settings.BtcWallet)); + Serial.print("btcString: "); + Serial.println(Settings.BtcWallet); + + //Convert the number value + Settings.Timezone = atoi(time_text_box_num.getValue()); + Serial.print("TimeZone fromUTC: "); + Serial.println(Settings.Timezone); + } - } - mMonitor.NerdStatus = NM_Connecting; - - //Conectado a la red Wifi - if(WiFi.status() == WL_CONNECTED){ - //tft.pushImage(0, 0, MinerWidth, MinerHeight, MinerScreen); - Serial.println(""); - Serial.println("WiFi connected"); - Serial.print("IP address: "); - Serial.println(WiFi.localIP()); - - // Lets deal with the user config values - - // Copy the string value - strncpy(poolString, pool_text_box.getValue(), sizeof(poolString)); - Serial.print("PoolString: "); - Serial.println(poolString); - - //Convert the number value - portNumber = atoi(port_text_box_num.getValue()); - Serial.print("portNumber: "); - Serial.println(portNumber); - - // Copy the string value - strncpy(btcString, addr_text_box.getValue(), sizeof(btcString)); - Serial.print("btcString: "); - Serial.println(btcString); - - //Convert the number value - GMTzone = atoi(time_text_box_num.getValue()); - Serial.print("TimeZone fromUTC: "); - Serial.println(GMTzone); - } - - // Save the custom parameters to FS - if (shouldSaveConfig) - { - saveConfigFile(); - } + // Save the custom parameters to FS + if (shouldSaveConfig) + { + nvMem.saveConfig(&Settings); + } } -void reset_configurations() { - Serial.println("Erasing Config, restarting"); - wm.resetSettings(); - SPIFFS.remove(JSON_CONFIG_FILE); //Borramos fichero - ESP.restart(); -} - - //----------------- MAIN PROCESS WIFI MANAGER -------------- int oldStatus = 0; void wifiManagerProcess() { - - wm.process(); // avoid delays() in loop when non-blocking and other long running code - - int newStatus = WiFi.status(); - if (newStatus != oldStatus) { - if (newStatus == WL_CONNECTED) { - Serial.println("CONNECTED - Current ip: " + WiFi.localIP().toString()); - } else { - Serial.print("[Error] - current status: "); - Serial.println(newStatus); + + wm.process(); // avoid delays() in loop when non-blocking and other long running code + + int newStatus = WiFi.status(); + if (newStatus != oldStatus) { + if (newStatus == WL_CONNECTED) { + Serial.println("CONNECTED - Current ip: " + WiFi.localIP().toString()); + } else { + Serial.print("[Error] - current status: "); + Serial.println(newStatus); + } + oldStatus = newStatus; } - oldStatus = newStatus; - } } - - diff --git a/src/wManager.h b/src/wManager.h index 870b435..ef2bd37 100644 --- a/src/wManager.h +++ b/src/wManager.h @@ -1,3 +1,8 @@ +#ifndef _WMANAGER_H +#define _WMANAGER_H + void init_WifiManager(); void wifiManagerProcess(); -void reset_configurations(); \ No newline at end of file +void reset_configuration(); + +#endif // _WMANAGER_H