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.

500 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. bool changePassword = getAdminPass().equals(ADMIN_PASS);
  233. #else
  234. bool changePassword = false;
  235. #endif
  236. if (changePassword) {
  237. root["webMode"] = WEB_MODE_PASSWORD;
  238. } else {
  239. char chipid[7];
  240. snprintf_P(chipid, sizeof(chipid), PSTR("%06X"), ESP.getChipId());
  241. uint8_t * bssid = WiFi.BSSID();
  242. char bssid_str[20];
  243. snprintf_P(bssid_str, sizeof(bssid_str),
  244. PSTR("%02X:%02X:%02X:%02X:%02X:%02X"),
  245. bssid[0], bssid[1], bssid[2], bssid[3], bssid[4], bssid[5]
  246. );
  247. root["webMode"] = WEB_MODE_NORMAL;
  248. root["app_name"] = APP_NAME;
  249. root["app_version"] = APP_VERSION;
  250. root["app_build"] = buildTime();
  251. #if defined(APP_REVISION)
  252. root["app_revision"] = APP_REVISION;
  253. #endif
  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 wsSend(ws_on_send_callback_f callback) {
  332. if (_ws.count() > 0) {
  333. DynamicJsonBuffer jsonBuffer;
  334. JsonObject& root = jsonBuffer.createObject();
  335. callback(root);
  336. String output;
  337. root.printTo(output);
  338. jsonBuffer.clear();
  339. _ws.textAll((char *) output.c_str());
  340. }
  341. }
  342. void wsSend(const char * payload) {
  343. if (_ws.count() > 0) {
  344. _ws.textAll(payload);
  345. }
  346. }
  347. void wsSend_P(PGM_P payload) {
  348. if (_ws.count() > 0) {
  349. char buffer[strlen_P(payload)];
  350. strcpy_P(buffer, payload);
  351. _ws.textAll(buffer);
  352. }
  353. }
  354. void wsSend(uint32_t client_id, ws_on_send_callback_f callback) {
  355. DynamicJsonBuffer jsonBuffer;
  356. JsonObject& root = jsonBuffer.createObject();
  357. callback(root);
  358. String output;
  359. root.printTo(output);
  360. jsonBuffer.clear();
  361. _ws.text(client_id, (char *) output.c_str());
  362. }
  363. void wsSend(uint32_t client_id, const char * payload) {
  364. _ws.text(client_id, payload);
  365. }
  366. void wsSend_P(uint32_t client_id, PGM_P payload) {
  367. char buffer[strlen_P(payload)];
  368. strcpy_P(buffer, payload);
  369. _ws.text(client_id, buffer);
  370. }
  371. void wsSetup() {
  372. _ws.onEvent(_wsEvent);
  373. webServer()->addHandler(&_ws);
  374. // CORS
  375. #ifdef WEB_REMOTE_DOMAIN
  376. DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin", WEB_REMOTE_DOMAIN);
  377. DefaultHeaders::Instance().addHeader("Access-Control-Allow-Credentials", "true");
  378. #endif
  379. webServer()->on("/auth", HTTP_GET, _onAuth);
  380. #if MQTT_SUPPORT
  381. mqttRegister(_wsMQTTCallback);
  382. #endif
  383. wsOnSendRegister(_wsOnStart);
  384. wsOnReceiveRegister(_wsOnReceive);
  385. espurnaRegisterLoop(_wsLoop);
  386. }
  387. #endif // WEB_SUPPORT