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.

607 lines
18 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. static uint8_t * message;
  303. // Authorize
  304. #ifndef NOWSAUTH
  305. if (!_wsAuth(client)) return;
  306. #endif
  307. if (type == WS_EVT_CONNECT) {
  308. IPAddress ip = client->remoteIP();
  309. 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());
  310. _wsStart(client->id());
  311. } else if(type == WS_EVT_DISCONNECT) {
  312. DEBUG_MSG("[WEBSOCKET] #%u disconnected\n", client->id());
  313. } else if(type == WS_EVT_ERROR) {
  314. DEBUG_MSG("[WEBSOCKET] #%u error(%u): %s\n", client->id(), *((uint16_t*)arg), (char*)data);
  315. } else if(type == WS_EVT_PONG) {
  316. DEBUG_MSG("[WEBSOCKET] #%u pong(%u): %s\n", client->id(), len, len ? (char*) data : "");
  317. } else if(type == WS_EVT_DATA) {
  318. AwsFrameInfo * info = (AwsFrameInfo*)arg;
  319. // First packet
  320. if (info->index == 0) {
  321. //Serial.printf("Before malloc: %d\n", ESP.getFreeHeap());
  322. message = (uint8_t*) malloc(info->len);
  323. //Serial.printf("After malloc: %d\n", ESP.getFreeHeap());
  324. }
  325. // Store data
  326. memcpy(message + info->index, data, len);
  327. // Last packet
  328. if (info->index + len == info->len) {
  329. _wsParse(client->id(), message, info->len);
  330. //Serial.printf("Before free: %d\n", ESP.getFreeHeap());
  331. free(message);
  332. //Serial.printf("After free: %d\n", ESP.getFreeHeap());
  333. }
  334. }
  335. }
  336. // -----------------------------------------------------------------------------
  337. // WEBSERVER
  338. // -----------------------------------------------------------------------------
  339. void _logRequest(AsyncWebServerRequest *request) {
  340. DEBUG_MSG("[WEBSERVER] Request: %s %s\n", request->methodToString(), request->url().c_str());
  341. }
  342. bool _authenticate(AsyncWebServerRequest *request) {
  343. String password = getSetting("adminPass", ADMIN_PASS);
  344. char httpPassword[password.length() + 1];
  345. password.toCharArray(httpPassword, password.length() + 1);
  346. return request->authenticate(HTTP_USERNAME, httpPassword);
  347. }
  348. void _onAuth(AsyncWebServerRequest *request) {
  349. _logRequest(request);
  350. if (!_authenticate(request)) return request->requestAuthentication();
  351. IPAddress ip = request->client()->remoteIP();
  352. unsigned long now = millis();
  353. unsigned short index;
  354. for (index = 0; index < WS_BUFFER_SIZE; index++) {
  355. if (_ticket[index].ip == ip) break;
  356. if (_ticket[index].timestamp == 0) break;
  357. if (now - _ticket[index].timestamp > WS_TIMEOUT) break;
  358. }
  359. if (index == WS_BUFFER_SIZE) {
  360. request->send(423);
  361. } else {
  362. _ticket[index].ip = ip;
  363. _ticket[index].timestamp = now;
  364. request->send(204);
  365. }
  366. }
  367. void _onHome(AsyncWebServerRequest *request) {
  368. _logRequest(request);
  369. if (!_authenticate(request)) return request->requestAuthentication();
  370. String password = getSetting("adminPass", ADMIN_PASS);
  371. if (password.equals(ADMIN_PASS)) {
  372. request->send(SPIFFS, "/password.html");
  373. } else {
  374. request->send(SPIFFS, "/index.html");
  375. }
  376. }
  377. bool _apiAuth(AsyncWebServerRequest *request) {
  378. if (getSetting("apiEnabled").toInt() == 0) {
  379. DEBUG_MSG("[WEBSERVER] HTTP API is not enabled\n");
  380. request->send(403);
  381. return false;
  382. }
  383. if (!request->hasParam("apikey", (request->method() == HTTP_PUT))) {
  384. DEBUG_MSG("[WEBSERVER] Missing apikey parameter\n");
  385. request->send(403);
  386. return false;
  387. }
  388. AsyncWebParameter* p = request->getParam("apikey", (request->method() == HTTP_PUT));
  389. if (!p->value().equals(getSetting("apiKey"))) {
  390. DEBUG_MSG("[WEBSERVER] Wrong apikey parameter\n");
  391. request->send(403);
  392. return false;
  393. }
  394. return true;
  395. }
  396. void _onRelay(AsyncWebServerRequest *request) {
  397. _logRequest(request);
  398. if (!_apiAuth(request)) return;
  399. bool asJson = false;
  400. if (request->hasHeader("Accept")) {
  401. AsyncWebHeader* h = request->getHeader("Accept");
  402. asJson = h->value().equals("application/json");
  403. }
  404. String output;
  405. if (asJson) {
  406. output = relayString();
  407. request->send(200, "application/json", output);
  408. } else {
  409. for (unsigned int i=0; i<relayCount(); i++) {
  410. output += "Relay #" + String(i) + String(": ") + String(relayStatus(i) ? "1" : "0") + "\n";
  411. }
  412. request->send(200, "text/plain", output);
  413. }
  414. };
  415. ArRequestHandlerFunction _onRelayStatusWrapper(unsigned int relayID) {
  416. return [relayID](AsyncWebServerRequest *request) {
  417. _logRequest(request);
  418. if (!_apiAuth(request)) return;
  419. if (request->method() == HTTP_PUT) {
  420. if (request->hasParam("status", true)) {
  421. AsyncWebParameter* p = request->getParam("status", true);
  422. wsSend((char *) String(relayID).c_str());
  423. wsSend((char *) p->value().c_str());
  424. unsigned int value = p->value().toInt();
  425. if (value == 2) {
  426. relayToggle(relayID);
  427. } else {
  428. relayStatus(relayID, value == 1);
  429. }
  430. }
  431. }
  432. bool asJson = false;
  433. if (request->hasHeader("Accept")) {
  434. AsyncWebHeader* h = request->getHeader("Accept");
  435. asJson = h->value().equals("application/json");
  436. }
  437. String output;
  438. if (asJson) {
  439. output = String("{\"relayStatus\": ") + String(relayStatus(relayID) ? "1" : "0") + "}";
  440. request->send(200, "application/json", output);
  441. } else {
  442. request->send(200, "text/plain", relayStatus(relayID) ? "1" : "0");
  443. }
  444. };
  445. }
  446. void webSetup() {
  447. // Setup websocket
  448. ws.onEvent(_wsEvent);
  449. mqttRegister(wsMQTTCallback);
  450. // Setup webserver
  451. server.addHandler(&ws);
  452. // Serve home (basic authentication protection)
  453. server.on("/", HTTP_GET, _onHome);
  454. server.on("/index.html", HTTP_GET, _onHome);
  455. server.on("/auth", HTTP_GET, _onAuth);
  456. // API entry points (protected with apikey)
  457. for (unsigned int relayID=0; relayID<relayCount(); relayID++) {
  458. char buffer[15];
  459. sprintf(buffer, "/api/relay/%d", relayID);
  460. server.on(buffer, HTTP_GET + HTTP_PUT, _onRelayStatusWrapper(relayID));
  461. }
  462. server.on("/api/relay", HTTP_GET, _onRelay);
  463. // Serve static files
  464. char lastModified[50];
  465. sprintf(lastModified, "%s %s GMT", __DATE__, __TIME__);
  466. server.serveStatic("/", SPIFFS, "/").setLastModified(lastModified);
  467. // 404
  468. server.onNotFound([](AsyncWebServerRequest *request){
  469. request->send(404);
  470. });
  471. // Run server
  472. server.begin();
  473. }