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.

507 lines
14 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 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. root["hbMode"] = getSetting("hbMode", HEARTBEAT_MODE).toInt();
  273. root["hbInterval"] = getSetting("hbInterval", HEARTBEAT_INTERVAL).toInt();
  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. client->_tempObject = nullptr;
  284. #ifndef NOWSAUTH
  285. if (!_wsAuth(client)) {
  286. wsSend_P(client->id(), PSTR("{\"message\": 10}"));
  287. DEBUG_MSG_P(PSTR("[WEBSOCKET] Validation check failed\n"));
  288. client->close();
  289. return;
  290. }
  291. #endif
  292. IPAddress ip = client->remoteIP();
  293. 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());
  294. _wsStart(client->id());
  295. client->_tempObject = new WebSocketIncommingBuffer(&_wsParse, true);
  296. wifiReconnectCheck();
  297. } else if(type == WS_EVT_DISCONNECT) {
  298. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u disconnected\n"), client->id());
  299. if (client->_tempObject) {
  300. delete (WebSocketIncommingBuffer *) client->_tempObject;
  301. }
  302. wifiReconnectCheck();
  303. } else if(type == WS_EVT_ERROR) {
  304. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u error(%u): %s\n"), client->id(), *((uint16_t*)arg), (char*)data);
  305. } else if(type == WS_EVT_PONG) {
  306. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u pong(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  307. } else if(type == WS_EVT_DATA) {
  308. //DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u data(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  309. WebSocketIncommingBuffer *buffer = (WebSocketIncommingBuffer *)client->_tempObject;
  310. AwsFrameInfo * info = (AwsFrameInfo*)arg;
  311. buffer->data_event(client, info, data, len);
  312. }
  313. }
  314. void _wsLoop() {
  315. static unsigned long last = 0;
  316. if (!wsConnected()) return;
  317. if (millis() - last > WS_UPDATE_INTERVAL) {
  318. last = millis();
  319. wsSend(_wsUpdate);
  320. }
  321. }
  322. // -----------------------------------------------------------------------------
  323. // Public API
  324. // -----------------------------------------------------------------------------
  325. bool wsConnected() {
  326. return (_ws.count() > 0);
  327. }
  328. void wsOnSendRegister(ws_on_send_callback_f callback) {
  329. _ws_on_send_callbacks.push_back(callback);
  330. }
  331. void wsOnReceiveRegister(ws_on_receive_callback_f callback) {
  332. _ws_on_receive_callbacks.push_back(callback);
  333. }
  334. void wsOnActionRegister(ws_on_action_callback_f callback) {
  335. _ws_on_action_callbacks.push_back(callback);
  336. }
  337. void wsSend(ws_on_send_callback_f callback) {
  338. if (_ws.count() > 0) {
  339. DynamicJsonBuffer jsonBuffer;
  340. JsonObject& root = jsonBuffer.createObject();
  341. callback(root);
  342. String output;
  343. root.printTo(output);
  344. jsonBuffer.clear();
  345. _ws.textAll((char *) output.c_str());
  346. }
  347. }
  348. void wsSend(const char * payload) {
  349. if (_ws.count() > 0) {
  350. _ws.textAll(payload);
  351. }
  352. }
  353. void wsSend_P(PGM_P payload) {
  354. if (_ws.count() > 0) {
  355. char buffer[strlen_P(payload)];
  356. strcpy_P(buffer, payload);
  357. _ws.textAll(buffer);
  358. }
  359. }
  360. void wsSend(uint32_t client_id, ws_on_send_callback_f callback) {
  361. DynamicJsonBuffer jsonBuffer;
  362. JsonObject& root = jsonBuffer.createObject();
  363. callback(root);
  364. String output;
  365. root.printTo(output);
  366. jsonBuffer.clear();
  367. _ws.text(client_id, (char *) output.c_str());
  368. }
  369. void wsSend(uint32_t client_id, const char * payload) {
  370. _ws.text(client_id, payload);
  371. }
  372. void wsSend_P(uint32_t client_id, PGM_P payload) {
  373. char buffer[strlen_P(payload)];
  374. strcpy_P(buffer, payload);
  375. _ws.text(client_id, buffer);
  376. }
  377. void wsSetup() {
  378. _ws.onEvent(_wsEvent);
  379. webServer()->addHandler(&_ws);
  380. // CORS
  381. #ifdef WEB_REMOTE_DOMAIN
  382. DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin", WEB_REMOTE_DOMAIN);
  383. DefaultHeaders::Instance().addHeader("Access-Control-Allow-Credentials", "true");
  384. #endif
  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