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.

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