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.

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