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.

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