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.

275 lines
7.9 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 == "httpPassword") {
  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. buildTopics();
  91. #if ENABLE_RF
  92. rfBuildCodes();
  93. #endif
  94. #if ENABLE_EMON
  95. setCurrentRatio(getSetting("emonRatio").toFloat());
  96. #endif
  97. // Check if we should reconfigure MQTT connection
  98. if (dirtyMQTT) {
  99. mqttDisconnect();
  100. }
  101. ws.text(client_id, "{\"message\": \"Changes saved\"}");
  102. } else {
  103. ws.text(client_id, "{\"message\": \"No changes detected\"}");
  104. }
  105. }
  106. }
  107. void webSocketStart(uint32_t client_id) {
  108. char app[64];
  109. sprintf(app, "%s %s", APP_NAME, APP_VERSION);
  110. char chipid[6];
  111. sprintf(chipid, "%06X", ESP.getChipId());
  112. DynamicJsonBuffer jsonBuffer;
  113. JsonObject& root = jsonBuffer.createObject();
  114. // CSRF
  115. if (client_id < CSRF_BUFFER_SIZE) {
  116. _csrf[client_id] = random(0x7fffffff);
  117. }
  118. root["csrf"] = _csrf[client_id % CSRF_BUFFER_SIZE];
  119. root["app"] = app;
  120. root["manufacturer"] = String(MANUFACTURER);
  121. root["chipid"] = chipid;
  122. root["mac"] = WiFi.macAddress();
  123. root["device"] = String(DEVICE);
  124. root["hostname"] = getSetting("hostname", HOSTNAME);
  125. root["network"] = getNetwork();
  126. root["ip"] = getIP();
  127. root["mqttStatus"] = mqttConnected() ? "1" : "0";
  128. root["mqttServer"] = getSetting("mqttServer", MQTT_SERVER);
  129. root["mqttPort"] = getSetting("mqttPort", String(MQTT_PORT));
  130. root["mqttUser"] = getSetting("mqttUser");
  131. root["mqttPassword"] = getSetting("mqttPassword");
  132. root["mqttTopic"] = getSetting("mqttTopic", MQTT_TOPIC);
  133. root["relayStatus"] = digitalRead(RELAY_PIN) == HIGH;
  134. root["relayMode"] = getSetting("relayMode", String(RELAY_MODE));
  135. #if ENABLE_DHT
  136. root["dhtVisible"] = 1;
  137. root["dhtTmp"] = getTemperature();
  138. root["dhtHum"] = getHumidity();
  139. #endif
  140. #if ENABLE_RF
  141. root["rfVisible"] = 1;
  142. root["rfChannel"] = getSetting("rfChannel", String(RF_CHANNEL));
  143. root["rfDevice"] = getSetting("rfDevice", String(RF_DEVICE));
  144. #endif
  145. #if ENABLE_EMON
  146. root["emonVisible"] = 1;
  147. root["emonPower"] = getPower();
  148. root["emonMains"] = getSetting("emonMains", String(EMON_MAINS_VOLTAGE));
  149. root["emonRatio"] = getSetting("emonRatio", String(EMON_CURRENT_RATIO));
  150. #endif
  151. #if ENABLE_POW
  152. root["powVisible"] = 1;
  153. root["powActivePower"] = getActivePower();
  154. #endif
  155. JsonArray& wifi = root.createNestedArray("wifi");
  156. for (byte i=0; i<3; i++) {
  157. JsonObject& network = wifi.createNestedObject();
  158. network["ssid"] = getSetting("ssid" + String(i));
  159. network["pass"] = getSetting("pass" + String(i));
  160. }
  161. String output;
  162. root.printTo(output);
  163. ws.text(client_id, (char *) output.c_str());
  164. }
  165. void webSocketEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){
  166. if (type == WS_EVT_CONNECT) {
  167. #if DEBUG_PORT
  168. {
  169. IPAddress ip = server.remoteIP(client->id());
  170. 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());
  171. }
  172. #endif
  173. webSocketStart(client->id());
  174. } else if(type == WS_EVT_DISCONNECT) {
  175. DEBUG_MSG("[WEBSOCKET] #%u disconnected\n", client->id());
  176. } else if(type == WS_EVT_ERROR) {
  177. DEBUG_MSG("[WEBSOCKET] #%u error(%u): %s\n", client->id(), *((uint16_t*)arg), (char*)data);
  178. } else if(type == WS_EVT_PONG) {
  179. DEBUG_MSG("[WEBSOCKET] #%u pong(%u): %s\n", client->id(), len, len ? (char*) data : "");
  180. } else if(type == WS_EVT_DATA) {
  181. webSocketParse(client->id(), data, len);
  182. }
  183. }
  184. // -----------------------------------------------------------------------------
  185. // WEBSERVER
  186. // -----------------------------------------------------------------------------
  187. void onHome(AsyncWebServerRequest *request){
  188. String password = getSetting("httpPassword", HTTP_PASSWORD);
  189. char httpPassword[password.length() + 1];
  190. password.toCharArray(httpPassword, password.length() + 1);
  191. Serial.println(httpPassword);
  192. if (!request->authenticate(HTTP_USERNAME, httpPassword)) {
  193. return request->requestAuthentication();
  194. }
  195. request->send(SPIFFS, "/index.html");
  196. }
  197. void webSetup() {
  198. // Setup websocket plugin
  199. ws.onEvent(webSocketEvent);
  200. server.addHandler(&ws);
  201. // Serve home
  202. server.on("/", HTTP_GET, onHome);
  203. server.on("/index.html", HTTP_GET, onHome);
  204. // Serve static files
  205. server.serveStatic("/", SPIFFS, "/");
  206. // 404
  207. server.onNotFound([](AsyncWebServerRequest *request){
  208. request->send(404);
  209. });
  210. // Run server
  211. server.begin();
  212. }