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.

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