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.

480 lines
13 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. Module key prefix: ws
  5. */
  6. #if WEB_SUPPORT
  7. #include <ESPAsyncTCP.h>
  8. #include <ESPAsyncWebServer.h>
  9. #include <ArduinoJson.h>
  10. #include <Ticker.h>
  11. #include <vector>
  12. #include "libs/WebSocketIncommingBuffer.h"
  13. AsyncWebSocket _ws("/ws");
  14. Ticker _web_defer;
  15. std::vector<ws_on_send_callback_f> _ws_on_send_callbacks;
  16. std::vector<ws_on_action_callback_f> _ws_on_action_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. if (!settingsKeyExists(key.c_str())) {
  170. delSetting(key);
  171. continue;
  172. }
  173. // Store values
  174. if (value.is<JsonArray&>()) {
  175. if (_wsStore(key, value.as<JsonArray&>())) changed = true;
  176. } else {
  177. if (_wsStore(key, value.as<String>())) changed = true;
  178. }
  179. // Update flags if value has changed
  180. if (changed) {
  181. save = true;
  182. #if MQTT_SUPPORT
  183. if (key.startsWith("mqtt")) changedMQTT = true;
  184. #endif
  185. }
  186. }
  187. // Save settings
  188. if (save) {
  189. // Callbacks
  190. espurnaReload();
  191. // This should got to callback as well
  192. // but first change management has to be in place
  193. #if MQTT_SUPPORT
  194. if (changedMQTT) mqttReset();
  195. #endif
  196. // Persist settings
  197. saveSettings();
  198. wsSend_P(client_id, PSTR("{\"message\": 8}"));
  199. } else {
  200. wsSend_P(client_id, PSTR("{\"message\": 9}"));
  201. }
  202. }
  203. }
  204. void _wsUpdate(JsonObject& root) {
  205. root["heap"] = getFreeHeap();
  206. root["uptime"] = getUptime();
  207. root["rssi"] = WiFi.RSSI();
  208. root["loadaverage"] = systemLoadAverage();
  209. #if ADC_MODE_VALUE == ADC_VCC
  210. root["vcc"] = ESP.getVcc();
  211. #endif
  212. #if NTP_SUPPORT
  213. if (ntpSynced()) root["now"] = now();
  214. #endif
  215. }
  216. bool _wsKeyCheck(const char * key) {
  217. return (strncmp(key, "ws", 2) == 0);
  218. }
  219. void _wsOnStart(JsonObject& root) {
  220. unsigned char web_mode = webMode();
  221. root["webMode"] = web_mode;
  222. if (WEB_MODE_NORMAL == web_mode) {
  223. char chipid[7];
  224. snprintf_P(chipid, sizeof(chipid), PSTR("%06X"), ESP.getChipId());
  225. uint8_t * bssid = WiFi.BSSID();
  226. char bssid_str[20];
  227. snprintf_P(bssid_str, sizeof(bssid_str),
  228. PSTR("%02X:%02X:%02X:%02X:%02X:%02X"),
  229. bssid[0], bssid[1], bssid[2], bssid[3], bssid[4], bssid[5]
  230. );
  231. root["app_name"] = APP_NAME;
  232. root["app_version"] = APP_VERSION;
  233. root["app_build"] = buildTime();
  234. #if defined(APP_REVISION)
  235. root["app_revision"] = APP_REVISION;
  236. #endif
  237. root["manufacturer"] = getManufacturer();
  238. root["chipid"] = String(chipid);
  239. root["mac"] = WiFi.macAddress();
  240. root["bssid"] = String(bssid_str);
  241. root["channel"] = WiFi.channel();
  242. root["device"] = getBoardName();
  243. root["hostname"] = getHostname();
  244. root["network"] = getNetwork();
  245. root["deviceip"] = getIP();
  246. root["sketch_size"] = ESP.getSketchSize();
  247. root["free_size"] = ESP.getFreeSketchSpace();
  248. root["sdk"] = ESP.getSdkVersion();
  249. root["core"] = getCoreVersion();
  250. _wsUpdate(root);
  251. root["wsAuth"] = getSetting("wsAuth", WS_AUTHENTICATION).toInt() == 1;
  252. #if TERMINAL_SUPPORT
  253. root["cmdVisible"] = 1;
  254. #endif
  255. }
  256. }
  257. void _wsStart(uint32_t client_id) {
  258. for (unsigned char i = 0; i < _ws_on_send_callbacks.size(); i++) {
  259. wsSend(client_id, _ws_on_send_callbacks[i]);
  260. }
  261. }
  262. void _wsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){
  263. if (type == WS_EVT_CONNECT) {
  264. #ifndef NOWSAUTH
  265. if (!_wsAuth(client)) return;
  266. #endif
  267. IPAddress ip = client->remoteIP();
  268. 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());
  269. _wsStart(client->id());
  270. client->_tempObject = new WebSocketIncommingBuffer(&_wsParse, true);
  271. wifiReconnectCheck();
  272. } else if(type == WS_EVT_DISCONNECT) {
  273. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u disconnected\n"), client->id());
  274. if (client->_tempObject) {
  275. delete (WebSocketIncommingBuffer *) client->_tempObject;
  276. }
  277. wifiReconnectCheck();
  278. } else if(type == WS_EVT_ERROR) {
  279. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u error(%u): %s\n"), client->id(), *((uint16_t*)arg), (char*)data);
  280. } else if(type == WS_EVT_PONG) {
  281. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u pong(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  282. } else if(type == WS_EVT_DATA) {
  283. //DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u data(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  284. WebSocketIncommingBuffer *buffer = (WebSocketIncommingBuffer *)client->_tempObject;
  285. AwsFrameInfo * info = (AwsFrameInfo*)arg;
  286. buffer->data_event(client, info, data, len);
  287. }
  288. }
  289. void _wsLoop() {
  290. static unsigned long last = 0;
  291. if (!wsConnected()) return;
  292. if (millis() - last > WS_UPDATE_INTERVAL) {
  293. last = millis();
  294. wsSend(_wsUpdate);
  295. }
  296. }
  297. // -----------------------------------------------------------------------------
  298. // Public API
  299. // -----------------------------------------------------------------------------
  300. bool wsConnected() {
  301. return (_ws.count() > 0);
  302. }
  303. void wsOnSendRegister(ws_on_send_callback_f callback) {
  304. _ws_on_send_callbacks.push_back(callback);
  305. }
  306. void wsOnActionRegister(ws_on_action_callback_f callback) {
  307. _ws_on_action_callbacks.push_back(callback);
  308. }
  309. void wsSend(ws_on_send_callback_f callback) {
  310. if (_ws.count() > 0) {
  311. DynamicJsonBuffer jsonBuffer;
  312. JsonObject& root = jsonBuffer.createObject();
  313. callback(root);
  314. String output;
  315. root.printTo(output);
  316. jsonBuffer.clear();
  317. _ws.textAll((char *) output.c_str());
  318. }
  319. }
  320. void wsSend(const char * payload) {
  321. if (_ws.count() > 0) {
  322. _ws.textAll(payload);
  323. }
  324. }
  325. void wsSend_P(PGM_P payload) {
  326. if (_ws.count() > 0) {
  327. char buffer[strlen_P(payload)];
  328. strcpy_P(buffer, payload);
  329. _ws.textAll(buffer);
  330. }
  331. }
  332. void wsSend(uint32_t client_id, ws_on_send_callback_f callback) {
  333. DynamicJsonBuffer jsonBuffer;
  334. JsonObject& root = jsonBuffer.createObject();
  335. callback(root);
  336. String output;
  337. root.printTo(output);
  338. jsonBuffer.clear();
  339. _ws.text(client_id, (char *) output.c_str());
  340. }
  341. void wsSend(uint32_t client_id, const char * payload) {
  342. _ws.text(client_id, payload);
  343. }
  344. void wsSend_P(uint32_t client_id, PGM_P payload) {
  345. char buffer[strlen_P(payload)];
  346. strcpy_P(buffer, payload);
  347. _ws.text(client_id, buffer);
  348. }
  349. void wsSetup() {
  350. _ws.onEvent(_wsEvent);
  351. webServer()->addHandler(&_ws);
  352. // CORS
  353. #ifdef WEB_REMOTE_DOMAIN
  354. DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin", WEB_REMOTE_DOMAIN);
  355. DefaultHeaders::Instance().addHeader("Access-Control-Allow-Credentials", "true");
  356. #endif
  357. webServer()->on("/auth", HTTP_GET, _onAuth);
  358. #if MQTT_SUPPORT
  359. mqttRegister(_wsMQTTCallback);
  360. #endif
  361. wsOnSendRegister(_wsOnStart);
  362. settingsRegisterKeyCheck(_wsKeyCheck);
  363. espurnaRegisterLoop(_wsLoop);
  364. }
  365. #endif // WEB_SUPPORT