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.

562 lines
15 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 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. #if WEB_SUPPORT
  6. #include <ESPAsyncTCP.h>
  7. #include <ESPAsyncWebServer.h>
  8. #include <ArduinoJson.h>
  9. #include <Ticker.h>
  10. #include <vector>
  11. #include "libs/WebSocketIncommingBuffer.h"
  12. AsyncWebSocket _ws("/ws");
  13. Ticker _web_defer;
  14. std::vector<ws_on_send_callback_f> _ws_on_send_callbacks;
  15. std::vector<ws_on_action_callback_f> _ws_on_action_callbacks;
  16. std::vector<ws_on_receive_callback_f> _ws_on_receive_callbacks;
  17. // -----------------------------------------------------------------------------
  18. // Private methods
  19. // -----------------------------------------------------------------------------
  20. typedef struct {
  21. IPAddress ip;
  22. unsigned long timestamp = 0;
  23. } ws_ticket_t;
  24. ws_ticket_t _ticket[WS_BUFFER_SIZE];
  25. void _onAuth(AsyncWebServerRequest *request) {
  26. webLog(request);
  27. if (!webAuthenticate(request)) return request->requestAuthentication();
  28. IPAddress ip = request->client()->remoteIP();
  29. unsigned long now = millis();
  30. unsigned short index;
  31. for (index = 0; index < WS_BUFFER_SIZE; index++) {
  32. if (_ticket[index].ip == ip) break;
  33. if (_ticket[index].timestamp == 0) break;
  34. if (now - _ticket[index].timestamp > WS_TIMEOUT) break;
  35. }
  36. if (index == WS_BUFFER_SIZE) {
  37. request->send(429);
  38. } else {
  39. _ticket[index].ip = ip;
  40. _ticket[index].timestamp = now;
  41. request->send(200, "text/plain", "OK");
  42. }
  43. }
  44. bool _wsAuth(AsyncWebSocketClient * client) {
  45. IPAddress ip = client->remoteIP();
  46. unsigned long now = millis();
  47. unsigned short index = 0;
  48. for (index = 0; index < WS_BUFFER_SIZE; index++) {
  49. if ((_ticket[index].ip == ip) && (now - _ticket[index].timestamp < WS_TIMEOUT)) break;
  50. }
  51. if (index == WS_BUFFER_SIZE) {
  52. return false;
  53. }
  54. return true;
  55. }
  56. #if DEBUG_WEB_SUPPORT
  57. bool wsDebugSend(const char* prefix, const char* message) {
  58. if (!wsConnected()) return false;
  59. if (getFreeHeap() < (strlen(message) * 3)) return false;
  60. DynamicJsonBuffer jsonBuffer;
  61. JsonObject &root = jsonBuffer.createObject();
  62. JsonObject &weblog = root.createNestedObject("weblog");
  63. weblog.set("message", message);
  64. if (prefix && (prefix[0] != '\0')) {
  65. weblog.set("prefix", prefix);
  66. }
  67. wsSend(root);
  68. return true;
  69. }
  70. #endif
  71. // -----------------------------------------------------------------------------
  72. #if MQTT_SUPPORT
  73. void _wsMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  74. if (type == MQTT_CONNECT_EVENT) wsSend_P(PSTR("{\"mqttStatus\": true}"));
  75. if (type == MQTT_DISCONNECT_EVENT) wsSend_P(PSTR("{\"mqttStatus\": false}"));
  76. }
  77. #endif
  78. bool _wsStore(String key, String value) {
  79. // HTTP port
  80. if (key == "webPort") {
  81. if ((value.toInt() == 0) || (value.toInt() == 80)) {
  82. return delSetting(key);
  83. }
  84. }
  85. if (value != getSetting(key)) {
  86. return setSetting(key, value);
  87. }
  88. return false;
  89. }
  90. bool _wsStore(String key, JsonArray& value) {
  91. bool changed = false;
  92. unsigned char index = 0;
  93. for (auto element : value) {
  94. if (_wsStore(key + index, element.as<String>())) changed = true;
  95. index++;
  96. }
  97. // Delete further values
  98. for (unsigned char i=index; i<SETTINGS_MAX_LIST_COUNT; i++) {
  99. if (!delSetting(key, index)) break;
  100. changed = true;
  101. }
  102. return changed;
  103. }
  104. void _wsParse(AsyncWebSocketClient *client, uint8_t * payload, size_t length) {
  105. //DEBUG_MSG_P(PSTR("[WEBSOCKET] Parsing: %s\n"), length ? (char*) payload : "");
  106. // Get client ID
  107. uint32_t client_id = client->id();
  108. // Parse JSON input
  109. DynamicJsonBuffer jsonBuffer;
  110. JsonObject& root = jsonBuffer.parseObject((char *) payload);
  111. if (!root.success()) {
  112. DEBUG_MSG_P(PSTR("[WEBSOCKET] Error parsing data\n"));
  113. wsSend_P(client_id, PSTR("{\"message\": 3}"));
  114. return;
  115. }
  116. // Check actions -----------------------------------------------------------
  117. const char* action = root["action"];
  118. if (action) {
  119. DEBUG_MSG_P(PSTR("[WEBSOCKET] Requested action: %s\n"), action);
  120. if (strcmp(action, "reboot") == 0) {
  121. deferredReset(100, CUSTOM_RESET_WEB);
  122. return;
  123. }
  124. if (strcmp(action, "reconnect") == 0) {
  125. _web_defer.once_ms(100, wifiDisconnect);
  126. return;
  127. }
  128. if (strcmp(action, "factory_reset") == 0) {
  129. DEBUG_MSG_P(PSTR("\n\nFACTORY RESET\n\n"));
  130. resetSettings();
  131. deferredReset(100, CUSTOM_RESET_FACTORY);
  132. return;
  133. }
  134. JsonObject& data = root["data"];
  135. if (data.success()) {
  136. // Callbacks
  137. for (unsigned char i = 0; i < _ws_on_action_callbacks.size(); i++) {
  138. (_ws_on_action_callbacks[i])(client_id, action, data);
  139. }
  140. // Restore configuration via websockets
  141. if (strcmp(action, "restore") == 0) {
  142. if (settingsRestoreJson(data)) {
  143. wsSend_P(client_id, PSTR("{\"message\": 5}"));
  144. } else {
  145. wsSend_P(client_id, PSTR("{\"message\": 4}"));
  146. }
  147. }
  148. return;
  149. }
  150. };
  151. // Check configuration -----------------------------------------------------
  152. JsonObject& config = root["config"];
  153. if (config.success()) {
  154. DEBUG_MSG_P(PSTR("[WEBSOCKET] Parsing configuration data\n"));
  155. String adminPass;
  156. bool save = false;
  157. for (auto kv: config) {
  158. bool changed = false;
  159. String key = kv.key;
  160. JsonVariant& value = kv.value;
  161. // Check password
  162. if (key == "adminPass") {
  163. if (!value.is<JsonArray&>()) continue;
  164. JsonArray& values = value.as<JsonArray&>();
  165. if (values.size() != 2) continue;
  166. if (values[0].as<String>().equals(values[1].as<String>())) {
  167. String password = values[0].as<String>();
  168. if (password.length() > 0) {
  169. setSetting(key, password);
  170. save = true;
  171. wsSend_P(client_id, PSTR("{\"action\": \"reload\"}"));
  172. }
  173. } else {
  174. wsSend_P(client_id, PSTR("{\"message\": 7}"));
  175. }
  176. continue;
  177. }
  178. // Check if key has to be processed
  179. bool found = false;
  180. for (unsigned char i = 0; i < _ws_on_receive_callbacks.size(); i++) {
  181. found |= (_ws_on_receive_callbacks[i])(key.c_str(), value);
  182. // TODO: remove this to call all OnReceiveCallbacks with the
  183. // current key/value
  184. if (found) break;
  185. }
  186. if (!found) {
  187. delSetting(key);
  188. continue;
  189. }
  190. // Store values
  191. if (value.is<JsonArray&>()) {
  192. if (_wsStore(key, value.as<JsonArray&>())) changed = true;
  193. } else {
  194. if (_wsStore(key, value.as<String>())) changed = true;
  195. }
  196. // Update flags if value has changed
  197. if (changed) {
  198. save = true;
  199. }
  200. }
  201. // Save settings
  202. if (save) {
  203. // Callbacks
  204. espurnaReload();
  205. // Persist settings
  206. saveSettings();
  207. wsSend_P(client_id, PSTR("{\"message\": 8}"));
  208. } else {
  209. wsSend_P(client_id, PSTR("{\"message\": 9}"));
  210. }
  211. }
  212. }
  213. void _wsUpdate(JsonObject& root) {
  214. root["heap"] = getFreeHeap();
  215. root["uptime"] = getUptime();
  216. root["rssi"] = WiFi.RSSI();
  217. root["loadaverage"] = systemLoadAverage();
  218. #if ADC_MODE_VALUE == ADC_VCC
  219. root["vcc"] = ESP.getVcc();
  220. #endif
  221. #if NTP_SUPPORT
  222. if (ntpSynced()) root["now"] = now();
  223. #endif
  224. }
  225. void _wsDoUpdate(bool reset = false) {
  226. static unsigned long last = millis();
  227. if (reset) {
  228. last = millis() + WS_UPDATE_INTERVAL;
  229. return;
  230. }
  231. if (millis() - last > WS_UPDATE_INTERVAL) {
  232. last = millis();
  233. wsSend(_wsUpdate);
  234. }
  235. }
  236. bool _wsOnReceive(const char * key, JsonVariant& value) {
  237. if (strncmp(key, "ws", 2) == 0) return true;
  238. if (strncmp(key, "admin", 5) == 0) return true;
  239. if (strncmp(key, "hostname", 8) == 0) return true;
  240. if (strncmp(key, "desc", 4) == 0) return true;
  241. if (strncmp(key, "webPort", 7) == 0) return true;
  242. return false;
  243. }
  244. void _wsOnStart(JsonObject& root) {
  245. char chipid[7];
  246. snprintf_P(chipid, sizeof(chipid), PSTR("%06X"), ESP.getChipId());
  247. uint8_t * bssid = WiFi.BSSID();
  248. char bssid_str[20];
  249. snprintf_P(bssid_str, sizeof(bssid_str),
  250. PSTR("%02X:%02X:%02X:%02X:%02X:%02X"),
  251. bssid[0], bssid[1], bssid[2], bssid[3], bssid[4], bssid[5]
  252. );
  253. root["webMode"] = WEB_MODE_NORMAL;
  254. root["app_name"] = APP_NAME;
  255. root["app_version"] = APP_VERSION;
  256. root["app_build"] = buildTime();
  257. #if defined(APP_REVISION)
  258. root["app_revision"] = APP_REVISION;
  259. #endif
  260. root["manufacturer"] = MANUFACTURER;
  261. root["chipid"] = String(chipid);
  262. root["mac"] = WiFi.macAddress();
  263. root["bssid"] = String(bssid_str);
  264. root["channel"] = WiFi.channel();
  265. root["device"] = DEVICE;
  266. root["hostname"] = getSetting("hostname");
  267. root["desc"] = getSetting("desc");
  268. root["network"] = getNetwork();
  269. root["deviceip"] = getIP();
  270. root["sketch_size"] = ESP.getSketchSize();
  271. root["free_size"] = ESP.getFreeSketchSpace();
  272. root["sdk"] = ESP.getSdkVersion();
  273. root["core"] = getCoreVersion();
  274. root["btnDelay"] = getSetting("btnDelay", BUTTON_DBLCLICK_DELAY).toInt();
  275. root["webPort"] = getSetting("webPort", WEB_PORT).toInt();
  276. root["wsAuth"] = getSetting("wsAuth", WS_AUTHENTICATION).toInt() == 1;
  277. #if TERMINAL_SUPPORT
  278. root["cmdVisible"] = 1;
  279. #endif
  280. root["hbMode"] = getSetting("hbMode", HEARTBEAT_MODE).toInt();
  281. root["hbInterval"] = getSetting("hbInterval", HEARTBEAT_INTERVAL).toInt();
  282. _wsDoUpdate(true);
  283. }
  284. void wsSend(JsonObject& root) {
  285. size_t len = root.measureLength();
  286. AsyncWebSocketMessageBuffer* buffer = _ws.makeBuffer(len);
  287. if (buffer) {
  288. root.printTo(reinterpret_cast<char*>(buffer->get()), len + 1);
  289. _ws.textAll(buffer);
  290. }
  291. }
  292. void wsSend(uint32_t client_id, JsonObject& root) {
  293. AsyncWebSocketClient* client = _ws.client(client_id);
  294. if (client == nullptr) return;
  295. size_t len = root.measureLength();
  296. AsyncWebSocketMessageBuffer* buffer = _ws.makeBuffer(len);
  297. if (buffer) {
  298. root.printTo(reinterpret_cast<char*>(buffer->get()), len + 1);
  299. client->text(buffer);
  300. }
  301. }
  302. void _wsStart(uint32_t client_id) {
  303. #if USE_PASSWORD && WEB_FORCE_PASS_CHANGE
  304. bool changePassword = getAdminPass().equals(ADMIN_PASS);
  305. #else
  306. bool changePassword = false;
  307. #endif
  308. DynamicJsonBuffer jsonBuffer;
  309. JsonObject& root = jsonBuffer.createObject();
  310. if (changePassword) {
  311. root["webMode"] = WEB_MODE_PASSWORD;
  312. wsSend(root);
  313. return;
  314. }
  315. for (auto& callback : _ws_on_send_callbacks) {
  316. callback(root);
  317. }
  318. wsSend(client_id, root);
  319. }
  320. void _wsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){
  321. if (type == WS_EVT_CONNECT) {
  322. client->_tempObject = nullptr;
  323. #ifndef NOWSAUTH
  324. if (!_wsAuth(client)) {
  325. wsSend_P(client->id(), PSTR("{\"message\": 10}"));
  326. DEBUG_MSG_P(PSTR("[WEBSOCKET] Validation check failed\n"));
  327. client->close();
  328. return;
  329. }
  330. #endif
  331. IPAddress ip = client->remoteIP();
  332. 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());
  333. _wsStart(client->id());
  334. client->_tempObject = new WebSocketIncommingBuffer(&_wsParse, true);
  335. wifiReconnectCheck();
  336. } else if(type == WS_EVT_DISCONNECT) {
  337. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u disconnected\n"), client->id());
  338. if (client->_tempObject) {
  339. delete (WebSocketIncommingBuffer *) client->_tempObject;
  340. }
  341. wifiReconnectCheck();
  342. } else if(type == WS_EVT_ERROR) {
  343. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u error(%u): %s\n"), client->id(), *((uint16_t*)arg), (char*)data);
  344. } else if(type == WS_EVT_PONG) {
  345. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u pong(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  346. } else if(type == WS_EVT_DATA) {
  347. //DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u data(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  348. WebSocketIncommingBuffer *buffer = (WebSocketIncommingBuffer *)client->_tempObject;
  349. AwsFrameInfo * info = (AwsFrameInfo*)arg;
  350. buffer->data_event(client, info, data, len);
  351. }
  352. }
  353. void _wsLoop() {
  354. if (!wsConnected()) return;
  355. _wsDoUpdate();
  356. }
  357. // -----------------------------------------------------------------------------
  358. // Public API
  359. // -----------------------------------------------------------------------------
  360. bool wsConnected() {
  361. return (_ws.count() > 0);
  362. }
  363. bool wsConnected(uint32_t client_id) {
  364. return _ws.hasClient(client_id);
  365. }
  366. void wsOnSendRegister(ws_on_send_callback_f callback) {
  367. _ws_on_send_callbacks.push_back(callback);
  368. }
  369. void wsOnReceiveRegister(ws_on_receive_callback_f callback) {
  370. _ws_on_receive_callbacks.push_back(callback);
  371. }
  372. void wsOnActionRegister(ws_on_action_callback_f callback) {
  373. _ws_on_action_callbacks.push_back(callback);
  374. }
  375. void wsSend(ws_on_send_callback_f callback) {
  376. if (_ws.count() > 0) {
  377. DynamicJsonBuffer jsonBuffer;
  378. JsonObject& root = jsonBuffer.createObject();
  379. callback(root);
  380. wsSend(root);
  381. }
  382. }
  383. void wsSend(const char * payload) {
  384. if (_ws.count() > 0) {
  385. _ws.textAll(payload);
  386. }
  387. }
  388. void wsSend_P(PGM_P payload) {
  389. if (_ws.count() > 0) {
  390. char buffer[strlen_P(payload)];
  391. strcpy_P(buffer, payload);
  392. _ws.textAll(buffer);
  393. }
  394. }
  395. void wsSend(uint32_t client_id, ws_on_send_callback_f callback) {
  396. AsyncWebSocketClient* client = _ws.client(client_id);
  397. if (client == nullptr) return;
  398. DynamicJsonBuffer jsonBuffer;
  399. JsonObject& root = jsonBuffer.createObject();
  400. callback(root);
  401. size_t len = root.measureLength();
  402. AsyncWebSocketMessageBuffer* buffer = _ws.makeBuffer(len);
  403. if (buffer) {
  404. root.printTo(reinterpret_cast<char*>(buffer->get()), len + 1);
  405. client->text(buffer);
  406. }
  407. }
  408. void wsSend(uint32_t client_id, const char * payload) {
  409. _ws.text(client_id, payload);
  410. }
  411. void wsSend_P(uint32_t client_id, PGM_P payload) {
  412. char buffer[strlen_P(payload)];
  413. strcpy_P(buffer, payload);
  414. _ws.text(client_id, buffer);
  415. }
  416. void wsSetup() {
  417. _ws.onEvent(_wsEvent);
  418. webServer()->addHandler(&_ws);
  419. // CORS
  420. #ifdef WEB_REMOTE_DOMAIN
  421. DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin", WEB_REMOTE_DOMAIN);
  422. DefaultHeaders::Instance().addHeader("Access-Control-Allow-Credentials", "true");
  423. #endif
  424. webServer()->on("/auth", HTTP_GET, _onAuth);
  425. #if MQTT_SUPPORT
  426. mqttRegister(_wsMQTTCallback);
  427. #endif
  428. wsOnSendRegister(_wsOnStart);
  429. wsOnReceiveRegister(_wsOnReceive);
  430. espurnaRegisterLoop(_wsLoop);
  431. }
  432. #endif // WEB_SUPPORT