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.

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