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.

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