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.

437 lines
13 KiB

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