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.

84 lines
2.3 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. // -----------------------------------------------------------------------------
  11. #if WEB_SUPPORT
  12. void _idbWSSend(JsonObject& root) {
  13. root["idbVisible"] = 1;
  14. root["idbHost"] = getSetting("idbHost");
  15. root["idbPort"] = getSetting("idbPort", INFLUXDB_PORT).toInt();
  16. root["idbDatabase"] = getSetting("idbDatabase");
  17. root["idbUsername"] = getSetting("idbUsername");
  18. root["idbPassword"] = getSetting("idbPassword");
  19. }
  20. #endif
  21. // -----------------------------------------------------------------------------
  22. template<typename T> bool idbSend(const char * topic, T payload) {
  23. if (!_idb_enabled) return true;
  24. if (!wifiConnected() || (WiFi.getMode() != WIFI_STA)) return true;
  25. DEBUG_MSG("[INFLUXDB] Sending\n");
  26. _idb_client.setTimeout(2);
  27. if (!_idb_client.connect(getSetting("idbHost").c_str(), getSetting("idbPort", INFLUXDB_PORT).toInt())) {
  28. DEBUG_MSG("[INFLUXDB] Connection failed\n");
  29. return false;
  30. }
  31. char data[128];
  32. snprintf(data, sizeof(data), "%s,device=%s value=%s", topic, getSetting("hostname").c_str(), String(payload).c_str());
  33. DEBUG_MSG("[INFLUXDB] Data: %s\n", data);
  34. char request[256];
  35. 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",
  36. getSetting("idbDatabase").c_str(), getSetting("idbUsername").c_str(), getSetting("idbPassword").c_str(),
  37. getSetting("idbHost").c_str(), getSetting("idbPort", INFLUXDB_PORT).toInt(),
  38. strlen(data), data);
  39. if (_idb_client.printf(request) > 0) {
  40. while (_idb_client.connected() && _idb_client.available() == 0) delay(1);
  41. while (_idb_client.available()) _idb_client.read();
  42. if (_idb_client.connected()) _idb_client.stop();
  43. return true;
  44. }
  45. _idb_client.stop();
  46. DEBUG_MSG("[INFLUXDB] Sent failed\n");
  47. while (_idb_client.connected()) delay(0);
  48. return false;
  49. }
  50. bool idbEnabled() {
  51. return _idb_enabled;
  52. }
  53. void idbConfigure() {
  54. _idb_enabled = getSetting("idbHost").length() > 0;
  55. }
  56. void idbSetup() {
  57. idbConfigure();
  58. #if WEB_SUPPORT
  59. wsRegister(_idbWSSend);
  60. #endif
  61. }
  62. #endif