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.

748 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. 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. unsigned char webMode = WEB_MODE_NORMAL;
  79. bool save = false;
  80. bool changed = false;
  81. bool changedMQTT = false;
  82. bool apiEnabled = false;
  83. #if ENABLE_FAUXMO
  84. bool fauxmoEnabled = false;
  85. #endif
  86. unsigned int network = 0;
  87. unsigned int dczRelayIdx = 0;
  88. String adminPass;
  89. for (unsigned int i=0; i<config.size(); i++) {
  90. String key = config[i]["name"];
  91. String value = config[i]["value"];
  92. #if ENABLE_POW
  93. if (key == "powExpectedPower") {
  94. powSetExpectedActivePower(value.toInt());
  95. changed = true;
  96. }
  97. if (key == "powExpectedVoltage") {
  98. powSetExpectedVoltage(value.toInt());
  99. changed = true;
  100. }
  101. if (key == "powExpectedCurrent") {
  102. powSetExpectedCurrent(value.toInt());
  103. changed = true;
  104. }
  105. if (key == "powExpectedReset") {
  106. powReset();
  107. changed = true;
  108. }
  109. #endif
  110. if (key.startsWith("pow")) continue;
  111. #if ENABLE_DOMOTICZ
  112. if (key == "dczRelayIdx") {
  113. if (dczRelayIdx >= relayCount()) continue;
  114. key = key + String(dczRelayIdx);
  115. ++dczRelayIdx;
  116. }
  117. #else
  118. if (key.startsWith("dcz")) continue;
  119. #endif
  120. // Web portions
  121. if (key == "webPort") {
  122. if ((value.toInt() == 0) || (value.toInt() == 80)) {
  123. save = changed = true;
  124. delSetting(key);
  125. continue;
  126. }
  127. }
  128. if (key == "webMode") {
  129. webMode = value.toInt();
  130. continue;
  131. }
  132. // Check password
  133. if (key == "adminPass1") {
  134. adminPass = value;
  135. continue;
  136. }
  137. if (key == "adminPass2") {
  138. if (!value.equals(adminPass)) {
  139. ws.text(client_id, "{\"message\": \"Passwords do not match!\"}");
  140. return;
  141. }
  142. if (value.length() == 0) continue;
  143. ws.text(client_id, "{\"action\": \"reload\"}");
  144. key = String("adminPass");
  145. }
  146. // Checkboxes
  147. if (key == "apiEnabled") {
  148. apiEnabled = true;
  149. continue;
  150. }
  151. #if ENABLE_FAUXMO
  152. if (key == "fauxmoEnabled") {
  153. fauxmoEnabled = true;
  154. continue;
  155. }
  156. #endif
  157. if (key == "ssid") {
  158. key = key + String(network);
  159. }
  160. if (key == "pass") {
  161. key = key + String(network);
  162. }
  163. if (key == "ip") {
  164. key = key + String(network);
  165. }
  166. if (key == "gw") {
  167. key = key + String(network);
  168. }
  169. if (key == "mask") {
  170. key = key + String(network);
  171. }
  172. if (key == "dns") {
  173. key = key + String(network);
  174. ++network;
  175. }
  176. if (value != getSetting(key)) {
  177. //DEBUG_MSG("[WEBSOCKET] Storing %s = %s\n", key.c_str(), value.c_str());
  178. setSetting(key, value);
  179. save = changed = true;
  180. if (key.startsWith("mqtt")) changedMQTT = true;
  181. }
  182. }
  183. if (webMode == WEB_MODE_NORMAL) {
  184. // Checkboxes
  185. if (apiEnabled != (getSetting("apiEnabled").toInt() == 1)) {
  186. setSetting("apiEnabled", apiEnabled);
  187. save = changed = true;
  188. }
  189. #if ENABLE_FAUXMO
  190. if (fauxmoEnabled != (getSetting("fauxmoEnabled").toInt() == 1)) {
  191. setSetting("fauxmoEnabled", fauxmoEnabled);
  192. save = changed = true;
  193. }
  194. #endif
  195. // Clean wifi networks
  196. int i = 0;
  197. while (i < network) {
  198. if (getSetting("ssid" + String(i)).length() == 0) {
  199. delSetting("ssid" + String(i));
  200. break;
  201. }
  202. if (getSetting("pass" + String(i)).length() == 0) delSetting("pass" + String(i));
  203. if (getSetting("ip" + String(i)).length() == 0) delSetting("ip" + String(i));
  204. if (getSetting("gw" + String(i)).length() == 0) delSetting("gw" + String(i));
  205. if (getSetting("mask" + String(i)).length() == 0) delSetting("mask" + String(i));
  206. if (getSetting("dns" + String(i)).length() == 0) delSetting("dns" + String(i));
  207. ++i;
  208. }
  209. while (i < WIFI_MAX_NETWORKS) {
  210. if (getSetting("ssid" + String(i)).length() > 0) {
  211. save = changed = true;
  212. }
  213. delSetting("ssid" + String(i));
  214. delSetting("pass" + String(i));
  215. delSetting("ip" + String(i));
  216. delSetting("gw" + String(i));
  217. delSetting("mask" + String(i));
  218. delSetting("dns" + String(i));
  219. ++i;
  220. }
  221. }
  222. // Save settings
  223. if (save) {
  224. saveSettings();
  225. wifiConfigure();
  226. otaConfigure();
  227. #if ENABLE_FAUXMO
  228. fauxmoConfigure();
  229. #endif
  230. buildTopics();
  231. #if ENABLE_RF
  232. rfBuildCodes();
  233. #endif
  234. #if ENABLE_EMON
  235. setCurrentRatio(getSetting("emonRatio").toFloat());
  236. #endif
  237. // Check if we should reconfigure MQTT connection
  238. if (changedMQTT) {
  239. mqttDisconnect();
  240. }
  241. }
  242. if (changed) {
  243. ws.text(client_id, "{\"message\": \"Changes saved\"}");
  244. } else {
  245. ws.text(client_id, "{\"message\": \"No changes detected\"}");
  246. }
  247. }
  248. }
  249. void _wsStart(uint32_t client_id) {
  250. char chipid[6];
  251. sprintf(chipid, "%06X", ESP.getChipId());
  252. DynamicJsonBuffer jsonBuffer;
  253. JsonObject& root = jsonBuffer.createObject();
  254. bool changePassword = false;
  255. #if FORCE_CHANGE_PASS == 1
  256. String adminPass = getSetting("adminPass", ADMIN_PASS);
  257. if (adminPass.equals(ADMIN_PASS)) changePassword = true;
  258. #endif
  259. if (changePassword) {
  260. root["webMode"] = WEB_MODE_PASSWORD;
  261. } else {
  262. root["webMode"] = WEB_MODE_NORMAL;
  263. root["app"] = APP_NAME;
  264. root["version"] = APP_VERSION;
  265. root["buildDate"] = __DATE__;
  266. root["buildTime"] = __TIME__;
  267. root["manufacturer"] = String(MANUFACTURER);
  268. root["chipid"] = chipid;
  269. root["mac"] = WiFi.macAddress();
  270. root["device"] = String(DEVICE);
  271. root["hostname"] = getSetting("hostname", HOSTNAME);
  272. root["network"] = getNetwork();
  273. root["deviceip"] = getIP();
  274. root["mqttStatus"] = mqttConnected();
  275. root["mqttServer"] = getSetting("mqttServer", MQTT_SERVER);
  276. root["mqttPort"] = getSetting("mqttPort", MQTT_PORT);
  277. root["mqttUser"] = getSetting("mqttUser");
  278. root["mqttPassword"] = getSetting("mqttPassword");
  279. root["mqttTopic"] = getSetting("mqttTopic", MQTT_TOPIC);
  280. JsonArray& relay = root.createNestedArray("relayStatus");
  281. for (unsigned char relayID=0; relayID<relayCount(); relayID++) {
  282. relay.add(relayStatus(relayID));
  283. }
  284. root["relayMode"] = getSetting("relayMode", RELAY_MODE);
  285. root["relayPulseMode"] = getSetting("relayPulseMode", RELAY_PULSE_MODE);
  286. root["relayPulseTime"] = getSetting("relayPulseTime", RELAY_PULSE_TIME);
  287. if (relayCount() > 1) {
  288. root["multirelayVisible"] = 1;
  289. root["relaySync"] = getSetting("relaySync", RELAY_SYNC);
  290. }
  291. root["webPort"] = getSetting("webPort", WEBSERVER_PORT).toInt();
  292. root["apiEnabled"] = getSetting("apiEnabled").toInt() == 1;
  293. root["apiKey"] = getSetting("apiKey");
  294. root["tmpUnits"] = getSetting("tmpUnits", TMP_UNITS).toInt();
  295. #if ENABLE_DOMOTICZ
  296. root["dczVisible"] = 1;
  297. root["dczTopicIn"] = getSetting("dczTopicIn", DOMOTICZ_IN_TOPIC);
  298. root["dczTopicOut"] = getSetting("dczTopicOut", DOMOTICZ_OUT_TOPIC);
  299. JsonArray& dczRelayIdx = root.createNestedArray("dczRelayIdx");
  300. for (byte i=0; i<relayCount(); i++) {
  301. dczRelayIdx.add(relayToIdx(i));
  302. }
  303. #if ENABLE_DHT
  304. root["dczTmpIdx"] = getSetting("dczTmpIdx").toInt();
  305. root["dczHumIdx"] = getSetting("dczHumIdx").toInt();
  306. #endif
  307. #if ENABLE_DS18B20
  308. root["dczTmpIdx"] = getSetting("dczTmpIdx").toInt();
  309. #endif
  310. #if ENABLE_EMON
  311. root["dczPowIdx"] = getSetting("dczPowIdx").toInt();
  312. root["dczEnergyIdx"] = getSetting("dczEnergyIdx").toInt();
  313. root["dczCurrentIdx"] = getSetting("dczCurrentIdx").toInt();
  314. #endif
  315. #if ENABLE_POW
  316. root["dczPowIdx"] = getSetting("dczPowIdx").toInt();
  317. root["dczEnergyIdx"] = getSetting("dczEnergyIdx").toInt();
  318. root["dczVoltIdx"] = getSetting("dczVoltIdx").toInt();
  319. root["dczCurrentIdx"] = getSetting("dczCurrentIdx").toInt();
  320. #endif
  321. #endif
  322. #if ENABLE_FAUXMO
  323. root["fauxmoVisible"] = 1;
  324. root["fauxmoEnabled"] = getSetting("fauxmoEnabled", FAUXMO_ENABLED).toInt() == 1;
  325. #endif
  326. #if ENABLE_DS18B20
  327. root["dsVisible"] = 1;
  328. root["dsTmp"] = getDSTemperature();
  329. #endif
  330. #if ENABLE_DHT
  331. root["dhtVisible"] = 1;
  332. root["dhtTmp"] = getDHTTemperature();
  333. root["dhtHum"] = getDHTHumidity();
  334. #endif
  335. #if ENABLE_RF
  336. root["rfVisible"] = 1;
  337. root["rfChannel"] = getSetting("rfChannel", RF_CHANNEL);
  338. root["rfDevice"] = getSetting("rfDevice", RF_DEVICE);
  339. #endif
  340. #if ENABLE_EMON
  341. root["emonVisible"] = 1;
  342. root["emonPower"] = getPower();
  343. root["emonMains"] = getSetting("emonMains", EMON_MAINS_VOLTAGE);
  344. root["emonRatio"] = getSetting("emonRatio", EMON_CURRENT_RATIO);
  345. #endif
  346. #if ENABLE_POW
  347. root["powVisible"] = 1;
  348. root["powActivePower"] = getActivePower();
  349. root["powApparentPower"] = getApparentPower();
  350. root["powReactivePower"] = getReactivePower();
  351. root["powVoltage"] = getVoltage();
  352. root["powCurrent"] = getCurrent();
  353. root["powPowerFactor"] = getPowerFactor();
  354. #endif
  355. root["maxNetworks"] = WIFI_MAX_NETWORKS;
  356. JsonArray& wifi = root.createNestedArray("wifi");
  357. for (byte i=0; i<WIFI_MAX_NETWORKS; i++) {
  358. if (getSetting("ssid" + String(i)).length() == 0) break;
  359. JsonObject& network = wifi.createNestedObject();
  360. network["ssid"] = getSetting("ssid" + String(i));
  361. network["pass"] = getSetting("pass" + String(i));
  362. network["ip"] = getSetting("ip" + String(i));
  363. network["gw"] = getSetting("gw" + String(i));
  364. network["mask"] = getSetting("mask" + String(i));
  365. network["dns"] = getSetting("dns" + String(i));
  366. }
  367. }
  368. String output;
  369. root.printTo(output);
  370. ws.text(client_id, (char *) output.c_str());
  371. }
  372. bool _wsAuth(AsyncWebSocketClient * client) {
  373. IPAddress ip = client->remoteIP();
  374. unsigned long now = millis();
  375. unsigned short index = 0;
  376. for (index = 0; index < WS_BUFFER_SIZE; index++) {
  377. if ((_ticket[index].ip == ip) && (now - _ticket[index].timestamp < WS_TIMEOUT)) break;
  378. }
  379. if (index == WS_BUFFER_SIZE) {
  380. DEBUG_MSG("[WEBSOCKET] Validation check failed\n");
  381. ws.text(client->id(), "{\"message\": \"Session expired, please reload page...\"}");
  382. return false;
  383. }
  384. return true;
  385. }
  386. void _wsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){
  387. static uint8_t * message;
  388. // Authorize
  389. #ifndef NOWSAUTH
  390. if (!_wsAuth(client)) return;
  391. #endif
  392. if (type == WS_EVT_CONNECT) {
  393. IPAddress ip = client->remoteIP();
  394. 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());
  395. _wsStart(client->id());
  396. } else if(type == WS_EVT_DISCONNECT) {
  397. DEBUG_MSG("[WEBSOCKET] #%u disconnected\n", client->id());
  398. } else if(type == WS_EVT_ERROR) {
  399. DEBUG_MSG("[WEBSOCKET] #%u error(%u): %s\n", client->id(), *((uint16_t*)arg), (char*)data);
  400. } else if(type == WS_EVT_PONG) {
  401. DEBUG_MSG("[WEBSOCKET] #%u pong(%u): %s\n", client->id(), len, len ? (char*) data : "");
  402. } else if(type == WS_EVT_DATA) {
  403. AwsFrameInfo * info = (AwsFrameInfo*)arg;
  404. // First packet
  405. if (info->index == 0) {
  406. //Serial.printf("Before malloc: %d\n", ESP.getFreeHeap());
  407. message = (uint8_t*) malloc(info->len);
  408. //Serial.printf("After malloc: %d\n", ESP.getFreeHeap());
  409. }
  410. // Store data
  411. memcpy(message + info->index, data, len);
  412. // Last packet
  413. if (info->index + len == info->len) {
  414. _wsParse(client->id(), message, info->len);
  415. //Serial.printf("Before free: %d\n", ESP.getFreeHeap());
  416. free(message);
  417. //Serial.printf("After free: %d\n", ESP.getFreeHeap());
  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 (request->method() == HTTP_PUT) {
  467. if (request->hasParam("value", true)) {
  468. AsyncWebParameter* p = request->getParam("value", true);
  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 _onHome(AsyncWebServerRequest *request) {
  536. webLogRequest(request);
  537. if (!_authenticate(request)) return request->requestAuthentication();
  538. request->send(SPIFFS, "/index.html");
  539. }
  540. void _onAuth(AsyncWebServerRequest *request) {
  541. webLogRequest(request);
  542. if (!_authenticate(request)) return request->requestAuthentication();
  543. IPAddress ip = request->client()->remoteIP();
  544. unsigned long now = millis();
  545. unsigned short index;
  546. for (index = 0; index < WS_BUFFER_SIZE; index++) {
  547. if (_ticket[index].ip == ip) break;
  548. if (_ticket[index].timestamp == 0) break;
  549. if (now - _ticket[index].timestamp > WS_TIMEOUT) break;
  550. }
  551. if (index == WS_BUFFER_SIZE) {
  552. request->send(423);
  553. } else {
  554. _ticket[index].ip = ip;
  555. _ticket[index].timestamp = now;
  556. request->send(204);
  557. }
  558. }
  559. void webSetup() {
  560. // Create server
  561. _server = new AsyncWebServer(getSetting("webPort", WEBSERVER_PORT).toInt());
  562. // Setup websocket
  563. ws.onEvent(_wsEvent);
  564. mqttRegister(wsMQTTCallback);
  565. // Setup webserver
  566. _server->addHandler(&ws);
  567. // Serve home (basic authentication protection)
  568. _server->on("/", HTTP_GET, _onHome);
  569. _server->on("/index.html", HTTP_GET, _onHome);
  570. _server->on("/auth", HTTP_GET, _onAuth);
  571. _server->on("/apis", HTTP_GET, _onAPIs);
  572. _server->on("/rpc", HTTP_GET, _onRPC);
  573. // Serve static files
  574. char lastModified[50];
  575. sprintf(lastModified, "%s %s GMT", __DATE__, __TIME__);
  576. _server->serveStatic("/", SPIFFS, "/").setLastModified(lastModified);
  577. // 404
  578. _server->onNotFound([](AsyncWebServerRequest *request){
  579. request->send(404);
  580. });
  581. // Run server
  582. _server->begin();
  583. }