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.

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