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.

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