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.

457 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. wsReload();
  160. // This should got to callback as well
  161. // but first change management has to be in place
  162. #if MQTT_SUPPORT
  163. if (changedMQTT) mqttReset();
  164. #endif
  165. // Persist settings
  166. saveSettings();
  167. wsSend_P(client_id, PSTR("{\"message\": 8}"));
  168. } else {
  169. wsSend_P(client_id, PSTR("{\"message\": 9}"));
  170. }
  171. }
  172. }
  173. void _wsUpdate(JsonObject& root) {
  174. root["heap"] = getFreeHeap();
  175. root["uptime"] = getUptime();
  176. root["rssi"] = WiFi.RSSI();
  177. root["loadaverage"] = systemLoadAverage();
  178. #if ADC_MODE_VALUE == ADC_VCC
  179. root["vcc"] = ESP.getVcc();
  180. #endif
  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. #if TERMINAL_SUPPORT
  233. root["cmdVisible"] = 1;
  234. #endif
  235. }
  236. }
  237. void _wsStart(uint32_t client_id) {
  238. for (unsigned char i = 0; i < _ws_on_send_callbacks.size(); i++) {
  239. wsSend(client_id, _ws_on_send_callbacks[i]);
  240. }
  241. }
  242. void _wsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){
  243. if (type == WS_EVT_CONNECT) {
  244. IPAddress ip = client->remoteIP();
  245. 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());
  246. _wsStart(client->id());
  247. client->_tempObject = new WebSocketIncommingBuffer(&_wsParse, true);
  248. wifiReconnectCheck();
  249. } else if(type == WS_EVT_DISCONNECT) {
  250. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u disconnected\n"), client->id());
  251. if (client->_tempObject) {
  252. delete (WebSocketIncommingBuffer *) client->_tempObject;
  253. }
  254. wifiReconnectCheck();
  255. } else if(type == WS_EVT_ERROR) {
  256. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u error(%u): %s\n"), client->id(), *((uint16_t*)arg), (char*)data);
  257. } else if(type == WS_EVT_PONG) {
  258. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u pong(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  259. } else if(type == WS_EVT_DATA) {
  260. //DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u data(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  261. WebSocketIncommingBuffer *buffer = (WebSocketIncommingBuffer *)client->_tempObject;
  262. AwsFrameInfo * info = (AwsFrameInfo*)arg;
  263. buffer->data_event(client, info, data, len);
  264. }
  265. }
  266. void _wsLoop() {
  267. static unsigned long last = 0;
  268. if (!wsConnected()) return;
  269. if (millis() - last > WS_UPDATE_INTERVAL) {
  270. last = millis();
  271. wsSend(_wsUpdate);
  272. }
  273. }
  274. // -----------------------------------------------------------------------------
  275. // Public API
  276. // -----------------------------------------------------------------------------
  277. bool wsConnected() {
  278. return (_ws.count() > 0);
  279. }
  280. void wsOnSendRegister(ws_on_send_callback_f callback) {
  281. _ws_on_send_callbacks.push_back(callback);
  282. }
  283. void wsOnReceiveRegister(ws_on_receive_callback_f callback) {
  284. _ws_on_receive_callbacks.push_back(callback);
  285. }
  286. void wsOnActionRegister(ws_on_action_callback_f callback) {
  287. _ws_on_action_callbacks.push_back(callback);
  288. }
  289. void wsOnAfterParseRegister(ws_on_after_parse_callback_f callback) {
  290. _ws_on_after_parse_callbacks.push_back(callback);
  291. }
  292. void wsSend(ws_on_send_callback_f callback) {
  293. if (_ws.count() > 0) {
  294. DynamicJsonBuffer jsonBuffer;
  295. JsonObject& root = jsonBuffer.createObject();
  296. callback(root);
  297. String output;
  298. root.printTo(output);
  299. _ws.textAll((char *) output.c_str());
  300. }
  301. }
  302. void wsSend(const char * payload) {
  303. if (_ws.count() > 0) {
  304. _ws.textAll(payload);
  305. }
  306. }
  307. void wsSend_P(PGM_P payload) {
  308. if (_ws.count() > 0) {
  309. char buffer[strlen_P(payload)];
  310. strcpy_P(buffer, payload);
  311. _ws.textAll(buffer);
  312. }
  313. }
  314. void wsSend(uint32_t client_id, ws_on_send_callback_f callback) {
  315. DynamicJsonBuffer jsonBuffer;
  316. JsonObject& root = jsonBuffer.createObject();
  317. callback(root);
  318. String output;
  319. root.printTo(output);
  320. _ws.text(client_id, (char *) output.c_str());
  321. }
  322. void wsSend(uint32_t client_id, const char * payload) {
  323. _ws.text(client_id, payload);
  324. }
  325. void wsSend_P(uint32_t client_id, PGM_P payload) {
  326. char buffer[strlen_P(payload)];
  327. strcpy_P(buffer, payload);
  328. _ws.text(client_id, buffer);
  329. }
  330. void wsConfigure() {
  331. #if USE_PASSWORD
  332. bool auth = getSetting("wsAuth", WS_AUTHENTICATION).toInt() == 1;
  333. if (auth) {
  334. _ws.setAuthentication(WEB_USERNAME, (const char *) getSetting("adminPass", ADMIN_PASS).c_str());
  335. } else {
  336. _ws.setAuthentication("", "");
  337. }
  338. #endif
  339. }
  340. // This method being public makes
  341. // _ws_on_after_parse_callbacks strange here,
  342. // it should belong somewhere else.
  343. void wsReload() {
  344. for (unsigned char i = 0; i < _ws_on_after_parse_callbacks.size(); i++) {
  345. (_ws_on_after_parse_callbacks[i])();
  346. }
  347. }
  348. void wsSetup() {
  349. _ws.onEvent(_wsEvent);
  350. wsConfigure();
  351. webServer()->addHandler(&_ws);
  352. #if MQTT_SUPPORT
  353. mqttRegister(_wsMQTTCallback);
  354. #endif
  355. wsOnSendRegister(_wsOnStart);
  356. wsOnReceiveRegister(_wsOnReceive);
  357. wsOnAfterParseRegister(wsConfigure);
  358. espurnaRegisterLoop(_wsLoop);
  359. }
  360. #endif // WEB_SUPPORT