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.

732 lines
20 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 years ago
6 years ago
6 years ago
6 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 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. #include "ws.h"
  6. #if WEB_SUPPORT
  7. #include <vector>
  8. #include "system.h"
  9. #include "web.h"
  10. #include "ntp.h"
  11. #include "utils.h"
  12. #include "ws_internal.h"
  13. #include "libs/WebSocketIncommingBuffer.h"
  14. AsyncWebSocket _ws("/ws");
  15. // -----------------------------------------------------------------------------
  16. // Periodic updates
  17. // -----------------------------------------------------------------------------
  18. uint32_t _ws_last_update = 0;
  19. void _wsResetUpdateTimer() {
  20. _ws_last_update = millis() + WS_UPDATE_INTERVAL;
  21. }
  22. void _wsUpdate(JsonObject& root) {
  23. root["heap"] = systemFreeHeap();
  24. root["uptime"] = systemUptime();
  25. root["rssi"] = WiFi.RSSI();
  26. root["loadaverage"] = systemLoadAverage();
  27. if (ADC_MODE_VALUE == ADC_VCC) {
  28. root["vcc"] = ESP.getVcc();
  29. } else {
  30. root["vcc"] = "N/A (TOUT) ";
  31. }
  32. #if NTP_SUPPORT
  33. // XXX: arduinojson will ignore info.now assignment (64bit time_t) when trying to store it as integer
  34. if (ntpSynced()) {
  35. auto info = ntpInfo();
  36. root["now"] = static_cast<double>(info.now);
  37. root["nowString"] = info.utc;
  38. root["nowLocalString"] = info.local.length()
  39. ? info.local
  40. : info.utc;
  41. }
  42. #endif
  43. }
  44. void _wsDoUpdate(const bool connected) {
  45. if (!connected) return;
  46. if (millis() - _ws_last_update > WS_UPDATE_INTERVAL) {
  47. _ws_last_update = millis();
  48. wsSend(_wsUpdate);
  49. }
  50. }
  51. // -----------------------------------------------------------------------------
  52. // WS callbacks
  53. // -----------------------------------------------------------------------------
  54. std::queue<WsPostponedCallbacks> _ws_queue;
  55. ws_callbacks_t _ws_callbacks;
  56. void wsPost(uint32_t client_id, ws_on_send_callback_f&& cb) {
  57. _ws_queue.emplace(client_id, std::move(cb));
  58. }
  59. void wsPost(ws_on_send_callback_f&& cb) {
  60. wsPost(0, std::move(cb));
  61. }
  62. void wsPost(uint32_t client_id, const ws_on_send_callback_f& cb) {
  63. _ws_queue.emplace(client_id, cb);
  64. }
  65. void wsPost(const ws_on_send_callback_f& cb) {
  66. wsPost(0, cb);
  67. }
  68. template <typename T>
  69. void _wsPostCallbacks(uint32_t client_id, T&& cbs, WsPostponedCallbacks::Mode mode) {
  70. _ws_queue.emplace(client_id, std::forward<T>(cbs), mode);
  71. }
  72. void wsPostAll(uint32_t client_id, ws_on_send_callback_list_t&& cbs) {
  73. _wsPostCallbacks(client_id, std::move(cbs), WsPostponedCallbacks::Mode::All);
  74. }
  75. void wsPostAll(ws_on_send_callback_list_t&& cbs) {
  76. wsPostAll(0, std::move(cbs));
  77. }
  78. void wsPostAll(uint32_t client_id, const ws_on_send_callback_list_t& cbs) {
  79. _wsPostCallbacks(client_id, cbs, WsPostponedCallbacks::Mode::All);
  80. }
  81. void wsPostAll(const ws_on_send_callback_list_t& cbs) {
  82. wsPostAll(0, cbs);
  83. }
  84. void wsPostSequence(uint32_t client_id, ws_on_send_callback_list_t&& cbs) {
  85. _wsPostCallbacks(client_id, std::move(cbs), WsPostponedCallbacks::Mode::Sequence);
  86. }
  87. void wsPostSequence(ws_on_send_callback_list_t&& cbs) {
  88. wsPostSequence(0, std::move(cbs));
  89. }
  90. void wsPostSequence(uint32_t client_id, const ws_on_send_callback_list_t& cbs) {
  91. _wsPostCallbacks(client_id, cbs, WsPostponedCallbacks::Mode::Sequence);
  92. }
  93. void wsPostSequence(const ws_on_send_callback_list_t& cbs) {
  94. wsPostSequence(0, cbs);
  95. }
  96. // -----------------------------------------------------------------------------
  97. ws_callbacks_t& ws_callbacks_t::onVisible(ws_on_send_callback_f cb) {
  98. on_visible.push_back(cb);
  99. return *this;
  100. }
  101. ws_callbacks_t& ws_callbacks_t::onConnected(ws_on_send_callback_f cb) {
  102. on_connected.push_back(cb);
  103. return *this;
  104. }
  105. ws_callbacks_t& ws_callbacks_t::onData(ws_on_send_callback_f cb) {
  106. on_data.push_back(cb);
  107. return *this;
  108. }
  109. ws_callbacks_t& ws_callbacks_t::onAction(ws_on_action_callback_f cb) {
  110. on_action.push_back(cb);
  111. return *this;
  112. }
  113. ws_callbacks_t& ws_callbacks_t::onKeyCheck(ws_on_keycheck_callback_f cb) {
  114. on_keycheck.push_back(cb);
  115. return *this;
  116. }
  117. // -----------------------------------------------------------------------------
  118. // WS authentication
  119. // -----------------------------------------------------------------------------
  120. WsTicket _ws_tickets[WS_BUFFER_SIZE];
  121. void _onAuth(AsyncWebServerRequest *request) {
  122. webLog(request);
  123. if (!webAuthenticate(request)) return request->requestAuthentication();
  124. IPAddress ip = request->client()->remoteIP();
  125. unsigned long now = millis();
  126. unsigned short index;
  127. for (index = 0; index < WS_BUFFER_SIZE; index++) {
  128. if (_ws_tickets[index].ip == ip) break;
  129. if (_ws_tickets[index].timestamp == 0) break;
  130. if (now - _ws_tickets[index].timestamp > WS_TIMEOUT) break;
  131. }
  132. if (index == WS_BUFFER_SIZE) {
  133. request->send(429);
  134. } else {
  135. _ws_tickets[index].ip = ip;
  136. _ws_tickets[index].timestamp = now;
  137. request->send(200, "text/plain", "OK");
  138. }
  139. }
  140. bool _wsAuth(AsyncWebSocketClient * client) {
  141. IPAddress ip = client->remoteIP();
  142. unsigned long now = millis();
  143. unsigned short index = 0;
  144. for (index = 0; index < WS_BUFFER_SIZE; index++) {
  145. if ((_ws_tickets[index].ip == ip) && (now - _ws_tickets[index].timestamp < WS_TIMEOUT)) break;
  146. }
  147. if (index == WS_BUFFER_SIZE) {
  148. return false;
  149. }
  150. return true;
  151. }
  152. // -----------------------------------------------------------------------------
  153. // Debug
  154. // -----------------------------------------------------------------------------
  155. #if DEBUG_WEB_SUPPORT
  156. constexpr size_t WsDebugMessagesMax = 8;
  157. WsDebug _ws_debug(WsDebugMessagesMax);
  158. void WsDebug::send(bool connected) {
  159. if (!connected && _flush) {
  160. clear();
  161. return;
  162. }
  163. if (!_flush) return;
  164. // ref: http://arduinojson.org/v5/assistant/
  165. // {"weblog": {"msg":[...],"pre":[...]}}
  166. DynamicJsonBuffer jsonBuffer(2*JSON_ARRAY_SIZE(_messages.size()) + JSON_OBJECT_SIZE(1) + JSON_OBJECT_SIZE(2));
  167. JsonObject& root = jsonBuffer.createObject();
  168. JsonObject& weblog = root.createNestedObject("weblog");
  169. JsonArray& msg_array = weblog.createNestedArray("msg");
  170. JsonArray& pre_array = weblog.createNestedArray("pre");
  171. for (auto& msg : _messages) {
  172. pre_array.add(msg.first.c_str());
  173. msg_array.add(msg.second.c_str());
  174. }
  175. wsSend(root);
  176. clear();
  177. }
  178. bool wsDebugSend(const char* prefix, const char* message) {
  179. if (!wsConnected()) return false;
  180. _ws_debug.add(prefix, message);
  181. return true;
  182. }
  183. #endif
  184. // Check the existing setting before saving it
  185. // TODO: this should know of the default values, somehow?
  186. // TODO: move webPort handling somewhere else?
  187. bool _wsStore(const String& key, const String& value) {
  188. if (key == "webPort") {
  189. if ((value.toInt() == 0) || (value.toInt() == 80)) {
  190. return delSetting(key);
  191. }
  192. }
  193. if (!hasSetting(key) || value != getSetting(key)) {
  194. return setSetting(key, value);
  195. }
  196. return false;
  197. }
  198. // -----------------------------------------------------------------------------
  199. // Store indexed key (key0, key1, etc.) from array
  200. // -----------------------------------------------------------------------------
  201. bool _wsStore(const String& key, JsonArray& values) {
  202. bool changed = false;
  203. unsigned char index = 0;
  204. for (auto& element : values) {
  205. const auto value = element.as<String>();
  206. auto setting = SettingsKey {key, index};
  207. if (!hasSetting(setting) || value != getSetting(setting)) {
  208. setSetting(setting, value);
  209. changed = true;
  210. }
  211. ++index;
  212. }
  213. // Delete further values
  214. for (unsigned char next_index=index; next_index < SETTINGS_MAX_LIST_COUNT; ++next_index) {
  215. if (!delSetting({key, next_index})) break;
  216. changed = true;
  217. }
  218. return changed;
  219. }
  220. bool _wsCheckKey(const String& key, JsonVariant& value) {
  221. for (auto& callback : _ws_callbacks.on_keycheck) {
  222. if (callback(key.c_str(), value)) return true;
  223. // TODO: remove this to call all OnKeyCheckCallbacks with the
  224. // current key/value
  225. }
  226. return false;
  227. }
  228. void _wsParse(AsyncWebSocketClient *client, uint8_t * payload, size_t length) {
  229. //DEBUG_MSG_P(PSTR("[WEBSOCKET] Parsing: %s\n"), length ? (char*) payload : "");
  230. // Get client ID
  231. uint32_t client_id = client->id();
  232. // Check early for empty object / nothing
  233. if ((length == 0) || (length == 1)) {
  234. return;
  235. }
  236. if ((length == 3) && (strcmp((char*) payload, "{}") == 0)) {
  237. return;
  238. }
  239. // Parse JSON input
  240. // TODO: json buffer should be pretty efficient with the non-const payload,
  241. // most of the space is taken by the object key references
  242. DynamicJsonBuffer jsonBuffer(512);
  243. JsonObject& root = jsonBuffer.parseObject((char *) payload);
  244. if (!root.success()) {
  245. DEBUG_MSG_P(PSTR("[WEBSOCKET] JSON parsing error\n"));
  246. wsSend_P(client_id, PSTR("{\"message\": 3}"));
  247. return;
  248. }
  249. // Check actions -----------------------------------------------------------
  250. const char* action = root["action"];
  251. if (action) {
  252. if (strcmp(action, "ping") == 0) {
  253. wsSend_P(client_id, PSTR("{\"pong\": 1}"));
  254. return;
  255. }
  256. DEBUG_MSG_P(PSTR("[WEBSOCKET] Requested action: %s\n"), action);
  257. if (strcmp(action, "reboot") == 0) {
  258. deferredReset(100, CustomResetReason::Web);
  259. return;
  260. }
  261. if (strcmp(action, "reconnect") == 0) {
  262. static Ticker timer;
  263. timer.once_ms_scheduled(100, []() {
  264. wifiDisconnect();
  265. yield();
  266. });
  267. return;
  268. }
  269. if (strcmp(action, "factory_reset") == 0) {
  270. factoryReset();
  271. return;
  272. }
  273. JsonObject& data = root["data"];
  274. if (data.success()) {
  275. // Callbacks
  276. for (auto& callback : _ws_callbacks.on_action) {
  277. callback(client_id, action, data);
  278. }
  279. // Restore configuration via websockets
  280. if (strcmp(action, "restore") == 0) {
  281. if (settingsRestoreJson(data)) {
  282. wsSend_P(client_id, PSTR("{\"message\": 5}"));
  283. } else {
  284. wsSend_P(client_id, PSTR("{\"message\": 4}"));
  285. }
  286. }
  287. return;
  288. }
  289. };
  290. // Check configuration -----------------------------------------------------
  291. JsonObject& config = root["config"];
  292. if (config.success()) {
  293. DEBUG_MSG_P(PSTR("[WEBSOCKET] Parsing configuration data\n"));
  294. String adminPass;
  295. bool save = false;
  296. for (auto kv: config) {
  297. bool changed = false;
  298. String key = kv.key;
  299. JsonVariant& value = kv.value;
  300. if (key == "adminPass") {
  301. if (!value.is<JsonArray&>()) continue;
  302. JsonArray& values = value.as<JsonArray&>();
  303. if (values.size() != 2) continue;
  304. if (values[0].as<String>().equals(values[1].as<String>())) {
  305. String password = values[0].as<String>();
  306. if (password.length() > 0) {
  307. setSetting(key, password);
  308. save = true;
  309. wsSend_P(client_id, PSTR("{\"action\": \"reload\"}"));
  310. }
  311. } else {
  312. wsSend_P(client_id, PSTR("{\"message\": 7}"));
  313. }
  314. continue;
  315. }
  316. #if NTP_SUPPORT
  317. else if (key == "ntpTZ") {
  318. _wsResetUpdateTimer();
  319. }
  320. #endif
  321. if (!_wsCheckKey(key, value)) {
  322. delSetting(key);
  323. continue;
  324. }
  325. // Store values
  326. if (value.is<JsonArray&>()) {
  327. if (_wsStore(key, value.as<JsonArray&>())) changed = true;
  328. } else {
  329. if (_wsStore(key, value.as<String>())) changed = true;
  330. }
  331. // Update flags if value has changed
  332. if (changed) {
  333. save = true;
  334. }
  335. }
  336. // Save settings
  337. if (save) {
  338. // Callbacks
  339. espurnaReload();
  340. // Persist settings
  341. saveSettings();
  342. wsSend_P(client_id, PSTR("{\"message\": 8}"));
  343. } else {
  344. wsSend_P(client_id, PSTR("{\"message\": 9}"));
  345. }
  346. }
  347. }
  348. bool _wsOnKeyCheck(const char * key, JsonVariant& value) {
  349. if (strncmp(key, "ws", 2) == 0) return true;
  350. if (strncmp(key, "admin", 5) == 0) return true;
  351. if (strncmp(key, "hostname", 8) == 0) return true;
  352. if (strncmp(key, "desc", 4) == 0) return true;
  353. if (strncmp(key, "webPort", 7) == 0) return true;
  354. return false;
  355. }
  356. void _wsOnConnected(JsonObject& root) {
  357. root["webMode"] = WEB_MODE_NORMAL;
  358. root["app_name"] = APP_NAME;
  359. root["app_version"] = getVersion().c_str();
  360. root["app_build"] = buildTime();
  361. root["device"] = getDevice().c_str();
  362. root["manufacturer"] = getManufacturer().c_str();
  363. root["chipid"] = getChipId().c_str();
  364. root["mac"] = WiFi.macAddress();
  365. root["bssid"] = WiFi.BSSIDstr();
  366. root["channel"] = WiFi.channel();
  367. root["hostname"] = getSetting("hostname");
  368. root["desc"] = getSetting("desc");
  369. root["network"] = getNetwork();
  370. root["deviceip"] = getIP();
  371. root["sketch_size"] = ESP.getSketchSize();
  372. root["free_size"] = ESP.getFreeSketchSpace();
  373. root["sdk"] = ESP.getSdkVersion();
  374. root["core"] = getCoreVersion();
  375. root["webPort"] = getSetting("webPort", WEB_PORT);
  376. root["wsAuth"] = getSetting("wsAuth", 1 == WS_AUTHENTICATION);
  377. }
  378. void _wsConnected(uint32_t client_id) {
  379. const bool changePassword = (USE_PASSWORD && WEB_FORCE_PASS_CHANGE)
  380. ? getAdminPass().equals(ADMIN_PASS)
  381. : false;
  382. if (changePassword) {
  383. StaticJsonBuffer<JSON_OBJECT_SIZE(1)> jsonBuffer;
  384. JsonObject& root = jsonBuffer.createObject();
  385. root["webMode"] = WEB_MODE_PASSWORD;
  386. wsSend(client_id, root);
  387. return;
  388. }
  389. wsPostAll(client_id, _ws_callbacks.on_visible);
  390. wsPostSequence(client_id, _ws_callbacks.on_connected);
  391. wsPostSequence(client_id, _ws_callbacks.on_data);
  392. }
  393. void _wsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){
  394. if (type == WS_EVT_CONNECT) {
  395. client->_tempObject = nullptr;
  396. #ifndef NOWSAUTH
  397. if (!_wsAuth(client)) {
  398. wsSend_P(client->id(), PSTR("{\"message\": 10}"));
  399. DEBUG_MSG_P(PSTR("[WEBSOCKET] Validation check failed\n"));
  400. client->close();
  401. return;
  402. }
  403. #endif
  404. IPAddress ip = client->remoteIP();
  405. 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());
  406. _wsConnected(client->id());
  407. _wsResetUpdateTimer();
  408. wifiReconnectCheck();
  409. client->_tempObject = new WebSocketIncommingBuffer(_wsParse, true);
  410. } else if(type == WS_EVT_DISCONNECT) {
  411. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u disconnected\n"), client->id());
  412. if (client->_tempObject) {
  413. delete (WebSocketIncommingBuffer *) client->_tempObject;
  414. }
  415. wifiReconnectCheck();
  416. } else if(type == WS_EVT_ERROR) {
  417. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u error(%u): %s\n"), client->id(), *((uint16_t*)arg), (char*)data);
  418. } else if(type == WS_EVT_PONG) {
  419. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u pong(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  420. } else if(type == WS_EVT_DATA) {
  421. //DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u data(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  422. if (!client->_tempObject) return;
  423. WebSocketIncommingBuffer *buffer = (WebSocketIncommingBuffer *)client->_tempObject;
  424. AwsFrameInfo * info = (AwsFrameInfo*)arg;
  425. buffer->data_event(client, info, data, len);
  426. }
  427. }
  428. // TODO: make this generic loop method to queue important ws messages?
  429. // or, if something uses ticker / async ctx to send messages,
  430. // it needs a retry mechanism built into the callback object
  431. void _wsHandlePostponedCallbacks(bool connected) {
  432. if (!connected && !_ws_queue.empty()) {
  433. _ws_queue.pop();
  434. return;
  435. }
  436. if (_ws_queue.empty()) return;
  437. auto& callbacks = _ws_queue.front();
  438. // avoid stalling forever when can't send anything
  439. constexpr decltype(ESP.getCycleCount()) WsQueueTimeoutClockCycles = microsecondsToClockCycles(10 * 1000 * 1000); // 10s
  440. if (ESP.getCycleCount() - callbacks.timestamp > WsQueueTimeoutClockCycles) {
  441. _ws_queue.pop();
  442. return;
  443. }
  444. // client_id == 0 means we need to send the message to every client
  445. if (callbacks.client_id) {
  446. AsyncWebSocketClient* ws_client = _ws.client(callbacks.client_id);
  447. // ...but, we need to check if client is still connected
  448. if (!ws_client) {
  449. _ws_queue.pop();
  450. return;
  451. }
  452. // wait until we can send the next batch of messages
  453. // XXX: enforce that callbacks send only one message per iteration
  454. if (ws_client->queueIsFull()) {
  455. return;
  456. }
  457. }
  458. // XXX: block allocation will try to create *2 next time,
  459. // likely failing and causing wsSend to reference empty objects
  460. // XXX: arduinojson6 will not do this, but we may need to use per-callback buffers
  461. constexpr size_t WsQueueJsonBufferSize = 3192;
  462. DynamicJsonBuffer jsonBuffer(WsQueueJsonBufferSize);
  463. JsonObject& root = jsonBuffer.createObject();
  464. callbacks.send(root);
  465. if (callbacks.client_id) {
  466. wsSend(callbacks.client_id, root);
  467. } else {
  468. wsSend(root);
  469. }
  470. yield();
  471. if (callbacks.done()) {
  472. _ws_queue.pop();
  473. }
  474. }
  475. void _wsLoop() {
  476. const bool connected = wsConnected();
  477. _wsDoUpdate(connected);
  478. _wsHandlePostponedCallbacks(connected);
  479. #if DEBUG_WEB_SUPPORT
  480. _ws_debug.send(connected);
  481. #endif
  482. }
  483. // -----------------------------------------------------------------------------
  484. // Public API
  485. // -----------------------------------------------------------------------------
  486. bool wsConnected() {
  487. return (_ws.count() > 0);
  488. }
  489. bool wsConnected(uint32_t client_id) {
  490. return _ws.hasClient(client_id);
  491. }
  492. ws_callbacks_t& wsRegister() {
  493. return _ws_callbacks;
  494. }
  495. void wsSend(JsonObject& root) {
  496. // Note: 'measurement' tries to serialize json contents byte-by-byte,
  497. // which is somewhat costly, but likely unavoidable for us.
  498. size_t len = root.measureLength();
  499. AsyncWebSocketMessageBuffer* buffer = _ws.makeBuffer(len);
  500. if (buffer) {
  501. root.printTo(reinterpret_cast<char*>(buffer->get()), len + 1);
  502. _ws.textAll(buffer);
  503. }
  504. }
  505. void wsSend(uint32_t client_id, JsonObject& root) {
  506. AsyncWebSocketClient* client = _ws.client(client_id);
  507. if (client == nullptr) return;
  508. size_t len = root.measureLength();
  509. AsyncWebSocketMessageBuffer* buffer = _ws.makeBuffer(len);
  510. if (buffer) {
  511. root.printTo(reinterpret_cast<char*>(buffer->get()), len + 1);
  512. client->text(buffer);
  513. }
  514. }
  515. void wsSend(ws_on_send_callback_f callback) {
  516. if (_ws.count() > 0) {
  517. DynamicJsonBuffer jsonBuffer(512);
  518. JsonObject& root = jsonBuffer.createObject();
  519. callback(root);
  520. wsSend(root);
  521. }
  522. }
  523. void wsSend(const char * payload) {
  524. if (_ws.count() > 0) {
  525. _ws.textAll(payload);
  526. }
  527. }
  528. void wsSend_P(PGM_P payload) {
  529. if (_ws.count() > 0) {
  530. char buffer[strlen_P(payload)];
  531. strcpy_P(buffer, payload);
  532. _ws.textAll(buffer);
  533. }
  534. }
  535. void wsSend(uint32_t client_id, ws_on_send_callback_f callback) {
  536. AsyncWebSocketClient* client = _ws.client(client_id);
  537. if (client == nullptr) return;
  538. DynamicJsonBuffer jsonBuffer(512);
  539. JsonObject& root = jsonBuffer.createObject();
  540. callback(root);
  541. wsSend(client_id, root);
  542. }
  543. void wsSend(uint32_t client_id, const char * payload) {
  544. _ws.text(client_id, payload);
  545. }
  546. void wsSend_P(uint32_t client_id, PGM_P payload) {
  547. char buffer[strlen_P(payload)];
  548. strcpy_P(buffer, payload);
  549. _ws.text(client_id, buffer);
  550. }
  551. void wsSetup() {
  552. _ws.onEvent(_wsEvent);
  553. webServer().addHandler(&_ws);
  554. // CORS
  555. const String webDomain = getSetting("webDomain", WEB_REMOTE_DOMAIN);
  556. DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin", webDomain);
  557. if (!webDomain.equals("*")) {
  558. DefaultHeaders::Instance().addHeader("Access-Control-Allow-Credentials", "true");
  559. }
  560. webServer().on("/auth", HTTP_GET, _onAuth);
  561. wsRegister()
  562. .onConnected(_wsOnConnected)
  563. .onKeyCheck(_wsOnKeyCheck);
  564. espurnaRegisterLoop(_wsLoop);
  565. }
  566. #endif // WEB_SUPPORT