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.

412 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. // Callbacks
  226. for (unsigned char i = 0; i < _ws_on_send_callbacks.size(); i++) {
  227. (_ws_on_send_callbacks[i])(root);
  228. }
  229. }
  230. String output;
  231. root.printTo(output);
  232. wsSend(client_id, (char *) output.c_str());
  233. }
  234. void _wsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){
  235. if (type == WS_EVT_CONNECT) {
  236. IPAddress ip = client->remoteIP();
  237. 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());
  238. _wsStart(client->id());
  239. client->_tempObject = new WebSocketIncommingBuffer(&_wsParse, true);
  240. wifiReconnectCheck();
  241. } else if(type == WS_EVT_DISCONNECT) {
  242. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u disconnected\n"), client->id());
  243. if (client->_tempObject) {
  244. delete (WebSocketIncommingBuffer *) client->_tempObject;
  245. }
  246. wifiReconnectCheck();
  247. } else if(type == WS_EVT_ERROR) {
  248. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u error(%u): %s\n"), client->id(), *((uint16_t*)arg), (char*)data);
  249. } else if(type == WS_EVT_PONG) {
  250. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u pong(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  251. } else if(type == WS_EVT_DATA) {
  252. //DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u data(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  253. WebSocketIncommingBuffer *buffer = (WebSocketIncommingBuffer *)client->_tempObject;
  254. AwsFrameInfo * info = (AwsFrameInfo*)arg;
  255. buffer->data_event(client, info, data, len);
  256. }
  257. }
  258. // -----------------------------------------------------------------------------
  259. // Piblic API
  260. // -----------------------------------------------------------------------------
  261. bool wsConnected() {
  262. return (_ws.count() > 0);
  263. }
  264. void wsOnSendRegister(ws_on_send_callback_f callback) {
  265. _ws_on_send_callbacks.push_back(callback);
  266. }
  267. void wsOnActionRegister(ws_on_action_callback_f callback) {
  268. _ws_on_action_callbacks.push_back(callback);
  269. }
  270. void wsOnAfterParseRegister(ws_on_after_parse_callback_f callback) {
  271. _ws_on_after_parse_callbacks.push_back(callback);
  272. }
  273. void wsSend(ws_on_send_callback_f callback) {
  274. if (_ws.count() > 0) {
  275. DynamicJsonBuffer jsonBuffer;
  276. JsonObject& root = jsonBuffer.createObject();
  277. callback(root);
  278. String output;
  279. root.printTo(output);
  280. wsSend((char *) output.c_str());
  281. }
  282. }
  283. void wsSend(const char * payload) {
  284. if (_ws.count() > 0) {
  285. _ws.textAll(payload);
  286. }
  287. }
  288. void wsSend_P(PGM_P payload) {
  289. if (_ws.count() > 0) {
  290. char buffer[strlen_P(payload)];
  291. strcpy_P(buffer, payload);
  292. _ws.textAll(buffer);
  293. }
  294. }
  295. void wsSend(uint32_t client_id, const char * payload) {
  296. _ws.text(client_id, payload);
  297. }
  298. void wsSend_P(uint32_t client_id, PGM_P payload) {
  299. char buffer[strlen_P(payload)];
  300. strcpy_P(buffer, payload);
  301. _ws.text(client_id, buffer);
  302. }
  303. void wsConfigure() {
  304. _ws.setAuthentication(WEB_USERNAME, (const char *) getSetting("adminPass", ADMIN_PASS).c_str());
  305. }
  306. void wsSetup() {
  307. _ws.onEvent(_wsEvent);
  308. wsConfigure();
  309. webServer()->addHandler(&_ws);
  310. mqttRegister(_wsMQTTCallback);
  311. wsOnAfterParseRegister(wsConfigure);
  312. }
  313. #endif // WEB_SUPPORT