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.

777 lines
23 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
7 years ago
7 years ago
7 years ago
7 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. #include <vector>
  14. #if EMBEDDED_WEB
  15. #include "config/data.h"
  16. #endif
  17. AsyncWebServer * _server;
  18. AsyncWebSocket ws("/ws");
  19. Ticker deferred;
  20. typedef struct {
  21. IPAddress ip;
  22. unsigned long timestamp = 0;
  23. } ws_ticket_t;
  24. ws_ticket_t _ticket[WS_BUFFER_SIZE];
  25. typedef struct {
  26. char * url;
  27. char * key;
  28. apiGetCallbackFunction getFn = NULL;
  29. apiPutCallbackFunction putFn = NULL;
  30. } web_api_t;
  31. std::vector<web_api_t> _apis;
  32. char _last_modified[50];
  33. // -----------------------------------------------------------------------------
  34. // WEBSOCKETS
  35. // -----------------------------------------------------------------------------
  36. bool wsSend(const char * payload) {
  37. DEBUG_MSG("[WEBSOCKET] Broadcasting '%s'\n", payload);
  38. ws.textAll(payload);
  39. }
  40. bool wsSend(uint32_t client_id, const char * payload) {
  41. DEBUG_MSG("[WEBSOCKET] Sending '%s' to #%ld\n", payload, client_id);
  42. ws.text(client_id, payload);
  43. }
  44. void wsMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  45. if (type == MQTT_CONNECT_EVENT) {
  46. wsSend("{\"mqttStatus\": true}");
  47. }
  48. if (type == MQTT_DISCONNECT_EVENT) {
  49. wsSend("{\"mqttStatus\": false}");
  50. }
  51. }
  52. void _wsParse(uint32_t client_id, uint8_t * payload, size_t length) {
  53. // Parse JSON input
  54. DynamicJsonBuffer jsonBuffer;
  55. JsonObject& root = jsonBuffer.parseObject((char *) payload);
  56. if (!root.success()) {
  57. DEBUG_MSG("[WEBSOCKET] Error parsing data\n");
  58. ws.text(client_id, "{\"message\": \"Error parsing data!\"}");
  59. return;
  60. }
  61. // Check actions
  62. if (root.containsKey("action")) {
  63. String action = root["action"];
  64. unsigned int relayID = 0;
  65. if (root.containsKey("relayID")) {
  66. String value = root["relayID"];
  67. relayID = value.toInt();
  68. }
  69. DEBUG_MSG("[WEBSOCKET] Requested action: %s\n", action.c_str());
  70. if (action.equals("reset")) ESP.reset();
  71. if (action.equals("reconnect")) {
  72. // Let the HTTP request return and disconnect after 100ms
  73. deferred.once_ms(100, wifiDisconnect);
  74. }
  75. if (action.equals("on")) relayStatus(relayID, true);
  76. if (action.equals("off")) relayStatus(relayID, false);
  77. };
  78. // Check config
  79. if (root.containsKey("config") && root["config"].is<JsonArray&>()) {
  80. JsonArray& config = root["config"];
  81. DEBUG_MSG("[WEBSOCKET] Parsing configuration data\n");
  82. unsigned char webMode = WEB_MODE_NORMAL;
  83. bool save = false;
  84. bool changed = false;
  85. bool changedMQTT = false;
  86. bool apiEnabled = false;
  87. #if ENABLE_FAUXMO
  88. bool fauxmoEnabled = false;
  89. #endif
  90. unsigned int network = 0;
  91. unsigned int dczRelayIdx = 0;
  92. String adminPass;
  93. for (unsigned int i=0; i<config.size(); i++) {
  94. String key = config[i]["name"];
  95. String value = config[i]["value"];
  96. #if ENABLE_POW
  97. if (key == "powExpectedPower") {
  98. powSetExpectedActivePower(value.toInt());
  99. changed = true;
  100. }
  101. if (key == "powExpectedVoltage") {
  102. powSetExpectedVoltage(value.toInt());
  103. changed = true;
  104. }
  105. if (key == "powExpectedCurrent") {
  106. powSetExpectedCurrent(value.toInt());
  107. changed = true;
  108. }
  109. if (key == "powExpectedReset") {
  110. powReset();
  111. changed = true;
  112. }
  113. #endif
  114. if (key.startsWith("pow")) continue;
  115. #if ENABLE_DOMOTICZ
  116. if (key == "dczRelayIdx") {
  117. if (dczRelayIdx >= relayCount()) continue;
  118. key = key + String(dczRelayIdx);
  119. ++dczRelayIdx;
  120. }
  121. #else
  122. if (key.startsWith("dcz")) continue;
  123. #endif
  124. // Web portions
  125. if (key == "webPort") {
  126. if ((value.toInt() == 0) || (value.toInt() == 80)) {
  127. save = changed = true;
  128. delSetting(key);
  129. continue;
  130. }
  131. }
  132. if (key == "webMode") {
  133. webMode = value.toInt();
  134. continue;
  135. }
  136. // Check password
  137. if (key == "adminPass1") {
  138. adminPass = value;
  139. continue;
  140. }
  141. if (key == "adminPass2") {
  142. if (!value.equals(adminPass)) {
  143. ws.text(client_id, "{\"message\": \"Passwords do not match!\"}");
  144. return;
  145. }
  146. if (value.length() == 0) continue;
  147. ws.text(client_id, "{\"action\": \"reload\"}");
  148. key = String("adminPass");
  149. }
  150. // Checkboxes
  151. if (key == "apiEnabled") {
  152. apiEnabled = true;
  153. continue;
  154. }
  155. #if ENABLE_FAUXMO
  156. if (key == "fauxmoEnabled") {
  157. fauxmoEnabled = true;
  158. continue;
  159. }
  160. #endif
  161. if (key == "ssid") {
  162. key = key + String(network);
  163. }
  164. if (key == "pass") {
  165. key = key + String(network);
  166. }
  167. if (key == "ip") {
  168. key = key + String(network);
  169. }
  170. if (key == "gw") {
  171. key = key + String(network);
  172. }
  173. if (key == "mask") {
  174. key = key + String(network);
  175. }
  176. if (key == "dns") {
  177. key = key + String(network);
  178. ++network;
  179. }
  180. if (value != getSetting(key)) {
  181. //DEBUG_MSG("[WEBSOCKET] Storing %s = %s\n", key.c_str(), value.c_str());
  182. setSetting(key, value);
  183. save = changed = true;
  184. if (key.startsWith("mqtt")) changedMQTT = true;
  185. }
  186. }
  187. if (webMode == WEB_MODE_NORMAL) {
  188. // Checkboxes
  189. if (apiEnabled != (getSetting("apiEnabled").toInt() == 1)) {
  190. setSetting("apiEnabled", apiEnabled);
  191. save = changed = true;
  192. }
  193. #if ENABLE_FAUXMO
  194. if (fauxmoEnabled != (getSetting("fauxmoEnabled").toInt() == 1)) {
  195. setSetting("fauxmoEnabled", fauxmoEnabled);
  196. save = changed = true;
  197. }
  198. #endif
  199. // Clean wifi networks
  200. int i = 0;
  201. while (i < network) {
  202. if (getSetting("ssid" + String(i)).length() == 0) {
  203. delSetting("ssid" + String(i));
  204. break;
  205. }
  206. if (getSetting("pass" + String(i)).length() == 0) delSetting("pass" + String(i));
  207. if (getSetting("ip" + String(i)).length() == 0) delSetting("ip" + String(i));
  208. if (getSetting("gw" + String(i)).length() == 0) delSetting("gw" + String(i));
  209. if (getSetting("mask" + String(i)).length() == 0) delSetting("mask" + String(i));
  210. if (getSetting("dns" + String(i)).length() == 0) delSetting("dns" + String(i));
  211. ++i;
  212. }
  213. while (i < WIFI_MAX_NETWORKS) {
  214. if (getSetting("ssid" + String(i)).length() > 0) {
  215. save = changed = true;
  216. }
  217. delSetting("ssid" + String(i));
  218. delSetting("pass" + String(i));
  219. delSetting("ip" + String(i));
  220. delSetting("gw" + String(i));
  221. delSetting("mask" + String(i));
  222. delSetting("dns" + String(i));
  223. ++i;
  224. }
  225. }
  226. // Save settings
  227. if (save) {
  228. saveSettings();
  229. wifiConfigure();
  230. otaConfigure();
  231. #if ENABLE_FAUXMO
  232. fauxmoConfigure();
  233. #endif
  234. buildTopics();
  235. #if ENABLE_RF
  236. rfBuildCodes();
  237. #endif
  238. #if ENABLE_EMON
  239. setCurrentRatio(getSetting("emonRatio").toFloat());
  240. #endif
  241. // Check if we should reconfigure MQTT connection
  242. if (changedMQTT) {
  243. mqttDisconnect();
  244. }
  245. }
  246. if (changed) {
  247. ws.text(client_id, "{\"message\": \"Changes saved\"}");
  248. } else {
  249. ws.text(client_id, "{\"message\": \"No changes detected\"}");
  250. }
  251. }
  252. }
  253. void _wsStart(uint32_t client_id) {
  254. char chipid[6];
  255. sprintf(chipid, "%06X", ESP.getChipId());
  256. DynamicJsonBuffer jsonBuffer;
  257. JsonObject& root = jsonBuffer.createObject();
  258. bool changePassword = false;
  259. #if FORCE_CHANGE_PASS == 1
  260. String adminPass = getSetting("adminPass", ADMIN_PASS);
  261. if (adminPass.equals(ADMIN_PASS)) changePassword = true;
  262. #endif
  263. if (changePassword) {
  264. root["webMode"] = WEB_MODE_PASSWORD;
  265. } else {
  266. root["webMode"] = WEB_MODE_NORMAL;
  267. root["app"] = APP_NAME;
  268. root["version"] = APP_VERSION;
  269. root["buildDate"] = __DATE__;
  270. root["buildTime"] = __TIME__;
  271. root["manufacturer"] = String(MANUFACTURER);
  272. root["chipid"] = chipid;
  273. root["mac"] = WiFi.macAddress();
  274. root["device"] = String(DEVICE);
  275. root["hostname"] = getSetting("hostname", HOSTNAME);
  276. root["network"] = getNetwork();
  277. root["deviceip"] = getIP();
  278. root["mqttStatus"] = mqttConnected();
  279. root["mqttServer"] = getSetting("mqttServer", MQTT_SERVER);
  280. root["mqttPort"] = getSetting("mqttPort", MQTT_PORT);
  281. root["mqttUser"] = getSetting("mqttUser");
  282. root["mqttPassword"] = getSetting("mqttPassword");
  283. root["mqttTopic"] = getSetting("mqttTopic", MQTT_TOPIC);
  284. JsonArray& relay = root.createNestedArray("relayStatus");
  285. for (unsigned char relayID=0; relayID<relayCount(); relayID++) {
  286. relay.add(relayStatus(relayID));
  287. }
  288. root["relayMode"] = getSetting("relayMode", RELAY_MODE);
  289. root["relayPulseMode"] = getSetting("relayPulseMode", RELAY_PULSE_MODE);
  290. root["relayPulseTime"] = getSetting("relayPulseTime", RELAY_PULSE_TIME);
  291. if (relayCount() > 1) {
  292. root["multirelayVisible"] = 1;
  293. root["relaySync"] = getSetting("relaySync", RELAY_SYNC);
  294. }
  295. root["webPort"] = getSetting("webPort", WEBSERVER_PORT).toInt();
  296. root["apiEnabled"] = getSetting("apiEnabled").toInt() == 1;
  297. root["apiKey"] = getSetting("apiKey");
  298. root["tmpUnits"] = getSetting("tmpUnits", TMP_UNITS).toInt();
  299. #if ENABLE_DOMOTICZ
  300. root["dczVisible"] = 1;
  301. root["dczTopicIn"] = getSetting("dczTopicIn", DOMOTICZ_IN_TOPIC);
  302. root["dczTopicOut"] = getSetting("dczTopicOut", DOMOTICZ_OUT_TOPIC);
  303. JsonArray& dczRelayIdx = root.createNestedArray("dczRelayIdx");
  304. for (byte i=0; i<relayCount(); i++) {
  305. dczRelayIdx.add(relayToIdx(i));
  306. }
  307. #if ENABLE_DHT
  308. root["dczTmpIdx"] = getSetting("dczTmpIdx").toInt();
  309. root["dczHumIdx"] = getSetting("dczHumIdx").toInt();
  310. #endif
  311. #if ENABLE_DS18B20
  312. root["dczTmpIdx"] = getSetting("dczTmpIdx").toInt();
  313. #endif
  314. #if ENABLE_EMON
  315. root["dczPowIdx"] = getSetting("dczPowIdx").toInt();
  316. root["dczEnergyIdx"] = getSetting("dczEnergyIdx").toInt();
  317. root["dczCurrentIdx"] = getSetting("dczCurrentIdx").toInt();
  318. #endif
  319. #if ENABLE_POW
  320. root["dczPowIdx"] = getSetting("dczPowIdx").toInt();
  321. root["dczEnergyIdx"] = getSetting("dczEnergyIdx").toInt();
  322. root["dczVoltIdx"] = getSetting("dczVoltIdx").toInt();
  323. root["dczCurrentIdx"] = getSetting("dczCurrentIdx").toInt();
  324. #endif
  325. #endif
  326. #if ENABLE_FAUXMO
  327. root["fauxmoVisible"] = 1;
  328. root["fauxmoEnabled"] = getSetting("fauxmoEnabled", FAUXMO_ENABLED).toInt() == 1;
  329. #endif
  330. #if ENABLE_DS18B20
  331. root["dsVisible"] = 1;
  332. root["dsTmp"] = getDSTemperature();
  333. #endif
  334. #if ENABLE_DHT
  335. root["dhtVisible"] = 1;
  336. root["dhtTmp"] = getDHTTemperature();
  337. root["dhtHum"] = getDHTHumidity();
  338. #endif
  339. #if ENABLE_RF
  340. root["rfVisible"] = 1;
  341. root["rfChannel"] = getSetting("rfChannel", RF_CHANNEL);
  342. root["rfDevice"] = getSetting("rfDevice", RF_DEVICE);
  343. #endif
  344. #if ENABLE_EMON
  345. root["emonVisible"] = 1;
  346. root["emonPower"] = getPower();
  347. root["emonMains"] = getSetting("emonMains", EMON_MAINS_VOLTAGE);
  348. root["emonRatio"] = getSetting("emonRatio", EMON_CURRENT_RATIO);
  349. #endif
  350. #if ENABLE_POW
  351. root["powVisible"] = 1;
  352. root["powActivePower"] = getActivePower();
  353. root["powApparentPower"] = getApparentPower();
  354. root["powReactivePower"] = getReactivePower();
  355. root["powVoltage"] = getVoltage();
  356. root["powCurrent"] = getCurrent();
  357. root["powPowerFactor"] = getPowerFactor();
  358. #endif
  359. root["maxNetworks"] = WIFI_MAX_NETWORKS;
  360. JsonArray& wifi = root.createNestedArray("wifi");
  361. for (byte i=0; i<WIFI_MAX_NETWORKS; i++) {
  362. if (getSetting("ssid" + String(i)).length() == 0) break;
  363. JsonObject& network = wifi.createNestedObject();
  364. network["ssid"] = getSetting("ssid" + String(i));
  365. network["pass"] = getSetting("pass" + String(i));
  366. network["ip"] = getSetting("ip" + String(i));
  367. network["gw"] = getSetting("gw" + String(i));
  368. network["mask"] = getSetting("mask" + String(i));
  369. network["dns"] = getSetting("dns" + String(i));
  370. }
  371. }
  372. String output;
  373. root.printTo(output);
  374. ws.text(client_id, (char *) output.c_str());
  375. }
  376. bool _wsAuth(AsyncWebSocketClient * client) {
  377. IPAddress ip = client->remoteIP();
  378. unsigned long now = millis();
  379. unsigned short index = 0;
  380. for (index = 0; index < WS_BUFFER_SIZE; index++) {
  381. if ((_ticket[index].ip == ip) && (now - _ticket[index].timestamp < WS_TIMEOUT)) break;
  382. }
  383. if (index == WS_BUFFER_SIZE) {
  384. DEBUG_MSG("[WEBSOCKET] Validation check failed\n");
  385. ws.text(client->id(), "{\"message\": \"Session expired, please reload page...\"}");
  386. return false;
  387. }
  388. return true;
  389. }
  390. void _wsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){
  391. static uint8_t * message;
  392. // Authorize
  393. #ifndef NOWSAUTH
  394. if (!_wsAuth(client)) return;
  395. #endif
  396. if (type == WS_EVT_CONNECT) {
  397. IPAddress ip = client->remoteIP();
  398. 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());
  399. _wsStart(client->id());
  400. } else if(type == WS_EVT_DISCONNECT) {
  401. DEBUG_MSG("[WEBSOCKET] #%u disconnected\n", client->id());
  402. } else if(type == WS_EVT_ERROR) {
  403. DEBUG_MSG("[WEBSOCKET] #%u error(%u): %s\n", client->id(), *((uint16_t*)arg), (char*)data);
  404. } else if(type == WS_EVT_PONG) {
  405. DEBUG_MSG("[WEBSOCKET] #%u pong(%u): %s\n", client->id(), len, len ? (char*) data : "");
  406. } else if(type == WS_EVT_DATA) {
  407. AwsFrameInfo * info = (AwsFrameInfo*)arg;
  408. // First packet
  409. if (info->index == 0) {
  410. message = (uint8_t*) malloc(info->len);
  411. }
  412. // Store data
  413. memcpy(message + info->index, data, len);
  414. // Last packet
  415. if (info->index + len == info->len) {
  416. _wsParse(client->id(), message, info->len);
  417. free(message);
  418. }
  419. }
  420. }
  421. // -----------------------------------------------------------------------------
  422. // WEBSERVER
  423. // -----------------------------------------------------------------------------
  424. void webLogRequest(AsyncWebServerRequest *request) {
  425. DEBUG_MSG("[WEBSERVER] Request: %s %s\n", request->methodToString(), request->url().c_str());
  426. }
  427. bool _authenticate(AsyncWebServerRequest *request) {
  428. String password = getSetting("adminPass", ADMIN_PASS);
  429. char httpPassword[password.length() + 1];
  430. password.toCharArray(httpPassword, password.length() + 1);
  431. return request->authenticate(HTTP_USERNAME, httpPassword);
  432. }
  433. bool _authAPI(AsyncWebServerRequest *request) {
  434. if (getSetting("apiEnabled").toInt() == 0) {
  435. DEBUG_MSG("[WEBSERVER] HTTP API is not enabled\n");
  436. request->send(403);
  437. return false;
  438. }
  439. if (!request->hasParam("apikey", (request->method() == HTTP_PUT))) {
  440. DEBUG_MSG("[WEBSERVER] Missing apikey parameter\n");
  441. request->send(403);
  442. return false;
  443. }
  444. AsyncWebParameter* p = request->getParam("apikey", (request->method() == HTTP_PUT));
  445. if (!p->value().equals(getSetting("apiKey"))) {
  446. DEBUG_MSG("[WEBSERVER] Wrong apikey parameter\n");
  447. request->send(403);
  448. return false;
  449. }
  450. return true;
  451. }
  452. bool _asJson(AsyncWebServerRequest *request) {
  453. bool asJson = false;
  454. if (request->hasHeader("Accept")) {
  455. AsyncWebHeader* h = request->getHeader("Accept");
  456. asJson = h->value().equals("application/json");
  457. }
  458. return asJson;
  459. }
  460. ArRequestHandlerFunction _bindAPI(unsigned int apiID) {
  461. return [apiID](AsyncWebServerRequest *request) {
  462. webLogRequest(request);
  463. if (!_authAPI(request)) return;
  464. bool asJson = _asJson(request);
  465. web_api_t api = _apis[apiID];
  466. if (api.putFn != NULL) {
  467. if (request->hasParam("value", request->method() == HTTP_PUT)) {
  468. AsyncWebParameter* p = request->getParam("value", request->method() == HTTP_PUT);
  469. (api.putFn)((p->value()).c_str());
  470. }
  471. }
  472. char value[10];
  473. (api.getFn)(value, 10);
  474. // jump over leading spaces
  475. char *p = value;
  476. while ((unsigned char) *p == ' ') ++p;
  477. if (asJson) {
  478. char buffer[64];
  479. sprintf_P(buffer, PSTR("{ \"%s\": %s }"), api.key, p);
  480. request->send(200, "application/json", buffer);
  481. } else {
  482. request->send(200, "text/plain", p);
  483. }
  484. };
  485. }
  486. void apiRegister(const char * url, const char * key, apiGetCallbackFunction getFn, apiPutCallbackFunction putFn) {
  487. // Store it
  488. web_api_t api;
  489. api.url = strdup(url);
  490. api.key = strdup(key);
  491. api.getFn = getFn;
  492. api.putFn = putFn;
  493. _apis.push_back(api);
  494. // Bind call
  495. unsigned int methods = HTTP_GET;
  496. if (putFn != NULL) methods += HTTP_PUT;
  497. _server->on(url, methods, _bindAPI(_apis.size() - 1));
  498. }
  499. void _onAPIs(AsyncWebServerRequest *request) {
  500. webLogRequest(request);
  501. if (!_authAPI(request)) return;
  502. bool asJson = _asJson(request);
  503. String output;
  504. if (asJson) {
  505. DynamicJsonBuffer jsonBuffer;
  506. JsonObject& root = jsonBuffer.createObject();
  507. for (unsigned int i=0; i < _apis.size(); i++) {
  508. root[_apis[i].key] = _apis[i].url;
  509. }
  510. root.printTo(output);
  511. request->send(200, "application/json", output);
  512. } else {
  513. for (unsigned int i=0; i < _apis.size(); i++) {
  514. output += _apis[i].key + String(" -> ") + _apis[i].url + String("\n<br />");
  515. }
  516. request->send(200, "text/plain", output);
  517. }
  518. }
  519. void _onRPC(AsyncWebServerRequest *request) {
  520. webLogRequest(request);
  521. if (!_authAPI(request)) return;
  522. //bool asJson = _asJson(request);
  523. int response = 404;
  524. if (request->hasParam("action")) {
  525. AsyncWebParameter* p = request->getParam("action");
  526. String action = p->value();
  527. DEBUG_MSG("[RPC] Action: %s\n", action.c_str());
  528. if (action.equals("reset")) {
  529. response = 200;
  530. deferred.once_ms(100, []() { ESP.reset(); });
  531. }
  532. }
  533. request->send(response);
  534. }
  535. void _onAuth(AsyncWebServerRequest *request) {
  536. webLogRequest(request);
  537. if (!_authenticate(request)) return request->requestAuthentication();
  538. IPAddress ip = request->client()->remoteIP();
  539. unsigned long now = millis();
  540. unsigned short index;
  541. for (index = 0; index < WS_BUFFER_SIZE; index++) {
  542. if (_ticket[index].ip == ip) break;
  543. if (_ticket[index].timestamp == 0) break;
  544. if (now - _ticket[index].timestamp > WS_TIMEOUT) break;
  545. }
  546. if (index == WS_BUFFER_SIZE) {
  547. request->send(429);
  548. } else {
  549. _ticket[index].ip = ip;
  550. _ticket[index].timestamp = now;
  551. request->send(204);
  552. }
  553. }
  554. #if EMBEDDED_WEB
  555. void _onHome(AsyncWebServerRequest *request) {
  556. webLogRequest(request);
  557. if (request->header("If-Modified-Since").equals(_last_modified)) {
  558. request->send(304);
  559. } else {
  560. AsyncWebServerResponse *response = request->beginResponse_P(200, "text/html", index_html_gz, index_html_gz_len);
  561. response->addHeader("Content-Encoding", "gzip");
  562. response->addHeader("Last-Modified", _last_modified);
  563. request->send(response);
  564. }
  565. }
  566. #endif
  567. void webSetup() {
  568. // Create server
  569. _server = new AsyncWebServer(getSetting("webPort", WEBSERVER_PORT).toInt());
  570. // Setup websocket
  571. ws.onEvent(_wsEvent);
  572. mqttRegister(wsMQTTCallback);
  573. // Cache the Last-Modifier header value
  574. sprintf(_last_modified, "%s %s GMT", __DATE__, __TIME__);
  575. // Setup webserver
  576. _server->addHandler(&ws);
  577. // Rewrites
  578. _server->rewrite("/", "/index.html");
  579. // Serve home (basic authentication protection)
  580. #if EMBEDDED_WEB
  581. _server->on("/index.html", HTTP_GET, _onHome);
  582. #endif
  583. _server->on("/auth", HTTP_GET, _onAuth);
  584. _server->on("/apis", HTTP_GET, _onAPIs);
  585. _server->on("/rpc", HTTP_GET, _onRPC);
  586. // Serve static files
  587. #if not EMBEDDED_WEB
  588. _server->serveStatic("/", SPIFFS, "/")
  589. .setLastModified(_last_modified)
  590. .setFilter([](AsyncWebServerRequest *request) -> bool {
  591. webLogRequest(request);
  592. return true;
  593. });
  594. #endif
  595. // 404
  596. _server->onNotFound([](AsyncWebServerRequest *request){
  597. request->send(404);
  598. });
  599. // Run server
  600. _server->begin();
  601. DEBUG_MSG("[WEBSERVER] Webserver running on port %d\n", getSetting("webPort", WEBSERVER_PORT).toInt());
  602. }