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.

224 lines
6.1 KiB

6 years ago
  1. /*
  2. THINGSPEAK MODULE
  3. Copyright (C) 2018 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #if THINGSPEAK_SUPPORT
  6. #if THINGSPEAK_USE_ASYNC
  7. #include <ESPAsyncTCP.h>
  8. AsyncClient _tspk_client;
  9. #else
  10. #include <ESP8266WiFi.h>
  11. #if THINGSPEAK_USE_SSL
  12. WiFiClientSecure _tspk_client;
  13. #else
  14. WiFiClient _tspk_client;
  15. #endif
  16. #endif
  17. const char THINGSPEAK_REQUEST_TEMPLATE[] PROGMEM =
  18. "POST %s HTTP/1.1\r\n"
  19. "Host: %s\r\n"
  20. "User-Agent: ESPurna\r\n"
  21. "Connection: close\r\n"
  22. "Content-Type: application/x-www-form-urlencoded\r\n"
  23. "Content-Length: %d\r\n\r\n"
  24. "%s\r\n";
  25. bool _tspk_enabled = false;
  26. char * _tspk_queue[8] = {NULL};
  27. bool _tspk_flush = false;
  28. unsigned long _tspk_last_flush = 0;
  29. // -----------------------------------------------------------------------------
  30. void _tspkWebSocketOnSend(JsonObject& root) {
  31. root["tspkVisible"] = 1;
  32. root["tspkEnabled"] = getSetting("tspkEnabled", THINGSPEAK_ENABLED).toInt() == 1;
  33. JsonArray& relays = root.createNestedArray("tspkRelays");
  34. for (byte i=0; i<relayCount(); i++) {
  35. relays.add(getSetting("tspkRelay", i, 0).toInt());
  36. }
  37. #if SENSOR_SUPPORT
  38. JsonArray& list = root.createNestedArray("tspkMagnitudes");
  39. for (byte i=0; i<magnitudeCount(); i++) {
  40. JsonObject& element = list.createNestedObject();
  41. element["name"] = magnitudeName(i);
  42. element["type"] = magnitudeType(i);
  43. element["index"] = magnitudeIndex(i);
  44. element["idx"] = getSetting("tspkMagnitude", i, 0).toInt();
  45. }
  46. #endif
  47. }
  48. void _tspkConfigure() {
  49. _tspk_enabled = getSetting("tspkEnabled", THINGSPEAK_ENABLED).toInt() == 1;
  50. if (_tspk_enabled && (getSetting("tspkKey").length() == 0)) {
  51. _tspk_enabled = false;
  52. setSetting("tspkEnabled", 0);
  53. }
  54. }
  55. #if THINGSPEAK_USE_ASYNC
  56. void _tspkPost(String data) {
  57. _tspk_client.onError([](void * arg, AsyncClient * client, int error) {
  58. DEBUG_MSG_P(PSTR("[THINGSPEAK] Connection error (%d)\n", error);
  59. _tspk_client = NULL;
  60. }, NULL);
  61. _tspk_client.onConnect([data](void * arg, AsyncClient * client) {
  62. DEBUG_MSG_P(PSTR("[THINGSPEAK] POST %s\n"), data.c_str());
  63. client->onData([](void * arg, AsyncClient * c, void * response, size_t len) {
  64. char * b = (char *) response;
  65. b[len] = 0;
  66. char * p = strstr((char *)response, "\r\n\r\n");
  67. unsigned int code = (p != NULL) ? atoi(&p[4]) : 0;
  68. DEBUG_MSG_P(PSTR("[THINGSPEAK] Response value: %d\n"), code);
  69. }, NULL);
  70. char buffer[strlen_P(THINGSPEAK_REQUEST_TEMPLATE) + strlen(THINGSPEAK_URL) + strlen(THINGSPEAK_HOST) + data.length()];
  71. snprintf_P(buffer, sizeof(buffer),
  72. THINGSPEAK_REQUEST_TEMPLATE,
  73. THINGSPEAK_URL,
  74. THINGSPEAK_HOST,
  75. data.length(),
  76. data.c_str()
  77. );
  78. client->write(buffer);
  79. }, NULL);
  80. #if ASYNC_TCP_SSL_ENABLED
  81. if (!_tspk_client.connect(THINGSPEAK_HOST, THINGSPEAK_PORT, THINGSPEAK_USE_SSL)) {
  82. #else
  83. if (!_tspk_client.connect(THINGSPEAK_HOST, THINGSPEAK_PORT)) {
  84. #endif
  85. DEBUG_MSG_P(PSTR("[THINGSPEAK] Connection failed\n"));
  86. }
  87. }
  88. #else // not THINGSPEAK_USE_ASYNC
  89. void _tspkPost(String data) {
  90. if (_tspk_client.connect(THINGSPEAK_HOST, THINGSPEAK_PORT)) {
  91. DEBUG_MSG_P(PSTR("[THINGSPEAK] POST %s\n"), data.c_str());
  92. char buffer[strlen_P(THINGSPEAK_REQUEST_TEMPLATE) + strlen(THINGSPEAK_URL) + strlen(THINGSPEAK_HOST) + data.length()];
  93. snprintf_P(buffer, sizeof(buffer),
  94. THINGSPEAK_REQUEST_TEMPLATE,
  95. THINGSPEAK_URL,
  96. THINGSPEAK_HOST,
  97. data.length(),
  98. data.c_str()
  99. );
  100. _tspk_client.print(buffer);
  101. nice_delay(100);
  102. String response = _tspk_client.readString();
  103. int pos = response.indexOf("\r\n\r\n");
  104. unsigned int code = (pos > 0) ? response.substring(pos + 4).toInt() : 0;
  105. DEBUG_MSG_P(PSTR("[THINGSPEAK] Response value: %d\n"), code);
  106. _tspk_client.stop();
  107. return;
  108. }
  109. DEBUG_MSG_P(PSTR("[THINGSPEAK] Connection failed\n"));
  110. }
  111. #endif // THINGSPEAK_USE_ASYNC
  112. bool _tspkEnqueue(unsigned char index, char * payload) {
  113. DEBUG_MSG_P(PSTR("[THINGSPEAK] Enqueuing field #%d with value %s\n"), index, payload);
  114. --index;
  115. if (_tspk_queue[index] != NULL) free(_tspk_queue[index]);
  116. _tspk_queue[index] = strdup(payload);
  117. }
  118. void _tspkFlush() {
  119. String data;
  120. // Walk the fields
  121. for (unsigned char id=0; id<8; id++) {
  122. if (_tspk_queue[id] != NULL) {
  123. if (data.length() > 0) data = data + String("&");
  124. data = data + String("field") + String(id+1) + String("=") + String(_tspk_queue[id]);
  125. free(_tspk_queue[id]);
  126. _tspk_queue[id] = NULL;
  127. }
  128. }
  129. // POST data if any
  130. if (data.length() > 0) {
  131. data = data + String("&api_key=") + getSetting("tspkKey");
  132. _tspkPost(data);
  133. _tspk_last_flush = millis();
  134. }
  135. }
  136. // -----------------------------------------------------------------------------
  137. bool tspkEnqueueRelay(unsigned char index, unsigned char status) {
  138. if (!_tspk_enabled) return true;
  139. unsigned char id = getSetting("tspkRelay", index, 0).toInt();
  140. if (id > 0) {
  141. char payload[3];
  142. itoa(status ? 1 : 0, payload, 10);
  143. _tspkEnqueue(id, payload);
  144. }
  145. }
  146. bool tspkEnqueueMeasurement(unsigned char index, char * payload) {
  147. if (!_tspk_enabled) return true;
  148. unsigned char id = getSetting("tspkMagnitude", index, 0).toInt();
  149. if (id > 0) {
  150. _tspkEnqueue(id, payload);
  151. }
  152. }
  153. void tspkFlush() {
  154. _tspk_flush = true;
  155. }
  156. bool tspkEnabled() {
  157. return _tspk_enabled;
  158. }
  159. void tspkSetup() {
  160. _tspkConfigure();
  161. #if WEB_SUPPORT
  162. wsOnSendRegister(_tspkWebSocketOnSend);
  163. wsOnAfterParseRegister(_tspkConfigure);
  164. #endif
  165. }
  166. void tspkLoop() {
  167. if (!_tspk_enabled) return;
  168. if (!wifiConnected() || (WiFi.getMode() != WIFI_STA)) return;
  169. if (_tspk_flush && (millis() - _tspk_last_flush > THINGSPEAK_MIN_INTERVAL)) {
  170. _tspkFlush();
  171. _tspk_flush = false;
  172. }
  173. }
  174. #endif