From 67811f76ffb8dcad6baed761b77ce6e8ef2cf7ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Xose=20P=C3=A9rez?= Date: Sun, 16 Jul 2017 18:22:54 +0200 Subject: [PATCH] Check wifi connection before trying to connect to influxdb host --- code/espurna/influxdb.ino | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/code/espurna/influxdb.ino b/code/espurna/influxdb.ino index aee0f4b4..652cd19a 100644 --- a/code/espurna/influxdb.ino +++ b/code/espurna/influxdb.ino @@ -12,38 +12,41 @@ Copyright (C) 2017 by Xose PĂ©rez #include "SyncClient.h" bool influxDBEnabled = false; +SyncClient _influxClient; template bool influxDBSend(const char * topic, T payload) { if (!influxDBEnabled) return true; + if (!wifiConnected() || (WiFi.getMode() != WIFI_STA)) return true; - SyncClient client; - if (!client.connect(getSetting("idbHost").c_str(), getSetting("idbPort", INFLUXDB_PORT).toInt())) { + DEBUG_MSG_P(("[INFLUXDB] Sending\n")); + + _influxClient.setTimeout(2); + if (!_influxClient.connect(getSetting("idbHost").c_str(), getSetting("idbPort", INFLUXDB_PORT).toInt())) { DEBUG_MSG_P(("[INFLUXDB] Connection failed\n")); return false; } - client.setTimeout(2); - char data[64]; + char data[128]; sprintf(data, "%s,device=%s value=%s", topic, getSetting("hostname", HOSTNAME).c_str(), String(payload).c_str()); DEBUG_MSG_P(("[INFLUXDB] Data: %s\n"), data); - char request[250]; + char request[256]; sprintf(request, "POST /write?db=%s&u=%s&p=%s HTTP/1.1\r\nHost: %s:%d\r\nContent-Length: %d\r\n\r\n%s", getSetting("idbDatabase").c_str(), getSetting("idbUsername").c_str(), getSetting("idbPassword").c_str(), getSetting("idbHost").c_str(), getSetting("idbPort", INFLUXDB_PORT).toInt(), strlen(data), data); - if (client.printf(request) > 0) { - while (client.connected() && client.available() == 0) delay(1); - while (client.available()) client.read(); - if (client.connected()) client.stop(); + if (_influxClient.printf(request) > 0) { + while (_influxClient.connected() && _influxClient.available() == 0) delay(1); + while (_influxClient.available()) _influxClient.read(); + if (_influxClient.connected()) _influxClient.stop(); return true; } - client.stop(); + _influxClient.stop(); DEBUG_MSG_P(("[INFLUXDB] Sent failed\n")); - while (client.connected()) delay(0); + while (_influxClient.connected()) delay(0); return false; }