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.

66 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 _idb_enabled = false;
  9. SyncClient _idb_client;
  10. template<typename T> bool idbSend(const char * topic, T payload) {
  11. if (!_idb_enabled) return true;
  12. if (!wifiConnected() || (WiFi.getMode() != WIFI_STA)) return true;
  13. DEBUG_MSG("[INFLUXDB] Sending\n");
  14. _idb_client.setTimeout(2);
  15. if (!_idb_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 (_idb_client.printf(request) > 0) {
  28. while (_idb_client.connected() && _idb_client.available() == 0) delay(1);
  29. while (_idb_client.available()) _idb_client.read();
  30. if (_idb_client.connected()) _idb_client.stop();
  31. return true;
  32. }
  33. _idb_client.stop();
  34. DEBUG_MSG("[INFLUXDB] Sent failed\n");
  35. while (_idb_client.connected()) delay(0);
  36. return false;
  37. }
  38. bool idbEnabled() {
  39. return _idb_enabled;
  40. }
  41. void idbConfigure() {
  42. _idb_enabled = getSetting("idbHost").length() > 0;
  43. }
  44. void idbSetup() {
  45. idbConfigure();
  46. }
  47. #endif