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.

434 lines
13 KiB

6 years ago
  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. bool _wsStore(String key, String value) {
  27. // HTTP port
  28. if (key == "webPort") {
  29. if ((value.toInt() == 0) || (value.toInt() == 80)) {
  30. return delSetting(key);
  31. }
  32. }
  33. if (value != getSetting(key)) {
  34. return setSetting(key, value);
  35. }
  36. return false;
  37. }
  38. bool _wsStore(String key, JsonArray& value) {
  39. bool changed = false;
  40. unsigned char index = 0;
  41. for (auto element : (JsonArray&) value) {
  42. if (_wsStore(key + index, element.as<String>())) changed = true;
  43. index++;
  44. }
  45. // Delete further values
  46. for (unsigned char i=index; i<SETTINGS_MAX_LIST_COUNT; i++) {
  47. if (!delSetting(key, index)) break;
  48. changed = true;
  49. }
  50. if (changed) Serial.println(key);
  51. return changed;
  52. }
  53. void _wsParse(AsyncWebSocketClient *client, uint8_t * payload, size_t length) {
  54. //DEBUG_MSG_P(PSTR("[WEBSOCKET] Parsing: %s\n"), length ? (char*) payload : "");
  55. // Get client ID
  56. uint32_t client_id = client->id();
  57. // Parse JSON input
  58. DynamicJsonBuffer jsonBuffer;
  59. JsonObject& root = jsonBuffer.parseObject((char *) payload);
  60. if (!root.success()) {
  61. DEBUG_MSG_P(PSTR("[WEBSOCKET] Error parsing data\n"));
  62. wsSend_P(client_id, PSTR("{\"message\": 3}"));
  63. return;
  64. }
  65. // Check actions -----------------------------------------------------------
  66. if (root.containsKey("action")) {
  67. String action = root["action"];
  68. JsonObject& data = root.containsKey("data") ? root["data"] : jsonBuffer.createObject();
  69. DEBUG_MSG_P(PSTR("[WEBSOCKET] Requested action: %s\n"), action.c_str());
  70. // Callbacks
  71. for (unsigned char i = 0; i < _ws_on_action_callbacks.size(); i++) {
  72. (_ws_on_action_callbacks[i])(action.c_str(), data);
  73. }
  74. if (action.equals("reboot")) deferredReset(100, CUSTOM_RESET_WEB);
  75. if (action.equals("reconnect")) _web_defer.once_ms(100, wifiDisconnect);
  76. if (action.equals("restore")) {
  77. if (!data.containsKey("app") || (data["app"] != APP_NAME)) {
  78. wsSend_P(client_id, PSTR("{\"message\": 4}"));
  79. return;
  80. }
  81. for (unsigned int i = EEPROM_DATA_END; i < SPI_FLASH_SEC_SIZE; i++) {
  82. EEPROM.write(i, 0xFF);
  83. }
  84. for (auto element : data) {
  85. if (strcmp(element.key, "app") == 0) continue;
  86. if (strcmp(element.key, "version") == 0) continue;
  87. setSetting(element.key, element.value.as<char*>());
  88. }
  89. saveSettings();
  90. wsSend_P(client_id, PSTR("{\"message\": 5}"));
  91. }
  92. };
  93. // Check configuration -----------------------------------------------------
  94. if (root.containsKey("config") && root["config"].is<JsonObject&>()) {
  95. JsonObject& config = root["config"];
  96. DEBUG_MSG_P(PSTR("[WEBSOCKET] Parsing configuration data\n"));
  97. String adminPass;
  98. bool save = false;
  99. #if MQTT_SUPPORT
  100. bool changedMQTT = false;
  101. #endif
  102. for (auto kv: config) {
  103. bool changed = false;
  104. String key = kv.key;
  105. JsonVariant& value = kv.value;
  106. // Check password
  107. if (key == "adminPass") {
  108. if (!value.is<JsonArray&>()) continue;
  109. JsonArray& values = value.as<JsonArray&>();
  110. if (values.size() != 2) continue;
  111. if (values[0].as<String>().equals(values[1].as<String>())) {
  112. String password = values[0].as<String>();
  113. if (password.length() > 0) {
  114. setSetting(key, password);
  115. save = true;
  116. }
  117. wsSend_P(client_id, PSTR("{\"action\": \"reload\"}"));
  118. } else {
  119. wsSend_P(client_id, PSTR("{\"message\": 7}"));
  120. }
  121. continue;
  122. }
  123. // -----------------------------------------------------------------
  124. // POWER
  125. // -----------------------------------------------------------------
  126. #if POWER_PROVIDER != POWER_PROVIDER_NONE
  127. double expected;
  128. if (key == "pwrExpectedP") {
  129. if (expected = value.as<double>()) {
  130. powerCalibrate(POWER_MAGNITUDE_ACTIVE, expected);
  131. save = true;
  132. }
  133. delSetting(key);
  134. continue;
  135. }
  136. if (key == "pwrExpectedV") {
  137. if (expected = value.as<double>()) {
  138. powerCalibrate(POWER_MAGNITUDE_VOLTAGE, expected);
  139. save = true;
  140. }
  141. delSetting(key);
  142. continue;
  143. }
  144. if (key == "pwrExpectedC") {
  145. if (expected = value.as<double>()) {
  146. powerCalibrate(POWER_MAGNITUDE_CURRENT, expected);
  147. save = true;
  148. }
  149. delSetting(key);
  150. continue;
  151. }
  152. if (key == "pwrExpectedF") {
  153. if (expected = value.as<double>()) {
  154. powerCalibrate(POWER_MAGNITUDE_POWER_FACTOR, expected);
  155. save = true;
  156. }
  157. delSetting(key);
  158. continue;
  159. }
  160. if (key == "pwrResetCalibration") {
  161. if (value.as<bool>()) {
  162. powerResetCalibration();
  163. save = true;
  164. Serial.println(key);
  165. }
  166. delSetting(key);
  167. continue;
  168. }
  169. #endif
  170. // Store values
  171. if (value.is<JsonArray&>()) {
  172. if (_wsStore(key, value.as<JsonArray&>())) changed = true;
  173. } else {
  174. if (_wsStore(key, value.as<String>())) changed = true;
  175. }
  176. // Update flags if value has changed
  177. if (changed) {
  178. save = true;
  179. #if MQTT_SUPPORT
  180. if (key.startsWith("mqtt")) changedMQTT = true;
  181. #endif
  182. }
  183. }
  184. // Save settings
  185. if (save) {
  186. // Callbacks
  187. for (unsigned char i = 0; i < _ws_on_after_parse_callbacks.size(); i++) {
  188. (_ws_on_after_parse_callbacks[i])();
  189. }
  190. // This should got to callback as well
  191. // but first change management has to be in place
  192. #if MQTT_SUPPORT
  193. if (changedMQTT) {
  194. mqttConfigure();
  195. mqttDisconnect();
  196. }
  197. #endif
  198. // Persist settings
  199. saveSettings();
  200. wsSend_P(client_id, PSTR("{\"message\": 8}"));
  201. } else {
  202. wsSend_P(client_id, PSTR("{\"message\": 9}"));
  203. }
  204. }
  205. }
  206. void _wsOnStart(JsonObject& root) {
  207. bool changePassword = false;
  208. #if WEB_FORCE_PASS_CHANGE
  209. String adminPass = getSetting("adminPass", ADMIN_PASS);
  210. if (adminPass.equals(ADMIN_PASS)) changePassword = true;
  211. #endif
  212. if (changePassword) {
  213. root["webMode"] = WEB_MODE_PASSWORD;
  214. } else {
  215. char chipid[7];
  216. snprintf_P(chipid, sizeof(chipid), PSTR("%06X"), ESP.getChipId());
  217. root["webMode"] = WEB_MODE_NORMAL;
  218. root["app_name"] = APP_NAME;
  219. root["app_version"] = APP_VERSION;
  220. root["app_build"] = buildTime();
  221. root["manufacturer"] = MANUFACTURER;
  222. root["chipid"] = String(chipid);
  223. root["mac"] = WiFi.macAddress();
  224. root["device"] = DEVICE;
  225. root["hostname"] = getSetting("hostname");
  226. root["network"] = getNetwork();
  227. root["deviceip"] = getIP();
  228. root["uptime"] = getUptime();
  229. root["heap"] = getFreeHeap();
  230. root["sketch_size"] = ESP.getSketchSize();
  231. root["free_size"] = ESP.getFreeSketchSpace();
  232. root["btnDelay"] = getSetting("btnDelay", BUTTON_DBLCLICK_DELAY).toInt();
  233. root["webPort"] = getSetting("webPort", WEB_PORT).toInt();
  234. root["tmpUnits"] = getSetting("tmpUnits", TMP_UNITS).toInt();
  235. root["tmpCorrection"] = getSetting("tmpCorrection", TEMPERATURE_CORRECTION).toFloat();
  236. }
  237. }
  238. void _wsStart(uint32_t client_id) {
  239. for (unsigned char i = 0; i < _ws_on_send_callbacks.size(); i++) {
  240. wsSend(client_id, _ws_on_send_callbacks[i]);
  241. }
  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. _ws.textAll((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, ws_on_send_callback_f callback) {
  305. DynamicJsonBuffer jsonBuffer;
  306. JsonObject& root = jsonBuffer.createObject();
  307. callback(root);
  308. String output;
  309. root.printTo(output);
  310. _ws.text(client_id, (char *) output.c_str());
  311. }
  312. void wsSend(uint32_t client_id, const char * payload) {
  313. _ws.text(client_id, payload);
  314. }
  315. void wsSend_P(uint32_t client_id, PGM_P payload) {
  316. char buffer[strlen_P(payload)];
  317. strcpy_P(buffer, payload);
  318. _ws.text(client_id, buffer);
  319. }
  320. void wsConfigure() {
  321. _ws.setAuthentication(WEB_USERNAME, (const char *) getSetting("adminPass", ADMIN_PASS).c_str());
  322. }
  323. void wsSetup() {
  324. _ws.onEvent(_wsEvent);
  325. wsConfigure();
  326. webServer()->addHandler(&_ws);
  327. #if MQTT_SUPPORT
  328. mqttRegister(_wsMQTTCallback);
  329. #endif
  330. wsOnSendRegister(_wsOnStart);
  331. wsOnAfterParseRegister(wsConfigure);
  332. }
  333. #endif // WEB_SUPPORT