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.

736 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. Ticker _ws_defer;
  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"] = getFreeHeap();
  25. root["uptime"] = getUptime();
  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 will ignore info.now assignment (64bit time_t) when trying to store it as integer
  35. if (ntpSynced()) {
  36. auto info = ntpInfo();
  37. root["now"] = static_cast<double>(info.now);
  38. root["nowString"] = info.utc;
  39. root["nowLocalString"] = info.local.length()
  40. ? info.local
  41. : info.utc;
  42. }
  43. #endif
  44. }
  45. void _wsDoUpdate(const bool connected) {
  46. if (!connected) return;
  47. if (millis() - _ws_last_update > WS_UPDATE_INTERVAL) {
  48. _ws_last_update = millis();
  49. wsSend(_wsUpdate);
  50. }
  51. }
  52. // -----------------------------------------------------------------------------
  53. // WS callbacks
  54. // -----------------------------------------------------------------------------
  55. std::queue<WsPostponedCallbacks> _ws_queue;
  56. ws_callbacks_t _ws_callbacks;
  57. void wsPost(uint32_t client_id, ws_on_send_callback_f&& cb) {
  58. _ws_queue.emplace(client_id, std::move(cb));
  59. }
  60. void wsPost(ws_on_send_callback_f&& cb) {
  61. wsPost(0, std::move(cb));
  62. }
  63. void wsPost(uint32_t client_id, const ws_on_send_callback_f& cb) {
  64. _ws_queue.emplace(client_id, cb);
  65. }
  66. void wsPost(const ws_on_send_callback_f& cb) {
  67. wsPost(0, cb);
  68. }
  69. template <typename T>
  70. void _wsPostCallbacks(uint32_t client_id, T&& cbs, WsPostponedCallbacks::Mode mode) {
  71. _ws_queue.emplace(client_id, std::forward<T>(cbs), mode);
  72. }
  73. void wsPostAll(uint32_t client_id, ws_on_send_callback_list_t&& cbs) {
  74. _wsPostCallbacks(client_id, std::move(cbs), WsPostponedCallbacks::Mode::All);
  75. }
  76. void wsPostAll(ws_on_send_callback_list_t&& cbs) {
  77. wsPostAll(0, std::move(cbs));
  78. }
  79. void wsPostAll(uint32_t client_id, const ws_on_send_callback_list_t& cbs) {
  80. _wsPostCallbacks(client_id, cbs, WsPostponedCallbacks::Mode::All);
  81. }
  82. void wsPostAll(const ws_on_send_callback_list_t& cbs) {
  83. wsPostAll(0, cbs);
  84. }
  85. void wsPostSequence(uint32_t client_id, ws_on_send_callback_list_t&& cbs) {
  86. _wsPostCallbacks(client_id, std::move(cbs), WsPostponedCallbacks::Mode::Sequence);
  87. }
  88. void wsPostSequence(ws_on_send_callback_list_t&& cbs) {
  89. wsPostSequence(0, std::move(cbs));
  90. }
  91. void wsPostSequence(uint32_t client_id, const ws_on_send_callback_list_t& cbs) {
  92. _wsPostCallbacks(client_id, cbs, WsPostponedCallbacks::Mode::Sequence);
  93. }
  94. void wsPostSequence(const ws_on_send_callback_list_t& cbs) {
  95. wsPostSequence(0, cbs);
  96. }
  97. // -----------------------------------------------------------------------------
  98. ws_callbacks_t& ws_callbacks_t::onVisible(ws_on_send_callback_f cb) {
  99. on_visible.push_back(cb);
  100. return *this;
  101. }
  102. ws_callbacks_t& ws_callbacks_t::onConnected(ws_on_send_callback_f cb) {
  103. on_connected.push_back(cb);
  104. return *this;
  105. }
  106. ws_callbacks_t& ws_callbacks_t::onData(ws_on_send_callback_f cb) {
  107. on_data.push_back(cb);
  108. return *this;
  109. }
  110. ws_callbacks_t& ws_callbacks_t::onAction(ws_on_action_callback_f cb) {
  111. on_action.push_back(cb);
  112. return *this;
  113. }
  114. ws_callbacks_t& ws_callbacks_t::onKeyCheck(ws_on_keycheck_callback_f cb) {
  115. on_keycheck.push_back(cb);
  116. return *this;
  117. }
  118. // -----------------------------------------------------------------------------
  119. // WS authentication
  120. // -----------------------------------------------------------------------------
  121. WsTicket _ws_tickets[WS_BUFFER_SIZE];
  122. void _onAuth(AsyncWebServerRequest *request) {
  123. webLog(request);
  124. if (!webAuthenticate(request)) return request->requestAuthentication();
  125. IPAddress ip = request->client()->remoteIP();
  126. unsigned long now = millis();
  127. unsigned short index;
  128. for (index = 0; index < WS_BUFFER_SIZE; index++) {
  129. if (_ws_tickets[index].ip == ip) break;
  130. if (_ws_tickets[index].timestamp == 0) break;
  131. if (now - _ws_tickets[index].timestamp > WS_TIMEOUT) break;
  132. }
  133. if (index == WS_BUFFER_SIZE) {
  134. request->send(429);
  135. } else {
  136. _ws_tickets[index].ip = ip;
  137. _ws_tickets[index].timestamp = now;
  138. request->send(200, "text/plain", "OK");
  139. }
  140. }
  141. bool _wsAuth(AsyncWebSocketClient * client) {
  142. IPAddress ip = client->remoteIP();
  143. unsigned long now = millis();
  144. unsigned short index = 0;
  145. for (index = 0; index < WS_BUFFER_SIZE; index++) {
  146. if ((_ws_tickets[index].ip == ip) && (now - _ws_tickets[index].timestamp < WS_TIMEOUT)) break;
  147. }
  148. if (index == WS_BUFFER_SIZE) {
  149. return false;
  150. }
  151. return true;
  152. }
  153. // -----------------------------------------------------------------------------
  154. // Debug
  155. // -----------------------------------------------------------------------------
  156. #if DEBUG_WEB_SUPPORT
  157. constexpr size_t WsDebugMessagesMax = 8;
  158. WsDebug _ws_debug(WsDebugMessagesMax);
  159. void WsDebug::send(bool connected) {
  160. if (!connected && _flush) {
  161. clear();
  162. return;
  163. }
  164. if (!_flush) return;
  165. // ref: http://arduinojson.org/v5/assistant/
  166. // {"weblog": {"msg":[...],"pre":[...]}}
  167. DynamicJsonBuffer jsonBuffer(2*JSON_ARRAY_SIZE(_messages.size()) + JSON_OBJECT_SIZE(1) + JSON_OBJECT_SIZE(2));
  168. JsonObject& root = jsonBuffer.createObject();
  169. JsonObject& weblog = root.createNestedObject("weblog");
  170. JsonArray& msg_array = weblog.createNestedArray("msg");
  171. JsonArray& pre_array = weblog.createNestedArray("pre");
  172. for (auto& msg : _messages) {
  173. pre_array.add(msg.first.c_str());
  174. msg_array.add(msg.second.c_str());
  175. }
  176. wsSend(root);
  177. clear();
  178. }
  179. bool wsDebugSend(const char* prefix, const char* message) {
  180. if (!wsConnected()) return false;
  181. _ws_debug.add(prefix, message);
  182. return true;
  183. }
  184. #endif
  185. // Check the existing setting before saving it
  186. // TODO: this should know of the default values, somehow?
  187. // TODO: move webPort handling somewhere else?
  188. bool _wsStore(const String& key, const String& value) {
  189. if (key == "webPort") {
  190. if ((value.toInt() == 0) || (value.toInt() == 80)) {
  191. return delSetting(key);
  192. }
  193. }
  194. if (!hasSetting(key) || value != getSetting(key)) {
  195. return setSetting(key, value);
  196. }
  197. return false;
  198. }
  199. // -----------------------------------------------------------------------------
  200. // Store indexed key (key0, key1, etc.) from array
  201. // -----------------------------------------------------------------------------
  202. bool _wsStore(const String& key, JsonArray& values) {
  203. bool changed = false;
  204. unsigned char index = 0;
  205. for (auto& element : values) {
  206. const auto value = element.as<String>();
  207. const auto keyobj = settings_key_t {key, index};
  208. if (!hasSetting(keyobj) || value != getSetting(keyobj)) {
  209. setSetting(keyobj, value);
  210. changed = true;
  211. }
  212. ++index;
  213. }
  214. // Delete further values
  215. for (unsigned char next_index=index; next_index < SETTINGS_MAX_LIST_COUNT; ++next_index) {
  216. if (!delSetting({key, next_index})) break;
  217. changed = true;
  218. }
  219. return changed;
  220. }
  221. bool _wsCheckKey(const String& key, JsonVariant& value) {
  222. for (auto& callback : _ws_callbacks.on_keycheck) {
  223. if (callback(key.c_str(), value)) return true;
  224. // TODO: remove this to call all OnKeyCheckCallbacks with the
  225. // current key/value
  226. }
  227. return false;
  228. }
  229. void _wsParse(AsyncWebSocketClient *client, uint8_t * payload, size_t length) {
  230. //DEBUG_MSG_P(PSTR("[WEBSOCKET] Parsing: %s\n"), length ? (char*) payload : "");
  231. // Get client ID
  232. uint32_t client_id = client->id();
  233. // Check early for empty object / nothing
  234. if ((length == 0) || (length == 1)) {
  235. return;
  236. }
  237. if ((length == 3) && (strcmp((char*) payload, "{}") == 0)) {
  238. return;
  239. }
  240. // Parse JSON input
  241. // TODO: json buffer should be pretty efficient with the non-const payload,
  242. // most of the space is taken by the object key references
  243. DynamicJsonBuffer jsonBuffer(512);
  244. JsonObject& root = jsonBuffer.parseObject((char *) payload);
  245. if (!root.success()) {
  246. DEBUG_MSG_P(PSTR("[WEBSOCKET] JSON parsing error\n"));
  247. wsSend_P(client_id, PSTR("{\"message\": 3}"));
  248. return;
  249. }
  250. // Check actions -----------------------------------------------------------
  251. const char* action = root["action"];
  252. if (action) {
  253. if (strcmp(action, "ping") == 0) {
  254. wsSend_P(client_id, PSTR("{\"pong\": 1}"));
  255. return;
  256. }
  257. DEBUG_MSG_P(PSTR("[WEBSOCKET] Requested action: %s\n"), action);
  258. if (strcmp(action, "reboot") == 0) {
  259. deferredReset(100, CUSTOM_RESET_WEB);
  260. return;
  261. }
  262. if (strcmp(action, "reconnect") == 0) {
  263. _ws_defer.once_ms(100, wifiDisconnect);
  264. return;
  265. }
  266. if (strcmp(action, "factory_reset") == 0) {
  267. DEBUG_MSG_P(PSTR("\n\nFACTORY RESET\n\n"));
  268. resetSettings();
  269. deferredReset(100, CUSTOM_RESET_FACTORY);
  270. return;
  271. }
  272. JsonObject& data = root["data"];
  273. if (data.success()) {
  274. // Callbacks
  275. for (auto& callback : _ws_callbacks.on_action) {
  276. callback(client_id, action, data);
  277. }
  278. // Restore configuration via websockets
  279. if (strcmp(action, "restore") == 0) {
  280. if (settingsRestoreJson(data)) {
  281. wsSend_P(client_id, PSTR("{\"message\": 5}"));
  282. } else {
  283. wsSend_P(client_id, PSTR("{\"message\": 4}"));
  284. }
  285. }
  286. return;
  287. }
  288. };
  289. // Check configuration -----------------------------------------------------
  290. JsonObject& config = root["config"];
  291. if (config.success()) {
  292. DEBUG_MSG_P(PSTR("[WEBSOCKET] Parsing configuration data\n"));
  293. String adminPass;
  294. bool save = false;
  295. for (auto kv: config) {
  296. bool changed = false;
  297. String key = kv.key;
  298. JsonVariant& value = kv.value;
  299. if (key == "adminPass") {
  300. if (!value.is<JsonArray&>()) continue;
  301. JsonArray& values = value.as<JsonArray&>();
  302. if (values.size() != 2) continue;
  303. if (values[0].as<String>().equals(values[1].as<String>())) {
  304. String password = values[0].as<String>();
  305. if (password.length() > 0) {
  306. setSetting(key, password);
  307. save = true;
  308. wsSend_P(client_id, PSTR("{\"action\": \"reload\"}"));
  309. }
  310. } else {
  311. wsSend_P(client_id, PSTR("{\"message\": 7}"));
  312. }
  313. continue;
  314. }
  315. #if NTP_SUPPORT
  316. else if (key == "ntpTZ") {
  317. _wsResetUpdateTimer();
  318. }
  319. #endif
  320. if (!_wsCheckKey(key, value)) {
  321. delSetting(key);
  322. continue;
  323. }
  324. // Store values
  325. if (value.is<JsonArray&>()) {
  326. if (_wsStore(key, value.as<JsonArray&>())) changed = true;
  327. } else {
  328. if (_wsStore(key, value.as<String>())) changed = true;
  329. }
  330. // Update flags if value has changed
  331. if (changed) {
  332. save = true;
  333. }
  334. }
  335. // Save settings
  336. if (save) {
  337. // Callbacks
  338. espurnaReload();
  339. // Persist settings
  340. saveSettings();
  341. wsSend_P(client_id, PSTR("{\"message\": 8}"));
  342. } else {
  343. wsSend_P(client_id, PSTR("{\"message\": 9}"));
  344. }
  345. }
  346. }
  347. bool _wsOnKeyCheck(const char * key, JsonVariant& value) {
  348. if (strncmp(key, "ws", 2) == 0) return true;
  349. if (strncmp(key, "admin", 5) == 0) return true;
  350. if (strncmp(key, "hostname", 8) == 0) return true;
  351. if (strncmp(key, "desc", 4) == 0) return true;
  352. if (strncmp(key, "webPort", 7) == 0) return true;
  353. return false;
  354. }
  355. void _wsOnConnected(JsonObject& root) {
  356. root["webMode"] = WEB_MODE_NORMAL;
  357. root["app_name"] = APP_NAME;
  358. root["app_version"] = APP_VERSION;
  359. root["app_build"] = buildTime();
  360. #if defined(APP_REVISION)
  361. root["app_revision"] = APP_REVISION;
  362. #endif
  363. root["device"] = getDevice().c_str();
  364. root["manufacturer"] = getManufacturer().c_str();
  365. root["chipid"] = getChipId().c_str();
  366. root["mac"] = WiFi.macAddress();
  367. root["bssid"] = WiFi.BSSIDstr();
  368. root["channel"] = WiFi.channel();
  369. root["hostname"] = getSetting("hostname");
  370. root["desc"] = getSetting("desc");
  371. root["network"] = getNetwork();
  372. root["deviceip"] = getIP();
  373. root["sketch_size"] = ESP.getSketchSize();
  374. root["free_size"] = ESP.getFreeSketchSpace();
  375. root["sdk"] = ESP.getSdkVersion();
  376. root["core"] = getCoreVersion();
  377. root["webPort"] = getSetting("webPort", WEB_PORT);
  378. root["wsAuth"] = getSetting("wsAuth", 1 == WS_AUTHENTICATION);
  379. root["hbMode"] = getSetting("hbMode", HEARTBEAT_MODE);
  380. root["hbInterval"] = getSetting("hbInterval", HEARTBEAT_INTERVAL);
  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. #ifndef NOWSAUTH
  401. if (!_wsAuth(client)) {
  402. wsSend_P(client->id(), PSTR("{\"message\": 10}"));
  403. DEBUG_MSG_P(PSTR("[WEBSOCKET] Validation check failed\n"));
  404. client->close();
  405. return;
  406. }
  407. #endif
  408. IPAddress ip = client->remoteIP();
  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(PGM_P 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, PGM_P 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