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.

260 lines
7.3 KiB

  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. #endif
  12. const char THINGSPEAK_REQUEST_TEMPLATE[] PROGMEM =
  13. "POST %s HTTP/1.1\r\n"
  14. "Host: %s\r\n"
  15. "User-Agent: ESPurna\r\n"
  16. "Connection: close\r\n"
  17. "Content-Type: application/x-www-form-urlencoded\r\n"
  18. "Content-Length: %d\r\n\r\n"
  19. "%s\r\n";
  20. bool _tspk_enabled = false;
  21. char * _tspk_queue[8] = {NULL};
  22. bool _tspk_flush = false;
  23. unsigned long _tspk_last_flush = 0;
  24. // -----------------------------------------------------------------------------
  25. void _tspkWebSocketOnSend(JsonObject& root) {
  26. root["tspkVisible"] = 1;
  27. root["tspkEnabled"] = getSetting("tspkEnabled", THINGSPEAK_ENABLED).toInt() == 1;
  28. root["tspkKey"] = getSetting("tspkKey");
  29. JsonArray& relays = root.createNestedArray("tspkRelays");
  30. for (byte i=0; i<relayCount(); i++) {
  31. relays.add(getSetting("tspkRelay", i, 0).toInt());
  32. }
  33. #if SENSOR_SUPPORT
  34. JsonArray& list = root.createNestedArray("tspkMagnitudes");
  35. for (byte i=0; i<magnitudeCount(); i++) {
  36. JsonObject& element = list.createNestedObject();
  37. element["name"] = magnitudeName(i);
  38. element["type"] = magnitudeType(i);
  39. element["index"] = magnitudeIndex(i);
  40. element["idx"] = getSetting("tspkMagnitude", i, 0).toInt();
  41. }
  42. #endif
  43. }
  44. void _tspkConfigure() {
  45. _tspk_enabled = getSetting("tspkEnabled", THINGSPEAK_ENABLED).toInt() == 1;
  46. if (_tspk_enabled && (getSetting("tspkKey").length() == 0)) {
  47. _tspk_enabled = false;
  48. setSetting("tspkEnabled", 0);
  49. }
  50. }
  51. #if THINGSPEAK_USE_ASYNC
  52. void _tspkPost(String data) {
  53. if (_tspk_client == NULL) {
  54. _tspk_client = new AsyncClient();
  55. }
  56. _tspk_client->onDisconnect([](void *s, AsyncClient *c) {
  57. DEBUG_MSG_P(PSTR("[THINGSPEAK] Disconnected\n"));
  58. _tspk_client->free();
  59. delete _tspk_client;
  60. _tspk_client = NULL;
  61. }, 0);
  62. _tspk_client->onTimeout([](void *s, AsyncClient *c, uint32_t time) {
  63. _tspk_client->close(true);
  64. }, 0);
  65. _tspk_client->onData([](void * arg, AsyncClient * c, void * response, size_t len) {
  66. char * b = (char *) response;
  67. b[len] = 0;
  68. char * p = strstr((char *)response, "\r\n\r\n");
  69. unsigned int code = (p != NULL) ? atoi(&p[4]) : 0;
  70. DEBUG_MSG_P(PSTR("[THINGSPEAK] Response value: %d\n"), code);
  71. _tspk_client->close(true);
  72. }, NULL);
  73. _tspk_client->onConnect([data](void * arg, AsyncClient * client) {
  74. DEBUG_MSG_P(PSTR("[THINGSPEAK] Connected to %s:%d\n"), THINGSPEAK_HOST, THINGSPEAK_PORT);
  75. #if THINGSPEAK_USE_SSL
  76. uint8_t fp[20] = {0};
  77. sslFingerPrintArray(THINGSPEAK_FINGERPRINT, fp);
  78. SSL * ssl = _tspk_client->getSSL();
  79. if (ssl_match_fingerprint(ssl, fp) != SSL_OK) {
  80. DEBUG_MSG_P(PSTR("[THINGSPEAK] Warning: certificate doesn't match\n"));
  81. }
  82. #endif
  83. DEBUG_MSG_P(PSTR("[THINGSPEAK] POST %s\n"), data.c_str());
  84. char buffer[strlen_P(THINGSPEAK_REQUEST_TEMPLATE) + strlen(THINGSPEAK_URL) + strlen(THINGSPEAK_HOST) + data.length()];
  85. snprintf_P(buffer, sizeof(buffer),
  86. THINGSPEAK_REQUEST_TEMPLATE,
  87. THINGSPEAK_URL,
  88. THINGSPEAK_HOST,
  89. data.length(),
  90. data.c_str()
  91. );
  92. client->write(buffer);
  93. }, NULL);
  94. #if ASYNC_TCP_SSL_ENABLED
  95. bool connected = _tspk_client->connect(THINGSPEAK_HOST, THINGSPEAK_PORT, THINGSPEAK_USE_SSL);
  96. #else
  97. bool connected = _tspk_client->connect(THINGSPEAK_HOST, THINGSPEAK_PORT);
  98. #endif
  99. if (!connected) {
  100. DEBUG_MSG_P(PSTR("[THINGSPEAK] Connection failed\n"));
  101. _tspk_client->close(true);
  102. }
  103. }
  104. #else // THINGSPEAK_USE_ASYNC
  105. void _tspkPost(String data) {
  106. #if THINGSPEAK_USE_SSL
  107. WiFiClientSecure _tspk_client;
  108. #else
  109. WiFiClient _tspk_client;
  110. #endif
  111. if (_tspk_client.connect(THINGSPEAK_HOST, THINGSPEAK_PORT)) {
  112. DEBUG_MSG_P(PSTR("[THINGSPEAK] Connected to %s:%d\n"), THINGSPEAK_HOST, THINGSPEAK_PORT);
  113. if (!_tspk_client.verify(THINGSPEAK_FINGERPRINT, THINGSPEAK_HOST)) {
  114. DEBUG_MSG_P(PSTR("[THINGSPEAK] Warning: certificate doesn't match\n"));
  115. }
  116. DEBUG_MSG_P(PSTR("[THINGSPEAK] POST %s\n"), data.c_str());
  117. char buffer[strlen_P(THINGSPEAK_REQUEST_TEMPLATE) + strlen(THINGSPEAK_URL) + strlen(THINGSPEAK_HOST) + data.length()];
  118. snprintf_P(buffer, sizeof(buffer),
  119. THINGSPEAK_REQUEST_TEMPLATE,
  120. THINGSPEAK_URL,
  121. THINGSPEAK_HOST,
  122. data.length(),
  123. data.c_str()
  124. );
  125. _tspk_client.print(buffer);
  126. nice_delay(100);
  127. String response = _tspk_client.readString();
  128. int pos = response.indexOf("\r\n\r\n");
  129. unsigned int code = (pos > 0) ? response.substring(pos + 4).toInt() : 0;
  130. DEBUG_MSG_P(PSTR("[THINGSPEAK] Response value: %d\n"), code);
  131. _tspk_client.stop();
  132. return;
  133. }
  134. DEBUG_MSG_P(PSTR("[THINGSPEAK] Connection failed\n"));
  135. }
  136. #endif // THINGSPEAK_USE_ASYNC
  137. bool _tspkEnqueue(unsigned char index, char * payload) {
  138. DEBUG_MSG_P(PSTR("[THINGSPEAK] Enqueuing field #%d with value %s\n"), index, payload);
  139. --index;
  140. if (_tspk_queue[index] != NULL) free(_tspk_queue[index]);
  141. _tspk_queue[index] = strdup(payload);
  142. }
  143. void _tspkFlush() {
  144. String data;
  145. // Walk the fields
  146. for (unsigned char id=0; id<8; id++) {
  147. if (_tspk_queue[id] != NULL) {
  148. if (data.length() > 0) data = data + String("&");
  149. data = data + String("field") + String(id+1) + String("=") + String(_tspk_queue[id]);
  150. free(_tspk_queue[id]);
  151. _tspk_queue[id] = NULL;
  152. }
  153. }
  154. // POST data if any
  155. if (data.length() > 0) {
  156. data = data + String("&api_key=") + getSetting("tspkKey");
  157. _tspkPost(data);
  158. _tspk_last_flush = millis();
  159. }
  160. }
  161. // -----------------------------------------------------------------------------
  162. bool tspkEnqueueRelay(unsigned char index, unsigned char status) {
  163. if (!_tspk_enabled) return true;
  164. unsigned char id = getSetting("tspkRelay", index, 0).toInt();
  165. if (id > 0) {
  166. char payload[3];
  167. itoa(status ? 1 : 0, payload, 10);
  168. _tspkEnqueue(id, payload);
  169. }
  170. }
  171. bool tspkEnqueueMeasurement(unsigned char index, char * payload) {
  172. if (!_tspk_enabled) return true;
  173. unsigned char id = getSetting("tspkMagnitude", index, 0).toInt();
  174. if (id > 0) {
  175. _tspkEnqueue(id, payload);
  176. }
  177. }
  178. void tspkFlush() {
  179. _tspk_flush = true;
  180. }
  181. bool tspkEnabled() {
  182. return _tspk_enabled;
  183. }
  184. void tspkSetup() {
  185. _tspkConfigure();
  186. #if WEB_SUPPORT
  187. wsOnSendRegister(_tspkWebSocketOnSend);
  188. wsOnAfterParseRegister(_tspkConfigure);
  189. #endif
  190. DEBUG_MSG_P(PSTR("[THINGSPEAK] Async %s, SSL %s\n"),
  191. THINGSPEAK_USE_ASYNC ? "ENABLED" : "DISABLED",
  192. THINGSPEAK_USE_SSL ? "ENABLED" : "DISABLED"
  193. );
  194. }
  195. void tspkLoop() {
  196. if (!_tspk_enabled) return;
  197. if (!wifiConnected() || (WiFi.getMode() != WIFI_STA)) return;
  198. if (_tspk_flush && (millis() - _tspk_last_flush > THINGSPEAK_MIN_INTERVAL)) {
  199. _tspkFlush();
  200. _tspk_flush = false;
  201. }
  202. }
  203. #endif