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.

446 lines
13 KiB

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