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.

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