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.

379 lines
11 KiB

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