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.

474 lines
13 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
  1. /*
  2. THINGSPEAK MODULE
  3. Copyright (C) 2019 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #include "thingspeak.h"
  6. #if THINGSPEAK_SUPPORT
  7. #include <memory>
  8. #include "mqtt.h"
  9. #include "relay.h"
  10. #include "rpc.h"
  11. #include "sensor.h"
  12. #include "ws.h"
  13. #if THINGSPEAK_USE_ASYNC
  14. #include <ESPAsyncTCP.h>
  15. #else
  16. #include <ESP8266HTTPClient.h>
  17. #endif
  18. #include "libs/URL.h"
  19. #include "libs/SecureClientHelpers.h"
  20. #include "libs/AsyncClientHelpers.h"
  21. #if SECURE_CLIENT != SECURE_CLIENT_NONE
  22. #if THINGSPEAK_SECURE_CLIENT_INCLUDE_CA
  23. #include "static/thingspeak_client_trusted_root_ca.h"
  24. #else
  25. #include "static/digicert_high_assurance_pem.h"
  26. #define _tspk_client_trusted_root_ca _ssl_digicert_high_assurance_ev_root_ca
  27. #endif
  28. #endif // SECURE_CLIENT != SECURE_CLIENT_NONE
  29. const char THINGSPEAK_REQUEST_TEMPLATE[] PROGMEM =
  30. "POST %s HTTP/1.1\r\n"
  31. "Host: %s\r\n"
  32. "User-Agent: ESPurna\r\n"
  33. "Connection: close\r\n"
  34. "Content-Type: application/x-www-form-urlencoded\r\n"
  35. "Content-Length: %d\r\n\r\n";
  36. bool _tspk_enabled = false;
  37. bool _tspk_clear = false;
  38. String _tspk_fields[THINGSPEAK_FIELDS];
  39. String _tspk_data;
  40. bool _tspk_flush = false;
  41. unsigned long _tspk_last_flush = 0;
  42. unsigned char _tspk_tries = THINGSPEAK_TRIES;
  43. #if THINGSPEAK_USE_ASYNC
  44. class AsyncThingspeak : public AsyncClient {
  45. public:
  46. URL address;
  47. AsyncThingspeak(const String& _url) : address(_url) { };
  48. bool connect() {
  49. #if ASYNC_TCP_SSL_ENABLED && THINGSPEAK_USE_SSL
  50. return AsyncClient::connect(address.host.c_str(), address.port, true);
  51. #else
  52. return AsyncClient::connect(address.host.c_str(), address.port);
  53. #endif
  54. }
  55. bool connect(const String& url) {
  56. address = url;
  57. return connect();
  58. }
  59. };
  60. AsyncThingspeak* _tspk_client = nullptr;
  61. AsyncClientState _tspk_state = AsyncClientState::Disconnected;
  62. #endif // THINGSPEAK_USE_ASYNC == 1
  63. // -----------------------------------------------------------------------------
  64. void _tspkRelayStatus(size_t id, bool status) {
  65. tspkEnqueueRelay(id, status);
  66. tspkFlush();
  67. }
  68. #if WEB_SUPPORT
  69. bool _tspkWebSocketOnKeyCheck(const char * key, JsonVariant& value) {
  70. return (strncmp(key, "tspk", 4) == 0);
  71. }
  72. void _tspkWebSocketOnVisible(JsonObject& root) {
  73. root["tspkVisible"] = static_cast<unsigned char>(haveRelaysOrSensors());
  74. }
  75. void _tspkWebSocketOnConnected(JsonObject& root) {
  76. root["tspkEnabled"] = getSetting("tspkEnabled", 1 == THINGSPEAK_ENABLED);
  77. root["tspkKey"] = getSetting("tspkKey", THINGSPEAK_APIKEY);
  78. root["tspkClear"] = getSetting("tspkClear", 1 == THINGSPEAK_CLEAR_CACHE);
  79. root["tspkAddress"] = getSetting("tspkAddress", THINGSPEAK_ADDRESS);
  80. JsonArray& relays = root.createNestedArray("tspkRelays");
  81. for (unsigned char i=0; i<relayCount(); i++) {
  82. relays.add(getSetting({"tspkRelay", i}, 0));
  83. }
  84. #if SENSOR_SUPPORT
  85. sensorWebSocketMagnitudes(root, "tspk");
  86. #endif
  87. }
  88. #endif
  89. void _tspkInitClient(const String& _url);
  90. void _tspkConfigure() {
  91. _tspk_clear = getSetting("tspkClear", 1 == THINGSPEAK_CLEAR_CACHE);
  92. _tspk_enabled = getSetting("tspkEnabled", 1 == THINGSPEAK_ENABLED);
  93. if (_tspk_enabled && (getSetting("tspkKey", THINGSPEAK_APIKEY).length() == 0)) {
  94. _tspk_enabled = false;
  95. setSetting("tspkEnabled", 0);
  96. }
  97. #if THINGSPEAK_USE_ASYNC
  98. if (_tspk_enabled && !_tspk_client) _tspkInitClient(getSetting("tspkAddress", THINGSPEAK_ADDRESS));
  99. #endif
  100. }
  101. void _tspkClearFields() {
  102. _tspk_tries = THINGSPEAK_TRIES;
  103. if (_tspk_clear) {
  104. for (size_t id = 0; id < THINGSPEAK_FIELDS; ++id) {
  105. _tspk_fields[id] = "";
  106. }
  107. }
  108. }
  109. void _tspkRetry(int code) {
  110. if ((0 == code) && _tspk_tries) {
  111. _tspk_flush = true;
  112. DEBUG_MSG_P(PSTR("[THINGSPEAK] Re-enqueuing %u more time(s)\n"), _tspk_tries);
  113. } else {
  114. _tspkClearFields();
  115. }
  116. }
  117. #if THINGSPEAK_USE_ASYNC
  118. enum class tspk_state_t : uint8_t {
  119. NONE,
  120. HEADERS,
  121. BODY
  122. };
  123. tspk_state_t _tspk_client_state = tspk_state_t::NONE;
  124. unsigned long _tspk_client_ts = 0;
  125. constexpr unsigned long THINGSPEAK_CLIENT_TIMEOUT = 5000;
  126. void _tspkInitClient(const String& _url) {
  127. _tspk_client = new AsyncThingspeak(_url);
  128. _tspk_client->onDisconnect([](void * s, AsyncClient * client) {
  129. DEBUG_MSG_P(PSTR("[THINGSPEAK] Disconnected\n"));
  130. _tspk_data = "";
  131. _tspk_client_ts = 0;
  132. _tspk_last_flush = millis();
  133. _tspk_state = AsyncClientState::Disconnected;
  134. _tspk_client_state = tspk_state_t::NONE;
  135. }, nullptr);
  136. _tspk_client->onTimeout([](void * s, AsyncClient * client, uint32_t time) {
  137. DEBUG_MSG_P(PSTR("[THINGSPEAK] Network timeout after %ums\n"), time);
  138. client->close(true);
  139. }, nullptr);
  140. _tspk_client->onPoll([](void * s, AsyncClient * client) {
  141. uint32_t ts = millis() - _tspk_client_ts;
  142. if (ts > THINGSPEAK_CLIENT_TIMEOUT) {
  143. DEBUG_MSG_P(PSTR("[THINGSPEAK] No response after %ums\n"), ts);
  144. client->close(true);
  145. }
  146. }, nullptr);
  147. _tspk_client->onData([](void * arg, AsyncClient * client, void * response, size_t len) {
  148. char * p = nullptr;
  149. do {
  150. p = nullptr;
  151. switch (_tspk_client_state) {
  152. case tspk_state_t::NONE:
  153. {
  154. p = strnstr(reinterpret_cast<const char *>(response), "HTTP/1.1 200 OK", len);
  155. if (!p) {
  156. client->close(true);
  157. return;
  158. }
  159. _tspk_client_state = tspk_state_t::HEADERS;
  160. continue;
  161. }
  162. case tspk_state_t::HEADERS:
  163. {
  164. p = strnstr(reinterpret_cast<const char *>(response), "\r\n\r\n", len);
  165. if (!p) return;
  166. _tspk_client_state = tspk_state_t::BODY;
  167. }
  168. case tspk_state_t::BODY:
  169. {
  170. if (!p) {
  171. p = strnstr(reinterpret_cast<const char *>(response), "\r\n\r\n", len);
  172. if (!p) return;
  173. }
  174. unsigned int code = (p) ? atoi(&p[4]) : 0;
  175. DEBUG_MSG_P(PSTR("[THINGSPEAK] Response value: %u\n"), code);
  176. _tspkRetry(code);
  177. client->close(true);
  178. _tspk_client_state = tspk_state_t::NONE;
  179. }
  180. }
  181. } while (_tspk_client_state != tspk_state_t::NONE);
  182. }, nullptr);
  183. _tspk_client->onConnect([](void * arg, AsyncClient * client) {
  184. _tspk_state = AsyncClientState::Disconnected;
  185. AsyncThingspeak* tspk_client = reinterpret_cast<AsyncThingspeak*>(client);
  186. DEBUG_MSG_P(PSTR("[THINGSPEAK] Connected to %s:%u\n"), tspk_client->address.host.c_str(), tspk_client->address.port);
  187. #if THINGSPEAK_USE_SSL
  188. uint8_t fp[20] = {0};
  189. sslFingerPrintArray(THINGSPEAK_FINGERPRINT, fp);
  190. SSL * ssl = tspk_client->getSSL();
  191. if (ssl_match_fingerprint(ssl, fp) != SSL_OK) {
  192. DEBUG_MSG_P(PSTR("[THINGSPEAK] Warning: certificate doesn't match\n"));
  193. }
  194. #endif
  195. DEBUG_MSG_P(PSTR("[THINGSPEAK] POST %s?%s\n"), tspk_client->address.path.c_str(), _tspk_data.c_str());
  196. char headers[strlen_P(THINGSPEAK_REQUEST_TEMPLATE) + tspk_client->address.path.length() + tspk_client->address.host.length() + 1];
  197. snprintf_P(headers, sizeof(headers),
  198. THINGSPEAK_REQUEST_TEMPLATE,
  199. tspk_client->address.path.c_str(),
  200. tspk_client->address.host.c_str(),
  201. _tspk_data.length()
  202. );
  203. client->write(headers);
  204. client->write(_tspk_data.c_str());
  205. }, nullptr);
  206. }
  207. void _tspkPost(const String& address) {
  208. if (_tspk_state != AsyncClientState::Disconnected) return;
  209. _tspk_client_ts = millis();
  210. _tspk_state = _tspk_client->connect(address)
  211. ? AsyncClientState::Connecting
  212. : AsyncClientState::Disconnected;
  213. if (_tspk_state == AsyncClientState::Disconnected) {
  214. DEBUG_MSG_P(PSTR("[THINGSPEAK] Connection failed\n"));
  215. _tspk_client->close(true);
  216. }
  217. }
  218. #else // THINGSPEAK_USE_ASYNC
  219. #if THINGSPEAK_USE_SSL && (SECURE_CLIENT == SECURE_CLIENT_BEARSSL)
  220. SecureClientConfig _tspk_sc_config {
  221. "THINGSPEAK",
  222. []() -> int {
  223. return getSetting("tspkScCheck", THINGSPEAK_SECURE_CLIENT_CHECK);
  224. },
  225. []() -> PGM_P {
  226. return _tspk_client_trusted_root_ca;
  227. },
  228. []() -> String {
  229. return getSetting("tspkFP", THINGSPEAK_FINGERPRINT);
  230. },
  231. []() -> uint16_t {
  232. return getSetting("tspkScMFLN", THINGSPEAK_SECURE_CLIENT_MFLN);
  233. },
  234. true
  235. };
  236. #endif // THINGSPEAK_USE_SSL && SECURE_CLIENT_BEARSSL
  237. void _tspkPost(WiFiClient& client, const URL& url, bool https) {
  238. DEBUG_MSG_P(PSTR("[THINGSPEAK] POST %s?%s\n"), url.path.c_str(), _tspk_data.c_str());
  239. HTTPClient http;
  240. http.begin(client, url.host, url.port, url.path, https);
  241. http.addHeader("User-agent", "ESPurna");
  242. http.addHeader("Content-Type", "application/x-www-form-urlencoded");
  243. const auto http_code = http.POST(_tspk_data);
  244. int value = 0;
  245. if (http_code == 200) {
  246. value = http.getString().toInt();
  247. DEBUG_MSG_P(PSTR("[THINGSPEAK] Response value: %u\n"), value);
  248. } else {
  249. DEBUG_MSG_P(PSTR("[THINGSPEAK] Response HTTP code: %d\n"), http_code);
  250. }
  251. _tspkRetry(value);
  252. _tspk_data = "";
  253. }
  254. void _tspkPost(const String& address) {
  255. const URL url(address);
  256. #if SECURE_CLIENT == SECURE_CLIENT_BEARSSL
  257. if (url.protocol == "https") {
  258. const int check = _tspk_sc_config.on_check();
  259. if (!ntpSynced() && (check == SECURE_CLIENT_CHECK_CA)) {
  260. DEBUG_MSG_P(PSTR("[THINGSPEAK] Time not synced! Cannot use CA validation\n"));
  261. return;
  262. }
  263. auto client = std::make_unique<SecureClient>(_tspk_sc_config);
  264. if (!client->beforeConnected()) {
  265. return;
  266. }
  267. _tspkPost(client->get(), url, true);
  268. return;
  269. }
  270. #endif
  271. if (url.protocol == "http") {
  272. auto client = std::make_unique<WiFiClient>();
  273. _tspkPost(*client.get(), url, false);
  274. return;
  275. }
  276. }
  277. #endif // THINGSPEAK_USE_ASYNC
  278. void _tspkEnqueue(size_t index, const char* payload) {
  279. if (index > 0) {
  280. DEBUG_MSG_P(PSTR("[THINGSPEAK] Enqueuing field #%hhu with value %s\n"), index, payload);
  281. _tspk_fields[--index] = payload;
  282. }
  283. }
  284. void _tspkFlush() {
  285. if (!_tspk_flush) return;
  286. if (millis() - _tspk_last_flush < THINGSPEAK_MIN_INTERVAL) return;
  287. #if THINGSPEAK_USE_ASYNC
  288. if (_tspk_state != AsyncClientState::Disconnected) return;
  289. #endif
  290. _tspk_last_flush = millis();
  291. _tspk_flush = false;
  292. _tspk_data.reserve(tspkDataBufferSize);
  293. // Walk the fields, numbered 1...THINGSPEAK_FIELDS
  294. for (size_t id = 0; id<THINGSPEAK_FIELDS; id++) {
  295. if (_tspk_fields[id].length()) {
  296. if (_tspk_data.length() > 0) _tspk_data.concat("&");
  297. char buf[32] = {0};
  298. snprintf_P(buf, sizeof(buf), PSTR("field%u=%s"), (id + 1), _tspk_fields[id].c_str());
  299. _tspk_data.concat(buf);
  300. }
  301. }
  302. // POST data if any
  303. if (_tspk_data.length()) {
  304. _tspk_data.concat("&api_key=");
  305. _tspk_data.concat(getSetting("tspkKey", THINGSPEAK_APIKEY));
  306. --_tspk_tries;
  307. _tspkPost(getSetting("tspkAddress", THINGSPEAK_ADDRESS));
  308. }
  309. }
  310. // -----------------------------------------------------------------------------
  311. bool tspkEnqueueRelay(size_t index, bool status) {
  312. if (_tspk_enabled) {
  313. unsigned char id = getSetting({"tspkRelay", index}, 0);
  314. if (id > 0) {
  315. _tspkEnqueue(id, status ? "1" : "0");
  316. return true;
  317. }
  318. return false;
  319. }
  320. return true;
  321. }
  322. bool tspkEnqueueMeasurement(unsigned char index, const char * payload) {
  323. if (!_tspk_enabled) return true;
  324. const auto id = getSetting({"tspkMagnitude", index}, 0);
  325. if (id > 0) {
  326. _tspkEnqueue(id, payload);
  327. return true;
  328. }
  329. return false;
  330. }
  331. void tspkFlush() {
  332. _tspk_flush = true;
  333. }
  334. bool tspkEnabled() {
  335. return _tspk_enabled;
  336. }
  337. void tspkLoop() {
  338. if (!_tspk_enabled) return;
  339. if (!wifiConnected() || (WiFi.getMode() != WIFI_STA)) return;
  340. _tspkFlush();
  341. }
  342. void tspkSetup() {
  343. _tspkConfigure();
  344. #if WEB_SUPPORT
  345. wsRegister()
  346. .onVisible(_tspkWebSocketOnVisible)
  347. .onConnected(_tspkWebSocketOnConnected)
  348. .onKeyCheck(_tspkWebSocketOnKeyCheck);
  349. #endif
  350. #if RELAY_SUPPORT
  351. relaySetStatusChange(_tspkRelayStatus);
  352. #endif
  353. DEBUG_MSG_P(PSTR("[THINGSPEAK] Async %s, SSL %s\n"),
  354. THINGSPEAK_USE_ASYNC ? "ENABLED" : "DISABLED",
  355. THINGSPEAK_USE_SSL ? "ENABLED" : "DISABLED"
  356. );
  357. // Main callbacks
  358. espurnaRegisterLoop(tspkLoop);
  359. espurnaRegisterReload(_tspkConfigure);
  360. }
  361. #endif