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.

420 lines
12 KiB

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