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.

513 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, "desc", 4) == 0) return true;
  226. if (strncmp(key, "webPort", 7) == 0) return true;
  227. return false;
  228. }
  229. void _wsOnStart(JsonObject& root) {
  230. #if USE_PASSWORD && WEB_FORCE_PASS_CHANGE
  231. bool changePassword = getAdminPass().equals(ADMIN_PASS);
  232. #else
  233. bool changePassword = false;
  234. #endif
  235. if (changePassword) {
  236. root["webMode"] = WEB_MODE_PASSWORD;
  237. } else {
  238. char chipid[7];
  239. snprintf_P(chipid, sizeof(chipid), PSTR("%06X"), ESP.getChipId());
  240. uint8_t * bssid = WiFi.BSSID();
  241. char bssid_str[20];
  242. snprintf_P(bssid_str, sizeof(bssid_str),
  243. PSTR("%02X:%02X:%02X:%02X:%02X:%02X"),
  244. bssid[0], bssid[1], bssid[2], bssid[3], bssid[4], bssid[5]
  245. );
  246. root["webMode"] = WEB_MODE_NORMAL;
  247. root["app_name"] = APP_NAME;
  248. root["app_version"] = APP_VERSION;
  249. root["app_build"] = buildTime();
  250. #if defined(APP_REVISION)
  251. root["app_revision"] = APP_REVISION;
  252. #endif
  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["desc"] = getSetting("desc");
  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. root["hbMode"] = getSetting("hbMode", HEARTBEAT_MODE).toInt();
  275. root["hbInterval"] = getSetting("hbInterval", HEARTBEAT_INTERVAL).toInt();
  276. }
  277. }
  278. void _wsStart(uint32_t client_id) {
  279. for (unsigned char i = 0; i < _ws_on_send_callbacks.size(); i++) {
  280. wsSend(client_id, _ws_on_send_callbacks[i]);
  281. }
  282. }
  283. void _wsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){
  284. if (type == WS_EVT_CONNECT) {
  285. client->_tempObject = nullptr;
  286. #ifndef NOWSAUTH
  287. if (!_wsAuth(client)) {
  288. wsSend_P(client->id(), PSTR("{\"message\": 10}"));
  289. DEBUG_MSG_P(PSTR("[WEBSOCKET] Validation check failed\n"));
  290. client->close();
  291. return;
  292. }
  293. #endif
  294. IPAddress ip = client->remoteIP();
  295. 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());
  296. _wsStart(client->id());
  297. client->_tempObject = new WebSocketIncommingBuffer(&_wsParse, true);
  298. wifiReconnectCheck();
  299. } else if(type == WS_EVT_DISCONNECT) {
  300. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u disconnected\n"), client->id());
  301. if (client->_tempObject) {
  302. delete (WebSocketIncommingBuffer *) client->_tempObject;
  303. }
  304. wifiReconnectCheck();
  305. } else if(type == WS_EVT_ERROR) {
  306. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u error(%u): %s\n"), client->id(), *((uint16_t*)arg), (char*)data);
  307. } else if(type == WS_EVT_PONG) {
  308. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u pong(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  309. } else if(type == WS_EVT_DATA) {
  310. //DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u data(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  311. WebSocketIncommingBuffer *buffer = (WebSocketIncommingBuffer *)client->_tempObject;
  312. AwsFrameInfo * info = (AwsFrameInfo*)arg;
  313. buffer->data_event(client, info, data, len);
  314. }
  315. }
  316. void _wsLoop() {
  317. static unsigned long last = 0;
  318. if (!wsConnected()) return;
  319. if (millis() - last > WS_UPDATE_INTERVAL) {
  320. last = millis();
  321. wsSend(_wsUpdate);
  322. }
  323. }
  324. // -----------------------------------------------------------------------------
  325. // Public API
  326. // -----------------------------------------------------------------------------
  327. bool wsConnected() {
  328. return (_ws.count() > 0);
  329. }
  330. bool wsConnected(uint32_t client_id) {
  331. return _ws.hasClient(client_id);
  332. }
  333. void wsOnSendRegister(ws_on_send_callback_f callback) {
  334. _ws_on_send_callbacks.push_back(callback);
  335. }
  336. void wsOnReceiveRegister(ws_on_receive_callback_f callback) {
  337. _ws_on_receive_callbacks.push_back(callback);
  338. }
  339. void wsOnActionRegister(ws_on_action_callback_f callback) {
  340. _ws_on_action_callbacks.push_back(callback);
  341. }
  342. void wsSend(ws_on_send_callback_f callback) {
  343. if (_ws.count() > 0) {
  344. DynamicJsonBuffer jsonBuffer;
  345. JsonObject& root = jsonBuffer.createObject();
  346. callback(root);
  347. String output;
  348. root.printTo(output);
  349. jsonBuffer.clear();
  350. _ws.textAll((char *) output.c_str());
  351. }
  352. }
  353. void wsSend(const char * payload) {
  354. if (_ws.count() > 0) {
  355. _ws.textAll(payload);
  356. }
  357. }
  358. void wsSend_P(PGM_P payload) {
  359. if (_ws.count() > 0) {
  360. char buffer[strlen_P(payload)];
  361. strcpy_P(buffer, payload);
  362. _ws.textAll(buffer);
  363. }
  364. }
  365. void wsSend(uint32_t client_id, ws_on_send_callback_f callback) {
  366. DynamicJsonBuffer jsonBuffer;
  367. JsonObject& root = jsonBuffer.createObject();
  368. callback(root);
  369. String output;
  370. root.printTo(output);
  371. jsonBuffer.clear();
  372. _ws.text(client_id, (char *) output.c_str());
  373. }
  374. void wsSend(uint32_t client_id, const char * payload) {
  375. _ws.text(client_id, payload);
  376. }
  377. void wsSend_P(uint32_t client_id, PGM_P payload) {
  378. char buffer[strlen_P(payload)];
  379. strcpy_P(buffer, payload);
  380. _ws.text(client_id, buffer);
  381. }
  382. void wsSetup() {
  383. _ws.onEvent(_wsEvent);
  384. webServer()->addHandler(&_ws);
  385. // CORS
  386. #ifdef WEB_REMOTE_DOMAIN
  387. DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin", WEB_REMOTE_DOMAIN);
  388. DefaultHeaders::Instance().addHeader("Access-Control-Allow-Credentials", "true");
  389. #endif
  390. webServer()->on("/auth", HTTP_GET, _onAuth);
  391. #if MQTT_SUPPORT
  392. mqttRegister(_wsMQTTCallback);
  393. #endif
  394. wsOnSendRegister(_wsOnStart);
  395. wsOnReceiveRegister(_wsOnReceive);
  396. espurnaRegisterLoop(_wsLoop);
  397. }
  398. #endif // WEB_SUPPORT