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.

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