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.

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