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.

514 lines
14 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
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. typedef struct {
  16. IPAddress ip;
  17. unsigned long timestamp = 0;
  18. } ws_ticket_t;
  19. ws_ticket_t _ticket[WS_BUFFER_SIZE];
  20. // -----------------------------------------------------------------------------
  21. // WEBSOCKETS
  22. // -----------------------------------------------------------------------------
  23. bool wsSend(char * payload) {
  24. //DEBUG_MSG("[WEBSOCKET] Broadcasting '%s'\n", payload);
  25. ws.textAll(payload);
  26. }
  27. bool wsSend(uint32_t client_id, char * payload) {
  28. //DEBUG_MSG("[WEBSOCKET] Sending '%s' to #%ld\n", payload, client_id);
  29. ws.text(client_id, payload);
  30. }
  31. void wsMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  32. if (type == MQTT_CONNECT_EVENT) {
  33. wsSend((char *) "{\"mqttStatus\": true}");
  34. }
  35. if (type == MQTT_DISCONNECT_EVENT) {
  36. wsSend((char *) "{\"mqttStatus\": false}");
  37. }
  38. }
  39. void _wsParse(uint32_t client_id, uint8_t * payload, size_t length) {
  40. // Parse JSON input
  41. DynamicJsonBuffer jsonBuffer;
  42. JsonObject& root = jsonBuffer.parseObject((char *) payload);
  43. if (!root.success()) {
  44. DEBUG_MSG("[WEBSOCKET] Error parsing data\n");
  45. ws.text(client_id, "{\"message\": \"Error parsing data!\"}");
  46. return;
  47. }
  48. // Check actions
  49. if (root.containsKey("action")) {
  50. String action = root["action"];
  51. unsigned int relayID = 0;
  52. if (root.containsKey("relayID")) {
  53. String value = root["relayID"];
  54. relayID = value.toInt();
  55. }
  56. DEBUG_MSG("[WEBSOCKET] Requested action: %s\n", action.c_str());
  57. if (action.equals("reset")) ESP.reset();
  58. if (action.equals("reconnect")) wifiDisconnect();
  59. if (action.equals("on")) relayStatus(relayID, true);
  60. if (action.equals("off")) relayStatus(relayID, false);
  61. };
  62. // Check config
  63. if (root.containsKey("config") && root["config"].is<JsonArray&>()) {
  64. JsonArray& config = root["config"];
  65. DEBUG_MSG("[WEBSOCKET] Parsing configuration data\n");
  66. bool dirty = false;
  67. bool dirtyMQTT = false;
  68. bool apiEnabled = false;
  69. #if ENABLE_FAUXMO
  70. bool fauxmoEnabled = false;
  71. #endif
  72. unsigned int network = 0;
  73. String adminPass;
  74. for (unsigned int i=0; i<config.size(); i++) {
  75. String key = config[i]["name"];
  76. String value = config[i]["value"];
  77. #if ENABLE_POW
  78. if (key == "powExpectedPower") {
  79. powSetExpectedActivePower(value.toInt());
  80. continue;
  81. }
  82. #endif
  83. // Check password
  84. if (key == "adminPass1") {
  85. adminPass = value;
  86. continue;
  87. }
  88. if (key == "adminPass2") {
  89. if (!value.equals(adminPass)) {
  90. ws.text(client_id, "{\"message\": \"Passwords do not match!\"}");
  91. return;
  92. }
  93. if (value.length() == 0) continue;
  94. ws.text(client_id, "{\"action\": \"reload\"}");
  95. key = String("adminPass");
  96. }
  97. // Checkboxes
  98. if (key == "apiEnabled") {
  99. apiEnabled = true;
  100. continue;
  101. }
  102. #if ENABLE_FAUXMO
  103. if (key == "fauxmoEnabled") {
  104. fauxmoEnabled = true;
  105. continue;
  106. }
  107. #endif
  108. if (key == "ssid") {
  109. key = key + String(network);
  110. }
  111. if (key == "pass") {
  112. key = key + String(network);
  113. ++network;
  114. }
  115. if (value != getSetting(key)) {
  116. setSetting(key, value);
  117. dirty = true;
  118. if (key.startsWith("mqtt")) dirtyMQTT = true;
  119. }
  120. }
  121. // Checkboxes
  122. if (apiEnabled != (getSetting("apiEnabled").toInt() == 1)) {
  123. setSetting("apiEnabled", apiEnabled);
  124. dirty = true;
  125. }
  126. #if ENABLE_FAUXMO
  127. if (fauxmoEnabled != (getSetting("fauxmoEnabled").toInt() == 1)) {
  128. setSetting("fauxmoEnabled", fauxmoEnabled);
  129. dirty = true;
  130. }
  131. #endif
  132. // Save settings
  133. if (dirty) {
  134. saveSettings();
  135. wifiConfigure();
  136. otaConfigure();
  137. #if ENABLE_FAUXMO
  138. fauxmoConfigure();
  139. #endif
  140. buildTopics();
  141. #if ENABLE_RF
  142. rfBuildCodes();
  143. #endif
  144. #if ENABLE_EMON
  145. setCurrentRatio(getSetting("emonRatio").toFloat());
  146. #endif
  147. // Check if we should reconfigure MQTT connection
  148. if (dirtyMQTT) {
  149. mqttDisconnect();
  150. }
  151. ws.text(client_id, "{\"message\": \"Changes saved\"}");
  152. } else {
  153. ws.text(client_id, "{\"message\": \"No changes detected\"}");
  154. }
  155. }
  156. }
  157. void _wsStart(uint32_t client_id) {
  158. char chipid[6];
  159. sprintf(chipid, "%06X", ESP.getChipId());
  160. DynamicJsonBuffer jsonBuffer;
  161. JsonObject& root = jsonBuffer.createObject();
  162. root["app"] = APP_NAME;
  163. root["version"] = APP_VERSION;
  164. root["buildDate"] = __DATE__;
  165. root["buildTime"] = __TIME__;
  166. root["manufacturer"] = String(MANUFACTURER);
  167. root["chipid"] = chipid;
  168. root["mac"] = WiFi.macAddress();
  169. root["device"] = String(DEVICE);
  170. root["hostname"] = getSetting("hostname", HOSTNAME);
  171. root["network"] = getNetwork();
  172. root["ip"] = getIP();
  173. root["mqttStatus"] = mqttConnected();
  174. root["mqttServer"] = getSetting("mqttServer", MQTT_SERVER);
  175. root["mqttPort"] = getSetting("mqttPort", MQTT_PORT);
  176. root["mqttUser"] = getSetting("mqttUser");
  177. root["mqttPassword"] = getSetting("mqttPassword");
  178. root["mqttTopic"] = getSetting("mqttTopic", MQTT_TOPIC);
  179. JsonArray& relay = root.createNestedArray("relayStatus");
  180. for (unsigned char relayID=0; relayID<relayCount(); relayID++) {
  181. relay.add(relayStatus(relayID));
  182. }
  183. root["relayMode"] = getSetting("relayMode", RELAY_MODE);
  184. if (relayCount() > 1) {
  185. root["multirelayVisible"] = 1;
  186. root["relaySync"] = getSetting("relaySync", RELAY_SYNC);
  187. }
  188. root["apiEnabled"] = getSetting("apiEnabled").toInt() == 1;
  189. root["apiKey"] = getSetting("apiKey");
  190. #if ENABLE_FAUXMO
  191. root["fauxmoVisible"] = 1;
  192. root["fauxmoEnabled"] = getSetting("fauxmoEnabled", FAUXMO_ENABLED).toInt() == 1;
  193. #endif
  194. #if ENABLE_DS18B20
  195. root["dsVisible"] = 1;
  196. root["dsTmp"] = getDSTemperature();
  197. #endif
  198. #if ENABLE_DHT
  199. root["dhtVisible"] = 1;
  200. root["dhtTmp"] = getDHTTemperature();
  201. root["dhtHum"] = getDHTHumidity();
  202. #endif
  203. #if ENABLE_RF
  204. root["rfVisible"] = 1;
  205. root["rfChannel"] = getSetting("rfChannel", RF_CHANNEL);
  206. root["rfDevice"] = getSetting("rfDevice", RF_DEVICE);
  207. #endif
  208. #if ENABLE_EMON
  209. root["emonVisible"] = 1;
  210. root["emonPower"] = getPower();
  211. root["emonMains"] = getSetting("emonMains", EMON_MAINS_VOLTAGE);
  212. root["emonRatio"] = getSetting("emonRatio", EMON_CURRENT_RATIO);
  213. #endif
  214. #if ENABLE_POW
  215. root["powVisible"] = 1;
  216. root["powActivePower"] = getActivePower();
  217. #endif
  218. JsonArray& wifi = root.createNestedArray("wifi");
  219. for (byte i=0; i<3; i++) {
  220. JsonObject& network = wifi.createNestedObject();
  221. network["ssid"] = getSetting("ssid" + String(i));
  222. network["pass"] = getSetting("pass" + String(i));
  223. }
  224. String output;
  225. root.printTo(output);
  226. ws.text(client_id, (char *) output.c_str());
  227. }
  228. bool _wsAuth(AsyncWebSocketClient * client) {
  229. IPAddress ip = client->remoteIP();
  230. unsigned long now = millis();
  231. unsigned short index = 0;
  232. for (index = 0; index < WS_BUFFER_SIZE; index++) {
  233. if ((_ticket[index].ip == ip) && (now - _ticket[index].timestamp < WS_TIMEOUT)) break;
  234. }
  235. if (index == WS_BUFFER_SIZE) {
  236. DEBUG_MSG("[WEBSOCKET] Validation check failed\n");
  237. ws.text(client->id(), "{\"message\": \"Session expired, please reload page...\"}");
  238. return false;
  239. }
  240. return true;
  241. }
  242. void _wsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){
  243. // Authorize
  244. #ifndef NOWSAUTH
  245. if (!_wsAuth(client)) return;
  246. #endif
  247. if (type == WS_EVT_CONNECT) {
  248. IPAddress ip = client->remoteIP();
  249. 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());
  250. _wsStart(client->id());
  251. } else if(type == WS_EVT_DISCONNECT) {
  252. DEBUG_MSG("[WEBSOCKET] #%u disconnected\n", client->id());
  253. } else if(type == WS_EVT_ERROR) {
  254. DEBUG_MSG("[WEBSOCKET] #%u error(%u): %s\n", client->id(), *((uint16_t*)arg), (char*)data);
  255. } else if(type == WS_EVT_PONG) {
  256. DEBUG_MSG("[WEBSOCKET] #%u pong(%u): %s\n", client->id(), len, len ? (char*) data : "");
  257. } else if(type == WS_EVT_DATA) {
  258. _wsParse(client->id(), data, len);
  259. }
  260. }
  261. // -----------------------------------------------------------------------------
  262. // WEBSERVER
  263. // -----------------------------------------------------------------------------
  264. void _logRequest(AsyncWebServerRequest *request) {
  265. DEBUG_MSG("[WEBSERVER] Request: %s %s\n", request->methodToString(), request->url().c_str());
  266. }
  267. bool _authenticate(AsyncWebServerRequest *request) {
  268. String password = getSetting("adminPass", ADMIN_PASS);
  269. char httpPassword[password.length() + 1];
  270. password.toCharArray(httpPassword, password.length() + 1);
  271. return request->authenticate(HTTP_USERNAME, httpPassword);
  272. }
  273. void _onAuth(AsyncWebServerRequest *request) {
  274. _logRequest(request);
  275. if (!_authenticate(request)) return request->requestAuthentication();
  276. IPAddress ip = request->client()->remoteIP();
  277. unsigned long now = millis();
  278. unsigned short index;
  279. for (index = 0; index < WS_BUFFER_SIZE; index++) {
  280. if (_ticket[index].ip == ip) break;
  281. if (_ticket[index].timestamp == 0) break;
  282. if (now - _ticket[index].timestamp > WS_TIMEOUT) break;
  283. }
  284. if (index == WS_BUFFER_SIZE) {
  285. request->send(423);
  286. } else {
  287. _ticket[index].ip = ip;
  288. _ticket[index].timestamp = now;
  289. request->send(204);
  290. }
  291. }
  292. void _onHome(AsyncWebServerRequest *request) {
  293. _logRequest(request);
  294. if (!_authenticate(request)) return request->requestAuthentication();
  295. String password = getSetting("adminPass", ADMIN_PASS);
  296. if (password.equals(ADMIN_PASS)) {
  297. request->send(SPIFFS, "/password.html");
  298. } else {
  299. request->send(SPIFFS, "/index.html");
  300. }
  301. }
  302. bool _apiAuth(AsyncWebServerRequest *request) {
  303. if (getSetting("apiEnabled").toInt() == 0) {
  304. DEBUG_MSG("[WEBSERVER] HTTP API is not enabled\n");
  305. request->send(403);
  306. return false;
  307. }
  308. if (!request->hasParam("apikey", (request->method() == HTTP_PUT))) {
  309. DEBUG_MSG("[WEBSERVER] Missing apikey parameter\n");
  310. request->send(403);
  311. return false;
  312. }
  313. AsyncWebParameter* p = request->getParam("apikey", (request->method() == HTTP_PUT));
  314. if (!p->value().equals(getSetting("apiKey"))) {
  315. DEBUG_MSG("[WEBSERVER] Wrong apikey parameter\n");
  316. request->send(403);
  317. return false;
  318. }
  319. return true;
  320. }
  321. void _onRelay(AsyncWebServerRequest *request) {
  322. _logRequest(request);
  323. if (!_apiAuth(request)) return;
  324. bool asJson = false;
  325. if (request->hasHeader("Accept")) {
  326. AsyncWebHeader* h = request->getHeader("Accept");
  327. asJson = h->value().equals("application/json");
  328. }
  329. String output;
  330. if (asJson) {
  331. output = relayString();
  332. request->send(200, "application/json", output);
  333. } else {
  334. for (unsigned int i=0; i<relayCount(); i++) {
  335. output += "Relay #" + String(i) + String(": ") + String(relayStatus(i) ? "1" : "0") + "\n";
  336. }
  337. request->send(200, "text/plain", output);
  338. }
  339. };
  340. ArRequestHandlerFunction _onRelayStatusWrapper(unsigned int relayID) {
  341. return [relayID](AsyncWebServerRequest *request) {
  342. _logRequest(request);
  343. if (!_apiAuth(request)) return;
  344. if (request->method() == HTTP_PUT) {
  345. if (request->hasParam("status", true)) {
  346. AsyncWebParameter* p = request->getParam("status", true);
  347. wsSend((char *) String(relayID).c_str());
  348. wsSend((char *) p->value().c_str());
  349. unsigned int value = p->value().toInt();
  350. if (value == 2) {
  351. relayToggle(relayID);
  352. } else {
  353. relayStatus(relayID, value == 1);
  354. }
  355. }
  356. }
  357. bool asJson = false;
  358. if (request->hasHeader("Accept")) {
  359. AsyncWebHeader* h = request->getHeader("Accept");
  360. asJson = h->value().equals("application/json");
  361. }
  362. String output;
  363. if (asJson) {
  364. output = String("{\"relayStatus\": ") + String(relayStatus(relayID) ? "1" : "0") + "}";
  365. request->send(200, "application/json", output);
  366. } else {
  367. request->send(200, "text/plain", relayStatus(relayID) ? "1" : "0");
  368. }
  369. };
  370. }
  371. void webSetup() {
  372. // Setup websocket
  373. ws.onEvent(_wsEvent);
  374. mqttRegister(wsMQTTCallback);
  375. // Setup webserver
  376. server.addHandler(&ws);
  377. // Serve home (basic authentication protection)
  378. server.on("/", HTTP_GET, _onHome);
  379. server.on("/index.html", HTTP_GET, _onHome);
  380. server.on("/auth", HTTP_GET, _onAuth);
  381. // API entry points (protected with apikey)
  382. for (unsigned int relayID=0; relayID<relayCount(); relayID++) {
  383. char buffer[15];
  384. sprintf(buffer, "/api/relay/%d", relayID);
  385. server.on(buffer, HTTP_GET + HTTP_PUT, _onRelayStatusWrapper(relayID));
  386. }
  387. server.on("/api/relay", HTTP_GET, _onRelay);
  388. // Serve static files
  389. char lastModified[50];
  390. sprintf(lastModified, "%s %s GMT", __DATE__, __TIME__);
  391. server.serveStatic("/", SPIFFS, "/").setLastModified(lastModified);
  392. // 404
  393. server.onNotFound([](AsyncWebServerRequest *request){
  394. request->send(404);
  395. });
  396. // Run server
  397. server.begin();
  398. }