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.

503 lines
14 KiB

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