moved to local wifi lib

This commit is contained in:
Simon 2024-04-27 20:46:37 +02:00
parent b3ec7ab03c
commit c5cbf0da8a
3 changed files with 243 additions and 209 deletions

View File

@ -1,226 +1,22 @@
// File System Library
#include <FS.h>
// SPI Flash Syetem Library
#include <SPIFFS.h>
#include <WiFi.h>
#include <WiFiManager.h> // https://github.com/tzapu/WiFiManager
#include <ArduinoJson.h>
#include "wifi.hpp"
WiFiServer server(80);
// Define WiFiManager Object
WiFiManager wm;
// Flag for saving data
bool shouldSaveConfig = false;
// JSON configuration file
#define JSON_CONFIG_FILE "/test_config.json"
// Variables to hold data from custom textboxes
char testString[50] = "test value";
int testNumber = 1234;
// Variable to store the HTTP request
String header;
// Assign output variables to GPIO pins
const int output5 = 25;
#define TRIGGER_PIN 0
void saveConfigFile()
// Save Config in JSON format
{
Serial.println(F("Saving configuration..."));
// Create a JSON document
StaticJsonDocument<512> json;
json["testString"] = testString;
json["testNumber"] = testNumber;
// 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);
serializeJsonPretty(json, Serial);
if (!error)
{
Serial.println("Parsing JSON");
strcpy(testString, json["testString"]);
testNumber = json["testNumber"].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()
// Callback notifying us of the need to save configuration
{
Serial.println("Should save config");
shouldSaveConfig = true;
}
void configModeCallback(WiFiManager *myWiFiManager)
// Called when config mode launched
{
Serial.println("Entered Configuration Mode");
Serial.print("Config SSID: ");
Serial.println(myWiFiManager->getConfigPortalSSID());
Serial.print("Config IP Address: ");
Serial.println(WiFi.softAPIP());
}
void setup()
{
// Change to true when testing to force configuration every time we run
bool forceConfig = false;
bool spiffsSetup = loadConfigFile();
if (!spiffsSetup)
{
Serial.println(F("Forcing config mode as there is no saved config"));
forceConfig = true;
}
pinMode(TRIGGER_PIN, INPUT);
pinMode(TRIGGER_PIN, INPUT);
WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP
// Setup Serial monitor
// Setup Serial monitor
Serial.begin(115200);
delay(10);
// Reset settings (only for development)
//wm.resetSettings();
// 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);
// Custom elements
// Text box (String) - 50 characters maximum
WiFiManagerParameter custom_text_box("key_text", "Enter your string here", testString, 50);
// Need to convert numerical input to string to display the default value.
char convertedValue[6];
sprintf(convertedValue, "%d", testNumber);
// Text box (Number) - 7 characters maximum
WiFiManagerParameter custom_text_box_num("key_num", "Enter your number here", convertedValue, 7);
// Add all defined parameters
wm.addParameter(&custom_text_box);
wm.addParameter(&custom_text_box_num);
if (forceConfig)
// Run if we need a configuration
{
if (!wm.startConfigPortal("NEWTEST_AP", "password"))
{
Serial.println("failed to connect and hit timeout");
delay(3000);
//reset and try again, or maybe put it to deep sleep
ESP.restart();
delay(5000);
}
}
else
{
if (!wm.autoConnect("NEWTEST_AP"))
{
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);
}
}
// If we get here, we are connected to the WiFi
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(testString, custom_text_box.getValue(), sizeof(testString));
Serial.print("testString: ");
Serial.println(testString);
//Convert the number value
testNumber = atoi(custom_text_box_num.getValue());
Serial.print("testNumber: ");
Serial.println(testNumber);
// Save the custom parameters to FS
if (shouldSaveConfig)
{
saveConfigFile();
}
setupWifi("island_temp");
server.begin();
}
@ -252,7 +48,6 @@ void loop()
client.println("Connection: close");
client.println();
// Display the HTML web page
client.println("<!DOCTYPE html><html>");
client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");

View File

@ -0,0 +1,205 @@
#include "wifi.hpp"
WiFiManager wm;
// Flag for saving data
bool shouldSaveConfig = false;
// Variables to hold data from custom textboxes
char testString[50] = "test value";
int testNumber = 1234;
// Variable to store the HTTP request
String header;
void setupWifi(const char *setupWifi)
{
// Change to true when testing to force configuration every time we run
bool forceConfig = false;
bool spiffsSetup = loadConfigFile();
if (!spiffsSetup)
{
Serial.println(F("Forcing config mode as there is no saved config"));
forceConfig = true;
}
// Reset settings (only for development)
// wm.resetSettings();
// 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);
// Custom elements
// Text box (String) - 50 characters maximum
WiFiManagerParameter custom_text_box("key_text", "Enter your string here", testString, 50);
// Need to convert numerical input to string to display the default value.
char convertedValue[6];
sprintf(convertedValue, "%d", testNumber);
// Text box (Number) - 7 characters maximum
WiFiManagerParameter custom_text_box_num("key_num", "Enter your number here", convertedValue, 7);
// Add all defined parameters
wm.addParameter(&custom_text_box);
wm.addParameter(&custom_text_box_num);
if (forceConfig)
// Run if we need a configuration
{
if (!wm.startConfigPortal(setupWifi))
{
Serial.println("failed to connect and hit timeout");
delay(3000);
// reset and try again, or maybe put it to deep sleep
ESP.restart();
delay(5000);
}
}
else
{
if (!wm.autoConnect(setupWifi))
{
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);
}
}
// If we get here, we are connected to the WiFi
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(testString, custom_text_box.getValue(), sizeof(testString));
Serial.print("testString: ");
Serial.println(testString);
// Convert the number value
testNumber = atoi(custom_text_box_num.getValue());
Serial.print("testNumber: ");
Serial.println(testNumber);
// Save the custom parameters to FS
if (shouldSaveConfig)
{
saveConfigFile();
}
}
void saveConfigCallback()
// Callback notifying us of the need to save configuration
{
Serial.println("Should save config");
shouldSaveConfig = true;
}
void configModeCallback(WiFiManager *myWiFiManager)
// Called when config mode launched
{
Serial.println("Entered Configuration Mode");
Serial.print("Config SSID: ");
Serial.println(myWiFiManager->getConfigPortalSSID());
Serial.print("Config IP Address: ");
Serial.println(WiFi.softAPIP());
}
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");
size_t size = configFile.size();
// Allocate a buffer to store contents of the file.
std::unique_ptr<char[]> buf(new char[size]);
configFile.readBytes(buf.get(), size);
JsonDocument doc;
auto deserializeError = deserializeJson(doc, buf.get());
serializeJson(doc, Serial);
// JsonObject& json = jsonBuffer.parseObject(buf.get());
// json.printTo(Serial);
if (!deserializeError)
{
Serial.println("Parsing JSON");
strcpy(testString, doc["testString"]);
testNumber = doc["testNumber"].as<int>();
return true;
}
else
{
Serial.println("failed to load json config");
}
configFile.close();
}
else
{
Serial.println("Missing Json file");
}
}
}
return false;
}
void saveConfigFile()
// Save Config in JSON format
{
Serial.println(F("Saving configuration..."));
// Create a JSON document
JsonDocument json;
json["testString"] = testString;
json["testNumber"] = testNumber;
// 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();
}

View File

@ -0,0 +1,34 @@
#ifndef WIFI_H
#define WIFI_H
// File System Library
#include <FS.h>
// SPI Flash Syetem Library
#include <SPIFFS.h>
#include <WiFi.h>
#include <WiFiManager.h> // https://github.com/tzapu/WiFiManager
#include <ArduinoJson.h>
extern WiFiManager wm;
// Flag for saving data
extern bool shouldSaveConfig;
// JSON configuration file
#define JSON_CONFIG_FILE "/test_config.json"
// Variables to hold data from custom textboxes
extern char testString[50] ;
extern int testNumber;
// Variable to store the HTTP request
extern String header;
void setupWifi(const char *apName);
void saveConfigCallback();
void configModeCallback(WiFiManager *myWiFiManager);
bool loadConfigFile();
void saveConfigFile();
#endif /* WIFI_H */