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.

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