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.

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