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.

705 lines
19 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. WEBSOCKET MODULE
  3. Copyright (C) 2016-2019 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #if WEB_SUPPORT
  6. #include <ESPAsyncTCP.h>
  7. #include <ESPAsyncWebServer.h>
  8. #include <ArduinoJson.h>
  9. #include <Ticker.h>
  10. #include <vector>
  11. #include "libs/WebSocketIncommingBuffer.h"
  12. AsyncWebSocket _ws("/ws");
  13. Ticker _web_defer;
  14. // -----------------------------------------------------------------------------
  15. // WS callbacks
  16. // -----------------------------------------------------------------------------
  17. ws_callbacks_t _ws_callbacks;
  18. struct ws_counter_t {
  19. ws_counter_t() : current(0), start(0), stop(0) {}
  20. ws_counter_t(uint32_t start, uint32_t stop) :
  21. current(start), start(start), stop(stop) {}
  22. void reset() {
  23. current = start;
  24. }
  25. void next() {
  26. if (current < stop) {
  27. ++current;
  28. }
  29. }
  30. bool done() {
  31. return (current >= stop);
  32. }
  33. uint32_t current;
  34. uint32_t start;
  35. uint32_t stop;
  36. };
  37. struct ws_data_t {
  38. enum mode_t {
  39. SEQUENCE,
  40. ALL
  41. };
  42. ws_data_t(const ws_on_send_callback_f& cb) :
  43. storage(new ws_on_send_callback_list_t {cb}),
  44. client_id(0),
  45. mode(ALL),
  46. callbacks(*storage.get()),
  47. counter(0, 1)
  48. {}
  49. ws_data_t(const uint32_t client_id, const ws_on_send_callback_list_t& callbacks, mode_t mode = SEQUENCE) :
  50. client_id(client_id),
  51. mode(mode),
  52. callbacks(callbacks),
  53. counter(0, callbacks.size())
  54. {}
  55. bool done() {
  56. return counter.done();
  57. }
  58. void sendAll(JsonObject& root) {
  59. while (!counter.done()) counter.next();
  60. for (auto& callback : callbacks) {
  61. callback(root);
  62. }
  63. }
  64. void sendCurrent(JsonObject& root) {
  65. callbacks[counter.current](root);
  66. counter.next();
  67. }
  68. void send(JsonObject& root) {
  69. switch (mode) {
  70. case SEQUENCE: sendCurrent(root); break;
  71. case ALL: sendAll(root); break;
  72. }
  73. }
  74. std::unique_ptr<ws_on_send_callback_list_t> storage;
  75. const uint32_t client_id;
  76. const mode_t mode;
  77. const ws_on_send_callback_list_t& callbacks;
  78. ws_counter_t counter;
  79. };
  80. std::queue<ws_data_t> _ws_client_data;
  81. // -----------------------------------------------------------------------------
  82. // WS authentication
  83. // -----------------------------------------------------------------------------
  84. struct ws_ticket_t {
  85. IPAddress ip;
  86. unsigned long timestamp = 0;
  87. };
  88. ws_ticket_t _ws_tickets[WS_BUFFER_SIZE];
  89. void _onAuth(AsyncWebServerRequest *request) {
  90. webLog(request);
  91. if (!webAuthenticate(request)) return request->requestAuthentication();
  92. IPAddress ip = request->client()->remoteIP();
  93. unsigned long now = millis();
  94. unsigned short index;
  95. for (index = 0; index < WS_BUFFER_SIZE; index++) {
  96. if (_ws_tickets[index].ip == ip) break;
  97. if (_ws_tickets[index].timestamp == 0) break;
  98. if (now - _ws_tickets[index].timestamp > WS_TIMEOUT) break;
  99. }
  100. if (index == WS_BUFFER_SIZE) {
  101. request->send(429);
  102. } else {
  103. _ws_tickets[index].ip = ip;
  104. _ws_tickets[index].timestamp = now;
  105. request->send(200, "text/plain", "OK");
  106. }
  107. }
  108. bool _wsAuth(AsyncWebSocketClient * client) {
  109. IPAddress ip = client->remoteIP();
  110. unsigned long now = millis();
  111. unsigned short index = 0;
  112. for (index = 0; index < WS_BUFFER_SIZE; index++) {
  113. if ((_ws_tickets[index].ip == ip) && (now - _ws_tickets[index].timestamp < WS_TIMEOUT)) break;
  114. }
  115. if (index == WS_BUFFER_SIZE) {
  116. return false;
  117. }
  118. return true;
  119. }
  120. // -----------------------------------------------------------------------------
  121. // Debug
  122. // -----------------------------------------------------------------------------
  123. #if DEBUG_WEB_SUPPORT
  124. bool wsDebugSend(const char* prefix, const char* message) {
  125. if (!wsConnected()) return false;
  126. // via: https://arduinojson.org/v6/assistant/
  127. // we use 1 object for "weblog", 2nd one for "message". "prefix", optional
  128. StaticJsonBuffer<JSON_OBJECT_SIZE(1) + JSON_OBJECT_SIZE(2)> jsonBuffer;
  129. JsonObject& root = jsonBuffer.createObject();
  130. JsonObject& weblog = root.createNestedObject("weblog");
  131. weblog["message"] = message;
  132. if (prefix && (prefix[0] != '\0')) {
  133. weblog["prefix"] = prefix;
  134. }
  135. // TODO: avoid serializing twice and just measure json ourselves?
  136. //const size_t len = strlen(message) + strlen(prefix)
  137. // + strlen("{\"weblog\":}")
  138. // + strlen("{\"message\":\"\"}")
  139. // + (strlen(prefix) ? strlen("\",\"prefix\":\"\"") : 0);
  140. //wsSend(root, len);
  141. wsSend(root);
  142. return true;
  143. }
  144. #endif
  145. // Check the existing setting before saving it
  146. // TODO: this should know of the default values, somehow?
  147. // TODO: move webPort handling somewhere else?
  148. bool _wsStore(const String& key, const String& value) {
  149. if (key == "webPort") {
  150. if ((value.toInt() == 0) || (value.toInt() == 80)) {
  151. return delSetting(key);
  152. }
  153. }
  154. if (value != getSetting(key)) {
  155. return setSetting(key, value);
  156. }
  157. return false;
  158. }
  159. // -----------------------------------------------------------------------------
  160. // Store indexed key (key0, key1, etc.) from array
  161. // -----------------------------------------------------------------------------
  162. bool _wsStore(const String& key, JsonArray& value) {
  163. bool changed = false;
  164. unsigned char index = 0;
  165. for (auto element : value) {
  166. if (_wsStore(key + index, element.as<String>())) changed = true;
  167. index++;
  168. }
  169. // Delete further values
  170. for (unsigned char i=index; i<SETTINGS_MAX_LIST_COUNT; i++) {
  171. if (!delSetting(key, index)) break;
  172. changed = true;
  173. }
  174. return changed;
  175. }
  176. bool _wsCheckKey(const String& key, JsonVariant& value) {
  177. for (auto& callback : _ws_callbacks.on_keycheck) {
  178. if (callback(key.c_str(), value)) return true;
  179. // TODO: remove this to call all OnKeyCheckCallbacks with the
  180. // current key/value
  181. }
  182. return false;
  183. }
  184. void _wsParse(AsyncWebSocketClient *client, uint8_t * payload, size_t length) {
  185. //DEBUG_MSG_P(PSTR("[WEBSOCKET] Parsing: %s\n"), length ? (char*) payload : "");
  186. // Get client ID
  187. uint32_t client_id = client->id();
  188. // Check early for empty object / nothing
  189. if ((length == 0) || (length == 1)) {
  190. return;
  191. }
  192. if ((length == 3) && (strcmp((char*) payload, "{}") == 0)) {
  193. return;
  194. }
  195. // Parse JSON input
  196. // TODO: json buffer should be pretty efficient with the non-const payload,
  197. // most of the space is taken by the object key references
  198. DynamicJsonBuffer jsonBuffer(512);
  199. JsonObject& root = jsonBuffer.parseObject((char *) payload);
  200. if (!root.success()) {
  201. DEBUG_MSG_P(PSTR("[WEBSOCKET] JSON parsing error\n"));
  202. wsSend_P(client_id, PSTR("{\"message\": 3}"));
  203. return;
  204. }
  205. // Check actions -----------------------------------------------------------
  206. const char* action = root["action"];
  207. if (action) {
  208. DEBUG_MSG_P(PSTR("[WEBSOCKET] Requested action: %s\n"), action);
  209. if (strcmp(action, "reboot") == 0) {
  210. deferredReset(100, CUSTOM_RESET_WEB);
  211. return;
  212. }
  213. if (strcmp(action, "reconnect") == 0) {
  214. _web_defer.once_ms(100, wifiDisconnect);
  215. return;
  216. }
  217. if (strcmp(action, "factory_reset") == 0) {
  218. DEBUG_MSG_P(PSTR("\n\nFACTORY RESET\n\n"));
  219. resetSettings();
  220. deferredReset(100, CUSTOM_RESET_FACTORY);
  221. return;
  222. }
  223. JsonObject& data = root["data"];
  224. if (data.success()) {
  225. // Callbacks
  226. for (auto& callback : _ws_callbacks.on_action) {
  227. callback(client_id, action, data);
  228. }
  229. // Restore configuration via websockets
  230. if (strcmp(action, "restore") == 0) {
  231. if (settingsRestoreJson(data)) {
  232. wsSend_P(client_id, PSTR("{\"message\": 5}"));
  233. } else {
  234. wsSend_P(client_id, PSTR("{\"message\": 4}"));
  235. }
  236. }
  237. return;
  238. }
  239. };
  240. // Check configuration -----------------------------------------------------
  241. JsonObject& config = root["config"];
  242. if (config.success()) {
  243. DEBUG_MSG_P(PSTR("[WEBSOCKET] Parsing configuration data\n"));
  244. String adminPass;
  245. bool save = false;
  246. for (auto kv: config) {
  247. bool changed = false;
  248. String key = kv.key;
  249. JsonVariant& value = kv.value;
  250. // Check password
  251. if (key == "adminPass") {
  252. if (!value.is<JsonArray&>()) continue;
  253. JsonArray& values = value.as<JsonArray&>();
  254. if (values.size() != 2) continue;
  255. if (values[0].as<String>().equals(values[1].as<String>())) {
  256. String password = values[0].as<String>();
  257. if (password.length() > 0) {
  258. setSetting(key, password);
  259. save = true;
  260. wsSend_P(client_id, PSTR("{\"action\": \"reload\"}"));
  261. }
  262. } else {
  263. wsSend_P(client_id, PSTR("{\"message\": 7}"));
  264. }
  265. continue;
  266. }
  267. if (!_wsCheckKey(key, value)) {
  268. delSetting(key);
  269. continue;
  270. }
  271. // Store values
  272. if (value.is<JsonArray&>()) {
  273. if (_wsStore(key, value.as<JsonArray&>())) changed = true;
  274. } else {
  275. if (_wsStore(key, value.as<String>())) changed = true;
  276. }
  277. // Update flags if value has changed
  278. if (changed) {
  279. save = true;
  280. }
  281. }
  282. // Save settings
  283. if (save) {
  284. // Callbacks
  285. espurnaReload();
  286. // Persist settings
  287. saveSettings();
  288. wsSend_P(client_id, PSTR("{\"message\": 8}"));
  289. } else {
  290. wsSend_P(client_id, PSTR("{\"message\": 9}"));
  291. }
  292. }
  293. }
  294. void _wsUpdate(JsonObject& root) {
  295. root["heap"] = getFreeHeap();
  296. root["uptime"] = getUptime();
  297. root["rssi"] = WiFi.RSSI();
  298. root["loadaverage"] = systemLoadAverage();
  299. #if ADC_MODE_VALUE == ADC_VCC
  300. root["vcc"] = ESP.getVcc();
  301. #endif
  302. #if NTP_SUPPORT
  303. if (ntpSynced()) root["now"] = now();
  304. #endif
  305. }
  306. void _wsDoUpdate(bool reset = false) {
  307. static unsigned long last = millis();
  308. if (reset) {
  309. last = millis() + WS_UPDATE_INTERVAL;
  310. return;
  311. }
  312. if (millis() - last > WS_UPDATE_INTERVAL) {
  313. last = millis();
  314. wsSend(_wsUpdate);
  315. }
  316. }
  317. bool _wsOnKeyCheck(const char * key, JsonVariant& value) {
  318. if (strncmp(key, "ws", 2) == 0) return true;
  319. if (strncmp(key, "admin", 5) == 0) return true;
  320. if (strncmp(key, "hostname", 8) == 0) return true;
  321. if (strncmp(key, "desc", 4) == 0) return true;
  322. if (strncmp(key, "webPort", 7) == 0) return true;
  323. return false;
  324. }
  325. void _wsOnConnected(JsonObject& root) {
  326. char chipid[7];
  327. snprintf_P(chipid, sizeof(chipid), PSTR("%06X"), ESP.getChipId());
  328. root["webMode"] = WEB_MODE_NORMAL;
  329. root["app_name"] = APP_NAME;
  330. root["app_version"] = APP_VERSION;
  331. root["app_build"] = buildTime();
  332. #if defined(APP_REVISION)
  333. root["app_revision"] = APP_REVISION;
  334. #endif
  335. root["manufacturer"] = MANUFACTURER;
  336. root["chipid"] = String(chipid);
  337. root["mac"] = WiFi.macAddress();
  338. root["bssid"] = WiFi.BSSIDstr();
  339. root["channel"] = WiFi.channel();
  340. root["device"] = DEVICE;
  341. root["hostname"] = getSetting("hostname");
  342. root["desc"] = getSetting("desc");
  343. root["network"] = getNetwork();
  344. root["deviceip"] = getIP();
  345. root["sketch_size"] = ESP.getSketchSize();
  346. root["free_size"] = ESP.getFreeSketchSpace();
  347. root["sdk"] = ESP.getSdkVersion();
  348. root["core"] = getCoreVersion();
  349. root["btnDelay"] = getSetting("btnDelay", BUTTON_DBLCLICK_DELAY).toInt();
  350. root["webPort"] = getSetting("webPort", WEB_PORT).toInt();
  351. root["wsAuth"] = getSetting("wsAuth", WS_AUTHENTICATION).toInt() == 1;
  352. #if TERMINAL_SUPPORT
  353. root["cmdVisible"] = 1;
  354. #endif
  355. root["hbMode"] = getSetting("hbMode", HEARTBEAT_MODE).toInt();
  356. root["hbInterval"] = getSetting("hbInterval", HEARTBEAT_INTERVAL).toInt();
  357. _wsDoUpdate(true);
  358. }
  359. void wsSend(JsonObject& root) {
  360. // TODO: avoid serializing twice?
  361. size_t len = root.measureLength();
  362. AsyncWebSocketMessageBuffer* buffer = _ws.makeBuffer(len);
  363. if (buffer) {
  364. root.printTo(reinterpret_cast<char*>(buffer->get()), len + 1);
  365. _ws.textAll(buffer);
  366. }
  367. }
  368. void wsSend(uint32_t client_id, JsonObject& root) {
  369. AsyncWebSocketClient* client = _ws.client(client_id);
  370. if (client == nullptr) return;
  371. // TODO: avoid serializing twice?
  372. size_t len = root.measureLength();
  373. AsyncWebSocketMessageBuffer* buffer = _ws.makeBuffer(len);
  374. if (buffer) {
  375. root.printTo(reinterpret_cast<char*>(buffer->get()), len + 1);
  376. client->text(buffer);
  377. }
  378. }
  379. void _wsConnected(uint32_t client_id) {
  380. const bool changePassword = (USE_PASSWORD && WEB_FORCE_PASS_CHANGE)
  381. ? getAdminPass().equals(ADMIN_PASS)
  382. : false;
  383. if (changePassword) {
  384. StaticJsonBuffer<JSON_OBJECT_SIZE(1)> jsonBuffer;
  385. JsonObject& root = jsonBuffer.createObject();
  386. root["webMode"] = WEB_MODE_PASSWORD;
  387. wsSend(client_id, root);
  388. return;
  389. }
  390. wsPostAll(client_id, _ws_callbacks.on_visible);
  391. wsPostSequence(client_id, _ws_callbacks.on_connected);
  392. wsPostSequence(client_id, _ws_callbacks.on_data);
  393. }
  394. void _wsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){
  395. if (type == WS_EVT_CONNECT) {
  396. client->_tempObject = nullptr;
  397. #ifndef NOWSAUTH
  398. if (!_wsAuth(client)) {
  399. wsSend_P(client->id(), PSTR("{\"message\": 10}"));
  400. DEBUG_MSG_P(PSTR("[WEBSOCKET] Validation check failed\n"));
  401. client->close();
  402. return;
  403. }
  404. #endif
  405. IPAddress ip = client->remoteIP();
  406. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u connected, ip: %d.%d.%d.%d, url: %s\n"), client->id(), ip[0], ip[1], ip[2], ip[3], server->url());
  407. _wsConnected(client->id());
  408. wifiReconnectCheck();
  409. } else if(type == WS_EVT_DISCONNECT) {
  410. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u disconnected\n"), client->id());
  411. if (client->_tempObject) {
  412. delete (WebSocketIncommingBuffer *) client->_tempObject;
  413. }
  414. wifiReconnectCheck();
  415. } else if(type == WS_EVT_ERROR) {
  416. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u error(%u): %s\n"), client->id(), *((uint16_t*)arg), (char*)data);
  417. } else if(type == WS_EVT_PONG) {
  418. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u pong(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  419. } else if(type == WS_EVT_DATA) {
  420. //DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u data(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  421. if (!client->_tempObject) return;
  422. WebSocketIncommingBuffer *buffer = (WebSocketIncommingBuffer *)client->_tempObject;
  423. AwsFrameInfo * info = (AwsFrameInfo*)arg;
  424. buffer->data_event(client, info, data, len);
  425. }
  426. }
  427. // TODO: make this generic loop method to queue important ws messages?
  428. // or, if something uses ticker / async ctx to send messages,
  429. // it needs a retry mechanism built into the callback object
  430. void _wsHandleClientData() {
  431. if (_ws_client_data.empty()) return;
  432. auto& data = _ws_client_data.front();
  433. AsyncWebSocketClient* ws_client = _ws.client(data.client_id);
  434. if (!ws_client) {
  435. _ws_client_data.pop();
  436. return;
  437. }
  438. // wait until we can send the next batch of messages
  439. // XXX: enforce that callbacks send only one message per iteration
  440. if (ws_client->queueIsFull()) {
  441. return;
  442. }
  443. // XXX: block allocation will try to create *2 next time,
  444. // likely failing and causing wsSend to reference empty objects
  445. // XXX: arduinojson6 will not do this, but we may need to use per-callback buffers
  446. constexpr const size_t BUFFER_SIZE = 3192;
  447. DynamicJsonBuffer jsonBuffer(BUFFER_SIZE);
  448. JsonObject& root = jsonBuffer.createObject();
  449. data.send(root);
  450. if (data.client_id) {
  451. wsSend(data.client_id, root);
  452. } else {
  453. wsSend(root);
  454. }
  455. yield();
  456. if (data.done()) {
  457. // push the queue and finally allow incoming messages
  458. _ws_client_data.pop();
  459. ws_client->_tempObject = new WebSocketIncommingBuffer(_wsParse, true);
  460. }
  461. }
  462. void _wsLoop() {
  463. if (!wsConnected()) return;
  464. _wsDoUpdate();
  465. _wsHandleClientData();
  466. }
  467. // -----------------------------------------------------------------------------
  468. // Public API
  469. // -----------------------------------------------------------------------------
  470. bool wsConnected() {
  471. return (_ws.count() > 0);
  472. }
  473. bool wsConnected(uint32_t client_id) {
  474. return _ws.hasClient(client_id);
  475. }
  476. ws_callbacks_t& wsRegister() {
  477. return _ws_callbacks;
  478. }
  479. void wsSend(ws_on_send_callback_f callback) {
  480. if (_ws.count() > 0) {
  481. DynamicJsonBuffer jsonBuffer(512);
  482. JsonObject& root = jsonBuffer.createObject();
  483. callback(root);
  484. wsSend(root);
  485. }
  486. }
  487. void wsSend(const char * payload) {
  488. if (_ws.count() > 0) {
  489. _ws.textAll(payload);
  490. }
  491. }
  492. void wsSend_P(PGM_P payload) {
  493. if (_ws.count() > 0) {
  494. char buffer[strlen_P(payload)];
  495. strcpy_P(buffer, payload);
  496. _ws.textAll(buffer);
  497. }
  498. }
  499. void wsSend(uint32_t client_id, ws_on_send_callback_f callback) {
  500. AsyncWebSocketClient* client = _ws.client(client_id);
  501. if (client == nullptr) return;
  502. DynamicJsonBuffer jsonBuffer(512);
  503. JsonObject& root = jsonBuffer.createObject();
  504. callback(root);
  505. wsSend(client_id, root);
  506. }
  507. void wsSend(uint32_t client_id, const char * payload) {
  508. _ws.text(client_id, payload);
  509. }
  510. void wsSend_P(uint32_t client_id, PGM_P payload) {
  511. char buffer[strlen_P(payload)];
  512. strcpy_P(buffer, payload);
  513. _ws.text(client_id, buffer);
  514. }
  515. void wsPost(const ws_on_send_callback_f& cb) {
  516. _ws_client_data.emplace(cb);
  517. }
  518. void wsPostAll(uint32_t client_id, const ws_on_send_callback_list_t& cbs) {
  519. _ws_client_data.emplace(client_id, cbs, ws_data_t::ALL);
  520. }
  521. void wsPostAll(const ws_on_send_callback_list_t& cbs) {
  522. _ws_client_data.emplace(0, cbs, ws_data_t::ALL);
  523. }
  524. void wsPostSequence(uint32_t client_id, const ws_on_send_callback_list_t& cbs) {
  525. _ws_client_data.emplace(client_id, cbs, ws_data_t::SEQUENCE);
  526. }
  527. void wsPostSequence(const ws_on_send_callback_list_t& cbs) {
  528. _ws_client_data.emplace(0, cbs, ws_data_t::SEQUENCE);
  529. }
  530. void wsSetup() {
  531. _ws.onEvent(_wsEvent);
  532. webServer()->addHandler(&_ws);
  533. // CORS
  534. const String webDomain = getSetting("webDomain", WEB_REMOTE_DOMAIN);
  535. DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin", webDomain);
  536. if (!webDomain.equals("*")) {
  537. DefaultHeaders::Instance().addHeader("Access-Control-Allow-Credentials", "true");
  538. }
  539. webServer()->on("/auth", HTTP_GET, _onAuth);
  540. wsRegister()
  541. .onConnected(_wsOnConnected)
  542. .onKeyCheck(_wsOnKeyCheck);
  543. espurnaRegisterLoop(_wsLoop);
  544. }
  545. #endif // WEB_SUPPORT