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.

413 lines
12 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. setSetting(key, value);
  165. save = changed = true;
  166. if (key.startsWith("mqtt")) changedMQTT = true;
  167. }
  168. }
  169. if (webMode == WEB_MODE_NORMAL) {
  170. if (wifiClean(network)) save = changed = true;
  171. }
  172. // Save settings
  173. if (save) {
  174. // Callbacks
  175. for (unsigned char i = 0; i < _ws_on_after_parse_callbacks.size(); i++) {
  176. (_ws_on_after_parse_callbacks[i])();
  177. }
  178. // This should got to callback as well
  179. // but first change management has to be in place
  180. if (changedMQTT) {
  181. mqttConfigure();
  182. mqttDisconnect();
  183. }
  184. // Persist settings
  185. saveSettings();
  186. }
  187. if (changed) {
  188. wsSend_P(client_id, PSTR("{\"message\": 8}"));
  189. } else {
  190. wsSend_P(client_id, PSTR("{\"message\": 9}"));
  191. }
  192. }
  193. }
  194. void _wsStart(uint32_t client_id) {
  195. DynamicJsonBuffer jsonBuffer;
  196. JsonObject& root = jsonBuffer.createObject();
  197. bool changePassword = false;
  198. #if WEB_FORCE_PASS_CHANGE
  199. String adminPass = getSetting("adminPass", ADMIN_PASS);
  200. if (adminPass.equals(ADMIN_PASS)) changePassword = true;
  201. #endif
  202. if (changePassword) {
  203. root["webMode"] = WEB_MODE_PASSWORD;
  204. } else {
  205. char chipid[7];
  206. snprintf_P(chipid, sizeof(chipid), PSTR("%06X"), ESP.getChipId());
  207. root["webMode"] = WEB_MODE_NORMAL;
  208. root["app_name"] = APP_NAME;
  209. root["app_version"] = APP_VERSION;
  210. root["app_build"] = buildTime();
  211. root["manufacturer"] = MANUFACTURER;
  212. root["chipid"] = chipid;
  213. root["mac"] = WiFi.macAddress();
  214. root["device"] = DEVICE;
  215. root["hostname"] = getSetting("hostname");
  216. root["network"] = getNetwork();
  217. root["deviceip"] = getIP();
  218. root["uptime"] = getUptime();
  219. root["heap"] = ESP.getFreeHeap();
  220. root["sketch_size"] = ESP.getSketchSize();
  221. root["free_size"] = ESP.getFreeSketchSpace();
  222. root["btnDelay"] = getSetting("btnDelay", BUTTON_DBLCLICK_DELAY).toInt();
  223. root["webPort"] = getSetting("webPort", WEB_PORT).toInt();
  224. root["tmpUnits"] = getSetting("tmpUnits", TMP_UNITS).toInt();
  225. root["tmpCorrection"] = getSetting("tmpCorrection", TMP_CORRECTION).toFloat();
  226. // Callbacks
  227. for (unsigned char i = 0; i < _ws_on_send_callbacks.size(); i++) {
  228. (_ws_on_send_callbacks[i])(root);
  229. }
  230. }
  231. String output;
  232. root.printTo(output);
  233. wsSend(client_id, (char *) output.c_str());
  234. }
  235. void _wsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){
  236. if (type == WS_EVT_CONNECT) {
  237. IPAddress ip = client->remoteIP();
  238. 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());
  239. _wsStart(client->id());
  240. client->_tempObject = new WebSocketIncommingBuffer(&_wsParse, true);
  241. wifiReconnectCheck();
  242. } else if(type == WS_EVT_DISCONNECT) {
  243. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u disconnected\n"), client->id());
  244. if (client->_tempObject) {
  245. delete (WebSocketIncommingBuffer *) client->_tempObject;
  246. }
  247. wifiReconnectCheck();
  248. } else if(type == WS_EVT_ERROR) {
  249. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u error(%u): %s\n"), client->id(), *((uint16_t*)arg), (char*)data);
  250. } else if(type == WS_EVT_PONG) {
  251. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u pong(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  252. } else if(type == WS_EVT_DATA) {
  253. //DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u data(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  254. WebSocketIncommingBuffer *buffer = (WebSocketIncommingBuffer *)client->_tempObject;
  255. AwsFrameInfo * info = (AwsFrameInfo*)arg;
  256. buffer->data_event(client, info, data, len);
  257. }
  258. }
  259. // -----------------------------------------------------------------------------
  260. // Piblic API
  261. // -----------------------------------------------------------------------------
  262. bool wsConnected() {
  263. return (_ws.count() > 0);
  264. }
  265. void wsOnSendRegister(ws_on_send_callback_f callback) {
  266. _ws_on_send_callbacks.push_back(callback);
  267. }
  268. void wsOnActionRegister(ws_on_action_callback_f callback) {
  269. _ws_on_action_callbacks.push_back(callback);
  270. }
  271. void wsOnAfterParseRegister(ws_on_after_parse_callback_f callback) {
  272. _ws_on_after_parse_callbacks.push_back(callback);
  273. }
  274. void wsSend(ws_on_send_callback_f callback) {
  275. if (_ws.count() > 0) {
  276. DynamicJsonBuffer jsonBuffer;
  277. JsonObject& root = jsonBuffer.createObject();
  278. callback(root);
  279. String output;
  280. root.printTo(output);
  281. wsSend((char *) output.c_str());
  282. }
  283. }
  284. void wsSend(const char * payload) {
  285. if (_ws.count() > 0) {
  286. _ws.textAll(payload);
  287. }
  288. }
  289. void wsSend_P(PGM_P payload) {
  290. if (_ws.count() > 0) {
  291. char buffer[strlen_P(payload)];
  292. strcpy_P(buffer, payload);
  293. _ws.textAll(buffer);
  294. }
  295. }
  296. void wsSend(uint32_t client_id, const char * payload) {
  297. _ws.text(client_id, payload);
  298. }
  299. void wsSend_P(uint32_t client_id, PGM_P payload) {
  300. char buffer[strlen_P(payload)];
  301. strcpy_P(buffer, payload);
  302. _ws.text(client_id, buffer);
  303. }
  304. void wsConfigure() {
  305. _ws.setAuthentication(WEB_USERNAME, (const char *) getSetting("adminPass", ADMIN_PASS).c_str());
  306. }
  307. void wsSetup() {
  308. _ws.onEvent(_wsEvent);
  309. wsConfigure();
  310. webServer()->addHandler(&_ws);
  311. mqttRegister(_wsMQTTCallback);
  312. wsOnAfterParseRegister(wsConfigure);
  313. }
  314. #endif // WEB_SUPPORT