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.

450 lines
13 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. 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. #if ADC_MODE_VALUE == ADC_VCC
  181. root["vcc"] = ESP.getVcc();
  182. #endif
  183. #if NTP_SUPPORT
  184. if (ntpSynced()) root["now"] = now();
  185. #endif
  186. }
  187. bool _wsOnReceive(const char * key, JsonVariant& value) {
  188. if (strncmp(key, "ws", 2) == 0) return true;
  189. if (strncmp(key, "admin", 5) == 0) return true;
  190. if (strncmp(key, "hostname", 8) == 0) return true;
  191. if (strncmp(key, "webPort", 7) == 0) return true;
  192. return false;
  193. }
  194. void _wsOnStart(JsonObject& root) {
  195. #if USE_PASSWORD && WEB_FORCE_PASS_CHANGE
  196. String adminPass = getSetting("adminPass", ADMIN_PASS);
  197. bool changePassword = adminPass.equals(ADMIN_PASS);
  198. #else
  199. bool changePassword = false;
  200. #endif
  201. if (changePassword) {
  202. root["webMode"] = WEB_MODE_PASSWORD;
  203. } else {
  204. char chipid[7];
  205. snprintf_P(chipid, sizeof(chipid), PSTR("%06X"), ESP.getChipId());
  206. uint8_t * bssid = WiFi.BSSID();
  207. char bssid_str[20];
  208. snprintf_P(bssid_str, sizeof(bssid_str),
  209. PSTR("%02X:%02X:%02X:%02X:%02X:%02X"),
  210. bssid[0], bssid[1], bssid[2], bssid[3], bssid[4], bssid[5]
  211. );
  212. root["webMode"] = WEB_MODE_NORMAL;
  213. root["app_name"] = APP_NAME;
  214. root["app_version"] = APP_VERSION;
  215. root["app_build"] = buildTime();
  216. root["app_revision"] = APP_REVISION;
  217. root["manufacturer"] = MANUFACTURER;
  218. root["chipid"] = String(chipid);
  219. root["mac"] = WiFi.macAddress();
  220. root["bssid"] = String(bssid_str);
  221. root["channel"] = WiFi.channel();
  222. root["device"] = DEVICE;
  223. root["hostname"] = getSetting("hostname");
  224. root["network"] = getNetwork();
  225. root["deviceip"] = getIP();
  226. root["sketch_size"] = ESP.getSketchSize();
  227. root["free_size"] = ESP.getFreeSketchSpace();
  228. root["sdk"] = ESP.getSdkVersion();
  229. root["core"] = getCoreVersion();
  230. _wsUpdate(root);
  231. root["btnDelay"] = getSetting("btnDelay", BUTTON_DBLCLICK_DELAY).toInt();
  232. root["webPort"] = getSetting("webPort", WEB_PORT).toInt();
  233. root["wsAuth"] = getSetting("wsAuth", WS_AUTHENTICATION).toInt() == 1;
  234. #if TERMINAL_SUPPORT
  235. root["cmdVisible"] = 1;
  236. #endif
  237. }
  238. }
  239. void _wsStart(uint32_t client_id) {
  240. for (unsigned char i = 0; i < _ws_on_send_callbacks.size(); i++) {
  241. wsSend(client_id, _ws_on_send_callbacks[i]);
  242. }
  243. }
  244. void _wsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){
  245. if (type == WS_EVT_CONNECT) {
  246. IPAddress ip = client->remoteIP();
  247. 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());
  248. _wsStart(client->id());
  249. client->_tempObject = new WebSocketIncommingBuffer(&_wsParse, true);
  250. wifiReconnectCheck();
  251. } else if(type == WS_EVT_DISCONNECT) {
  252. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u disconnected\n"), client->id());
  253. if (client->_tempObject) {
  254. delete (WebSocketIncommingBuffer *) client->_tempObject;
  255. }
  256. wifiReconnectCheck();
  257. } else if(type == WS_EVT_ERROR) {
  258. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u error(%u): %s\n"), client->id(), *((uint16_t*)arg), (char*)data);
  259. } else if(type == WS_EVT_PONG) {
  260. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u pong(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  261. } else if(type == WS_EVT_DATA) {
  262. //DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u data(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  263. WebSocketIncommingBuffer *buffer = (WebSocketIncommingBuffer *)client->_tempObject;
  264. AwsFrameInfo * info = (AwsFrameInfo*)arg;
  265. buffer->data_event(client, info, data, len);
  266. }
  267. }
  268. void _wsLoop() {
  269. static unsigned long last = 0;
  270. if (!wsConnected()) return;
  271. if (millis() - last > WS_UPDATE_INTERVAL) {
  272. last = millis();
  273. wsSend(_wsUpdate);
  274. }
  275. }
  276. // -----------------------------------------------------------------------------
  277. // Public API
  278. // -----------------------------------------------------------------------------
  279. bool wsConnected() {
  280. return (_ws.count() > 0);
  281. }
  282. void wsOnSendRegister(ws_on_send_callback_f callback) {
  283. _ws_on_send_callbacks.push_back(callback);
  284. }
  285. void wsOnReceiveRegister(ws_on_receive_callback_f callback) {
  286. _ws_on_receive_callbacks.push_back(callback);
  287. }
  288. void wsOnActionRegister(ws_on_action_callback_f callback) {
  289. _ws_on_action_callbacks.push_back(callback);
  290. }
  291. void wsOnAfterParseRegister(ws_on_after_parse_callback_f callback) {
  292. _ws_on_after_parse_callbacks.push_back(callback);
  293. }
  294. void wsSend(ws_on_send_callback_f callback) {
  295. if (_ws.count() > 0) {
  296. DynamicJsonBuffer jsonBuffer;
  297. JsonObject& root = jsonBuffer.createObject();
  298. callback(root);
  299. String output;
  300. root.printTo(output);
  301. _ws.textAll((char *) output.c_str());
  302. }
  303. }
  304. void wsSend(const char * payload) {
  305. if (_ws.count() > 0) {
  306. _ws.textAll(payload);
  307. }
  308. }
  309. void wsSend_P(PGM_P payload) {
  310. if (_ws.count() > 0) {
  311. char buffer[strlen_P(payload)];
  312. strcpy_P(buffer, payload);
  313. _ws.textAll(buffer);
  314. }
  315. }
  316. void wsSend(uint32_t client_id, ws_on_send_callback_f callback) {
  317. DynamicJsonBuffer jsonBuffer;
  318. JsonObject& root = jsonBuffer.createObject();
  319. callback(root);
  320. String output;
  321. root.printTo(output);
  322. _ws.text(client_id, (char *) output.c_str());
  323. }
  324. void wsSend(uint32_t client_id, const char * payload) {
  325. _ws.text(client_id, payload);
  326. }
  327. void wsSend_P(uint32_t client_id, PGM_P payload) {
  328. char buffer[strlen_P(payload)];
  329. strcpy_P(buffer, payload);
  330. _ws.text(client_id, buffer);
  331. }
  332. void wsConfigure() {
  333. #if USE_PASSWORD
  334. bool auth = getSetting("wsAuth", WS_AUTHENTICATION).toInt() == 1;
  335. if (auth) {
  336. _ws.setAuthentication(WEB_USERNAME, (const char *) getSetting("adminPass", ADMIN_PASS).c_str());
  337. } else {
  338. _ws.setAuthentication("", "");
  339. }
  340. #endif
  341. }
  342. void wsSetup() {
  343. _ws.onEvent(_wsEvent);
  344. wsConfigure();
  345. webServer()->addHandler(&_ws);
  346. #if MQTT_SUPPORT
  347. mqttRegister(_wsMQTTCallback);
  348. #endif
  349. wsOnSendRegister(_wsOnStart);
  350. wsOnReceiveRegister(_wsOnReceive);
  351. wsOnAfterParseRegister(wsConfigure);
  352. espurnaRegisterLoop(_wsLoop);
  353. }
  354. #endif // WEB_SUPPORT