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.

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