separate spiffs

This commit is contained in:
elmo128 2023-09-12 09:26:28 +02:00
parent d5d0a1e63b
commit 37ca603ed5
5 changed files with 342 additions and 275 deletions

View File

@ -0,0 +1,129 @@
#ifndef _SPISTORAGE_H_
#define _SPISTORAGE_H_
#define ESP_DRD_USE_SPIFFS true
#include <WiFiManager.h>
#include <SPIFFS.h>
#include <FS.h>
#include <ArduinoJson.h>
#include "..\drivers.h"
#include "..\storage.h"
// JSON configuration file
#define JSON_CONFIG_FILE "/config.json"
class SPIStorage
{
private:
bool SPIFFSInitialized_;
public:
SPIStorage()
{
SPIFFSInitialized_ = init();
}
~SPIStorage()
{
SPIFFS.end();
};
void saveConfigFile(TSettings*Settings)
{
// Save Config in JSON format
Serial.println(F("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
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 init()
{
if (SPIFFSInitialized_)
return SPIFFSInitialized_;
return SPIFFS.begin(false) || SPIFFS.begin(true);
};
TSettings loadConfigFile()
{
// Load existing configuration file
// Uncomment if we need to format filesystem
// SPIFFS.format();
// Read configuration from FS json
Serial.println("Mounting File System...");
TSettings Settings;
// May need to make it begin(true) first time you are using SPIFFS
if ((SPIFFSInitialized_)||(init()))
{
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(Settings.PoolAddress, json["poolString"]);
strcpy(Settings.BtcWallet, json["btcString"]);
Settings.PoolPort = json["portNumber"].as<int>();
Settings.Timezone = json["gmtZone"].as<int>();
Settings.holdsData = 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 Settings;
}
void deleteConfigFile()
{
Serial.println("Erasing config file..");
SPIFFS.remove(JSON_CONFIG_FILE); //Borramos fichero
}
};
#endif // _SPISTORAGE_H_

16
src/drivers/storage.h Normal file
View File

@ -0,0 +1,16 @@
#ifndef _STORAGE_H_
#define _STORAGE_H_
class TSettings
{
public:
char WifiSSID[80]{ "sA51" };
char WifiPW[80]{ "0000" };
char PoolAddress[80]{ "public-pool.io" };
char BtcWallet[80]{ "yourBtcAddress" };
uint32_t PoolPort{ 21496 };
uint32_t Timezone{ 2 };
bool holdsData{ false };
};
#endif // _STORAGE_H_

View File

@ -9,6 +9,7 @@
#include "utils.h" #include "utils.h"
#include "monitor.h" #include "monitor.h"
#include "drivers/display.h" #include "drivers/display.h"
#include "drivers/storage.h"
unsigned long templates = 0; unsigned long templates = 0;
unsigned long hashes= 0; unsigned long hashes= 0;
@ -23,9 +24,8 @@ unsigned int valids; // increased if blockhash <= target
double best_diff = 0.0; double best_diff = 0.0;
// Variables to hold data from custom textboxes // Variables to hold data from custom textboxes
extern char poolString[80]; extern TSettings Settings;
extern int portNumber;
extern char btcString[80];
IPAddress serverIP(1, 1, 1, 1); //Temporally save poolIPaddres IPAddress serverIP(1, 1, 1, 1); //Temporally save poolIPaddres
//Global work data //Global work data
@ -49,14 +49,14 @@ bool checkPoolConnection(void) {
//Resolve first time pool DNS and save IP //Resolve first time pool DNS and save IP
if(serverIP == IPAddress(1,1,1,1)) { 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()); Serial.printf("Resolved DNS and save ip (first time) got: %s\n", serverIP.toString());
} }
//Try connecting pool IP //Try connecting pool IP
if (!client.connect(serverIP, portNumber)) { if (!client.connect(serverIP, Settings.PoolPort)) {
Serial.println("Imposible to connect to : " + String(poolString)); Serial.println("Imposible to connect to : " + String(Settings.PoolAddress));
WiFi.hostByName(poolString, serverIP); WiFi.hostByName(Settings.PoolAddress, serverIP);
Serial.printf("Resolved DNS got: %s\n", serverIP.toString()); Serial.printf("Resolved DNS got: %s\n", serverIP.toString());
vTaskDelay(1000 / portTICK_PERIOD_MS); vTaskDelay(1000 / portTICK_PERIOD_MS);
return false; return false;
@ -156,7 +156,7 @@ void runStratumWorker(void *name) {
continue; continue;
} }
strcpy(mWorker.wName, btcString); strcpy(mWorker.wName, Settings.BtcWallet);
strcpy(mWorker.wPass, "x"); strcpy(mWorker.wPass, "x");
// STEP 2: Pool authorize work (Block Info) // STEP 2: Pool authorize work (Block Info)
tx_mining_auth(client, mWorker.wName, mWorker.wPass); //Don't verifies authoritzation, TODO tx_mining_auth(client, mWorker.wName, mWorker.wPass); //Don't verifies authoritzation, TODO

View File

@ -7,8 +7,8 @@
#include "mining.h" #include "mining.h"
#include "utils.h" #include "utils.h"
#include "monitor.h" #include "monitor.h"
#include "drivers/storage.h"
extern char poolString[80];
extern unsigned long templates; extern unsigned long templates;
extern unsigned long hashes; extern unsigned long hashes;
extern unsigned long Mhashes; extern unsigned long Mhashes;
@ -22,7 +22,7 @@ extern double best_diff; // track best diff
extern monitor_data mMonitor; extern monitor_data mMonitor;
extern int GMTzone; //Gotten from saved config extern TSettings Settings; //Gotten from saved config
WiFiUDP ntpUDP; WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "europe.pool.ntp.org", 3600, 60000); NTPClient timeClient(ntpUDP, "europe.pool.ntp.org", 3600, 60000);
@ -37,7 +37,7 @@ void setup_monitor(void){
// Adjust offset depending on your zone // Adjust offset depending on your zone
// GMT +2 in seconds (zona horaria de Europa Central) // GMT +2 in seconds (zona horaria de Europa Central)
timeClient.setTimeOffset(3600 * GMTzone); timeClient.setTimeOffset(3600 * Settings.Timezone);
Serial.println("TimeClient setup done"); Serial.println("TimeClient setup done");
} }

View File

@ -1,117 +1,38 @@
#define ESP_DRD_USE_SPIFFS true
// Include Libraries // Include Libraries
//#include ".h" //#include ".h"
#include <WiFi.h> #include <WiFi.h>
#include <SPIFFS.h>
#include <FS.h>
#include <WiFiManager.h> #include <WiFiManager.h>
#include <ArduinoJson.h>
#include "wManager.h" #include "wManager.h"
#include "monitor.h" #include "monitor.h"
#include "drivers/display.h" #include "drivers/display.h"
// JSON configuration file #include "drivers/SPIStorage/SPIStorage.h"
#define JSON_CONFIG_FILE "/config.json" #include "drivers/storage.h"
// Flag for saving data // Flag for saving data
bool shouldSaveConfig = false; bool shouldSaveConfig = false;
// Variables to hold data from custom textboxes DisplayDriver dongleDisplayDriver = {};
char poolString[80] = "public-pool.io";
int portNumber = 21496;//3333;
char btcString[80] = "yourBtcAddress";
int GMTzone = 2; //Currently selected in spain
TSettings Settings;
/* {
.BtcWallet = "",
.holdsData = false,
.PoolAddress = "",
.PoolPort = 0,
.Timezone = 0,
.WifiPW = "",
.WifiSSID = ""
}
*/
// Define WiFiManager Object // Define WiFiManager Object
WiFiManager wm; WiFiManager wm;
extern monitor_data mMonitor; extern monitor_data mMonitor;
void saveConfigFile() SPIStorage SPIFS;
// 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;
// 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<int>();
GMTzone = json["gmtZone"].as<int>();
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() void saveConfigCallback()
// Callback notifying us of the need to save configuration // Callback notifying us of the need to save configuration
@ -133,6 +54,15 @@ void configModeCallback(WiFiManager *myWiFiManager)
Serial.println(WiFi.softAPIP()); Serial.println(WiFi.softAPIP());
} }
void reset_configurations()
{
Serial.println("Erasing Config, restarting");
SPIFS.deleteConfigFile();
wm.resetSettings();
ESP.restart();
}
void init_WifiManager() void init_WifiManager()
{ {
#ifdef MONITOR_SPEED #ifdef MONITOR_SPEED
@ -155,21 +85,20 @@ 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();
forceConfig = true; forceConfig = true;
wm.setBreakAfterConfig(true); //Set to detect config edition and save wm.setBreakAfterConfig(true); //Set to detect config edition and save
} }
#endif #endif
// Explicitly set WiFi mode
WiFi.mode(WIFI_STA);
bool spiffsSetup = loadConfigFile(); Settings = SPIFS.loadConfigFile();
if (!spiffsSetup) if (!Settings.holdsData)
{ {
Serial.println(F("Forcing config mode as there is no saved config")); Serial.println(F("Forcing config mode as there is no saved config"));
forceConfig = true; forceConfig = true;
};
}
// Explicitly set WiFi mode
WiFi.mode(WIFI_STA);
// Reset settings (only for development) // Reset settings (only for development)
//wm.resetSettings(); //wm.resetSettings();
@ -195,21 +124,21 @@ void init_WifiManager()
// Custom elements // Custom elements
// Text box (String) - 80 characters maximum // Text box (String) - 80 characters maximum
WiFiManagerParameter pool_text_box("Poolurl", "Pool url", poolString, 80); WiFiManagerParameter pool_text_box("Poolurl", "Pool url", Settings.PoolAddress, 80);
// Need to convert numerical input to string to display the default value. // Need to convert numerical input to string to display the default value.
char convertedValue[6]; char convertedValue[6];
sprintf(convertedValue, "%d", portNumber); sprintf(convertedValue, "%d", Settings.PoolPort);
// Text box (Number) - 7 characters maximum // Text box (Number) - 7 characters maximum
WiFiManagerParameter port_text_box_num("Poolport", "Pool port", convertedValue, 7); WiFiManagerParameter port_text_box_num("Poolport", "Pool port", convertedValue, 7);
// Text box (String) - 80 characters maximum // Text box (String) - 80 characters maximum
WiFiManagerParameter addr_text_box("btcAddress", "Your BTC address", btcString, 80); WiFiManagerParameter addr_text_box("btcAddress", "Your BTC address", Settings.BtcWallet, 80);
// Text box (Number) - 2 characters maximum // Text box (Number) - 2 characters maximum
char charZone[6]; 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 time_text_box_num("TimeZone", "TimeZone fromUTC (-12/+12)", charZone, 3);
// Add all defined parameters // Add all defined parameters
@ -225,15 +154,16 @@ void init_WifiManager()
//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();
if (!wm.startConfigPortal("NerdMinerAP","MineYourCoins")) Settings = TSettings();
if (!wm.startConfigPortal(Settings.WifiSSID, Settings.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(poolString, pool_text_box.getValue(), sizeof(poolString)); strncpy(Settings.PoolAddress, pool_text_box.getValue(), sizeof(Settings.PoolAddress));
portNumber = atoi(port_text_box_num.getValue()); Settings.PoolPort = atoi(port_text_box_num.getValue());
strncpy(btcString, addr_text_box.getValue(), sizeof(btcString)); strncpy(Settings.BtcWallet, addr_text_box.getValue(), sizeof(Settings.BtcWallet));
GMTzone = atoi(time_text_box_num.getValue()); Settings.Timezone = atoi(time_text_box_num.getValue());
saveConfigFile(); 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
ESP.restart(); ESP.restart();
@ -245,7 +175,7 @@ void init_WifiManager()
//Tratamos de conectar con la configuración inicial ya almacenada //Tratamos de conectar con la configuración inicial ya almacenada
mMonitor.NerdStatus = NM_Connecting; mMonitor.NerdStatus = NM_Connecting;
wm.setCaptivePortalEnable(false); // disable captive portal redirection wm.setCaptivePortalEnable(false); // disable captive portal redirection
if (!wm.autoConnect("NerdMinerAP","MineYourCoins")) if (!wm.autoConnect(Settings.WifiSSID, Settings.WifiPW))
{ {
Serial.println("Failed to connect and hit timeout"); Serial.println("Failed to connect and hit timeout");
//delay(3000); //delay(3000);
@ -268,41 +198,33 @@ void init_WifiManager()
// Lets deal with the user config values // Lets deal with the user config values
// Copy the string value // Copy the string value
strncpy(poolString, pool_text_box.getValue(), sizeof(poolString)); strncpy(Settings.PoolAddress, pool_text_box.getValue(), sizeof(Settings.PoolAddress));
Serial.print("PoolString: "); Serial.print("PoolString: ");
Serial.println(poolString); Serial.println(Settings.PoolAddress);
//Convert the number value //Convert the number value
portNumber = atoi(port_text_box_num.getValue()); Settings.PoolPort = atoi(port_text_box_num.getValue());
Serial.print("portNumber: "); Serial.print("portNumber: ");
Serial.println(portNumber); Serial.println(Settings.PoolPort);
// Copy the string value // Copy the string value
strncpy(btcString, addr_text_box.getValue(), sizeof(btcString)); strncpy(Settings.BtcWallet, addr_text_box.getValue(), sizeof(Settings.BtcWallet));
Serial.print("btcString: "); Serial.print("btcString: ");
Serial.println(btcString); Serial.println(Settings.BtcWallet);
//Convert the number value //Convert the number value
GMTzone = atoi(time_text_box_num.getValue()); Settings.Timezone = atoi(time_text_box_num.getValue());
Serial.print("TimeZone fromUTC: "); Serial.print("TimeZone fromUTC: ");
Serial.println(GMTzone); Serial.println(Settings.Timezone);
} }
// Save the custom parameters to FS // Save the custom parameters to FS
if (shouldSaveConfig) if (shouldSaveConfig)
{ {
saveConfigFile(); SPIFS.saveConfigFile(&Settings);
} }
} }
void reset_configurations() {
Serial.println("Erasing Config, restarting");
wm.resetSettings();
SPIFFS.remove(JSON_CONFIG_FILE); //Borramos fichero
ESP.restart();
}
//----------------- MAIN PROCESS WIFI MANAGER -------------- //----------------- MAIN PROCESS WIFI MANAGER --------------
int oldStatus = 0; int oldStatus = 0;