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