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.

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