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.

334 lines
8.9 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
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. #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. bool _tspk_clear = false;
  22. char * _tspk_queue[THINGSPEAK_FIELDS] = {NULL};
  23. bool _tspk_flush = false;
  24. unsigned long _tspk_last_flush = 0;
  25. unsigned char _tspk_tries = 0;
  26. // -----------------------------------------------------------------------------
  27. #if BROKER_SUPPORT
  28. void _tspkBrokerCallback(const unsigned char type, const char * topic, unsigned char id, const char * payload) {
  29. // Process status messages
  30. if (BROKER_MSG_TYPE_STATUS == type) {
  31. tspkEnqueueRelay(id, (char *) payload);
  32. tspkFlush();
  33. }
  34. // Porcess sensor messages
  35. if (BROKER_MSG_TYPE_SENSOR == type) {
  36. //tspkEnqueueMeasurement(id, (char *) payload);
  37. //tspkFlush();
  38. }
  39. }
  40. #endif // BROKER_SUPPORT
  41. #if WEB_SUPPORT
  42. bool _tspkWebSocketOnReceive(const char * key, JsonVariant& value) {
  43. return (strncmp(key, "tspk", 4) == 0);
  44. }
  45. void _tspkWebSocketOnSend(JsonObject& root) {
  46. unsigned char visible = 0;
  47. root["tspkEnabled"] = getSetting("tspkEnabled", THINGSPEAK_ENABLED).toInt() == 1;
  48. root["tspkKey"] = getSetting("tspkKey");
  49. root["tspkClear"] = getSetting("tspkClear", THINGSPEAK_CLEAR_CACHE).toInt() == 1;
  50. JsonArray& relays = root.createNestedArray("tspkRelays");
  51. for (byte i=0; i<relayCount(); i++) {
  52. relays.add(getSetting("tspkRelay", i, 0).toInt());
  53. }
  54. if (relayCount() > 0) visible = 1;
  55. #if SENSOR_SUPPORT
  56. _sensorWebSocketMagnitudes(root, "tspk");
  57. visible = visible || (magnitudeCount() > 0);
  58. #endif
  59. root["tspkVisible"] = visible;
  60. }
  61. #endif
  62. void _tspkConfigure() {
  63. _tspk_clear = getSetting("tspkClear", THINGSPEAK_CLEAR_CACHE).toInt() == 1;
  64. _tspk_enabled = getSetting("tspkEnabled", THINGSPEAK_ENABLED).toInt() == 1;
  65. if (_tspk_enabled && (getSetting("tspkKey").length() == 0)) {
  66. _tspk_enabled = false;
  67. setSetting("tspkEnabled", 0);
  68. }
  69. }
  70. #if THINGSPEAK_USE_ASYNC
  71. void _tspkPost(String data) {
  72. if (_tspk_client == NULL) {
  73. _tspk_client = new AsyncClient();
  74. }
  75. _tspk_client->onDisconnect([](void *s, AsyncClient *c) {
  76. DEBUG_MSG_P(PSTR("[THINGSPEAK] Disconnected\n"));
  77. _tspk_client->free();
  78. delete _tspk_client;
  79. _tspk_client = NULL;
  80. }, 0);
  81. _tspk_client->onTimeout([](void *s, AsyncClient *c, uint32_t time) {
  82. _tspk_client->close(true);
  83. }, 0);
  84. _tspk_client->onData([](void * arg, AsyncClient * c, void * response, size_t len) {
  85. char * b = (char *) response;
  86. b[len] = 0;
  87. char * p = strstr((char *)response, "\r\n\r\n");
  88. unsigned int code = (p != NULL) ? atoi(&p[4]) : 0;
  89. DEBUG_MSG_P(PSTR("[THINGSPEAK] Response value: %d\n"), code);
  90. _tspk_last_flush = millis();
  91. if ((0 == code) && (--_tspk_tries > 0)) {
  92. _tspk_flush = true;
  93. DEBUG_MSG_P(PSTR("[THINGSPEAK] Re-enqueuing\n"));
  94. } else {
  95. _tspkClearQueue();
  96. }
  97. _tspk_client->close(true);
  98. }, NULL);
  99. _tspk_client->onConnect([data](void * arg, AsyncClient * client) {
  100. DEBUG_MSG_P(PSTR("[THINGSPEAK] Connected to %s:%d\n"), THINGSPEAK_HOST, THINGSPEAK_PORT);
  101. #if THINGSPEAK_USE_SSL
  102. uint8_t fp[20] = {0};
  103. sslFingerPrintArray(THINGSPEAK_FINGERPRINT, fp);
  104. SSL * ssl = _tspk_client->getSSL();
  105. if (ssl_match_fingerprint(ssl, fp) != SSL_OK) {
  106. DEBUG_MSG_P(PSTR("[THINGSPEAK] Warning: certificate doesn't match\n"));
  107. }
  108. #endif
  109. DEBUG_MSG_P(PSTR("[THINGSPEAK] POST %s?%s\n"), THINGSPEAK_URL, data.c_str());
  110. char buffer[strlen_P(THINGSPEAK_REQUEST_TEMPLATE) + strlen(THINGSPEAK_URL) + strlen(THINGSPEAK_HOST) + data.length()];
  111. snprintf_P(buffer, sizeof(buffer),
  112. THINGSPEAK_REQUEST_TEMPLATE,
  113. THINGSPEAK_URL,
  114. THINGSPEAK_HOST,
  115. data.length(),
  116. data.c_str()
  117. );
  118. client->write(buffer);
  119. }, NULL);
  120. #if ASYNC_TCP_SSL_ENABLED
  121. bool connected = _tspk_client->connect(THINGSPEAK_HOST, THINGSPEAK_PORT, THINGSPEAK_USE_SSL);
  122. #else
  123. bool connected = _tspk_client->connect(THINGSPEAK_HOST, THINGSPEAK_PORT);
  124. #endif
  125. if (!connected) {
  126. DEBUG_MSG_P(PSTR("[THINGSPEAK] Connection failed\n"));
  127. _tspk_client->close(true);
  128. }
  129. }
  130. #else // THINGSPEAK_USE_ASYNC
  131. void _tspkPost(String data) {
  132. #if THINGSPEAK_USE_SSL
  133. WiFiClientSecure _tspk_client;
  134. #else
  135. WiFiClient _tspk_client;
  136. #endif
  137. if (_tspk_client.connect(THINGSPEAK_HOST, THINGSPEAK_PORT)) {
  138. DEBUG_MSG_P(PSTR("[THINGSPEAK] Connected to %s:%d\n"), THINGSPEAK_HOST, THINGSPEAK_PORT);
  139. if (!_tspk_client.verify(THINGSPEAK_FINGERPRINT, THINGSPEAK_HOST)) {
  140. DEBUG_MSG_P(PSTR("[THINGSPEAK] Warning: certificate doesn't match\n"));
  141. }
  142. DEBUG_MSG_P(PSTR("[THINGSPEAK] POST %s?%s\n"), THINGSPEAK_URL, data.c_str());
  143. char buffer[strlen_P(THINGSPEAK_REQUEST_TEMPLATE) + strlen(THINGSPEAK_URL) + strlen(THINGSPEAK_HOST) + data.length()];
  144. snprintf_P(buffer, sizeof(buffer),
  145. THINGSPEAK_REQUEST_TEMPLATE,
  146. THINGSPEAK_URL,
  147. THINGSPEAK_HOST,
  148. data.length(),
  149. data.c_str()
  150. );
  151. _tspk_client.print(buffer);
  152. nice_delay(100);
  153. String response = _tspk_client.readString();
  154. int pos = response.indexOf("\r\n\r\n");
  155. unsigned int code = (pos > 0) ? response.substring(pos + 4).toInt() : 0;
  156. DEBUG_MSG_P(PSTR("[THINGSPEAK] Response value: %d\n"), code);
  157. _tspk_client.stop();
  158. _tspk_last_flush = millis();
  159. if ((0 == code) && (--_tspk_tries > 0)) {
  160. _tspk_flush = true;
  161. DEBUG_MSG_P(PSTR("[THINGSPEAK] Re-enqueuing\n"));
  162. } else {
  163. _tspkClearQueue();
  164. }
  165. return;
  166. }
  167. DEBUG_MSG_P(PSTR("[THINGSPEAK] Connection failed\n"));
  168. }
  169. #endif // THINGSPEAK_USE_ASYNC
  170. void _tspkEnqueue(unsigned char index, char * payload) {
  171. DEBUG_MSG_P(PSTR("[THINGSPEAK] Enqueuing field #%d with value %s\n"), index, payload);
  172. --index;
  173. if (_tspk_queue[index] != NULL) free(_tspk_queue[index]);
  174. _tspk_queue[index] = strdup(payload);
  175. }
  176. void _tspkClearQueue() {
  177. if (_tspk_clear) {
  178. for (unsigned char id=0; id<THINGSPEAK_FIELDS; id++) {
  179. if (_tspk_queue[id] != NULL) {
  180. free(_tspk_queue[id]);
  181. _tspk_queue[id] = NULL;
  182. }
  183. }
  184. }
  185. }
  186. void _tspkFlush() {
  187. _tspk_flush = false;
  188. // Walk the fields
  189. String data;
  190. for (unsigned char id=0; id<THINGSPEAK_FIELDS; id++) {
  191. if (_tspk_queue[id] != NULL) {
  192. if (data.length() > 0) data = data + String("&");
  193. data = data + String("field") + String(id+1) + String("=") + String(_tspk_queue[id]);
  194. }
  195. }
  196. // POST data if any
  197. if (data.length() > 0) {
  198. data = data + String("&api_key=") + getSetting("tspkKey");
  199. _tspk_tries = THINGSPEAK_TRIES;
  200. _tspkPost(data);
  201. }
  202. }
  203. // -----------------------------------------------------------------------------
  204. bool tspkEnqueueRelay(unsigned char index, char * payload) {
  205. if (!_tspk_enabled) return true;
  206. unsigned char id = getSetting("tspkRelay", index, 0).toInt();
  207. if (id > 0) {
  208. _tspkEnqueue(id, payload);
  209. return true;
  210. }
  211. return false;
  212. }
  213. bool tspkEnqueueMeasurement(unsigned char index, char * payload) {
  214. if (!_tspk_enabled) return true;
  215. unsigned char id = getSetting("tspkMagnitude", index, 0).toInt();
  216. if (id > 0) {
  217. _tspkEnqueue(id, payload);
  218. return true;
  219. }
  220. return false;
  221. }
  222. void tspkFlush() {
  223. _tspk_flush = true;
  224. }
  225. bool tspkEnabled() {
  226. return _tspk_enabled;
  227. }
  228. void tspkSetup() {
  229. _tspkConfigure();
  230. #if WEB_SUPPORT
  231. wsOnSendRegister(_tspkWebSocketOnSend);
  232. wsOnReceiveRegister(_tspkWebSocketOnReceive);
  233. #endif
  234. #if BROKER_SUPPORT
  235. brokerRegister(_tspkBrokerCallback);
  236. #endif
  237. DEBUG_MSG_P(PSTR("[THINGSPEAK] Async %s, SSL %s\n"),
  238. THINGSPEAK_USE_ASYNC ? "ENABLED" : "DISABLED",
  239. THINGSPEAK_USE_SSL ? "ENABLED" : "DISABLED"
  240. );
  241. // Main callbacks
  242. espurnaRegisterLoop(tspkLoop);
  243. espurnaRegisterReload(_tspkConfigure);
  244. }
  245. void tspkLoop() {
  246. if (!_tspk_enabled) return;
  247. if (!wifiConnected() || (WiFi.getMode() != WIFI_STA)) return;
  248. if (_tspk_flush && (millis() - _tspk_last_flush > THINGSPEAK_MIN_INTERVAL)) {
  249. _tspkFlush();
  250. }
  251. }
  252. #endif