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.

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