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.

292 lines
8.4 KiB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
  1. /*
  2. ESPurna
  3. WEBSERVER MODULE
  4. Copyright (C) 2016 by Xose Pérez <xose dot perez at gmail dot com>
  5. */
  6. #include <ESPAsyncTCP.h>
  7. #include <ESPAsyncWebServer.h>
  8. #include <ESP8266mDNS.h>
  9. #include <FS.h>
  10. #include <Hash.h>
  11. #include <AsyncJson.h>
  12. #include <ArduinoJson.h>
  13. AsyncWebServer server(80);
  14. AsyncWebSocket ws("/ws");
  15. unsigned long _csrf[CSRF_BUFFER_SIZE];
  16. // -----------------------------------------------------------------------------
  17. // WEBSOCKETS
  18. // -----------------------------------------------------------------------------
  19. bool webSocketSend(char * payload) {
  20. //DEBUG_MSG("[WEBSOCKET] Broadcasting '%s'\n", payload);
  21. ws.textAll(payload);
  22. }
  23. bool webSocketSend(uint32_t client_id, char * payload) {
  24. //DEBUG_MSG("[WEBSOCKET] Sending '%s' to #%ld\n", payload, client_id);
  25. ws.text(client_id, payload);
  26. }
  27. void webSocketParse(uint32_t client_id, uint8_t * payload, size_t length) {
  28. // Parse JSON input
  29. DynamicJsonBuffer jsonBuffer;
  30. JsonObject& root = jsonBuffer.parseObject((char *) payload);
  31. if (!root.success()) {
  32. DEBUG_MSG("[WEBSOCKET] Error parsing data\n");
  33. ws.text(client_id, "{\"message\": \"Error parsing data!\"}");
  34. return;
  35. }
  36. // CSRF
  37. unsigned long csrf = 0;
  38. if (root.containsKey("csrf")) csrf = root["csrf"];
  39. if (csrf != _csrf[client_id % CSRF_BUFFER_SIZE]) {
  40. DEBUG_MSG("[WEBSOCKET] CSRF check failed\n");
  41. ws.text(client_id, "{\"message\": \"Session expired, please reload page...\"}");
  42. return;
  43. }
  44. // Check actions
  45. if (root.containsKey("action")) {
  46. String action = root["action"];
  47. DEBUG_MSG("[WEBSOCKET] Requested action: %s\n", action.c_str());
  48. if (action.equals("reset")) ESP.reset();
  49. if (action.equals("reconnect")) wifiDisconnect();
  50. if (action.equals("on")) switchRelayOn();
  51. if (action.equals("off")) switchRelayOff();
  52. };
  53. // Check config
  54. if (root.containsKey("config") && root["config"].is<JsonArray&>()) {
  55. JsonArray& config = root["config"];
  56. DEBUG_MSG("[WEBSOCKET] Parsing configuration data\n");
  57. bool dirty = false;
  58. bool dirtyMQTT = false;
  59. unsigned int network = 0;
  60. for (unsigned int i=0; i<config.size(); i++) {
  61. String key = config[i]["name"];
  62. String value = config[i]["value"];
  63. #if ENABLE_POW
  64. if (key == "powExpectedPower") {
  65. powSetExpectedActivePower(value.toInt());
  66. continue;
  67. }
  68. #endif
  69. // Do not change the password if empty
  70. if (key == "adminPass") {
  71. if (value.length() == 0) continue;
  72. }
  73. if (key == "ssid") {
  74. key = key + String(network);
  75. }
  76. if (key == "pass") {
  77. key = key + String(network);
  78. ++network;
  79. }
  80. if (value != getSetting(key)) {
  81. setSetting(key, value);
  82. dirty = true;
  83. if (key.startsWith("mqtt")) dirtyMQTT = true;
  84. }
  85. }
  86. // Save settings
  87. if (dirty) {
  88. saveSettings();
  89. wifiConfigure();
  90. otaConfigure();
  91. buildTopics();
  92. #if ENABLE_RF
  93. rfBuildCodes();
  94. #endif
  95. #if ENABLE_EMON
  96. setCurrentRatio(getSetting("emonRatio").toFloat());
  97. #endif
  98. // Check if we should reconfigure MQTT connection
  99. if (dirtyMQTT) {
  100. mqttDisconnect();
  101. }
  102. ws.text(client_id, "{\"message\": \"Changes saved\"}");
  103. } else {
  104. ws.text(client_id, "{\"message\": \"No changes detected\"}");
  105. }
  106. }
  107. }
  108. void webSocketStart(uint32_t client_id) {
  109. char app[64];
  110. sprintf(app, "%s %s", APP_NAME, APP_VERSION);
  111. char chipid[6];
  112. sprintf(chipid, "%06X", ESP.getChipId());
  113. DynamicJsonBuffer jsonBuffer;
  114. JsonObject& root = jsonBuffer.createObject();
  115. // CSRF
  116. if (client_id < CSRF_BUFFER_SIZE) {
  117. _csrf[client_id] = random(0x7fffffff);
  118. }
  119. root["csrf"] = _csrf[client_id % CSRF_BUFFER_SIZE];
  120. root["app"] = app;
  121. root["manufacturer"] = String(MANUFACTURER);
  122. root["chipid"] = chipid;
  123. root["mac"] = WiFi.macAddress();
  124. root["device"] = String(DEVICE);
  125. root["hostname"] = getSetting("hostname", HOSTNAME);
  126. root["network"] = getNetwork();
  127. root["ip"] = getIP();
  128. root["mqttStatus"] = mqttConnected() ? "1" : "0";
  129. root["mqttServer"] = getSetting("mqttServer", MQTT_SERVER);
  130. root["mqttPort"] = getSetting("mqttPort", String(MQTT_PORT));
  131. root["mqttUser"] = getSetting("mqttUser");
  132. root["mqttPassword"] = getSetting("mqttPassword");
  133. root["mqttTopic"] = getSetting("mqttTopic", MQTT_TOPIC);
  134. root["relayStatus"] = digitalRead(RELAY_PIN) == HIGH;
  135. root["relayMode"] = getSetting("relayMode", String(RELAY_MODE));
  136. #if ENABLE_DHT
  137. root["dhtVisible"] = 1;
  138. root["dhtTmp"] = getTemperature();
  139. root["dhtHum"] = getHumidity();
  140. #endif
  141. #if ENABLE_RF
  142. root["rfVisible"] = 1;
  143. root["rfChannel"] = getSetting("rfChannel", String(RF_CHANNEL));
  144. root["rfDevice"] = getSetting("rfDevice", String(RF_DEVICE));
  145. #endif
  146. #if ENABLE_EMON
  147. root["emonVisible"] = 1;
  148. root["emonPower"] = getPower();
  149. root["emonMains"] = getSetting("emonMains", String(EMON_MAINS_VOLTAGE));
  150. root["emonRatio"] = getSetting("emonRatio", String(EMON_CURRENT_RATIO));
  151. #endif
  152. #if ENABLE_POW
  153. root["powVisible"] = 1;
  154. root["powActivePower"] = getActivePower();
  155. #endif
  156. JsonArray& wifi = root.createNestedArray("wifi");
  157. for (byte i=0; i<3; i++) {
  158. JsonObject& network = wifi.createNestedObject();
  159. network["ssid"] = getSetting("ssid" + String(i));
  160. network["pass"] = getSetting("pass" + String(i));
  161. }
  162. String output;
  163. root.printTo(output);
  164. ws.text(client_id, (char *) output.c_str());
  165. }
  166. void webSocketEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){
  167. if (type == WS_EVT_CONNECT) {
  168. #if DEBUG_PORT
  169. {
  170. IPAddress ip = server.remoteIP(client->id());
  171. DEBUG_MSG("[WEBSOCKET] #%u connected, ip: %d.%d.%d.%d, url: %s\n", client->id(), ip[0], ip[1], ip[2], ip[3], server->url());
  172. }
  173. #endif
  174. webSocketStart(client->id());
  175. } else if(type == WS_EVT_DISCONNECT) {
  176. DEBUG_MSG("[WEBSOCKET] #%u disconnected\n", client->id());
  177. } else if(type == WS_EVT_ERROR) {
  178. DEBUG_MSG("[WEBSOCKET] #%u error(%u): %s\n", client->id(), *((uint16_t*)arg), (char*)data);
  179. } else if(type == WS_EVT_PONG) {
  180. DEBUG_MSG("[WEBSOCKET] #%u pong(%u): %s\n", client->id(), len, len ? (char*) data : "");
  181. } else if(type == WS_EVT_DATA) {
  182. webSocketParse(client->id(), data, len);
  183. }
  184. }
  185. // -----------------------------------------------------------------------------
  186. // WEBSERVER
  187. // -----------------------------------------------------------------------------
  188. void onHome(AsyncWebServerRequest *request) {
  189. DEBUG_MSG("[WEBSERVER] Request: %s\n", request->url().c_str());
  190. String password = getSetting("adminPass", ADMIN_PASS);
  191. char httpPassword[password.length() + 1];
  192. password.toCharArray(httpPassword, password.length() + 1);
  193. if (!request->authenticate(HTTP_USERNAME, httpPassword)) {
  194. return request->requestAuthentication();
  195. }
  196. request->send(SPIFFS, "/index.html");
  197. }
  198. void onRelayOn(AsyncWebServerRequest *request) {
  199. DEBUG_MSG("[WEBSERVER] Request: %s\n", request->url().c_str());
  200. switchRelayOn();
  201. request->send(200, "text/plain", "ON");
  202. };
  203. void onRelayOff(AsyncWebServerRequest *request) {
  204. DEBUG_MSG("[WEBSERVER] Request: %s\n", request->url().c_str());
  205. switchRelayOff();
  206. request->send(200, "text/plain", "OFF");
  207. };
  208. void webSetup() {
  209. // Setup websocket plugin
  210. ws.onEvent(webSocketEvent);
  211. server.addHandler(&ws);
  212. // Serve home (password protected)
  213. server.on("/", HTTP_GET, onHome);
  214. server.on("/index.html", HTTP_GET, onHome);
  215. // API entry points (non protected)
  216. server.on("/relay/on", HTTP_GET, onRelayOn);
  217. server.on("/relay/off", HTTP_GET, onRelayOff);
  218. // Serve static files
  219. server.serveStatic("/", SPIFFS, "/");
  220. // 404
  221. server.onNotFound([](AsyncWebServerRequest *request){
  222. request->send(404);
  223. });
  224. // Run server
  225. server.begin();
  226. }