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.

735 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...)
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 "ntp.h"
  10. #include "utils.h"
  11. #include "web.h"
  12. #include "wifi.h"
  13. #include "ws_internal.h"
  14. #include "libs/WebSocketIncommingBuffer.h"
  15. AsyncWebSocket _ws("/ws");
  16. // -----------------------------------------------------------------------------
  17. // Periodic updates
  18. // -----------------------------------------------------------------------------
  19. uint32_t _ws_last_update = 0;
  20. void _wsResetUpdateTimer() {
  21. _ws_last_update = millis() + WS_UPDATE_INTERVAL;
  22. }
  23. void _wsUpdate(JsonObject& root) {
  24. root["heap"] = systemFreeHeap();
  25. root["uptime"] = systemUptime();
  26. root["rssi"] = WiFi.RSSI();
  27. root["loadaverage"] = systemLoadAverage();
  28. if (ADC_MODE_VALUE == ADC_VCC) {
  29. root["vcc"] = ESP.getVcc();
  30. } else {
  31. root["vcc"] = "N/A (TOUT) ";
  32. }
  33. #if NTP_SUPPORT
  34. // XXX: arduinojson default config stores:
  35. // - double as float
  36. // - int64_t as int32_t
  37. // Simply send the string...
  38. if (ntpSynced()) {
  39. auto info = ntpInfo();
  40. constexpr size_t TimeSize { sizeof(time_t) };
  41. const char* const fmt = (TimeSize == 8) ? "%lld" : "%ld";
  42. char buffer[TimeSize * 4];
  43. sprintf(buffer, fmt, info.now);
  44. root["now"] = String(buffer);
  45. root["nowString"] = info.utc;
  46. root["nowLocalString"] = info.local.length()
  47. ? info.local
  48. : info.utc;
  49. }
  50. #endif
  51. }
  52. void _wsDoUpdate(const bool connected) {
  53. if (!connected) return;
  54. if (millis() - _ws_last_update > WS_UPDATE_INTERVAL) {
  55. _ws_last_update = millis();
  56. wsSend(_wsUpdate);
  57. }
  58. }
  59. // -----------------------------------------------------------------------------
  60. // WS callbacks
  61. // -----------------------------------------------------------------------------
  62. std::queue<WsPostponedCallbacks> _ws_queue;
  63. ws_callbacks_t _ws_callbacks;
  64. void wsPost(uint32_t client_id, ws_on_send_callback_f&& cb) {
  65. _ws_queue.emplace(client_id, std::move(cb));
  66. }
  67. void wsPost(ws_on_send_callback_f&& cb) {
  68. wsPost(0, std::move(cb));
  69. }
  70. void wsPost(uint32_t client_id, const ws_on_send_callback_f& cb) {
  71. _ws_queue.emplace(client_id, cb);
  72. }
  73. void wsPost(const ws_on_send_callback_f& cb) {
  74. wsPost(0, cb);
  75. }
  76. template <typename T>
  77. void _wsPostCallbacks(uint32_t client_id, T&& cbs, WsPostponedCallbacks::Mode mode) {
  78. _ws_queue.emplace(client_id, std::forward<T>(cbs), mode);
  79. }
  80. void wsPostAll(uint32_t client_id, ws_on_send_callback_list_t&& cbs) {
  81. _wsPostCallbacks(client_id, std::move(cbs), WsPostponedCallbacks::Mode::All);
  82. }
  83. void wsPostAll(ws_on_send_callback_list_t&& cbs) {
  84. wsPostAll(0, std::move(cbs));
  85. }
  86. void wsPostAll(uint32_t client_id, const ws_on_send_callback_list_t& cbs) {
  87. _wsPostCallbacks(client_id, cbs, WsPostponedCallbacks::Mode::All);
  88. }
  89. void wsPostAll(const ws_on_send_callback_list_t& cbs) {
  90. wsPostAll(0, cbs);
  91. }
  92. void wsPostSequence(uint32_t client_id, ws_on_send_callback_list_t&& cbs) {
  93. _wsPostCallbacks(client_id, std::move(cbs), WsPostponedCallbacks::Mode::Sequence);
  94. }
  95. void wsPostSequence(ws_on_send_callback_list_t&& cbs) {
  96. wsPostSequence(0, std::move(cbs));
  97. }
  98. void wsPostSequence(uint32_t client_id, const ws_on_send_callback_list_t& cbs) {
  99. _wsPostCallbacks(client_id, cbs, WsPostponedCallbacks::Mode::Sequence);
  100. }
  101. void wsPostSequence(const ws_on_send_callback_list_t& cbs) {
  102. wsPostSequence(0, cbs);
  103. }
  104. // -----------------------------------------------------------------------------
  105. ws_callbacks_t& ws_callbacks_t::onVisible(ws_on_send_callback_f cb) {
  106. on_visible.push_back(cb);
  107. return *this;
  108. }
  109. ws_callbacks_t& ws_callbacks_t::onConnected(ws_on_send_callback_f cb) {
  110. on_connected.push_back(cb);
  111. return *this;
  112. }
  113. ws_callbacks_t& ws_callbacks_t::onData(ws_on_send_callback_f cb) {
  114. on_data.push_back(cb);
  115. return *this;
  116. }
  117. ws_callbacks_t& ws_callbacks_t::onAction(ws_on_action_callback_f cb) {
  118. on_action.push_back(cb);
  119. return *this;
  120. }
  121. ws_callbacks_t& ws_callbacks_t::onKeyCheck(ws_on_keycheck_callback_f cb) {
  122. on_keycheck.push_back(cb);
  123. return *this;
  124. }
  125. // -----------------------------------------------------------------------------
  126. // WS authentication
  127. // -----------------------------------------------------------------------------
  128. WsTicket _ws_tickets[WS_BUFFER_SIZE];
  129. void _onAuth(AsyncWebServerRequest *request) {
  130. webLog(request);
  131. if (!webAuthenticate(request)) return request->requestAuthentication();
  132. IPAddress ip = request->client()->remoteIP();
  133. unsigned long now = millis();
  134. unsigned short index;
  135. for (index = 0; index < WS_BUFFER_SIZE; index++) {
  136. if (_ws_tickets[index].ip == ip) break;
  137. if (_ws_tickets[index].timestamp == 0) break;
  138. if (now - _ws_tickets[index].timestamp > WS_TIMEOUT) break;
  139. }
  140. if (index == WS_BUFFER_SIZE) {
  141. request->send(429);
  142. } else {
  143. _ws_tickets[index].ip = ip;
  144. _ws_tickets[index].timestamp = now;
  145. request->send(200, "text/plain", "OK");
  146. }
  147. }
  148. bool _wsAuth(AsyncWebSocketClient * client) {
  149. IPAddress ip = client->remoteIP();
  150. unsigned long now = millis();
  151. unsigned short index = 0;
  152. for (index = 0; index < WS_BUFFER_SIZE; index++) {
  153. if ((_ws_tickets[index].ip == ip) && (now - _ws_tickets[index].timestamp < WS_TIMEOUT)) break;
  154. }
  155. if (index == WS_BUFFER_SIZE) {
  156. return false;
  157. }
  158. return true;
  159. }
  160. // -----------------------------------------------------------------------------
  161. // Debug
  162. // -----------------------------------------------------------------------------
  163. #if DEBUG_WEB_SUPPORT
  164. constexpr size_t WsDebugMessagesMax = 8;
  165. WsDebug _ws_debug(WsDebugMessagesMax);
  166. void WsDebug::send(bool connected) {
  167. if (!connected && _flush) {
  168. clear();
  169. return;
  170. }
  171. if (!_flush) return;
  172. // ref: http://arduinojson.org/v5/assistant/
  173. // {"weblog": {"msg":[...],"pre":[...]}}
  174. DynamicJsonBuffer jsonBuffer(2*JSON_ARRAY_SIZE(_messages.size()) + JSON_OBJECT_SIZE(1) + JSON_OBJECT_SIZE(2));
  175. JsonObject& root = jsonBuffer.createObject();
  176. JsonObject& weblog = root.createNestedObject("weblog");
  177. JsonArray& msg_array = weblog.createNestedArray("msg");
  178. JsonArray& pre_array = weblog.createNestedArray("pre");
  179. for (auto& msg : _messages) {
  180. pre_array.add(msg.first.c_str());
  181. msg_array.add(msg.second.c_str());
  182. }
  183. wsSend(root);
  184. clear();
  185. }
  186. bool wsDebugSend(const char* prefix, const char* message) {
  187. if (wifiConnected() && wsConnected()) {
  188. _ws_debug.add(prefix, message);
  189. return true;
  190. }
  191. return false;
  192. }
  193. #endif
  194. // Check the existing setting before saving it
  195. // TODO: this should know of the default values, somehow?
  196. // TODO: move webPort handling somewhere else?
  197. bool _wsStore(const String& key, const String& value) {
  198. if (key == "webPort") {
  199. if ((value.toInt() == 0) || (value.toInt() == 80)) {
  200. return delSetting(key);
  201. }
  202. }
  203. if (!hasSetting(key) || value != getSetting(key)) {
  204. return setSetting(key, value);
  205. }
  206. return false;
  207. }
  208. // -----------------------------------------------------------------------------
  209. // Store indexed key (key0, key1, etc.) from array
  210. // -----------------------------------------------------------------------------
  211. bool _wsStore(const String& key, JsonArray& values) {
  212. bool changed = false;
  213. unsigned char index = 0;
  214. for (auto& element : values) {
  215. const auto value = element.as<String>();
  216. auto setting = SettingsKey {key, index};
  217. if (!hasSetting(setting) || value != getSetting(setting)) {
  218. setSetting(setting, value);
  219. changed = true;
  220. }
  221. ++index;
  222. }
  223. // Delete further values
  224. for (unsigned char next_index=index; next_index < SETTINGS_MAX_LIST_COUNT; ++next_index) {
  225. if (!delSetting({key, next_index})) break;
  226. changed = true;
  227. }
  228. return changed;
  229. }
  230. bool _wsCheckKey(const String& key, JsonVariant& value) {
  231. for (auto& callback : _ws_callbacks.on_keycheck) {
  232. if (callback(key.c_str(), value)) return true;
  233. // TODO: remove this to call all OnKeyCheckCallbacks with the
  234. // current key/value
  235. }
  236. return false;
  237. }
  238. void _wsParse(AsyncWebSocketClient *client, uint8_t * payload, size_t length) {
  239. //DEBUG_MSG_P(PSTR("[WEBSOCKET] Parsing: %s\n"), length ? (char*) payload : "");
  240. // Get client ID
  241. uint32_t client_id = client->id();
  242. // Check early for empty object / nothing
  243. if ((length == 0) || (length == 1)) {
  244. return;
  245. }
  246. if ((length == 3) && (strcmp((char*) payload, "{}") == 0)) {
  247. return;
  248. }
  249. // Parse JSON input
  250. // TODO: json buffer should be pretty efficient with the non-const payload,
  251. // most of the space is taken by the object key references
  252. DynamicJsonBuffer jsonBuffer(512);
  253. JsonObject& root = jsonBuffer.parseObject((char *) payload);
  254. if (!root.success()) {
  255. DEBUG_MSG_P(PSTR("[WEBSOCKET] JSON parsing error\n"));
  256. wsSend_P(client_id, PSTR("{\"message\": \"Cannot parse the data!\"}"));
  257. return;
  258. }
  259. // Check actions -----------------------------------------------------------
  260. const char* action = root["action"];
  261. if (action) {
  262. if (strcmp(action, "ping") == 0) {
  263. wsSend_P(client_id, PSTR("{\"pong\": 1}"));
  264. return;
  265. }
  266. if (strcmp(action, "reboot") == 0) {
  267. deferredReset(100, CustomResetReason::Web);
  268. return;
  269. }
  270. if (strcmp(action, "reconnect") == 0) {
  271. static Ticker timer;
  272. timer.once_ms_scheduled(100, []() {
  273. wifiDisconnect();
  274. yield();
  275. });
  276. return;
  277. }
  278. if (strcmp(action, "factory_reset") == 0) {
  279. factoryReset();
  280. return;
  281. }
  282. JsonObject& data = root["data"];
  283. if (data.success()) {
  284. if (strcmp(action, "restore") == 0) {
  285. if (settingsRestoreJson(data)) {
  286. wsSend_P(client_id, PSTR("{\"message\": \"Changes saved, you should be able to reboot now.\"}"));
  287. } else {
  288. wsSend_P(client_id, PSTR("{\"message\": \"Could not restore the configuration, see the debug log for more information.\"}"));
  289. }
  290. return;
  291. }
  292. for (auto& callback : _ws_callbacks.on_action) {
  293. callback(client_id, action, data);
  294. }
  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\": \"Passwords do not match!\"}"));
  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("{\"saved\": true, \"message\": \"Changes saved.\"}"));
  350. } else {
  351. wsSend_P(client_id, PSTR("{\"message\": \"No changes detected.\"}"));
  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"] = wifiStaSsid();
  377. root["deviceip"] = wifiStaIp().toString();
  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. IPAddress ip = client->remoteIP();
  404. #ifndef NOWSAUTH
  405. if (!_wsAuth(client)) {
  406. wsSend_P(client->id(), PSTR("{\"action\": \"reload\", \"message\": \"Session expired.\"}"));
  407. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u session expired, ip: %d.%d.%d.%d\n"), client->id(), ip[0], ip[1], ip[2], ip[3]);
  408. client->close();
  409. return;
  410. }
  411. #endif
  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. client->_tempObject = new WebSocketIncommingBuffer(_wsParse, true);
  416. } else if(type == WS_EVT_DISCONNECT) {
  417. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u disconnected\n"), client->id());
  418. if (client->_tempObject) {
  419. delete (WebSocketIncommingBuffer *) client->_tempObject;
  420. }
  421. wifiApCheck();
  422. } else if(type == WS_EVT_ERROR) {
  423. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u error(%u): %s\n"), client->id(), *((uint16_t*)arg), (char*)data);
  424. } else if(type == WS_EVT_PONG) {
  425. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u pong(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  426. } else if(type == WS_EVT_DATA) {
  427. //DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u data(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  428. if (!client->_tempObject) return;
  429. WebSocketIncommingBuffer *buffer = (WebSocketIncommingBuffer *)client->_tempObject;
  430. AwsFrameInfo * info = (AwsFrameInfo*)arg;
  431. buffer->data_event(client, info, data, len);
  432. }
  433. }
  434. // TODO: make this generic loop method to queue important ws messages?
  435. // or, if something uses ticker / async ctx to send messages,
  436. // it needs a retry mechanism built into the callback object
  437. void _wsHandlePostponedCallbacks(bool connected) {
  438. if (!connected && !_ws_queue.empty()) {
  439. _ws_queue.pop();
  440. return;
  441. }
  442. if (_ws_queue.empty()) return;
  443. auto& callbacks = _ws_queue.front();
  444. // avoid stalling forever when can't send anything
  445. constexpr decltype(ESP.getCycleCount()) WsQueueTimeoutClockCycles = microsecondsToClockCycles(10 * 1000 * 1000); // 10s
  446. if (ESP.getCycleCount() - callbacks.timestamp > WsQueueTimeoutClockCycles) {
  447. _ws_queue.pop();
  448. return;
  449. }
  450. // client_id == 0 means we need to send the message to every client
  451. if (callbacks.client_id) {
  452. AsyncWebSocketClient* ws_client = _ws.client(callbacks.client_id);
  453. // ...but, we need to check if client is still connected
  454. if (!ws_client) {
  455. _ws_queue.pop();
  456. return;
  457. }
  458. // wait until we can send the next batch of messages
  459. // XXX: enforce that callbacks send only one message per iteration
  460. if (ws_client->queueIsFull()) {
  461. return;
  462. }
  463. }
  464. // XXX: block allocation will try to create *2 next time,
  465. // likely failing and causing wsSend to reference empty objects
  466. // XXX: arduinojson6 will not do this, but we may need to use per-callback buffers
  467. constexpr size_t WsQueueJsonBufferSize = 3192;
  468. DynamicJsonBuffer jsonBuffer(WsQueueJsonBufferSize);
  469. JsonObject& root = jsonBuffer.createObject();
  470. callbacks.send(root);
  471. if (callbacks.client_id) {
  472. wsSend(callbacks.client_id, root);
  473. } else {
  474. wsSend(root);
  475. }
  476. yield();
  477. if (callbacks.done()) {
  478. _ws_queue.pop();
  479. }
  480. }
  481. void _wsLoop() {
  482. const bool connected = wsConnected();
  483. _wsDoUpdate(connected);
  484. _wsHandlePostponedCallbacks(connected);
  485. #if DEBUG_WEB_SUPPORT
  486. _ws_debug.send(connected);
  487. #endif
  488. }
  489. // -----------------------------------------------------------------------------
  490. // Public API
  491. // -----------------------------------------------------------------------------
  492. bool wsConnected() {
  493. return (_ws.count() > 0);
  494. }
  495. bool wsConnected(uint32_t client_id) {
  496. return _ws.hasClient(client_id);
  497. }
  498. ws_callbacks_t& wsRegister() {
  499. return _ws_callbacks;
  500. }
  501. void wsSend(JsonObject& root) {
  502. // Note: 'measurement' tries to serialize json contents byte-by-byte,
  503. // which is somewhat costly, but likely unavoidable for us.
  504. size_t len = root.measureLength();
  505. AsyncWebSocketMessageBuffer* buffer = _ws.makeBuffer(len);
  506. if (buffer) {
  507. root.printTo(reinterpret_cast<char*>(buffer->get()), len + 1);
  508. _ws.textAll(buffer);
  509. }
  510. }
  511. void wsSend(uint32_t client_id, JsonObject& root) {
  512. AsyncWebSocketClient* client = _ws.client(client_id);
  513. if (client == nullptr) return;
  514. size_t len = root.measureLength();
  515. AsyncWebSocketMessageBuffer* buffer = _ws.makeBuffer(len);
  516. if (buffer) {
  517. root.printTo(reinterpret_cast<char*>(buffer->get()), len + 1);
  518. client->text(buffer);
  519. }
  520. }
  521. void wsSend(ws_on_send_callback_f callback) {
  522. if (_ws.count() > 0) {
  523. DynamicJsonBuffer jsonBuffer(512);
  524. JsonObject& root = jsonBuffer.createObject();
  525. callback(root);
  526. wsSend(root);
  527. }
  528. }
  529. void wsSend(const char * payload) {
  530. if (_ws.count() > 0) {
  531. _ws.textAll(payload);
  532. }
  533. }
  534. void wsSend_P(const char* payload) {
  535. if (_ws.count() > 0) {
  536. char buffer[strlen_P(payload)];
  537. strcpy_P(buffer, payload);
  538. _ws.textAll(buffer);
  539. }
  540. }
  541. void wsSend(uint32_t client_id, ws_on_send_callback_f callback) {
  542. AsyncWebSocketClient* client = _ws.client(client_id);
  543. if (client == nullptr) return;
  544. DynamicJsonBuffer jsonBuffer(512);
  545. JsonObject& root = jsonBuffer.createObject();
  546. callback(root);
  547. wsSend(client_id, root);
  548. }
  549. void wsSend(uint32_t client_id, const char * payload) {
  550. _ws.text(client_id, payload);
  551. }
  552. void wsSend_P(uint32_t client_id, const char* payload) {
  553. char buffer[strlen_P(payload)];
  554. strcpy_P(buffer, payload);
  555. _ws.text(client_id, buffer);
  556. }
  557. void wsSetup() {
  558. _ws.onEvent(_wsEvent);
  559. webServer().addHandler(&_ws);
  560. // CORS
  561. const String webDomain = getSetting("webDomain", WEB_REMOTE_DOMAIN);
  562. DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin", webDomain);
  563. if (!webDomain.equals("*")) {
  564. DefaultHeaders::Instance().addHeader("Access-Control-Allow-Credentials", "true");
  565. }
  566. webServer().on("/auth", HTTP_GET, _onAuth);
  567. wsRegister()
  568. .onConnected(_wsOnConnected)
  569. .onKeyCheck(_wsOnKeyCheck);
  570. espurnaRegisterLoop(_wsLoop);
  571. }
  572. #endif // WEB_SUPPORT