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.

445 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. }
  233. }
  234. void _wsStart(uint32_t client_id) {
  235. for (unsigned char i = 0; i < _ws_on_send_callbacks.size(); i++) {
  236. wsSend(client_id, _ws_on_send_callbacks[i]);
  237. }
  238. }
  239. void _wsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){
  240. if (type == WS_EVT_CONNECT) {
  241. IPAddress ip = client->remoteIP();
  242. 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());
  243. _wsStart(client->id());
  244. client->_tempObject = new WebSocketIncommingBuffer(&_wsParse, true);
  245. wifiReconnectCheck();
  246. } else if(type == WS_EVT_DISCONNECT) {
  247. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u disconnected\n"), client->id());
  248. if (client->_tempObject) {
  249. delete (WebSocketIncommingBuffer *) client->_tempObject;
  250. }
  251. wifiReconnectCheck();
  252. } else if(type == WS_EVT_ERROR) {
  253. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u error(%u): %s\n"), client->id(), *((uint16_t*)arg), (char*)data);
  254. } else if(type == WS_EVT_PONG) {
  255. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u pong(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  256. } else if(type == WS_EVT_DATA) {
  257. //DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u data(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  258. WebSocketIncommingBuffer *buffer = (WebSocketIncommingBuffer *)client->_tempObject;
  259. AwsFrameInfo * info = (AwsFrameInfo*)arg;
  260. buffer->data_event(client, info, data, len);
  261. }
  262. }
  263. void _wsLoop() {
  264. static unsigned long last = 0;
  265. if (!wsConnected()) return;
  266. if (millis() - last > WS_UPDATE_INTERVAL) {
  267. last = millis();
  268. wsSend(_wsUpdate);
  269. }
  270. }
  271. // -----------------------------------------------------------------------------
  272. // Public API
  273. // -----------------------------------------------------------------------------
  274. bool wsConnected() {
  275. return (_ws.count() > 0);
  276. }
  277. void wsOnSendRegister(ws_on_send_callback_f callback) {
  278. _ws_on_send_callbacks.push_back(callback);
  279. }
  280. void wsOnReceiveRegister(ws_on_receive_callback_f callback) {
  281. _ws_on_receive_callbacks.push_back(callback);
  282. }
  283. void wsOnActionRegister(ws_on_action_callback_f callback) {
  284. _ws_on_action_callbacks.push_back(callback);
  285. }
  286. void wsOnAfterParseRegister(ws_on_after_parse_callback_f callback) {
  287. _ws_on_after_parse_callbacks.push_back(callback);
  288. }
  289. void wsSend(ws_on_send_callback_f callback) {
  290. if (_ws.count() > 0) {
  291. DynamicJsonBuffer jsonBuffer;
  292. JsonObject& root = jsonBuffer.createObject();
  293. callback(root);
  294. String output;
  295. root.printTo(output);
  296. _ws.textAll((char *) output.c_str());
  297. }
  298. }
  299. void wsSend(const char * payload) {
  300. if (_ws.count() > 0) {
  301. _ws.textAll(payload);
  302. }
  303. }
  304. void wsSend_P(PGM_P payload) {
  305. if (_ws.count() > 0) {
  306. char buffer[strlen_P(payload)];
  307. strcpy_P(buffer, payload);
  308. _ws.textAll(buffer);
  309. }
  310. }
  311. void wsSend(uint32_t client_id, ws_on_send_callback_f callback) {
  312. DynamicJsonBuffer jsonBuffer;
  313. JsonObject& root = jsonBuffer.createObject();
  314. callback(root);
  315. String output;
  316. root.printTo(output);
  317. _ws.text(client_id, (char *) output.c_str());
  318. }
  319. void wsSend(uint32_t client_id, const char * payload) {
  320. _ws.text(client_id, payload);
  321. }
  322. void wsSend_P(uint32_t client_id, PGM_P payload) {
  323. char buffer[strlen_P(payload)];
  324. strcpy_P(buffer, payload);
  325. _ws.text(client_id, buffer);
  326. }
  327. void wsConfigure() {
  328. #if USE_PASSWORD
  329. bool auth = getSetting("wsAuth", WS_AUTHENTICATION).toInt() == 1;
  330. if (auth) {
  331. _ws.setAuthentication(WEB_USERNAME, (const char *) getSetting("adminPass", ADMIN_PASS).c_str());
  332. } else {
  333. _ws.setAuthentication("", "");
  334. }
  335. #endif
  336. }
  337. void wsSetup() {
  338. _ws.onEvent(_wsEvent);
  339. wsConfigure();
  340. webServer()->addHandler(&_ws);
  341. #if MQTT_SUPPORT
  342. mqttRegister(_wsMQTTCallback);
  343. #endif
  344. wsOnSendRegister(_wsOnStart);
  345. wsOnReceiveRegister(_wsOnReceive);
  346. wsOnAfterParseRegister(wsConfigure);
  347. espurnaRegisterLoop(_wsLoop);
  348. }
  349. #endif // WEB_SUPPORT