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.

463 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 _wsOnStart(JsonObject& root) {
  230. bool changePassword = false;
  231. #if WEB_FORCE_PASS_CHANGE
  232. String adminPass = getSetting("adminPass", ADMIN_PASS);
  233. if (adminPass.equals(ADMIN_PASS)) changePassword = true;
  234. #endif
  235. if (changePassword) {
  236. root["webMode"] = WEB_MODE_PASSWORD;
  237. } else {
  238. char chipid[7];
  239. snprintf_P(chipid, sizeof(chipid), PSTR("%06X"), ESP.getChipId());
  240. root["webMode"] = WEB_MODE_NORMAL;
  241. root["app_name"] = APP_NAME;
  242. root["app_version"] = APP_VERSION;
  243. root["app_build"] = buildTime();
  244. root["manufacturer"] = MANUFACTURER;
  245. root["chipid"] = chipid;
  246. root["mac"] = WiFi.macAddress();
  247. root["device"] = DEVICE;
  248. root["hostname"] = getSetting("hostname");
  249. root["network"] = getNetwork();
  250. root["deviceip"] = getIP();
  251. root["uptime"] = getUptime();
  252. root["heap"] = getFreeHeap();
  253. root["sketch_size"] = ESP.getSketchSize();
  254. root["free_size"] = ESP.getFreeSketchSpace();
  255. root["btnDelay"] = getSetting("btnDelay", BUTTON_DBLCLICK_DELAY).toInt();
  256. root["webPort"] = getSetting("webPort", WEB_PORT).toInt();
  257. root["tmpUnits"] = getSetting("tmpUnits", SENSOR_TEMPERATURE_UNITS).toInt();
  258. root["tmpCorrection"] = getSetting("tmpCorrection", SENSOR_TEMPERATURE_CORRECTION).toFloat();
  259. }
  260. }
  261. void _wsStart(uint32_t client_id) {
  262. for (unsigned char i = 0; i < _ws_on_send_callbacks.size(); i++) {
  263. wsSend(client_id, _ws_on_send_callbacks[i]);
  264. }
  265. }
  266. void _wsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){
  267. if (type == WS_EVT_CONNECT) {
  268. IPAddress ip = client->remoteIP();
  269. 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());
  270. _wsStart(client->id());
  271. client->_tempObject = new WebSocketIncommingBuffer(&_wsParse, true);
  272. wifiReconnectCheck();
  273. } else if(type == WS_EVT_DISCONNECT) {
  274. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u disconnected\n"), client->id());
  275. if (client->_tempObject) {
  276. delete (WebSocketIncommingBuffer *) client->_tempObject;
  277. }
  278. wifiReconnectCheck();
  279. } else if(type == WS_EVT_ERROR) {
  280. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u error(%u): %s\n"), client->id(), *((uint16_t*)arg), (char*)data);
  281. } else if(type == WS_EVT_PONG) {
  282. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u pong(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  283. } else if(type == WS_EVT_DATA) {
  284. //DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u data(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  285. WebSocketIncommingBuffer *buffer = (WebSocketIncommingBuffer *)client->_tempObject;
  286. AwsFrameInfo * info = (AwsFrameInfo*)arg;
  287. buffer->data_event(client, info, data, len);
  288. }
  289. }
  290. // -----------------------------------------------------------------------------
  291. // Piblic API
  292. // -----------------------------------------------------------------------------
  293. bool wsConnected() {
  294. return (_ws.count() > 0);
  295. }
  296. void wsOnSendRegister(ws_on_send_callback_f callback) {
  297. _ws_on_send_callbacks.push_back(callback);
  298. }
  299. void wsOnActionRegister(ws_on_action_callback_f callback) {
  300. _ws_on_action_callbacks.push_back(callback);
  301. }
  302. void wsOnAfterParseRegister(ws_on_after_parse_callback_f callback) {
  303. _ws_on_after_parse_callbacks.push_back(callback);
  304. }
  305. void wsSend(ws_on_send_callback_f callback) {
  306. if (_ws.count() > 0) {
  307. DynamicJsonBuffer jsonBuffer;
  308. JsonObject& root = jsonBuffer.createObject();
  309. callback(root);
  310. String output;
  311. root.printTo(output);
  312. _ws.textAll((char *) output.c_str());
  313. }
  314. }
  315. void wsSend(const char * payload) {
  316. if (_ws.count() > 0) {
  317. _ws.textAll(payload);
  318. }
  319. }
  320. void wsSend_P(PGM_P payload) {
  321. if (_ws.count() > 0) {
  322. char buffer[strlen_P(payload)];
  323. strcpy_P(buffer, payload);
  324. _ws.textAll(buffer);
  325. }
  326. }
  327. void wsSend(uint32_t client_id, ws_on_send_callback_f callback) {
  328. DynamicJsonBuffer jsonBuffer;
  329. JsonObject& root = jsonBuffer.createObject();
  330. callback(root);
  331. String output;
  332. root.printTo(output);
  333. _ws.text(client_id, (char *) output.c_str());
  334. }
  335. void wsSend(uint32_t client_id, const char * payload) {
  336. _ws.text(client_id, payload);
  337. }
  338. void wsSend_P(uint32_t client_id, PGM_P payload) {
  339. char buffer[strlen_P(payload)];
  340. strcpy_P(buffer, payload);
  341. _ws.text(client_id, buffer);
  342. }
  343. void wsConfigure() {
  344. _ws.setAuthentication(WEB_USERNAME, (const char *) getSetting("adminPass", ADMIN_PASS).c_str());
  345. }
  346. void wsSetup() {
  347. _ws.onEvent(_wsEvent);
  348. wsConfigure();
  349. webServer()->addHandler(&_ws);
  350. #if MQTT_SUPPORT
  351. mqttRegister(_wsMQTTCallback);
  352. #endif
  353. wsOnSendRegister(_wsOnStart);
  354. wsOnAfterParseRegister(wsConfigure);
  355. }
  356. #endif // WEB_SUPPORT