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.

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