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.

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