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.

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