Browse Source

Check wifi connection before trying to connect to influxdb host

fastled
Xose Pérez 7 years ago
parent
commit
67811f76ff
1 changed files with 14 additions and 11 deletions
  1. +14
    -11
      code/espurna/influxdb.ino

+ 14
- 11
code/espurna/influxdb.ino View File

@ -12,38 +12,41 @@ Copyright (C) 2017 by Xose Pérez <xose dot perez at gmail dot com>
#include "SyncClient.h" #include "SyncClient.h"
bool influxDBEnabled = false; bool influxDBEnabled = false;
SyncClient _influxClient;
template<typename T> bool influxDBSend(const char * topic, T payload) { template<typename T> bool influxDBSend(const char * topic, T payload) {
if (!influxDBEnabled) return true; 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")); DEBUG_MSG_P(("[INFLUXDB] Connection failed\n"));
return false; 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()); 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); 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", 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("idbDatabase").c_str(), getSetting("idbUsername").c_str(), getSetting("idbPassword").c_str(),
getSetting("idbHost").c_str(), getSetting("idbPort", INFLUXDB_PORT).toInt(), getSetting("idbHost").c_str(), getSetting("idbPort", INFLUXDB_PORT).toInt(),
strlen(data), data); 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; return true;
} }
client.stop();
_influxClient.stop();
DEBUG_MSG_P(("[INFLUXDB] Sent failed\n")); DEBUG_MSG_P(("[INFLUXDB] Sent failed\n"));
while (client.connected()) delay(0);
while (_influxClient.connected()) delay(0);
return false; return false;
} }


Loading…
Cancel
Save