Improved network fail tolerance, fixes

This commit is contained in:
Juan Ferrer 2019-07-24 16:46:03 +02:00
parent 81c918491a
commit 924567e243
2 changed files with 32 additions and 16 deletions

View File

@ -2,6 +2,7 @@
* Configuration template file, copy it to config.h
* and make your changes there.
*/
#define DEBUG true
#define DB_HOST "localhost"
#define DB_USER "energy-meter"
#define DB_PASS ""
@ -11,6 +12,7 @@
#define DEBUG_INTERVAL 1000
#define RECORD_INTERVAL 60000
#define N_INPUTS 9
#define LED_PIN 13
int pins[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};

View File

@ -19,7 +19,6 @@ unsigned long lastRecord;
Input inputs[N_INPUTS];
EthernetClient ethClient;
MySQL_Connection db((Client *) &ethClient);
IPAddress dbServer;
void printTitle(String title) {
#ifdef DEBUG
@ -29,14 +28,9 @@ void printTitle(String title) {
#endif
}
void showError(String error) {
#ifdef DEBUG
Serial.println(error);
#endif
}
void abortWithError(String error) {
showError(error);
digitalWrite(LED_PIN, HIGH);
while (true) delay(1);
}
@ -52,19 +46,20 @@ void setup() {
while (!Serial);
#endif
pinMode(LED_PIN, OUTPUT);
printTitle("Initializing");
if (Ethernet.begin(mac) == 0)
abortWithError("DHCP config failed.");
if (Ethernet.hardwareStatus() == EthernetNoHardware)
abortWithError("Eth shield not found.");
if (Ethernet.linkStatus() == LinkOFF)
abortWithError("Eth cable not connected.");
#ifdef DEBUG
Serial.println("IP: " + String(Ethernet.localIP()));
Serial.print("IP: ");
Serial.println(Ethernet.localIP());
#endif
if (!dbConnect())
abortWithError("Aborting.");
dbConnect();
unsigned long now = millis();
lastRefresh = now;
@ -83,8 +78,27 @@ void setup() {
#endif
}
void showError(String error) {
digitalWrite(LED_PIN, HIGH);
#ifdef DEBUG
Serial.println(error);
#endif
}
boolean dbConnect() {
if (Ethernet.linkStatus() == LinkOFF) {
showError("Eth cable not connected.");
return false;
}
if (db.connected()) {
digitalWrite(LED_PIN, LOW);
return true;
}
DNSClient dns;
IPAddress dbServer;
dns.begin(Ethernet.dnsServerIP());
if (dns.getHostByName(DB_HOST, dbServer) != 1) {
@ -93,7 +107,8 @@ boolean dbConnect() {
}
#ifdef DEBUG
Serial.println("Connecting to DB: " + String(dbServer));
Serial.print("Connecting to DB: ");
Serial.println(dbServer);
#endif
if (!db.connect(dbServer, DB_PORT, DB_USER, DB_PASS)) {
@ -101,6 +116,7 @@ boolean dbConnect() {
return false;
}
digitalWrite(LED_PIN, LOW);
return true;
}
@ -143,9 +159,7 @@ void loop() {
if (millis() - lastRecord > RECORD_INTERVAL) {
printTitle("Recording to DB");
if (!db.connected())
dbConnect();
dbConnect();
for (int i = 0; i < N_INPUTS; i++) {
refreshTimers();