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.

285 lines
7.8 KiB

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