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.

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