Fork of the espurna firmware for `mhsw` switches
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

65 lines
1.8 KiB

  1. /*
  2. I2C MODULE
  3. Copyright (C) 2017 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #if INFLUXDB_SUPPORT
  6. #include "ESPAsyncTCP.h"
  7. #include "SyncClient.h"
  8. bool _influxdb_enabled = false;
  9. SyncClient _influx_client;
  10. template<typename T> bool influxDBSend(const char * topic, T payload) {
  11. if (!_influxdb_enabled) return true;
  12. if (!wifiConnected() || (WiFi.getMode() != WIFI_STA)) return true;
  13. DEBUG_MSG("[INFLUXDB] Sending\n");
  14. _influx_client.setTimeout(2);
  15. if (!_influx_client.connect(getSetting("idbHost").c_str(), getSetting("idbPort", INFLUXDB_PORT).toInt())) {
  16. DEBUG_MSG("[INFLUXDB] Connection failed\n");
  17. return false;
  18. }
  19. char data[128];
  20. snprintf(data, sizeof(data), "%s,device=%s value=%s", topic, getSetting("hostname").c_str(), String(payload).c_str());
  21. DEBUG_MSG("[INFLUXDB] Data: %s\n", data);
  22. char request[256];
  23. snprintf(request, sizeof(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",
  24. getSetting("idbDatabase").c_str(), getSetting("idbUsername").c_str(), getSetting("idbPassword").c_str(),
  25. getSetting("idbHost").c_str(), getSetting("idbPort", INFLUXDB_PORT).toInt(),
  26. strlen(data), data);
  27. if (_influx_client.printf(request) > 0) {
  28. while (_influx_client.connected() && _influx_client.available() == 0) delay(1);
  29. while (_influx_client.available()) _influx_client.read();
  30. if (_influx_client.connected()) _influx_client.stop();
  31. return true;
  32. }
  33. _influx_client.stop();
  34. DEBUG_MSG("[INFLUXDB] Sent failed\n");
  35. while (_influx_client.connected()) delay(0);
  36. return false;
  37. }
  38. bool influxdbEnabled() {
  39. return _influxdb_enabled;
  40. }
  41. void influxDBConfigure() {
  42. _influxdb_enabled = getSetting("idbHost").length() > 0;
  43. }
  44. void influxDBSetup() {
  45. influxDBConfigure();
  46. }
  47. #endif