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.

459 lines
14 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 "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. // -----------------------------------------------------------------------------
  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("reboot")) 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 wifiIdx = 0;
  77. unsigned int dczRelayIdx = 0;
  78. unsigned int mqttGroupIdx = 0;
  79. String adminPass;
  80. for (unsigned int i=0; i<config.size(); i++) {
  81. String key = config[i]["name"];
  82. String value = config[i]["value"];
  83. // Skip firmware filename
  84. if (key.equals("filename")) continue;
  85. // -----------------------------------------------------------------
  86. // GENERAL
  87. // -----------------------------------------------------------------
  88. // Web mode (normal or password)
  89. if (key == "webMode") {
  90. webMode = value.toInt();
  91. continue;
  92. }
  93. // HTTP port
  94. if (key == "webPort") {
  95. if ((value.toInt() == 0) || (value.toInt() == 80)) {
  96. save = changed = true;
  97. delSetting(key);
  98. continue;
  99. }
  100. }
  101. // Check password
  102. if (key == "adminPass1") {
  103. adminPass = value;
  104. continue;
  105. }
  106. if (key == "adminPass2") {
  107. if (!value.equals(adminPass)) {
  108. wsSend_P(client_id, PSTR("{\"message\": 7}"));
  109. return;
  110. }
  111. if (value.length() == 0) continue;
  112. wsSend_P(client_id, PSTR("{\"action\": \"reload\"}"));
  113. key = String("adminPass");
  114. }
  115. // -----------------------------------------------------------------
  116. // POWER
  117. // -----------------------------------------------------------------
  118. #if POWER_PROVIDER != POWER_PROVIDER_NONE
  119. if (key == "pwrExpectedP") {
  120. powerCalibrate(POWER_MAGNITUDE_ACTIVE, value.toFloat());
  121. changed = true;
  122. continue;
  123. }
  124. if (key == "pwrExpectedV") {
  125. powerCalibrate(POWER_MAGNITUDE_VOLTAGE, value.toFloat());
  126. changed = true;
  127. continue;
  128. }
  129. if (key == "pwrExpectedC") {
  130. powerCalibrate(POWER_MAGNITUDE_CURRENT, value.toFloat());
  131. changed = true;
  132. continue;
  133. }
  134. if (key == "pwrExpectedF") {
  135. powerCalibrate(POWER_MAGNITUDE_POWER_FACTOR, value.toFloat());
  136. changed = true;
  137. continue;
  138. }
  139. if (key == "pwrResetCalibration") {
  140. if (value.toInt() == 1) {
  141. powerResetCalibration();
  142. changed = true;
  143. }
  144. continue;
  145. }
  146. #endif
  147. // -----------------------------------------------------------------
  148. // DOMOTICZ
  149. // -----------------------------------------------------------------
  150. #if DOMOTICZ_SUPPORT
  151. if (key == "dczRelayIdx") {
  152. if (dczRelayIdx >= relayCount()) continue;
  153. key = key + String(dczRelayIdx);
  154. ++dczRelayIdx;
  155. }
  156. #else
  157. if (key.startsWith("dcz")) continue;
  158. #endif
  159. // -----------------------------------------------------------------
  160. // MQTT GROUP TOPICS
  161. // -----------------------------------------------------------------
  162. #if MQTT_SUPPORT
  163. if (key == "mqttGroup") {
  164. key = key + String(mqttGroupIdx);
  165. }
  166. if (key == "mqttGroupInv") {
  167. key = key + String(mqttGroupIdx);
  168. ++mqttGroupIdx;
  169. }
  170. #endif
  171. // -----------------------------------------------------------------
  172. // WIFI
  173. // -----------------------------------------------------------------
  174. if (key == "ssid") {
  175. key = key + String(wifiIdx);
  176. }
  177. if (key == "pass") {
  178. key = key + String(wifiIdx);
  179. }
  180. if (key == "ip") {
  181. key = key + String(wifiIdx);
  182. }
  183. if (key == "gw") {
  184. key = key + String(wifiIdx);
  185. }
  186. if (key == "mask") {
  187. key = key + String(wifiIdx);
  188. }
  189. if (key == "dns") {
  190. key = key + String(wifiIdx);
  191. ++wifiIdx;
  192. }
  193. // -----------------------------------------------------------------
  194. if (value != getSetting(key)) {
  195. setSetting(key, value);
  196. save = changed = true;
  197. #if MQTT_SUPPORT
  198. if (key.startsWith("mqtt")) changedMQTT = true;
  199. #endif
  200. }
  201. }
  202. if (webMode == WEB_MODE_NORMAL) {
  203. if (wifiClean(wifiIdx)) save = changed = true;
  204. }
  205. // Save settings
  206. if (save) {
  207. // Callbacks
  208. for (unsigned char i = 0; i < _ws_on_after_parse_callbacks.size(); i++) {
  209. (_ws_on_after_parse_callbacks[i])();
  210. }
  211. // This should got to callback as well
  212. // but first change management has to be in place
  213. #if MQTT_SUPPORT
  214. if (changedMQTT) {
  215. mqttConfigure();
  216. mqttDisconnect();
  217. }
  218. #endif
  219. // Persist settings
  220. saveSettings();
  221. }
  222. if (changed) {
  223. wsSend_P(client_id, PSTR("{\"message\": 8}"));
  224. } else {
  225. wsSend_P(client_id, PSTR("{\"message\": 9}"));
  226. }
  227. }
  228. }
  229. void _wsStart(uint32_t client_id) {
  230. DynamicJsonBuffer jsonBuffer;
  231. JsonObject& root = jsonBuffer.createObject();
  232. bool changePassword = false;
  233. #if WEB_FORCE_PASS_CHANGE
  234. String adminPass = getSetting("adminPass", ADMIN_PASS);
  235. if (adminPass.equals(ADMIN_PASS)) changePassword = true;
  236. #endif
  237. if (changePassword) {
  238. root["webMode"] = WEB_MODE_PASSWORD;
  239. } else {
  240. char chipid[7];
  241. snprintf_P(chipid, sizeof(chipid), PSTR("%06X"), ESP.getChipId());
  242. root["webMode"] = WEB_MODE_NORMAL;
  243. root["app_name"] = APP_NAME;
  244. root["app_version"] = APP_VERSION;
  245. root["app_build"] = buildTime();
  246. root["manufacturer"] = MANUFACTURER;
  247. root["chipid"] = chipid;
  248. root["mac"] = WiFi.macAddress();
  249. root["device"] = DEVICE;
  250. root["hostname"] = getSetting("hostname");
  251. root["network"] = getNetwork();
  252. root["deviceip"] = getIP();
  253. root["uptime"] = getUptime();
  254. root["heap"] = getFreeHeap();
  255. root["sketch_size"] = ESP.getSketchSize();
  256. root["free_size"] = ESP.getFreeSketchSpace();
  257. root["btnDelay"] = getSetting("btnDelay", BUTTON_DBLCLICK_DELAY).toInt();
  258. root["webPort"] = getSetting("webPort", WEB_PORT).toInt();
  259. root["tmpUnits"] = getSetting("tmpUnits", SENSOR_TEMPERATURE_UNITS).toInt();
  260. root["tmpCorrection"] = getSetting("tmpCorrection", SENSOR_TEMPERATURE_CORRECTION).toFloat();
  261. // Callbacks
  262. for (unsigned char i = 0; i < _ws_on_send_callbacks.size(); i++) {
  263. (_ws_on_send_callbacks[i])(root);
  264. }
  265. }
  266. String output;
  267. root.printTo(output);
  268. wsSend(client_id, (char *) output.c_str());
  269. }
  270. void _wsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){
  271. if (type == WS_EVT_CONNECT) {
  272. IPAddress ip = client->remoteIP();
  273. 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());
  274. _wsStart(client->id());
  275. client->_tempObject = new WebSocketIncommingBuffer(&_wsParse, true);
  276. wifiReconnectCheck();
  277. } else if(type == WS_EVT_DISCONNECT) {
  278. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u disconnected\n"), client->id());
  279. if (client->_tempObject) {
  280. delete (WebSocketIncommingBuffer *) client->_tempObject;
  281. }
  282. wifiReconnectCheck();
  283. } else if(type == WS_EVT_ERROR) {
  284. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u error(%u): %s\n"), client->id(), *((uint16_t*)arg), (char*)data);
  285. } else if(type == WS_EVT_PONG) {
  286. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u pong(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  287. } else if(type == WS_EVT_DATA) {
  288. //DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u data(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  289. WebSocketIncommingBuffer *buffer = (WebSocketIncommingBuffer *)client->_tempObject;
  290. AwsFrameInfo * info = (AwsFrameInfo*)arg;
  291. buffer->data_event(client, info, data, len);
  292. }
  293. }
  294. // -----------------------------------------------------------------------------
  295. // Piblic API
  296. // -----------------------------------------------------------------------------
  297. bool wsConnected() {
  298. return (_ws.count() > 0);
  299. }
  300. void wsOnSendRegister(ws_on_send_callback_f callback) {
  301. _ws_on_send_callbacks.push_back(callback);
  302. }
  303. void wsOnActionRegister(ws_on_action_callback_f callback) {
  304. _ws_on_action_callbacks.push_back(callback);
  305. }
  306. void wsOnAfterParseRegister(ws_on_after_parse_callback_f callback) {
  307. _ws_on_after_parse_callbacks.push_back(callback);
  308. }
  309. void wsSend(ws_on_send_callback_f callback) {
  310. if (_ws.count() > 0) {
  311. DynamicJsonBuffer jsonBuffer;
  312. JsonObject& root = jsonBuffer.createObject();
  313. callback(root);
  314. String output;
  315. root.printTo(output);
  316. wsSend((char *) output.c_str());
  317. }
  318. }
  319. void wsSend(const char * payload) {
  320. if (_ws.count() > 0) {
  321. _ws.textAll(payload);
  322. }
  323. }
  324. void wsSend_P(PGM_P payload) {
  325. if (_ws.count() > 0) {
  326. char buffer[strlen_P(payload)];
  327. strcpy_P(buffer, payload);
  328. _ws.textAll(buffer);
  329. }
  330. }
  331. void wsSend(uint32_t client_id, const char * payload) {
  332. _ws.text(client_id, payload);
  333. }
  334. void wsSend_P(uint32_t client_id, PGM_P payload) {
  335. char buffer[strlen_P(payload)];
  336. strcpy_P(buffer, payload);
  337. _ws.text(client_id, buffer);
  338. }
  339. void wsConfigure() {
  340. _ws.setAuthentication(WEB_USERNAME, (const char *) getSetting("adminPass", ADMIN_PASS).c_str());
  341. }
  342. void wsSetup() {
  343. _ws.onEvent(_wsEvent);
  344. wsConfigure();
  345. webServer()->addHandler(&_ws);
  346. #if MQTT_SUPPORT
  347. mqttRegister(_wsMQTTCallback);
  348. #endif
  349. wsOnAfterParseRegister(wsConfigure);
  350. }
  351. #endif // WEB_SUPPORT