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.

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