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.

423 lines
13 KiB

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