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. // -----------------------------------------------------------------------------
  16. // Periodic updates
  17. // -----------------------------------------------------------------------------
  18. uint32_t _ws_last_update = 0;
  19. void _wsResetUpdateTimer() {
  20. _ws_last_update = millis() + WS_UPDATE_INTERVAL;
  21. }
  22. void _wsUpdate(JsonObject& root) {
  23. root["heap"] = getFreeHeap();
  24. root["uptime"] = getUptime();
  25. root["rssi"] = WiFi.RSSI();
  26. root["loadaverage"] = systemLoadAverage();
  27. if (ADC_MODE_VALUE == ADC_VCC) {
  28. root["vcc"] = ESP.getVcc();
  29. } else {
  30. root["vcc"] = "N/A (TOUT) ";
  31. }
  32. #if NTP_SUPPORT
  33. // XXX: arduinojson will ignore info.now assignment (64bit time_t) when trying to store it as integer
  34. if (ntpSynced()) {
  35. auto info = ntpInfo();
  36. root["now"] = static_cast<double>(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. auto setting = SettingsKey {key, index};
  207. if (!hasSetting(setting) || value != getSetting(setting)) {
  208. setSetting(setting, 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. static Ticker timer;
  263. timer.once_ms_scheduled(100, []() {
  264. wifiDisconnect();
  265. yield();
  266. });
  267. return;
  268. }
  269. if (strcmp(action, "factory_reset") == 0) {
  270. DEBUG_MSG_P(PSTR("\n\nFACTORY RESET\n\n"));
  271. resetSettings();
  272. deferredReset(100, CUSTOM_RESET_FACTORY);
  273. return;
  274. }
  275. JsonObject& data = root["data"];
  276. if (data.success()) {
  277. // Callbacks
  278. for (auto& callback : _ws_callbacks.on_action) {
  279. callback(client_id, action, data);
  280. }
  281. // Restore configuration via websockets
  282. if (strcmp(action, "restore") == 0) {
  283. if (settingsRestoreJson(data)) {
  284. wsSend_P(client_id, PSTR("{\"message\": 5}"));
  285. } else {
  286. wsSend_P(client_id, PSTR("{\"message\": 4}"));
  287. }
  288. }
  289. return;
  290. }
  291. };
  292. // Check configuration -----------------------------------------------------
  293. JsonObject& config = root["config"];
  294. if (config.success()) {
  295. DEBUG_MSG_P(PSTR("[WEBSOCKET] Parsing configuration data\n"));
  296. String adminPass;
  297. bool save = false;
  298. for (auto kv: config) {
  299. bool changed = false;
  300. String key = kv.key;
  301. JsonVariant& value = kv.value;
  302. if (key == "adminPass") {
  303. if (!value.is<JsonArray&>()) continue;
  304. JsonArray& values = value.as<JsonArray&>();
  305. if (values.size() != 2) continue;
  306. if (values[0].as<String>().equals(values[1].as<String>())) {
  307. String password = values[0].as<String>();
  308. if (password.length() > 0) {
  309. setSetting(key, password);
  310. save = true;
  311. wsSend_P(client_id, PSTR("{\"action\": \"reload\"}"));
  312. }
  313. } else {
  314. wsSend_P(client_id, PSTR("{\"message\": 7}"));
  315. }
  316. continue;
  317. }
  318. #if NTP_SUPPORT
  319. else if (key == "ntpTZ") {
  320. _wsResetUpdateTimer();
  321. }
  322. #endif
  323. if (!_wsCheckKey(key, value)) {
  324. delSetting(key);
  325. continue;
  326. }
  327. // Store values
  328. if (value.is<JsonArray&>()) {
  329. if (_wsStore(key, value.as<JsonArray&>())) changed = true;
  330. } else {
  331. if (_wsStore(key, value.as<String>())) changed = true;
  332. }
  333. // Update flags if value has changed
  334. if (changed) {
  335. save = true;
  336. }
  337. }
  338. // Save settings
  339. if (save) {
  340. // Callbacks
  341. espurnaReload();
  342. // Persist settings
  343. saveSettings();
  344. wsSend_P(client_id, PSTR("{\"message\": 8}"));
  345. } else {
  346. wsSend_P(client_id, PSTR("{\"message\": 9}"));
  347. }
  348. }
  349. }
  350. bool _wsOnKeyCheck(const char * key, JsonVariant& value) {
  351. if (strncmp(key, "ws", 2) == 0) return true;
  352. if (strncmp(key, "admin", 5) == 0) return true;
  353. if (strncmp(key, "hostname", 8) == 0) return true;
  354. if (strncmp(key, "desc", 4) == 0) return true;
  355. if (strncmp(key, "webPort", 7) == 0) return true;
  356. return false;
  357. }
  358. void _wsOnConnected(JsonObject& root) {
  359. root["webMode"] = WEB_MODE_NORMAL;
  360. root["app_name"] = APP_NAME;
  361. root["app_version"] = getVersion().c_str();
  362. root["app_build"] = buildTime();
  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