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.

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