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.

467 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. /*
  120. if (key == "pwrExpectedP") {
  121. powerCalibrate(POWER_MAGNITUDE_ACTIVE, value.toFloat());
  122. changed = true;
  123. continue;
  124. }
  125. if (key == "pwrExpectedV") {
  126. powerCalibrate(POWER_MAGNITUDE_VOLTAGE, value.toFloat());
  127. changed = true;
  128. continue;
  129. }
  130. if (key == "pwrExpectedC") {
  131. powerCalibrate(POWER_MAGNITUDE_CURRENT, value.toFloat());
  132. changed = true;
  133. continue;
  134. }
  135. if (key == "pwrExpectedF") {
  136. powerCalibrate(POWER_MAGNITUDE_POWER_FACTOR, value.toFloat());
  137. changed = true;
  138. continue;
  139. }
  140. if (key == "pwrResetCalibration") {
  141. if (value.toInt() == 1) {
  142. powerResetCalibration();
  143. changed = true;
  144. }
  145. continue;
  146. }
  147. */
  148. #endif
  149. // -----------------------------------------------------------------
  150. // DOMOTICZ
  151. // -----------------------------------------------------------------
  152. #if DOMOTICZ_SUPPORT
  153. if (key == "dczRelayIdx") {
  154. if (dczRelayIdx >= relayCount()) continue;
  155. key = key + String(dczRelayIdx);
  156. ++dczRelayIdx;
  157. }
  158. #else
  159. if (key.startsWith("dcz")) continue;
  160. #endif
  161. // -----------------------------------------------------------------
  162. // MQTT GROUP TOPICS
  163. // -----------------------------------------------------------------
  164. #if MQTT_SUPPORT
  165. if (key == "mqttGroup") {
  166. key = key + String(mqttGroupIdx);
  167. }
  168. if (key == "mqttGroupInv") {
  169. key = key + String(mqttGroupIdx);
  170. ++mqttGroupIdx;
  171. }
  172. #endif
  173. // -----------------------------------------------------------------
  174. // WIFI
  175. // -----------------------------------------------------------------
  176. if (key == "ssid") {
  177. key = key + String(wifiIdx);
  178. }
  179. if (key == "pass") {
  180. key = key + String(wifiIdx);
  181. }
  182. if (key == "ip") {
  183. key = key + String(wifiIdx);
  184. }
  185. if (key == "gw") {
  186. key = key + String(wifiIdx);
  187. }
  188. if (key == "mask") {
  189. key = key + String(wifiIdx);
  190. }
  191. if (key == "dns") {
  192. key = key + String(wifiIdx);
  193. ++wifiIdx;
  194. }
  195. // -----------------------------------------------------------------
  196. if (value != getSetting(key)) {
  197. setSetting(key, value);
  198. save = changed = true;
  199. #if MQTT_SUPPORT
  200. if (key.startsWith("mqtt")) changedMQTT = true;
  201. #endif
  202. }
  203. }
  204. if (webMode == WEB_MODE_NORMAL) {
  205. if (wifiClean(wifiIdx)) save = changed = true;
  206. }
  207. // Save settings
  208. if (save) {
  209. // Callbacks
  210. for (unsigned char i = 0; i < _ws_on_after_parse_callbacks.size(); i++) {
  211. (_ws_on_after_parse_callbacks[i])();
  212. }
  213. // This should got to callback as well
  214. // but first change management has to be in place
  215. #if MQTT_SUPPORT
  216. if (changedMQTT) {
  217. mqttConfigure();
  218. mqttDisconnect();
  219. }
  220. #endif
  221. // Persist settings
  222. saveSettings();
  223. }
  224. if (changed) {
  225. wsSend_P(client_id, PSTR("{\"message\": 8}"));
  226. } else {
  227. wsSend_P(client_id, PSTR("{\"message\": 9}"));
  228. }
  229. }
  230. }
  231. void _wsOnStart(JsonObject& root) {
  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. }
  262. }
  263. void _wsStart(uint32_t client_id) {
  264. for (unsigned char i = 0; i < _ws_on_send_callbacks.size(); i++) {
  265. wsSend(client_id, _ws_on_send_callbacks[i]);
  266. }
  267. }
  268. void _wsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){
  269. if (type == WS_EVT_CONNECT) {
  270. IPAddress ip = client->remoteIP();
  271. 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());
  272. _wsStart(client->id());
  273. client->_tempObject = new WebSocketIncommingBuffer(&_wsParse, true);
  274. wifiReconnectCheck();
  275. } else if(type == WS_EVT_DISCONNECT) {
  276. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u disconnected\n"), client->id());
  277. if (client->_tempObject) {
  278. delete (WebSocketIncommingBuffer *) client->_tempObject;
  279. }
  280. wifiReconnectCheck();
  281. } else if(type == WS_EVT_ERROR) {
  282. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u error(%u): %s\n"), client->id(), *((uint16_t*)arg), (char*)data);
  283. } else if(type == WS_EVT_PONG) {
  284. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u pong(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  285. } else if(type == WS_EVT_DATA) {
  286. //DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u data(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  287. WebSocketIncommingBuffer *buffer = (WebSocketIncommingBuffer *)client->_tempObject;
  288. AwsFrameInfo * info = (AwsFrameInfo*)arg;
  289. buffer->data_event(client, info, data, len);
  290. }
  291. }
  292. // -----------------------------------------------------------------------------
  293. // Piblic API
  294. // -----------------------------------------------------------------------------
  295. bool wsConnected() {
  296. return (_ws.count() > 0);
  297. }
  298. void wsOnSendRegister(ws_on_send_callback_f callback) {
  299. _ws_on_send_callbacks.push_back(callback);
  300. }
  301. void wsOnActionRegister(ws_on_action_callback_f callback) {
  302. _ws_on_action_callbacks.push_back(callback);
  303. }
  304. void wsOnAfterParseRegister(ws_on_after_parse_callback_f callback) {
  305. _ws_on_after_parse_callbacks.push_back(callback);
  306. }
  307. void wsSend(ws_on_send_callback_f callback) {
  308. if (_ws.count() > 0) {
  309. DynamicJsonBuffer jsonBuffer;
  310. JsonObject& root = jsonBuffer.createObject();
  311. callback(root);
  312. String output;
  313. root.printTo(output);
  314. _ws.textAll((char *) output.c_str());
  315. }
  316. }
  317. void wsSend(const char * payload) {
  318. if (_ws.count() > 0) {
  319. _ws.textAll(payload);
  320. }
  321. }
  322. void wsSend_P(PGM_P payload) {
  323. if (_ws.count() > 0) {
  324. char buffer[strlen_P(payload)];
  325. strcpy_P(buffer, payload);
  326. _ws.textAll(buffer);
  327. }
  328. }
  329. void wsSend(uint32_t client_id, ws_on_send_callback_f callback) {
  330. DynamicJsonBuffer jsonBuffer;
  331. JsonObject& root = jsonBuffer.createObject();
  332. callback(root);
  333. String output;
  334. root.printTo(output);
  335. _ws.text(client_id, (char *) output.c_str());
  336. }
  337. void wsSend(uint32_t client_id, const char * payload) {
  338. _ws.text(client_id, payload);
  339. }
  340. void wsSend_P(uint32_t client_id, PGM_P payload) {
  341. char buffer[strlen_P(payload)];
  342. strcpy_P(buffer, payload);
  343. _ws.text(client_id, buffer);
  344. }
  345. void wsConfigure() {
  346. _ws.setAuthentication(WEB_USERNAME, (const char *) getSetting("adminPass", ADMIN_PASS).c_str());
  347. }
  348. void wsSetup() {
  349. _ws.onEvent(_wsEvent);
  350. wsConfigure();
  351. webServer()->addHandler(&_ws);
  352. #if MQTT_SUPPORT
  353. mqttRegister(_wsMQTTCallback);
  354. #endif
  355. wsOnSendRegister(_wsOnStart);
  356. wsOnAfterParseRegister(wsConfigure);
  357. }
  358. #endif // WEB_SUPPORT