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.

804 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. #if TERMINAL_SUPPORT
  422. root["cmdVisible"] = 1;
  423. #endif
  424. root["hbMode"] = getSetting("hbMode", HEARTBEAT_MODE).toInt();
  425. root["hbInterval"] = getSetting("hbInterval", HEARTBEAT_INTERVAL).toInt();
  426. }
  427. void wsSend(JsonObject& root) {
  428. // TODO: avoid serializing twice?
  429. size_t len = root.measureLength();
  430. AsyncWebSocketMessageBuffer* buffer = _ws.makeBuffer(len);
  431. if (buffer) {
  432. root.printTo(reinterpret_cast<char*>(buffer->get()), len + 1);
  433. _ws.textAll(buffer);
  434. }
  435. }
  436. void wsSend(uint32_t client_id, JsonObject& root) {
  437. AsyncWebSocketClient* client = _ws.client(client_id);
  438. if (client == nullptr) return;
  439. // TODO: avoid serializing twice?
  440. size_t len = root.measureLength();
  441. AsyncWebSocketMessageBuffer* buffer = _ws.makeBuffer(len);
  442. if (buffer) {
  443. root.printTo(reinterpret_cast<char*>(buffer->get()), len + 1);
  444. client->text(buffer);
  445. }
  446. }
  447. void _wsConnected(uint32_t client_id) {
  448. const bool changePassword = (USE_PASSWORD && WEB_FORCE_PASS_CHANGE)
  449. ? getAdminPass().equals(ADMIN_PASS)
  450. : false;
  451. if (changePassword) {
  452. StaticJsonBuffer<JSON_OBJECT_SIZE(1)> jsonBuffer;
  453. JsonObject& root = jsonBuffer.createObject();
  454. root["webMode"] = WEB_MODE_PASSWORD;
  455. wsSend(client_id, root);
  456. return;
  457. }
  458. wsPostAll(client_id, _ws_callbacks.on_visible);
  459. wsPostSequence(client_id, _ws_callbacks.on_connected);
  460. wsPostSequence(client_id, _ws_callbacks.on_data);
  461. }
  462. void _wsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){
  463. if (type == WS_EVT_CONNECT) {
  464. client->_tempObject = nullptr;
  465. #ifndef NOWSAUTH
  466. if (!_wsAuth(client)) {
  467. wsSend_P(client->id(), PSTR("{\"message\": 10}"));
  468. DEBUG_MSG_P(PSTR("[WEBSOCKET] Validation check failed\n"));
  469. client->close();
  470. return;
  471. }
  472. #endif
  473. IPAddress ip = client->remoteIP();
  474. 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());
  475. _wsConnected(client->id());
  476. _wsResetUpdateTimer();
  477. wifiReconnectCheck();
  478. client->_tempObject = new WebSocketIncommingBuffer(_wsParse, true);
  479. } else if(type == WS_EVT_DISCONNECT) {
  480. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u disconnected\n"), client->id());
  481. if (client->_tempObject) {
  482. delete (WebSocketIncommingBuffer *) client->_tempObject;
  483. }
  484. wifiReconnectCheck();
  485. } else if(type == WS_EVT_ERROR) {
  486. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u error(%u): %s\n"), client->id(), *((uint16_t*)arg), (char*)data);
  487. } else if(type == WS_EVT_PONG) {
  488. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u pong(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  489. } else if(type == WS_EVT_DATA) {
  490. //DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u data(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  491. if (!client->_tempObject) return;
  492. WebSocketIncommingBuffer *buffer = (WebSocketIncommingBuffer *)client->_tempObject;
  493. AwsFrameInfo * info = (AwsFrameInfo*)arg;
  494. buffer->data_event(client, info, data, len);
  495. }
  496. }
  497. // TODO: make this generic loop method to queue important ws messages?
  498. // or, if something uses ticker / async ctx to send messages,
  499. // it needs a retry mechanism built into the callback object
  500. void _wsHandleClientData(const bool connected) {
  501. if (!connected && !_ws_client_data.empty()) {
  502. _ws_client_data.pop();
  503. return;
  504. }
  505. if (_ws_client_data.empty()) return;
  506. auto& data = _ws_client_data.front();
  507. // client_id == 0 means we need to send the message to every client
  508. if (data.client_id) {
  509. AsyncWebSocketClient* ws_client = _ws.client(data.client_id);
  510. if (!ws_client) {
  511. _ws_client_data.pop();
  512. return;
  513. }
  514. // wait until we can send the next batch of messages
  515. // XXX: enforce that callbacks send only one message per iteration
  516. if (ws_client->queueIsFull()) {
  517. return;
  518. }
  519. }
  520. // XXX: block allocation will try to create *2 next time,
  521. // likely failing and causing wsSend to reference empty objects
  522. // XXX: arduinojson6 will not do this, but we may need to use per-callback buffers
  523. constexpr const size_t BUFFER_SIZE = 3192;
  524. DynamicJsonBuffer jsonBuffer(BUFFER_SIZE);
  525. JsonObject& root = jsonBuffer.createObject();
  526. data.send(root);
  527. if (data.client_id) {
  528. wsSend(data.client_id, root);
  529. } else {
  530. wsSend(root);
  531. }
  532. yield();
  533. if (data.done()) {
  534. _ws_client_data.pop();
  535. }
  536. }
  537. void _wsLoop() {
  538. const bool connected = wsConnected();
  539. _wsDoUpdate(connected);
  540. _wsHandleClientData(connected);
  541. #if DEBUG_WEB_SUPPORT
  542. _ws_debug.send(connected);
  543. #endif
  544. }
  545. // -----------------------------------------------------------------------------
  546. // Public API
  547. // -----------------------------------------------------------------------------
  548. bool wsConnected() {
  549. return (_ws.count() > 0);
  550. }
  551. bool wsConnected(uint32_t client_id) {
  552. return _ws.hasClient(client_id);
  553. }
  554. ws_callbacks_t& wsRegister() {
  555. return _ws_callbacks;
  556. }
  557. void wsSend(ws_on_send_callback_f callback) {
  558. if (_ws.count() > 0) {
  559. DynamicJsonBuffer jsonBuffer(512);
  560. JsonObject& root = jsonBuffer.createObject();
  561. callback(root);
  562. wsSend(root);
  563. }
  564. }
  565. void wsSend(const char * payload) {
  566. if (_ws.count() > 0) {
  567. _ws.textAll(payload);
  568. }
  569. }
  570. void wsSend_P(PGM_P payload) {
  571. if (_ws.count() > 0) {
  572. char buffer[strlen_P(payload)];
  573. strcpy_P(buffer, payload);
  574. _ws.textAll(buffer);
  575. }
  576. }
  577. void wsSend(uint32_t client_id, ws_on_send_callback_f callback) {
  578. AsyncWebSocketClient* client = _ws.client(client_id);
  579. if (client == nullptr) return;
  580. DynamicJsonBuffer jsonBuffer(512);
  581. JsonObject& root = jsonBuffer.createObject();
  582. callback(root);
  583. wsSend(client_id, root);
  584. }
  585. void wsSend(uint32_t client_id, const char * payload) {
  586. _ws.text(client_id, payload);
  587. }
  588. void wsSend_P(uint32_t client_id, PGM_P payload) {
  589. char buffer[strlen_P(payload)];
  590. strcpy_P(buffer, payload);
  591. _ws.text(client_id, buffer);
  592. }
  593. void wsPost(const ws_on_send_callback_f& cb) {
  594. _ws_client_data.emplace(cb);
  595. }
  596. void wsPostAll(uint32_t client_id, const ws_on_send_callback_list_t& cbs) {
  597. _ws_client_data.emplace(client_id, cbs, ws_data_t::ALL);
  598. }
  599. void wsPostAll(const ws_on_send_callback_list_t& cbs) {
  600. _ws_client_data.emplace(0, cbs, ws_data_t::ALL);
  601. }
  602. void wsPostSequence(uint32_t client_id, const ws_on_send_callback_list_t& cbs) {
  603. _ws_client_data.emplace(client_id, cbs, ws_data_t::SEQUENCE);
  604. }
  605. void wsPostSequence(uint32_t client_id, ws_on_send_callback_list_t&& cbs) {
  606. _ws_client_data.emplace(client_id, std::forward<ws_on_send_callback_list_t>(cbs), ws_data_t::SEQUENCE);
  607. }
  608. void wsPostSequence(const ws_on_send_callback_list_t& cbs) {
  609. _ws_client_data.emplace(0, cbs, ws_data_t::SEQUENCE);
  610. }
  611. void wsSetup() {
  612. _ws.onEvent(_wsEvent);
  613. webServer()->addHandler(&_ws);
  614. // CORS
  615. const String webDomain = getSetting("webDomain", WEB_REMOTE_DOMAIN);
  616. DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin", webDomain);
  617. if (!webDomain.equals("*")) {
  618. DefaultHeaders::Instance().addHeader("Access-Control-Allow-Credentials", "true");
  619. }
  620. webServer()->on("/auth", HTTP_GET, _onAuth);
  621. wsRegister()
  622. .onConnected(_wsOnConnected)
  623. .onKeyCheck(_wsOnKeyCheck);
  624. espurnaRegisterLoop(_wsLoop);
  625. }
  626. #endif // WEB_SUPPORT