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