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.

725 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
7 years ago
7 years ago
7 years ago
7 years ago
8 years ago
8 years ago
8 years ago
8 years ago
7 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
7 years ago
8 years ago
7 years ago
8 years ago
7 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. #endif
  287. #endif
  288. #if ENABLE_FAUXMO
  289. root["fauxmoVisible"] = 1;
  290. root["fauxmoEnabled"] = getSetting("fauxmoEnabled", FAUXMO_ENABLED).toInt() == 1;
  291. #endif
  292. #if ENABLE_DS18B20
  293. root["dsVisible"] = 1;
  294. root["dsTmp"] = getDSTemperature();
  295. #endif
  296. #if ENABLE_DHT
  297. root["dhtVisible"] = 1;
  298. root["dhtTmp"] = getDHTTemperature();
  299. root["dhtHum"] = getDHTHumidity();
  300. #endif
  301. #if ENABLE_RF
  302. root["rfVisible"] = 1;
  303. root["rfChannel"] = getSetting("rfChannel", RF_CHANNEL);
  304. root["rfDevice"] = getSetting("rfDevice", RF_DEVICE);
  305. #endif
  306. #if ENABLE_EMON
  307. root["emonVisible"] = 1;
  308. root["emonPower"] = getPower();
  309. root["emonMains"] = getSetting("emonMains", EMON_MAINS_VOLTAGE);
  310. root["emonRatio"] = getSetting("emonRatio", EMON_CURRENT_RATIO);
  311. #endif
  312. #if ENABLE_POW
  313. root["powVisible"] = 1;
  314. root["powActivePower"] = getActivePower();
  315. root["powApparentPower"] = getApparentPower();
  316. root["powReactivePower"] = getReactivePower();
  317. root["powVoltage"] = getVoltage();
  318. root["powCurrent"] = getCurrent();
  319. root["powPowerFactor"] = getPowerFactor();
  320. #endif
  321. root["maxNetworks"] = WIFI_MAX_NETWORKS;
  322. JsonArray& wifi = root.createNestedArray("wifi");
  323. for (byte i=0; i<WIFI_MAX_NETWORKS; i++) {
  324. if (getSetting("ssid" + String(i)).length() == 0) break;
  325. JsonObject& network = wifi.createNestedObject();
  326. network["ssid"] = getSetting("ssid" + String(i));
  327. network["pass"] = getSetting("pass" + String(i));
  328. network["ip"] = getSetting("ip" + String(i));
  329. network["gw"] = getSetting("gw" + String(i));
  330. network["mask"] = getSetting("mask" + String(i));
  331. network["dns"] = getSetting("dns" + String(i));
  332. }
  333. String output;
  334. root.printTo(output);
  335. ws.text(client_id, (char *) output.c_str());
  336. }
  337. bool _wsAuth(AsyncWebSocketClient * client) {
  338. IPAddress ip = client->remoteIP();
  339. unsigned long now = millis();
  340. unsigned short index = 0;
  341. for (index = 0; index < WS_BUFFER_SIZE; index++) {
  342. if ((_ticket[index].ip == ip) && (now - _ticket[index].timestamp < WS_TIMEOUT)) break;
  343. }
  344. if (index == WS_BUFFER_SIZE) {
  345. DEBUG_MSG("[WEBSOCKET] Validation check failed\n");
  346. ws.text(client->id(), "{\"message\": \"Session expired, please reload page...\"}");
  347. return false;
  348. }
  349. return true;
  350. }
  351. void _wsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){
  352. static uint8_t * message;
  353. // Authorize
  354. #ifndef NOWSAUTH
  355. if (!_wsAuth(client)) return;
  356. #endif
  357. if (type == WS_EVT_CONNECT) {
  358. IPAddress ip = client->remoteIP();
  359. 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());
  360. _wsStart(client->id());
  361. } else if(type == WS_EVT_DISCONNECT) {
  362. DEBUG_MSG("[WEBSOCKET] #%u disconnected\n", client->id());
  363. } else if(type == WS_EVT_ERROR) {
  364. DEBUG_MSG("[WEBSOCKET] #%u error(%u): %s\n", client->id(), *((uint16_t*)arg), (char*)data);
  365. } else if(type == WS_EVT_PONG) {
  366. DEBUG_MSG("[WEBSOCKET] #%u pong(%u): %s\n", client->id(), len, len ? (char*) data : "");
  367. } else if(type == WS_EVT_DATA) {
  368. AwsFrameInfo * info = (AwsFrameInfo*)arg;
  369. // First packet
  370. if (info->index == 0) {
  371. //Serial.printf("Before malloc: %d\n", ESP.getFreeHeap());
  372. message = (uint8_t*) malloc(info->len);
  373. //Serial.printf("After malloc: %d\n", ESP.getFreeHeap());
  374. }
  375. // Store data
  376. memcpy(message + info->index, data, len);
  377. // Last packet
  378. if (info->index + len == info->len) {
  379. _wsParse(client->id(), message, info->len);
  380. //Serial.printf("Before free: %d\n", ESP.getFreeHeap());
  381. free(message);
  382. //Serial.printf("After free: %d\n", ESP.getFreeHeap());
  383. }
  384. }
  385. }
  386. // -----------------------------------------------------------------------------
  387. // WEBSERVER
  388. // -----------------------------------------------------------------------------
  389. void webLogRequest(AsyncWebServerRequest *request) {
  390. DEBUG_MSG("[WEBSERVER] Request: %s %s\n", request->methodToString(), request->url().c_str());
  391. }
  392. bool _authenticate(AsyncWebServerRequest *request) {
  393. String password = getSetting("adminPass", ADMIN_PASS);
  394. char httpPassword[password.length() + 1];
  395. password.toCharArray(httpPassword, password.length() + 1);
  396. return request->authenticate(HTTP_USERNAME, httpPassword);
  397. }
  398. bool _authAPI(AsyncWebServerRequest *request) {
  399. if (getSetting("apiEnabled").toInt() == 0) {
  400. DEBUG_MSG("[WEBSERVER] HTTP API is not enabled\n");
  401. request->send(403);
  402. return false;
  403. }
  404. if (!request->hasParam("apikey", (request->method() == HTTP_PUT))) {
  405. DEBUG_MSG("[WEBSERVER] Missing apikey parameter\n");
  406. request->send(403);
  407. return false;
  408. }
  409. AsyncWebParameter* p = request->getParam("apikey", (request->method() == HTTP_PUT));
  410. if (!p->value().equals(getSetting("apiKey"))) {
  411. DEBUG_MSG("[WEBSERVER] Wrong apikey parameter\n");
  412. request->send(403);
  413. return false;
  414. }
  415. return true;
  416. }
  417. bool _asJson(AsyncWebServerRequest *request) {
  418. bool asJson = false;
  419. if (request->hasHeader("Accept")) {
  420. AsyncWebHeader* h = request->getHeader("Accept");
  421. asJson = h->value().equals("application/json");
  422. }
  423. return asJson;
  424. }
  425. ArRequestHandlerFunction _bindAPI(unsigned int apiID) {
  426. return [apiID](AsyncWebServerRequest *request) {
  427. webLogRequest(request);
  428. if (!_authAPI(request)) return;
  429. bool asJson = _asJson(request);
  430. web_api_t api = _apis[apiID];
  431. if (request->method() == HTTP_PUT) {
  432. if (request->hasParam("value", true)) {
  433. AsyncWebParameter* p = request->getParam("value", true);
  434. (api.putFn)((p->value()).c_str());
  435. }
  436. }
  437. char value[10];
  438. (api.getFn)(value, 10);
  439. // jump over leading spaces
  440. char *p = value;
  441. while ((unsigned char) *p == ' ') ++p;
  442. if (asJson) {
  443. char buffer[64];
  444. sprintf_P(buffer, PSTR("{ \"%s\": %s }"), api.key, p);
  445. request->send(200, "application/json", buffer);
  446. } else {
  447. request->send(200, "text/plain", p);
  448. }
  449. };
  450. }
  451. void apiRegister(const char * url, const char * key, apiGetCallbackFunction getFn, apiPutCallbackFunction putFn) {
  452. // Store it
  453. web_api_t api;
  454. api.url = strdup(url);
  455. api.key = strdup(key);
  456. api.getFn = getFn;
  457. api.putFn = putFn;
  458. _apis.push_back(api);
  459. // Bind call
  460. unsigned int methods = HTTP_GET;
  461. if (putFn != NULL) methods += HTTP_PUT;
  462. server.on(url, methods, _bindAPI(_apis.size() - 1));
  463. }
  464. void _onAPIs(AsyncWebServerRequest *request) {
  465. webLogRequest(request);
  466. if (!_authAPI(request)) return;
  467. bool asJson = _asJson(request);
  468. String output;
  469. if (asJson) {
  470. DynamicJsonBuffer jsonBuffer;
  471. JsonObject& root = jsonBuffer.createObject();
  472. for (unsigned int i=0; i < _apis.size(); i++) {
  473. root[_apis[i].key] = _apis[i].url;
  474. }
  475. root.printTo(output);
  476. request->send(200, "application/json", output);
  477. } else {
  478. for (unsigned int i=0; i < _apis.size(); i++) {
  479. output += _apis[i].key + String(" -> ") + _apis[i].url + String("\n<br />");
  480. }
  481. request->send(200, "text/plain", output);
  482. }
  483. }
  484. void _onRPC(AsyncWebServerRequest *request) {
  485. webLogRequest(request);
  486. if (!_authAPI(request)) return;
  487. //bool asJson = _asJson(request);
  488. int response = 404;
  489. if (request->hasParam("action")) {
  490. AsyncWebParameter* p = request->getParam("action");
  491. String action = p->value();
  492. DEBUG_MSG("[RPC] Action: %s\n", action.c_str());
  493. if (action.equals("reset")) {
  494. response = 200;
  495. deferred.once_ms(100, []() { ESP.reset(); });
  496. }
  497. }
  498. request->send(response);
  499. }
  500. void _onHome(AsyncWebServerRequest *request) {
  501. DEBUG_MSG("[DEBUG] Free heap: %d bytes\n", ESP.getFreeHeap());
  502. FSInfo fs_info;
  503. if (SPIFFS.info(fs_info)) {
  504. DEBUG_MSG("[DEBUG] File system total size: %d bytes\n", fs_info.totalBytes);
  505. DEBUG_MSG(" used size : %d bytes\n", fs_info.usedBytes);
  506. DEBUG_MSG(" block size: %d bytes\n", fs_info.blockSize);
  507. DEBUG_MSG(" page size : %d bytes\n", fs_info.pageSize);
  508. DEBUG_MSG(" max files : %d\n", fs_info.maxOpenFiles);
  509. DEBUG_MSG(" max length: %d\n", fs_info.maxPathLength);
  510. } else {
  511. DEBUG_MSG("[DEBUG] Error, FS not accesible!\n");
  512. }
  513. webLogRequest(request);
  514. if (!_authenticate(request)) return request->requestAuthentication();
  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. }
  522. void _onAuth(AsyncWebServerRequest *request) {
  523. webLogRequest(request);
  524. if (!_authenticate(request)) return request->requestAuthentication();
  525. IPAddress ip = request->client()->remoteIP();
  526. unsigned long now = millis();
  527. unsigned short index;
  528. for (index = 0; index < WS_BUFFER_SIZE; index++) {
  529. if (_ticket[index].ip == ip) break;
  530. if (_ticket[index].timestamp == 0) break;
  531. if (now - _ticket[index].timestamp > WS_TIMEOUT) break;
  532. }
  533. if (index == WS_BUFFER_SIZE) {
  534. request->send(423);
  535. } else {
  536. _ticket[index].ip = ip;
  537. _ticket[index].timestamp = now;
  538. request->send(204);
  539. }
  540. }
  541. AsyncWebServer * getServer() {
  542. return &server;
  543. }
  544. void webSetup() {
  545. // Setup websocket
  546. ws.onEvent(_wsEvent);
  547. mqttRegister(wsMQTTCallback);
  548. // Setup webserver
  549. server.addHandler(&ws);
  550. // Serve home (basic authentication protection)
  551. server.on("/", HTTP_GET, _onHome);
  552. server.on("/index.html", HTTP_GET, _onHome);
  553. server.on("/auth", HTTP_GET, _onAuth);
  554. server.on("/apis", HTTP_GET, _onAPIs);
  555. server.on("/rpc", HTTP_GET, _onRPC);
  556. // Serve static files
  557. char lastModified[50];
  558. sprintf(lastModified, "%s %s GMT", __DATE__, __TIME__);
  559. server.serveStatic("/", SPIFFS, "/").setLastModified(lastModified);
  560. // 404
  561. server.onNotFound([](AsyncWebServerRequest *request){
  562. request->send(404);
  563. });
  564. // Run server
  565. server.begin();
  566. }