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.

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