cleanup, fix

This commit is contained in:
elmo128 2023-09-14 22:32:25 +02:00
parent 787d92820c
commit ab48dbf5e3
6 changed files with 192 additions and 229 deletions

View File

@ -11,8 +11,6 @@
#include "storage.h" #include "storage.h"
#include "SPIStorage.h" #include "SPIStorage.h"
#define JSON_CONFIG_FILE "/config.json"
class SDCard class SDCard
{ {
private: private:
@ -20,7 +18,7 @@ private:
public: public:
SDCard() SDCard()
{ {
cardInitialized_ = initSDcard(); cardInitialized_ = false;
} }
~SDCard() ~SDCard()
@ -29,42 +27,26 @@ public:
SD_MMC.end(); SD_MMC.end();
} }
bool initSDcard() void SD2SPIStorage(SPIStorage* spifs)
{ {
if (cardInitialized_) TSettings Settings;
return cardInitialized_; if (loadConfigFile(&Settings))
bool oneBitMode = true;
#if defined (SDMMC_D0) && defined (SDMMC_D1) && defined (SDMMC_D2) && defined (SDMMC_D3)
if (SD_MMC.cardType() == CARD_NONE)
SD_MMC.setPins(SDMMC_CLK, SDMMC_CMD, SDMMC_D0, SDMMC_D1, SDMMC_D2, SDMMC_D3);
oneBitMode = false;
#elif defined (SDMMC_D0) && !(defined (SDMMC_D1) && defined (SDMMC_D2) && defined (SDMMC_D3))
if (SD_MMC.cardType() == CARD_NONE)
SD_MMC.setPins(SDMMC_CLK, SDMMC_CMD, SDMMC_D0);
#else
Serial.println("SDCard: interface not available.");
return false;
#endif // dataPinsDefined
if ((!SD_MMC.begin("/sdcard", oneBitMode)) || (SD_MMC.cardType() == CARD_NONE))
{ {
Serial.println("SDCard: No card found."); spifs->saveConfigFile(&Settings);
return false; WiFi.begin(Settings.WifiSSID, Settings.WifiPW);
Serial.println("SDCard: Settings transfered to internal memory. Restarting now.");
ESP.restart();
} }
return true;
} }
TSettings loadConfigFile() bool loadConfigFile(TSettings* Settings)
{ {
// Load existing configuration file // Load existing configuration file
// Read configuration from FS json // Read configuration from FS json
Serial.println("SDCard: Mounting File System..."); Serial.println("SDCard: Mounting File System...");
TSettings Settings;
if (initSDcard()) if (initSDcard())
{ {
Serial.println("SDCard: Mounted");
if (SD_MMC.exists(JSON_CONFIG_FILE)) if (SD_MMC.exists(JSON_CONFIG_FILE))
{ {
// The file exists, reading and loading // The file exists, reading and loading
@ -77,16 +59,20 @@ public:
DeserializationError error = deserializeJson(json, configFile); DeserializationError error = deserializeJson(json, configFile);
configFile.close(); configFile.close();
serializeJsonPretty(json, Serial); serializeJsonPretty(json, Serial);
Serial.print('\n');
if (!error) if (!error)
{ {
Serial.println("SDCard: Parsing JSON"); Serial.println("SDCard: Parsing JSON");
strcpy(Settings.WifiSSID, json["SSID"]); strcpy(Settings->WifiSSID, json[JSON_KEY_SSID] | Settings->WifiSSID);
strcpy(Settings.WifiPW, json["Password"]); strcpy(Settings->WifiPW, json[JSON_KEY_PASW] | Settings->WifiPW);
strcpy(Settings.PoolAddress, json["PoolURL"]); strcpy(Settings->PoolAddress, json[JSON_KEY_POOLURL] | Settings->PoolAddress);
strcpy(Settings.BtcWallet, json["WalletID"]); strcpy(Settings->BtcWallet, json[JSON_KEY_WALLETID] | Settings->BtcWallet);
Settings.PoolPort = json["Port"].as<int>(); if (json.containsKey(JSON_KEY_POOLPORT))
Settings.Timezone = json["Timezone"].as<int>(); Settings->PoolPort = json[JSON_KEY_POOLPORT].as<int>();
Settings.holdsData = true; if (json.containsKey(JSON_KEY_TIMEZONE))
Settings->Timezone = json[JSON_KEY_TIMEZONE].as<int>();
SD_MMC.end();
return true;
} }
else else
{ {
@ -94,26 +80,54 @@ public:
Serial.println("SDCard: Failed to load json config"); Serial.println("SDCard: Failed to load json config");
} }
} }
SD_MMC.end();
} }
else
{
Serial.println("SDCard: No config file available!");
}
SD_MMC.end();
}
return false;
}
private:
bool initSDcard()
{
if((cardInitialized_)&&(SD_MMC.cardType() != CARD_NONE))
{
Serial.println("SDCard: Already mounted.");
return cardInitialized_;
}
bool oneBitMode = true;
#if defined (SDMMC_D0) && defined (SDMMC_D1) && defined (SDMMC_D2) && defined (SDMMC_D3)
if (SD_MMC.cardType() == CARD_NONE)
{
SD_MMC.setPins(SDMMC_CLK, SDMMC_CMD, SDMMC_D0, SDMMC_D1, SDMMC_D2, SDMMC_D3);
oneBitMode = false;
Serial.println("SDCard: 4-Bit Mode.");
}
#elif defined (SDMMC_D0) && !(defined (SDMMC_D1) && defined (SDMMC_D2) && defined (SDMMC_D3))
if (SD_MMC.cardType() == CARD_NONE)
{
SD_MMC.setPins(SDMMC_CLK, SDMMC_CMD, SDMMC_D0);
Serial.println("SDCard: 1-Bit Mode.");
}
#else
Serial.println("SDCard: interface not available.");
return false;
#endif // dataPinsDefined
cardInitialized_ = SD_MMC.begin("/sdcard", oneBitMode);
if ((cardInitialized_) && (SD_MMC.cardType() != CARD_NONE))
{
Serial.println("SDCard: Card mounted.");
return true;
} }
else else
{ {
// Error mounting file system Serial.println("SDCard: No card found.");
Serial.println("SDCard: Failed to mount."); return false;
}
return Settings;
}
void SD2SPIStorage(SPIStorage* spifs)
{
TSettings Settings = loadConfigFile();
if (Settings.holdsData)
{
spifs->saveConfigFile(&Settings);
WiFi.begin(Settings.WifiSSID, Settings.WifiPW);
Serial.println("SDCard: Settings transfered to internal memory. Restarting now.");
ESP.restart();
} }
} }
}; };

View File

@ -12,9 +12,6 @@
#include "..\drivers.h" #include "..\drivers.h"
#include "storage.h" #include "storage.h"
// JSON configuration file
#define JSON_CONFIG_FILE "/config.json"
class SPIStorage class SPIStorage
{ {
private: private:
@ -22,65 +19,60 @@ private:
public: public:
SPIStorage() SPIStorage()
{ {
SPIFFSInitialized_ = init(); SPIFFSInitialized_ = false;
} }
~SPIStorage() ~SPIStorage()
{ {
SPIFFS.end(); if (SPIFFSInitialized_)
SPIFFS.end();
}; };
void saveConfigFile(TSettings*Settings) void saveConfigFile(TSettings*Settings)
{ {
// Save Config in JSON format if (init())
Serial.println(F("SPIFS: Saving configuration..."));
// Create a JSON document
StaticJsonDocument<512> json;
json["poolString"] = Settings->PoolAddress;
json["portNumber"] = Settings->PoolPort;
json["btcString"] = Settings->BtcWallet;
json["gmtZone"] = Settings->Timezone;
// Open config file
File configFile = SPIFFS.open(JSON_CONFIG_FILE, "w");
if (!configFile)
{ {
// Error, file did not open // Save Config in JSON format
Serial.println("SPIFS: failed to open config file for writing"); Serial.println(F("SPIFS: Saving configuration..."));
}
// Serialize JSON data to write to file // Create a JSON document
serializeJsonPretty(json, Serial); StaticJsonDocument<512> json;
if (serializeJson(json, configFile) == 0) json[JSON_KEY_POOLURL] = Settings->PoolAddress;
{ json[JSON_KEY_POOLPORT] = Settings->PoolPort;
// Error writing file json[JSON_KEY_WALLETID] = Settings->BtcWallet;
Serial.println(F("SPIFS: Failed to write to file")); json[JSON_KEY_TIMEZONE] = Settings->Timezone;
}
// Close file // Open config file
configFile.close(); 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");
}
// 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"));
}
// Close file
configFile.close();
};
} }
bool init() bool loadConfigFile(TSettings* Settings)
{ {
if (SPIFFSInitialized_)
return SPIFFSInitialized_;
return SPIFFS.begin(false) || SPIFFS.begin(true);
};
TSettings loadConfigFile()
{
// Load existing configuration file
// Uncomment if we need to format filesystem // Uncomment if we need to format filesystem
// SPIFFS.format(); // SPIFFS.format();
// Load existing configuration file
// Read configuration from FS json // Read configuration from FS json
Serial.println("SPIFS: Mounting File System...");
TSettings Settings; if (init())
// May need to make it begin(true) first time you are using SPIFFS
if ((SPIFFSInitialized_)||(init()))
{ {
Serial.println("SPIFS: Mounted");
if (SPIFFS.exists(JSON_CONFIG_FILE)) if (SPIFFS.exists(JSON_CONFIG_FILE))
{ {
// The file exists, reading and loading // The file exists, reading and loading
@ -93,15 +85,17 @@ public:
DeserializationError error = deserializeJson(json, configFile); DeserializationError error = deserializeJson(json, configFile);
configFile.close(); configFile.close();
serializeJsonPretty(json, Serial); serializeJsonPretty(json, Serial);
Serial.print('\n');
if (!error) if (!error)
{ {
Serial.println("SPIFS: Parsing JSON"); Serial.println("SPIFS: Parsing JSON");
strcpy(Settings->PoolAddress, json[JSON_KEY_POOLURL] | Settings->PoolAddress);
strcpy(Settings.PoolAddress, json["poolString"]); strcpy(Settings->BtcWallet, json[JSON_KEY_WALLETID] | Settings->BtcWallet);
strcpy(Settings.BtcWallet, json["btcString"]); if(json.containsKey(JSON_KEY_POOLPORT))
Settings.PoolPort = json["portNumber"].as<int>(); Settings->PoolPort = json[JSON_KEY_POOLPORT].as<int>();
Settings.Timezone = json["gmtZone"].as<int>(); if (json.containsKey(JSON_KEY_TIMEZONE))
Settings.holdsData = true; Settings->Timezone = json[JSON_KEY_TIMEZONE].as<int>();
return true;
} }
else else
{ {
@ -111,12 +105,7 @@ public:
} }
} }
} }
else return false;
{
// Error mounting file system
Serial.println("SPIFS: Failed to mount.");
}
return Settings;
} }
void deleteConfigFile() void deleteConfigFile()
@ -124,6 +113,22 @@ public:
Serial.println("SPIFS: Erasing config file.."); Serial.println("SPIFS: Erasing config file..");
SPIFFS.remove(JSON_CONFIG_FILE); //Borramos fichero SPIFFS.remove(JSON_CONFIG_FILE); //Borramos fichero
} }
private:
bool init()
{
if (!SPIFFSInitialized_)
{
Serial.println("SPIFS: Mounting File System...");
// May need to make it begin(true) first time you are using SPIFFS
SPIFFSInitialized_ = SPIFFS.begin(false) || SPIFFS.begin(true);
SPIFFSInitialized_ ? Serial.println("SPIFS: Mounted") : Serial.println("SPIFS: Mounting failed.");
}
else
{
Serial.println("SPIFS: Already Mounted");
}
return SPIFFSInitialized_;
};
}; };
#endif // _SPISTORAGE_H_ #endif // _SPISTORAGE_H_

View File

@ -1,100 +0,0 @@
#ifndef _UARTCFGUI_H_
#define _UARTCFGUI_H_
#include <Arduino.h>
#include "storage.h"
#include "SPIStorage.h"
class SerialCfgUI
{
public:
SerialCfgUI()
{
#ifdef MONITOR_SPEED
Serial.begin(MONITOR_SPEED);
#else
Serial.begin(115200);
#endif //MONITOR_SPEED
}
void UARTUI2SPIStorage(SPIStorage* spifs)
{
TSettings Settings;
if ((spifs->loadConfigFile(&Settings)) && StartUI(&Settings))
{
spifs->saveConfigFile(&Settings);
WiFi.begin(Settings.WifiSSID, Settings.WifiPW);
Serial.println("SerialUI: Settings transfered to internal memory. Restarting now.");
ESP.restart();
}
Serial.println("SerialUI: not started.");
}
private:
bool StartUI(TSettings* Settings)
{
Serial.println("Welcome to Nerdminer v2 serial config Interface.");
Serial.println("Fill out the form to set up your Nerdminer.");
Serial.println("Press 'Enter' to save your input or the default value.");
strcpy(Settings->WifiSSID, readEntry<const char*>("Enter Wifi SSID:", Settings->WifiSSID));
strcpy(Settings->WifiPW, readEntry<const char*>("Enter Wifi Password:", Settings->WifiPW));
strcpy(Settings->PoolAddress, readEntry<const char*>("Enter Pool Address:", Settings->PoolAddress));
Settings->PoolPort = readEntry<int>("Enter Pool Port:", Settings->PoolPort);
strcpy(Settings->BtcWallet, readEntry<const char*>("Enter your BTC Wallet ID:", Settings->BtcWallet));
Settings->Timezone = readEntry<int>("Enter your Timezone (UTC+-12):", Settings->Timezone);
Serial.println("Setup complete.");
return true;
}
template <typename T>
T readEntry(const char* message = "newEntry:", T defaultvalue = "", const char delimieter = '\n')
requires(
(std::is_same_v<T, const char*>)
|| (std::is_same_v<T, char*>)
|| (std::is_same_v<T, int>)
|| (std::is_same_v<T, double>)
|| (std::is_same_v<T, float>)
|| (std::is_same_v<T, String>))
{
Serial.println(message);
if(!String(defaultvalue).isEmpty())
{
Serial.print("Default Value: >");
Serial.print(defaultvalue);
Serial.println("<");
};
String value = Serial.readStringUntil(delimieter);
value.trim();
while((value.length() > 0) && value.endsWith(String('\r')))
value.remove(value.length()-1);
value.trim();
if (value.length() > 0)
{
if constexpr (std::is_same_v<T, String>)
return value;
else if constexpr ((std::is_same_v<T, const char*>)|| (std::is_same_v<T, char*>))
return value.c_str();
else if constexpr (std::is_same_v<T, int>)
return value.toInt();
else if constexpr (std::is_same_v<T, double>)
return value.toDouble();
else if constexpr (std::is_same_v<T, float>)
return value.toFloat();
}
else
{
return defaultvalue;
}
}
};
#endif // _UARTCFGUI_H_

View File

@ -1,16 +1,53 @@
#ifndef _STORAGE_H_ #ifndef _STORAGE_H_
#define _STORAGE_H_ #define _STORAGE_H_
#define DEFAULT_SSID "NMAP"
#define DEFAULT_WIFIPW "1234567890"
#define DEFAULT_POOLURL "public-pool.io"
#define DEFAULT_WALLETID "yourBtcAddress"
#define DEFAULT_POOLPORT 21496
#define DEFAULT_TIMEZONE 2
// 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"
class TSettings class TSettings
{ {
public: public:
char WifiSSID[80]{ "sA51" }; char WifiSSID[80]{ DEFAULT_SSID };
char WifiPW[80]{ "0000" }; char WifiPW[80]{ DEFAULT_WIFIPW };
char PoolAddress[80]{ "public-pool.io" }; char PoolAddress[80]{ DEFAULT_POOLURL };
char BtcWallet[80]{ "yourBtcAddress" }; char BtcWallet[80]{ DEFAULT_WALLETID };
uint32_t PoolPort{ 21496 }; uint32_t PoolPort{ DEFAULT_POOLPORT };
uint32_t Timezone{ 2 }; uint32_t Timezone{ DEFAULT_TIMEZONE };
bool holdsData{ false };
void print()
{
Serial.print("WifiSSID:>");
Serial.print(WifiSSID);
Serial.print("<, ");
Serial.print("WifiPW:>");
Serial.print(WifiPW);
Serial.print("<, ");
Serial.print("PoolAddress:>");
Serial.print(PoolAddress);
Serial.print("<, ");
Serial.print("BtcWallet:>");
Serial.print(BtcWallet);
Serial.print("<, ");
Serial.print("PoolPort:>");
Serial.print(PoolPort);
Serial.print("<, ");
Serial.print("Timezone:>");
Serial.print(Timezone);
Serial.println("<");
}
}; };
#endif // _STORAGE_H_ #endif // _STORAGE_H_

View File

@ -402,8 +402,8 @@ void runMonitor(void *name)
if (elapsedKHs == 0) if (elapsedKHs == 0)
{ {
Serial.printf(">>> [i] Miner: newJob>%s / inRun>%s) - Client: connected>%s / subscribed>%s / wificonnected>%s\n", Serial.printf(">>> [i] Miner: newJob>%s / inRun>%s) - Client: connected>%s / subscribed>%s / wificonnected>%s\n",
mMiner.newJob ? "true" : "false", mMiner.inRun ? "true" : "false", mMiner.newJob ? "true" : "false", mMiner.inRun ? "true" : "false",
client.connected() ? "true" : "false", isMinerSuscribed ? "true" : "false", WiFi.status() == WL_CONNECTED ? "true" : "false"); client.connected() ? "true" : "false", isMinerSuscribed ? "true" : "false", WiFi.status() == WL_CONNECTED ? "true" : "false");
} }
#ifdef DEBUG_MEMORY #ifdef DEBUG_MEMORY

View File

@ -12,6 +12,7 @@
#include "drivers/storage/SPIStorage.h" #include "drivers/storage/SPIStorage.h"
#include "drivers/storage/storage.h" #include "drivers/storage/storage.h"
// Flag for saving data // Flag for saving data
bool shouldSaveConfig = false; bool shouldSaveConfig = false;
@ -45,7 +46,7 @@ void configModeCallback(WiFiManager* myWiFiManager)
Serial.println(WiFi.softAPIP()); Serial.println(WiFi.softAPIP());
} }
void reset_configurations() void reset_configurations()
{ {
Serial.println("Erasing Config, restarting"); Serial.println("Erasing Config, restarting");
SPIFS.deleteConfigFile(); SPIFS.deleteConfigFile();
@ -53,7 +54,6 @@ void reset_configurations()
ESP.restart(); ESP.restart();
} }
void init_WifiManager() void init_WifiManager()
{ {
#ifdef MONITOR_SPEED #ifdef MONITOR_SPEED
@ -76,7 +76,7 @@ void init_WifiManager()
// Check if button2 is pressed to enter configMode with actual configuration // Check if button2 is pressed to enter configMode with actual configuration
if (!digitalRead(PIN_BUTTON_2)) { if (!digitalRead(PIN_BUTTON_2)) {
Serial.println(F("Button pressed to force start config mode")); Serial.println(F("Button pressed to force start config mode"));
resetConfig(); reset_configurations();
forceConfig = true; forceConfig = true;
wm.setBreakAfterConfig(true); //Set to detect config edition and save wm.setBreakAfterConfig(true); //Set to detect config edition and save
} }
@ -84,16 +84,20 @@ void init_WifiManager()
// Explicitly set WiFi mode // Explicitly set WiFi mode
WiFi.mode(WIFI_STA); WiFi.mode(WIFI_STA);
Settings = SPIFS.loadConfigFile(); if (!SPIFS.loadConfigFile(&Settings))
if (!Settings.holdsData)
{ {
Serial.println(F("No config file on internal flash."));
SDCard sdc; SDCard sdc;
if (sdc.loadConfigFile().holdsData) if (!sdc.loadConfigFile(&Settings))
{ {
Serial.println(F("No config file on internal flash, force config mode.")); Serial.println(F("No config file on SD card."));
sdc.SD2SPIStorage(&SPIFS); // reboot on success.
forceConfig = true; forceConfig = true;
}; }
else
{
Serial.println(F("Config file on SD card. Copy and restart."));
sdc.SD2SPIStorage(&SPIFS); // reboot on success.
}
}; };
// Reset settings (only for development) // Reset settings (only for development)
@ -136,7 +140,7 @@ void init_WifiManager()
char charZone[6]; char charZone[6];
sprintf(charZone, "%d", Settings.Timezone); sprintf(charZone, "%d", Settings.Timezone);
WiFiManagerParameter time_text_box_num("TimeZone", "TimeZone fromUTC (-12/+12)", charZone, 3); WiFiManagerParameter time_text_box_num("TimeZone", "TimeZone fromUTC (-12/+12)", charZone, 3);
// Add all defined parameters // Add all defined parameters
wm.addParameter(&pool_text_box); wm.addParameter(&pool_text_box);
wm.addParameter(&port_text_box_num); wm.addParameter(&port_text_box_num);
@ -144,21 +148,23 @@ void init_WifiManager()
wm.addParameter(&time_text_box_num); wm.addParameter(&time_text_box_num);
Serial.println("AllDone: "); Serial.println("AllDone: ");
if (forceConfig) if (forceConfig)
// Run if we need a configuration
{ {
// Run if we need a configuration
//No configuramos timeout al modulo //No configuramos timeout al modulo
wm.setConfigPortalBlocking(true); //Hacemos que el portal SI bloquee el firmware wm.setConfigPortalBlocking(true); //Hacemos que el portal SI bloquee el firmware
drawSetupScreen(); drawSetupScreen();
Settings = TSettings();
if (!wm.startConfigPortal(Settings.WifiSSID, Settings.WifiPW)) if (!wm.startConfigPortal(DEFAULT_SSID, DEFAULT_WIFIPW))
{ {
Serial.println("failed to connect and hit timeout"); Serial.println("failed to connect and hit timeout");
//Could be break forced after edditing, so save new config //Could be break forced after edditing, so save new config
strncpy(Settings.PoolAddress, pool_text_box.getValue(), sizeof(Settings.PoolAddress)); strncpy(Settings.PoolAddress, pool_text_box.getValue(), sizeof(Settings.PoolAddress));
Settings.PoolPort = atoi(port_text_box_num.getValue()); Settings.PoolPort = atoi(port_text_box_num.getValue());
strncpy(Settings.BtcWallet, addr_text_box.getValue(), sizeof(Settings.BtcWallet)); strncpy(Settings.BtcWallet, addr_text_box.getValue(), sizeof(Settings.BtcWallet));
Settings.Timezone = atoi(time_text_box_num.getValue()); Settings.Timezone = atoi(time_text_box_num.getValue());
SPIFS.saveConfigFile(&Settings); SPIFS.saveConfigFile(&Settings);
delay(3000); delay(3000);
//reset and try again, or maybe put it to deep sleep //reset and try again, or maybe put it to deep sleep
@ -212,6 +218,7 @@ void init_WifiManager()
Settings.Timezone = atoi(time_text_box_num.getValue()); Settings.Timezone = atoi(time_text_box_num.getValue());
Serial.print("TimeZone fromUTC: "); Serial.print("TimeZone fromUTC: ");
Serial.println(Settings.Timezone); Serial.println(Settings.Timezone);
} }
// Save the custom parameters to FS // Save the custom parameters to FS