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