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.

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