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.

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