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.

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