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
21 KiB

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...)
3 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...)
3 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\": \"Cannot parse the data!\"}"));
  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. if (strcmp(action, "reboot") == 0) {
  264. deferredReset(100, CustomResetReason::Web);
  265. return;
  266. }
  267. if (strcmp(action, "reconnect") == 0) {
  268. static Ticker timer;
  269. timer.once_ms_scheduled(100, []() {
  270. wifiDisconnect();
  271. yield();
  272. });
  273. return;
  274. }
  275. if (strcmp(action, "factory_reset") == 0) {
  276. factoryReset();
  277. return;
  278. }
  279. JsonObject& data = root["data"];
  280. if (data.success()) {
  281. if (strcmp(action, "restore") == 0) {
  282. if (settingsRestoreJson(data)) {
  283. wsSend_P(client_id, PSTR("{\"message\": \"Changes saved, you should be able to reboot now.\"}"));
  284. } else {
  285. wsSend_P(client_id, PSTR("{\"message\": \"Could not restore the configuration, see the debug log for more information.\"}"));
  286. }
  287. return;
  288. }
  289. for (auto& callback : _ws_callbacks.on_action) {
  290. callback(client_id, action, data);
  291. }
  292. }
  293. };
  294. // Check configuration -----------------------------------------------------
  295. JsonObject& config = root["config"];
  296. if (config.success()) {
  297. DEBUG_MSG_P(PSTR("[WEBSOCKET] Parsing configuration data\n"));
  298. String adminPass;
  299. bool save = false;
  300. for (auto kv: config) {
  301. bool changed = false;
  302. String key = kv.key;
  303. JsonVariant& value = kv.value;
  304. if (key == "adminPass") {
  305. if (!value.is<JsonArray&>()) continue;
  306. JsonArray& values = value.as<JsonArray&>();
  307. if (values.size() != 2) continue;
  308. if (values[0].as<String>().equals(values[1].as<String>())) {
  309. String password = values[0].as<String>();
  310. if (password.length() > 0) {
  311. setSetting(key, password);
  312. save = true;
  313. wsSend_P(client_id, PSTR("{\"action\": \"reload\"}"));
  314. }
  315. } else {
  316. wsSend_P(client_id, PSTR("{\"message\": \"Passwords do not match!\"}"));
  317. }
  318. continue;
  319. }
  320. #if NTP_SUPPORT
  321. else if (key == "ntpTZ") {
  322. _wsResetUpdateTimer();
  323. }
  324. #endif
  325. if (!_wsCheckKey(key, value)) {
  326. delSetting(key);
  327. continue;
  328. }
  329. // Store values
  330. if (value.is<JsonArray&>()) {
  331. if (_wsStore(key, value.as<JsonArray&>())) changed = true;
  332. } else {
  333. if (_wsStore(key, value.as<String>())) changed = true;
  334. }
  335. // Update flags if value has changed
  336. if (changed) {
  337. save = true;
  338. }
  339. }
  340. // Save settings
  341. if (save) {
  342. // Callbacks
  343. espurnaReload();
  344. // Persist settings
  345. saveSettings();
  346. wsSend_P(client_id, PSTR("{\"saved\": true, \"message\": \"Changes saved.\"}"));
  347. } else {
  348. wsSend_P(client_id, PSTR("{\"message\": \"No changes detected.\"}"));
  349. }
  350. }
  351. }
  352. bool _wsOnKeyCheck(const char * key, JsonVariant& value) {
  353. if (strncmp(key, "ws", 2) == 0) return true;
  354. if (strncmp(key, "admin", 5) == 0) return true;
  355. if (strncmp(key, "hostname", 8) == 0) return true;
  356. if (strncmp(key, "desc", 4) == 0) return true;
  357. if (strncmp(key, "webPort", 7) == 0) return true;
  358. return false;
  359. }
  360. void _wsOnConnected(JsonObject& root) {
  361. root["webMode"] = WEB_MODE_NORMAL;
  362. root["app_name"] = APP_NAME;
  363. root["app_version"] = getVersion().c_str();
  364. root["app_build"] = buildTime();
  365. root["device"] = getDevice().c_str();
  366. root["manufacturer"] = getManufacturer().c_str();
  367. root["chipid"] = getChipId().c_str();
  368. root["mac"] = WiFi.macAddress();
  369. root["bssid"] = WiFi.BSSIDstr();
  370. root["channel"] = WiFi.channel();
  371. root["hostname"] = getSetting("hostname");
  372. root["desc"] = getSetting("desc");
  373. root["network"] = getNetwork();
  374. root["deviceip"] = getIP();
  375. root["sketch_size"] = ESP.getSketchSize();
  376. root["free_size"] = ESP.getFreeSketchSpace();
  377. root["sdk"] = ESP.getSdkVersion();
  378. root["core"] = getCoreVersion();
  379. root["webPort"] = getSetting("webPort", WEB_PORT);
  380. root["wsAuth"] = getSetting("wsAuth", 1 == WS_AUTHENTICATION);
  381. }
  382. void _wsConnected(uint32_t client_id) {
  383. const bool changePassword = (USE_PASSWORD && WEB_FORCE_PASS_CHANGE)
  384. ? getAdminPass().equals(ADMIN_PASS)
  385. : false;
  386. if (changePassword) {
  387. StaticJsonBuffer<JSON_OBJECT_SIZE(1)> jsonBuffer;
  388. JsonObject& root = jsonBuffer.createObject();
  389. root["webMode"] = WEB_MODE_PASSWORD;
  390. wsSend(client_id, root);
  391. return;
  392. }
  393. wsPostAll(client_id, _ws_callbacks.on_visible);
  394. wsPostSequence(client_id, _ws_callbacks.on_connected);
  395. wsPostSequence(client_id, _ws_callbacks.on_data);
  396. }
  397. void _wsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){
  398. if (type == WS_EVT_CONNECT) {
  399. client->_tempObject = nullptr;
  400. IPAddress ip = client->remoteIP();
  401. #ifndef NOWSAUTH
  402. if (!_wsAuth(client)) {
  403. wsSend_P(client->id(), PSTR("{\"action\": \"reload\", \"message\": \"Session expired.\"}"));
  404. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u session expired, ip: %d.%d.%d.%d\n"), client->id(), ip[0], ip[1], ip[2], ip[3]);
  405. client->close();
  406. return;
  407. }
  408. #endif
  409. 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());
  410. _wsConnected(client->id());
  411. _wsResetUpdateTimer();
  412. wifiReconnectCheck();
  413. client->_tempObject = new WebSocketIncommingBuffer(_wsParse, true);
  414. } else if(type == WS_EVT_DISCONNECT) {
  415. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u disconnected\n"), client->id());
  416. if (client->_tempObject) {
  417. delete (WebSocketIncommingBuffer *) client->_tempObject;
  418. }
  419. wifiReconnectCheck();
  420. } else if(type == WS_EVT_ERROR) {
  421. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u error(%u): %s\n"), client->id(), *((uint16_t*)arg), (char*)data);
  422. } else if(type == WS_EVT_PONG) {
  423. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u pong(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  424. } else if(type == WS_EVT_DATA) {
  425. //DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u data(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  426. if (!client->_tempObject) return;
  427. WebSocketIncommingBuffer *buffer = (WebSocketIncommingBuffer *)client->_tempObject;
  428. AwsFrameInfo * info = (AwsFrameInfo*)arg;
  429. buffer->data_event(client, info, data, len);
  430. }
  431. }
  432. // TODO: make this generic loop method to queue important ws messages?
  433. // or, if something uses ticker / async ctx to send messages,
  434. // it needs a retry mechanism built into the callback object
  435. void _wsHandlePostponedCallbacks(bool connected) {
  436. if (!connected && !_ws_queue.empty()) {
  437. _ws_queue.pop();
  438. return;
  439. }
  440. if (_ws_queue.empty()) return;
  441. auto& callbacks = _ws_queue.front();
  442. // avoid stalling forever when can't send anything
  443. constexpr decltype(ESP.getCycleCount()) WsQueueTimeoutClockCycles = microsecondsToClockCycles(10 * 1000 * 1000); // 10s
  444. if (ESP.getCycleCount() - callbacks.timestamp > WsQueueTimeoutClockCycles) {
  445. _ws_queue.pop();
  446. return;
  447. }
  448. // client_id == 0 means we need to send the message to every client
  449. if (callbacks.client_id) {
  450. AsyncWebSocketClient* ws_client = _ws.client(callbacks.client_id);
  451. // ...but, we need to check if client is still connected
  452. if (!ws_client) {
  453. _ws_queue.pop();
  454. return;
  455. }
  456. // wait until we can send the next batch of messages
  457. // XXX: enforce that callbacks send only one message per iteration
  458. if (ws_client->queueIsFull()) {
  459. return;
  460. }
  461. }
  462. // XXX: block allocation will try to create *2 next time,
  463. // likely failing and causing wsSend to reference empty objects
  464. // XXX: arduinojson6 will not do this, but we may need to use per-callback buffers
  465. constexpr size_t WsQueueJsonBufferSize = 3192;
  466. DynamicJsonBuffer jsonBuffer(WsQueueJsonBufferSize);
  467. JsonObject& root = jsonBuffer.createObject();
  468. callbacks.send(root);
  469. if (callbacks.client_id) {
  470. wsSend(callbacks.client_id, root);
  471. } else {
  472. wsSend(root);
  473. }
  474. yield();
  475. if (callbacks.done()) {
  476. _ws_queue.pop();
  477. }
  478. }
  479. void _wsLoop() {
  480. const bool connected = wsConnected();
  481. _wsDoUpdate(connected);
  482. _wsHandlePostponedCallbacks(connected);
  483. #if DEBUG_WEB_SUPPORT
  484. _ws_debug.send(connected);
  485. #endif
  486. }
  487. // -----------------------------------------------------------------------------
  488. // Public API
  489. // -----------------------------------------------------------------------------
  490. bool wsConnected() {
  491. return (_ws.count() > 0);
  492. }
  493. bool wsConnected(uint32_t client_id) {
  494. return _ws.hasClient(client_id);
  495. }
  496. ws_callbacks_t& wsRegister() {
  497. return _ws_callbacks;
  498. }
  499. void wsSend(JsonObject& root) {
  500. // Note: 'measurement' tries to serialize json contents byte-by-byte,
  501. // which is somewhat costly, but likely unavoidable for us.
  502. size_t len = root.measureLength();
  503. AsyncWebSocketMessageBuffer* buffer = _ws.makeBuffer(len);
  504. if (buffer) {
  505. root.printTo(reinterpret_cast<char*>(buffer->get()), len + 1);
  506. _ws.textAll(buffer);
  507. }
  508. }
  509. void wsSend(uint32_t client_id, JsonObject& root) {
  510. AsyncWebSocketClient* client = _ws.client(client_id);
  511. if (client == nullptr) return;
  512. size_t len = root.measureLength();
  513. AsyncWebSocketMessageBuffer* buffer = _ws.makeBuffer(len);
  514. if (buffer) {
  515. root.printTo(reinterpret_cast<char*>(buffer->get()), len + 1);
  516. client->text(buffer);
  517. }
  518. }
  519. void wsSend(ws_on_send_callback_f callback) {
  520. if (_ws.count() > 0) {
  521. DynamicJsonBuffer jsonBuffer(512);
  522. JsonObject& root = jsonBuffer.createObject();
  523. callback(root);
  524. wsSend(root);
  525. }
  526. }
  527. void wsSend(const char * payload) {
  528. if (_ws.count() > 0) {
  529. _ws.textAll(payload);
  530. }
  531. }
  532. void wsSend_P(const char* payload) {
  533. if (_ws.count() > 0) {
  534. char buffer[strlen_P(payload)];
  535. strcpy_P(buffer, payload);
  536. _ws.textAll(buffer);
  537. }
  538. }
  539. void wsSend(uint32_t client_id, ws_on_send_callback_f callback) {
  540. AsyncWebSocketClient* client = _ws.client(client_id);
  541. if (client == nullptr) return;
  542. DynamicJsonBuffer jsonBuffer(512);
  543. JsonObject& root = jsonBuffer.createObject();
  544. callback(root);
  545. wsSend(client_id, root);
  546. }
  547. void wsSend(uint32_t client_id, const char * payload) {
  548. _ws.text(client_id, payload);
  549. }
  550. void wsSend_P(uint32_t client_id, const char* payload) {
  551. char buffer[strlen_P(payload)];
  552. strcpy_P(buffer, payload);
  553. _ws.text(client_id, buffer);
  554. }
  555. void wsSetup() {
  556. _ws.onEvent(_wsEvent);
  557. webServer().addHandler(&_ws);
  558. // CORS
  559. const String webDomain = getSetting("webDomain", WEB_REMOTE_DOMAIN);
  560. DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin", webDomain);
  561. if (!webDomain.equals("*")) {
  562. DefaultHeaders::Instance().addHeader("Access-Control-Allow-Credentials", "true");
  563. }
  564. webServer().on("/auth", HTTP_GET, _onAuth);
  565. wsRegister()
  566. .onConnected(_wsOnConnected)
  567. .onKeyCheck(_wsOnKeyCheck);
  568. espurnaRegisterLoop(_wsLoop);
  569. }
  570. #endif // WEB_SUPPORT