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.

399 lines
11 KiB

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