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.

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