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.

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