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.

574 lines
16 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. #if MQTT_SUPPORT
  158. bool changedMQTT = false;
  159. #endif
  160. for (auto kv: config) {
  161. bool changed = false;
  162. String key = kv.key;
  163. JsonVariant& value = kv.value;
  164. // Check password
  165. if (key == "adminPass") {
  166. if (!value.is<JsonArray&>()) continue;
  167. JsonArray& values = value.as<JsonArray&>();
  168. if (values.size() != 2) continue;
  169. if (values[0].as<String>().equals(values[1].as<String>())) {
  170. String password = values[0].as<String>();
  171. if (password.length() > 0) {
  172. setSetting(key, password);
  173. save = true;
  174. wsSend_P(client_id, PSTR("{\"action\": \"reload\"}"));
  175. }
  176. } else {
  177. wsSend_P(client_id, PSTR("{\"message\": 7}"));
  178. }
  179. continue;
  180. }
  181. // Check if key has to be processed
  182. bool found = false;
  183. for (unsigned char i = 0; i < _ws_on_receive_callbacks.size(); i++) {
  184. found |= (_ws_on_receive_callbacks[i])(key.c_str(), value);
  185. // TODO: remove this to call all OnReceiveCallbacks with the
  186. // current key/value
  187. if (found) break;
  188. }
  189. if (!found) {
  190. delSetting(key);
  191. continue;
  192. }
  193. // Store values
  194. if (value.is<JsonArray&>()) {
  195. if (_wsStore(key, value.as<JsonArray&>())) changed = true;
  196. } else {
  197. if (_wsStore(key, value.as<String>())) changed = true;
  198. }
  199. // Update flags if value has changed
  200. if (changed) {
  201. save = true;
  202. #if MQTT_SUPPORT
  203. if (key.startsWith("mqtt")) changedMQTT = true;
  204. #endif
  205. }
  206. }
  207. // Save settings
  208. if (save) {
  209. // Callbacks
  210. espurnaReload();
  211. // This should got to callback as well
  212. // but first change management has to be in place
  213. #if MQTT_SUPPORT
  214. if (changedMQTT) mqttReset();
  215. #endif
  216. // Persist settings
  217. saveSettings();
  218. wsSend_P(client_id, PSTR("{\"message\": 8}"));
  219. } else {
  220. wsSend_P(client_id, PSTR("{\"message\": 9}"));
  221. }
  222. }
  223. }
  224. void _wsUpdate(JsonObject& root) {
  225. root["heap"] = getFreeHeap();
  226. root["uptime"] = getUptime();
  227. root["rssi"] = WiFi.RSSI();
  228. root["loadaverage"] = systemLoadAverage();
  229. #if ADC_MODE_VALUE == ADC_VCC
  230. root["vcc"] = ESP.getVcc();
  231. #endif
  232. #if NTP_SUPPORT
  233. if (ntpSynced()) root["now"] = now();
  234. #endif
  235. }
  236. void _wsDoUpdate(bool reset = false) {
  237. static unsigned long last = 0;
  238. if (reset) {
  239. last = 0;
  240. return;
  241. }
  242. if (millis() - last > WS_UPDATE_INTERVAL) {
  243. last = millis();
  244. wsSend(_wsUpdate);
  245. }
  246. }
  247. bool _wsOnReceive(const char * key, JsonVariant& value) {
  248. if (strncmp(key, "ws", 2) == 0) return true;
  249. if (strncmp(key, "admin", 5) == 0) return true;
  250. if (strncmp(key, "hostname", 8) == 0) return true;
  251. if (strncmp(key, "desc", 4) == 0) return true;
  252. if (strncmp(key, "webPort", 7) == 0) return true;
  253. return false;
  254. }
  255. void _wsOnStart(JsonObject& root) {
  256. char chipid[7];
  257. snprintf_P(chipid, sizeof(chipid), PSTR("%06X"), ESP.getChipId());
  258. uint8_t * bssid = WiFi.BSSID();
  259. char bssid_str[20];
  260. snprintf_P(bssid_str, sizeof(bssid_str),
  261. PSTR("%02X:%02X:%02X:%02X:%02X:%02X"),
  262. bssid[0], bssid[1], bssid[2], bssid[3], bssid[4], bssid[5]
  263. );
  264. root["webMode"] = WEB_MODE_NORMAL;
  265. root["app_name"] = APP_NAME;
  266. root["app_version"] = APP_VERSION;
  267. root["app_build"] = buildTime();
  268. #if defined(APP_REVISION)
  269. root["app_revision"] = APP_REVISION;
  270. #endif
  271. root["manufacturer"] = MANUFACTURER;
  272. root["chipid"] = String(chipid);
  273. root["mac"] = WiFi.macAddress();
  274. root["bssid"] = String(bssid_str);
  275. root["channel"] = WiFi.channel();
  276. root["device"] = DEVICE;
  277. root["hostname"] = getSetting("hostname");
  278. root["desc"] = getSetting("desc");
  279. root["network"] = getNetwork();
  280. root["deviceip"] = getIP();
  281. root["sketch_size"] = ESP.getSketchSize();
  282. root["free_size"] = ESP.getFreeSketchSpace();
  283. root["sdk"] = ESP.getSdkVersion();
  284. root["core"] = getCoreVersion();
  285. root["btnDelay"] = getSetting("btnDelay", BUTTON_DBLCLICK_DELAY).toInt();
  286. root["webPort"] = getSetting("webPort", WEB_PORT).toInt();
  287. root["wsAuth"] = getSetting("wsAuth", WS_AUTHENTICATION).toInt() == 1;
  288. #if TERMINAL_SUPPORT
  289. root["cmdVisible"] = 1;
  290. #endif
  291. root["hbMode"] = getSetting("hbMode", HEARTBEAT_MODE).toInt();
  292. root["hbInterval"] = getSetting("hbInterval", HEARTBEAT_INTERVAL).toInt();
  293. _wsDoUpdate(true);
  294. }
  295. void wsSend(JsonObject& root) {
  296. size_t len = root.measureLength();
  297. AsyncWebSocketMessageBuffer* buffer = _ws.makeBuffer(len);
  298. if (buffer) {
  299. root.printTo(reinterpret_cast<char*>(buffer->get()), len + 1);
  300. _ws.textAll(buffer);
  301. }
  302. }
  303. void wsSend(uint32_t client_id, JsonObject& root) {
  304. AsyncWebSocketClient* client = _ws.client(client_id);
  305. if (client == nullptr) return;
  306. size_t len = root.measureLength();
  307. AsyncWebSocketMessageBuffer* buffer = _ws.makeBuffer(len);
  308. if (buffer) {
  309. root.printTo(reinterpret_cast<char*>(buffer->get()), len + 1);
  310. client->text(buffer);
  311. }
  312. }
  313. void _wsStart(uint32_t client_id) {
  314. #if USE_PASSWORD && WEB_FORCE_PASS_CHANGE
  315. bool changePassword = getAdminPass().equals(ADMIN_PASS);
  316. #else
  317. bool changePassword = false;
  318. #endif
  319. DynamicJsonBuffer jsonBuffer;
  320. JsonObject& root = jsonBuffer.createObject();
  321. if (changePassword) {
  322. root["webMode"] = WEB_MODE_PASSWORD;
  323. wsSend(root);
  324. return;
  325. }
  326. for (auto& callback : _ws_on_send_callbacks) {
  327. callback(root);
  328. }
  329. wsSend(client_id, root);
  330. }
  331. void _wsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){
  332. if (type == WS_EVT_CONNECT) {
  333. client->_tempObject = nullptr;
  334. #ifndef NOWSAUTH
  335. if (!_wsAuth(client)) {
  336. wsSend_P(client->id(), PSTR("{\"message\": 10}"));
  337. DEBUG_MSG_P(PSTR("[WEBSOCKET] Validation check failed\n"));
  338. client->close();
  339. return;
  340. }
  341. #endif
  342. IPAddress ip = client->remoteIP();
  343. 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());
  344. _wsStart(client->id());
  345. client->_tempObject = new WebSocketIncommingBuffer(&_wsParse, true);
  346. wifiReconnectCheck();
  347. } else if(type == WS_EVT_DISCONNECT) {
  348. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u disconnected\n"), client->id());
  349. if (client->_tempObject) {
  350. delete (WebSocketIncommingBuffer *) client->_tempObject;
  351. }
  352. wifiReconnectCheck();
  353. } else if(type == WS_EVT_ERROR) {
  354. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u error(%u): %s\n"), client->id(), *((uint16_t*)arg), (char*)data);
  355. } else if(type == WS_EVT_PONG) {
  356. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u pong(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  357. } else if(type == WS_EVT_DATA) {
  358. //DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u data(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  359. WebSocketIncommingBuffer *buffer = (WebSocketIncommingBuffer *)client->_tempObject;
  360. AwsFrameInfo * info = (AwsFrameInfo*)arg;
  361. buffer->data_event(client, info, data, len);
  362. }
  363. }
  364. void _wsLoop() {
  365. if (!wsConnected()) return;
  366. _wsDoUpdate();
  367. }
  368. // -----------------------------------------------------------------------------
  369. // Public API
  370. // -----------------------------------------------------------------------------
  371. bool wsConnected() {
  372. return (_ws.count() > 0);
  373. }
  374. bool wsConnected(uint32_t client_id) {
  375. return _ws.hasClient(client_id);
  376. }
  377. void wsOnSendRegister(ws_on_send_callback_f callback) {
  378. _ws_on_send_callbacks.push_back(callback);
  379. }
  380. void wsOnReceiveRegister(ws_on_receive_callback_f callback) {
  381. _ws_on_receive_callbacks.push_back(callback);
  382. }
  383. void wsOnActionRegister(ws_on_action_callback_f callback) {
  384. _ws_on_action_callbacks.push_back(callback);
  385. }
  386. void wsSend(ws_on_send_callback_f callback) {
  387. if (_ws.count() > 0) {
  388. DynamicJsonBuffer jsonBuffer;
  389. JsonObject& root = jsonBuffer.createObject();
  390. callback(root);
  391. wsSend(root);
  392. }
  393. }
  394. void wsSend(const char * payload) {
  395. if (_ws.count() > 0) {
  396. _ws.textAll(payload);
  397. }
  398. }
  399. void wsSend_P(PGM_P payload) {
  400. if (_ws.count() > 0) {
  401. char buffer[strlen_P(payload)];
  402. strcpy_P(buffer, payload);
  403. _ws.textAll(buffer);
  404. }
  405. }
  406. void wsSend(uint32_t client_id, ws_on_send_callback_f callback) {
  407. AsyncWebSocketClient* client = _ws.client(client_id);
  408. if (client == nullptr) return;
  409. DynamicJsonBuffer jsonBuffer;
  410. JsonObject& root = jsonBuffer.createObject();
  411. callback(root);
  412. size_t len = root.measureLength();
  413. AsyncWebSocketMessageBuffer* buffer = _ws.makeBuffer(len);
  414. if (buffer) {
  415. root.printTo(reinterpret_cast<char*>(buffer->get()), len + 1);
  416. client->text(buffer);
  417. }
  418. }
  419. void wsSend(uint32_t client_id, const char * payload) {
  420. _ws.text(client_id, payload);
  421. }
  422. void wsSend_P(uint32_t client_id, PGM_P payload) {
  423. char buffer[strlen_P(payload)];
  424. strcpy_P(buffer, payload);
  425. _ws.text(client_id, buffer);
  426. }
  427. void wsSetup() {
  428. _ws.onEvent(_wsEvent);
  429. webServer()->addHandler(&_ws);
  430. // CORS
  431. #ifdef WEB_REMOTE_DOMAIN
  432. DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin", WEB_REMOTE_DOMAIN);
  433. DefaultHeaders::Instance().addHeader("Access-Control-Allow-Credentials", "true");
  434. #endif
  435. webServer()->on("/auth", HTTP_GET, _onAuth);
  436. #if MQTT_SUPPORT
  437. mqttRegister(_wsMQTTCallback);
  438. #endif
  439. wsOnSendRegister(_wsOnStart);
  440. wsOnReceiveRegister(_wsOnReceive);
  441. espurnaRegisterLoop(_wsLoop);
  442. }
  443. #endif // WEB_SUPPORT