Domotique/WifiControlSensor/EEPROM.ino
2016-12-14 22:57:01 +01:00

100 lines
2.7 KiB
C++

/* EEPROM LAYOUT
"BOOTMODE;SSID;PASSWORD;HOSTNAME;MQTT_SERVER;MQTT_USERNAME;MQTT_PASSWD;MQTT_PORT;IP_CONFIG;IP;GATEWAY;NETMASK;DNS1;DNS2;"
BOOTMODE could be 0 for Setup, 1 for normal use, 2 for OTA
IP_CONFIG could be 0 for DHCP, 1 for static
Setup mode is trigger by setting GPIO3 to ground or at first boot
*/
#include "EEPROM.h"
char eeprom[CONFIG_EEPROM_SIZE];
int EepromSaveConfig(productConfig &config) {
String eeprom;
eeprom = String(config.bootMode) + ";" + config.ssid + ";" + config.password + ";"
+ config.host + ";" + config.mqttServer + ";"
+ config.mqttUser + ";" + config.mqttPasswd + ";"
+ String(config.mqttPort) + ";"
+ String(config.ip_mode) + ";"
+ config.ip + ";" + config.gw + ";" + config.mask + ";"
+ config.dns + ";" + config.dns2 + ";";
if (eeprom.length() > CONFIG_EEPROM_SIZE )
return -EMSGSIZE;
SKETCH_DEBUG_PRINTLN("Saving " + eeprom);
for (uint i = 0; i < eeprom.length() && i < CONFIG_EEPROM_SIZE; i++) {
EEPROM.write(i, eeprom.charAt(i));
}
EEPROM.commit();
delay(100);
return 0;
}
int EepromSaveBootMode(uint8_t bootMode) {
EEPROM.write(0, String(bootMode).charAt(0));
EEPROM.commit();
delay(100);
return 0;
}
void readConfElement(char** element, int &i) {
*element = &eeprom[i];
do {
eeprom[i] = EEPROM.read(i);
i++;
} while (i < CONFIG_EEPROM_SIZE && eeprom[i - 1] != ';');
eeprom[i - 1] = '\0';
if (i >= CONFIG_EEPROM_SIZE){
SKETCH_DEBUG_PRINTLN("Looks like there is a configuration issue (too long)");
**element = '\0';
}
}
void EepromReadConfig(productConfig &config) {
int i = 2;
uint8_t boot = EEPROM.read(0);
char *tmpString;
if (boot == '1') {
config.bootMode = BOOTMODE_SETUP;
} else if (boot == '2') {
config.bootMode = BOOTMODE_NORMAL;
} else if (boot == '3') {
config.bootMode = BOOTMODE_OTA;
} else {
//Do not need to parse EEPROM when not configured
config.bootMode = BOOTMODE_SETUP;
return;
}
readConfElement(&config.ssid, i);
readConfElement(&config.password, i);
readConfElement(&config.host, i);
readConfElement(&config.mqttServer, i);
readConfElement(&config.mqttUser, i);
readConfElement(&config.mqttPasswd, i);
readConfElement(&tmpString, i);
config.mqttPort = atoi(tmpString);
readConfElement(&tmpString, i);
config.ip_mode = atoi(tmpString);
readConfElement(&tmpString, i);
config.ip = atoi(tmpString);
readConfElement(&tmpString, i);
config.gw = atoi(tmpString);
readConfElement(&tmpString, i);
config.mask = atoi(tmpString);
readConfElement(&tmpString, i);
config.dns = atoi(tmpString);
readConfElement(&tmpString, i);
config.dns2 = atoi(tmpString);
}