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.

417 lines
12 KiB

7 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 : 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. return changed;
  51. }
  52. void _wsParse(AsyncWebSocketClient *client, uint8_t * payload, size_t length) {
  53. //DEBUG_MSG_P(PSTR("[WEBSOCKET] Parsing: %s\n"), length ? (char*) payload : "");
  54. // Get client ID
  55. uint32_t client_id = client->id();
  56. // Parse JSON input
  57. DynamicJsonBuffer jsonBuffer;
  58. JsonObject& root = jsonBuffer.parseObject((char *) payload);
  59. if (!root.success()) {
  60. DEBUG_MSG_P(PSTR("[WEBSOCKET] Error parsing data\n"));
  61. wsSend_P(client_id, PSTR("{\"message\": 3}"));
  62. return;
  63. }
  64. // Check actions -----------------------------------------------------------
  65. const char* action = root["action"];
  66. if (action) {
  67. DEBUG_MSG_P(PSTR("[WEBSOCKET] Requested action: %s\n"), action);
  68. if (strcmp(action, "reboot") == 0) deferredReset(100, CUSTOM_RESET_WEB);
  69. if (strcmp(action, "reconnect") == 0) _web_defer.once_ms(100, wifiDisconnect);
  70. JsonObject& data = root["data"];
  71. if (data.success()) {
  72. // Callbacks
  73. for (unsigned char i = 0; i < _ws_on_action_callbacks.size(); i++) {
  74. (_ws_on_action_callbacks[i])(action, data);
  75. }
  76. // Restore configuration via websockets
  77. if (strcmp(action, "restore") == 0) {
  78. if (settingsRestore(data)) {
  79. wsSend_P(client_id, PSTR("{\"message\": 5}"));
  80. } else {
  81. wsSend_P(client_id, PSTR("{\"message\": 4}"));
  82. }
  83. }
  84. }
  85. };
  86. // Check configuration -----------------------------------------------------
  87. JsonObject& config = root["config"];
  88. if (config.success()) {
  89. DEBUG_MSG_P(PSTR("[WEBSOCKET] Parsing configuration data\n"));
  90. String adminPass;
  91. bool save = false;
  92. #if MQTT_SUPPORT
  93. bool changedMQTT = false;
  94. #endif
  95. for (auto kv: config) {
  96. bool changed = false;
  97. String key = kv.key;
  98. JsonVariant& value = kv.value;
  99. // Check password
  100. if (key == "adminPass") {
  101. if (!value.is<JsonArray&>()) continue;
  102. JsonArray& values = value.as<JsonArray&>();
  103. if (values.size() != 2) continue;
  104. if (values[0].as<String>().equals(values[1].as<String>())) {
  105. String password = values[0].as<String>();
  106. if (password.length() > 0) {
  107. setSetting(key, password);
  108. save = true;
  109. wsSend_P(client_id, PSTR("{\"action\": \"reload\"}"));
  110. }
  111. } else {
  112. wsSend_P(client_id, PSTR("{\"message\": 7}"));
  113. }
  114. continue;
  115. }
  116. // -----------------------------------------------------------------
  117. // POWER
  118. // -----------------------------------------------------------------
  119. #if POWER_PROVIDER != POWER_PROVIDER_NONE
  120. double expected;
  121. if (key == "pwrExpectedP") {
  122. if (expected = value.as<double>()) {
  123. powerCalibrate(POWER_MAGNITUDE_ACTIVE, expected);
  124. save = true;
  125. }
  126. continue;
  127. }
  128. if (key == "pwrExpectedV") {
  129. if (expected = value.as<double>()) {
  130. powerCalibrate(POWER_MAGNITUDE_VOLTAGE, expected);
  131. save = true;
  132. }
  133. continue;
  134. }
  135. if (key == "pwrExpectedC") {
  136. if (expected = value.as<double>()) {
  137. powerCalibrate(POWER_MAGNITUDE_CURRENT, expected);
  138. save = true;
  139. }
  140. continue;
  141. }
  142. if (key == "pwrExpectedF") {
  143. if (expected = value.as<double>()) {
  144. powerCalibrate(POWER_MAGNITUDE_POWER_FACTOR, expected);
  145. save = true;
  146. }
  147. continue;
  148. }
  149. if (key == "pwrResetCalibration") {
  150. if (value.as<bool>()) {
  151. powerResetCalibration();
  152. save = true;
  153. }
  154. continue;
  155. }
  156. #endif
  157. // Store values
  158. if (value.is<JsonArray&>()) {
  159. if (_wsStore(key, value.as<JsonArray&>())) changed = true;
  160. } else {
  161. if (_wsStore(key, value.as<String>())) changed = true;
  162. }
  163. // Update flags if value has changed
  164. if (changed) {
  165. save = true;
  166. #if MQTT_SUPPORT
  167. if (key.startsWith("mqtt")) changedMQTT = true;
  168. #endif
  169. }
  170. }
  171. // Save settings
  172. if (save) {
  173. // Callbacks
  174. for (unsigned char i = 0; i < _ws_on_after_parse_callbacks.size(); i++) {
  175. (_ws_on_after_parse_callbacks[i])();
  176. }
  177. // This should got to callback as well
  178. // but first change management has to be in place
  179. #if MQTT_SUPPORT
  180. if (changedMQTT) {
  181. mqttConfigure();
  182. mqttDisconnect();
  183. }
  184. #endif
  185. // Persist settings
  186. saveSettings();
  187. wsSend_P(client_id, PSTR("{\"message\": 8}"));
  188. } else {
  189. wsSend_P(client_id, PSTR("{\"message\": 9}"));
  190. }
  191. }
  192. }
  193. void _wsOnStart(JsonObject& root) {
  194. #if WEB_FORCE_PASS_CHANGE
  195. String adminPass = getSetting("adminPass", ADMIN_PASS);
  196. bool changePassword = adminPass.equals(ADMIN_PASS);
  197. #else
  198. bool changePassword = false;
  199. #endif
  200. if (changePassword) {
  201. root["webMode"] = WEB_MODE_PASSWORD;
  202. } else {
  203. char chipid[7];
  204. snprintf_P(chipid, sizeof(chipid), PSTR("%06X"), ESP.getChipId());
  205. root["webMode"] = WEB_MODE_NORMAL;
  206. root["app_name"] = APP_NAME;
  207. root["app_version"] = APP_VERSION;
  208. root["app_build"] = buildTime();
  209. root["manufacturer"] = MANUFACTURER;
  210. root["chipid"] = String(chipid);
  211. root["mac"] = WiFi.macAddress();
  212. root["device"] = DEVICE;
  213. root["hostname"] = getSetting("hostname");
  214. root["network"] = getNetwork();
  215. root["deviceip"] = getIP();
  216. root["uptime"] = getUptime();
  217. root["heap"] = getFreeHeap();
  218. root["sketch_size"] = ESP.getSketchSize();
  219. root["free_size"] = ESP.getFreeSketchSpace();
  220. root["btnDelay"] = getSetting("btnDelay", BUTTON_DBLCLICK_DELAY).toInt();
  221. root["webPort"] = getSetting("webPort", WEB_PORT).toInt();
  222. root["tmpUnits"] = getSetting("tmpUnits", TMP_UNITS).toInt();
  223. root["tmpCorrection"] = getSetting("tmpCorrection", TEMPERATURE_CORRECTION).toFloat();
  224. }
  225. }
  226. void _wsStart(uint32_t client_id) {
  227. for (unsigned char i = 0; i < _ws_on_send_callbacks.size(); i++) {
  228. wsSend(client_id, _ws_on_send_callbacks[i]);
  229. }
  230. }
  231. void _wsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){
  232. if (type == WS_EVT_CONNECT) {
  233. IPAddress ip = client->remoteIP();
  234. 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());
  235. _wsStart(client->id());
  236. client->_tempObject = new WebSocketIncommingBuffer(&_wsParse, true);
  237. wifiReconnectCheck();
  238. } else if(type == WS_EVT_DISCONNECT) {
  239. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u disconnected\n"), client->id());
  240. if (client->_tempObject) {
  241. delete (WebSocketIncommingBuffer *) client->_tempObject;
  242. }
  243. wifiReconnectCheck();
  244. } else if(type == WS_EVT_ERROR) {
  245. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u error(%u): %s\n"), client->id(), *((uint16_t*)arg), (char*)data);
  246. } else if(type == WS_EVT_PONG) {
  247. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u pong(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  248. } else if(type == WS_EVT_DATA) {
  249. //DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u data(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  250. WebSocketIncommingBuffer *buffer = (WebSocketIncommingBuffer *)client->_tempObject;
  251. AwsFrameInfo * info = (AwsFrameInfo*)arg;
  252. buffer->data_event(client, info, data, len);
  253. }
  254. }
  255. // -----------------------------------------------------------------------------
  256. // Piblic API
  257. // -----------------------------------------------------------------------------
  258. bool wsConnected() {
  259. return (_ws.count() > 0);
  260. }
  261. void wsOnSendRegister(ws_on_send_callback_f callback) {
  262. _ws_on_send_callbacks.push_back(callback);
  263. }
  264. void wsOnActionRegister(ws_on_action_callback_f callback) {
  265. _ws_on_action_callbacks.push_back(callback);
  266. }
  267. void wsOnAfterParseRegister(ws_on_after_parse_callback_f callback) {
  268. _ws_on_after_parse_callbacks.push_back(callback);
  269. }
  270. void wsSend(ws_on_send_callback_f callback) {
  271. if (_ws.count() > 0) {
  272. DynamicJsonBuffer jsonBuffer;
  273. JsonObject& root = jsonBuffer.createObject();
  274. callback(root);
  275. String output;
  276. root.printTo(output);
  277. _ws.textAll((char *) output.c_str());
  278. }
  279. }
  280. void wsSend(const char * payload) {
  281. if (_ws.count() > 0) {
  282. _ws.textAll(payload);
  283. }
  284. }
  285. void wsSend_P(PGM_P payload) {
  286. if (_ws.count() > 0) {
  287. char buffer[strlen_P(payload)];
  288. strcpy_P(buffer, payload);
  289. _ws.textAll(buffer);
  290. }
  291. }
  292. void wsSend(uint32_t client_id, ws_on_send_callback_f callback) {
  293. DynamicJsonBuffer jsonBuffer;
  294. JsonObject& root = jsonBuffer.createObject();
  295. callback(root);
  296. String output;
  297. root.printTo(output);
  298. _ws.text(client_id, (char *) output.c_str());
  299. }
  300. void wsSend(uint32_t client_id, const char * payload) {
  301. _ws.text(client_id, payload);
  302. }
  303. void wsSend_P(uint32_t client_id, PGM_P payload) {
  304. char buffer[strlen_P(payload)];
  305. strcpy_P(buffer, payload);
  306. _ws.text(client_id, buffer);
  307. }
  308. void wsConfigure() {
  309. _ws.setAuthentication(WEB_USERNAME, (const char *) getSetting("adminPass", ADMIN_PASS).c_str());
  310. }
  311. void wsSetup() {
  312. _ws.onEvent(_wsEvent);
  313. wsConfigure();
  314. webServer()->addHandler(&_ws);
  315. #if MQTT_SUPPORT
  316. mqttRegister(_wsMQTTCallback);
  317. #endif
  318. wsOnSendRegister(_wsOnStart);
  319. wsOnAfterParseRegister(wsConfigure);
  320. }
  321. #endif // WEB_SUPPORT