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.

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