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.

817 lines
24 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
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. #if EMBEDDED_WEB
  15. #include "config/data.h"
  16. #endif
  17. AsyncWebServer * _server;
  18. AsyncWebSocket ws("/ws");
  19. Ticker deferred;
  20. typedef struct {
  21. IPAddress ip;
  22. unsigned long timestamp = 0;
  23. } ws_ticket_t;
  24. ws_ticket_t _ticket[WS_BUFFER_SIZE];
  25. typedef struct {
  26. char * url;
  27. char * key;
  28. apiGetCallbackFunction getFn = NULL;
  29. apiPutCallbackFunction putFn = NULL;
  30. } web_api_t;
  31. std::vector<web_api_t> _apis;
  32. char _last_modified[50];
  33. // -----------------------------------------------------------------------------
  34. // WEBSOCKETS
  35. // -----------------------------------------------------------------------------
  36. bool wsSend(const char * payload) {
  37. DEBUG_MSG("[WEBSOCKET] Broadcasting '%s'\n", payload);
  38. ws.textAll(payload);
  39. }
  40. bool wsSend(uint32_t client_id, const char * payload) {
  41. DEBUG_MSG("[WEBSOCKET] Sending '%s' to #%ld\n", payload, client_id);
  42. ws.text(client_id, payload);
  43. }
  44. void wsMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  45. if (type == MQTT_CONNECT_EVENT) {
  46. wsSend("{\"mqttStatus\": true}");
  47. }
  48. if (type == MQTT_DISCONNECT_EVENT) {
  49. wsSend("{\"mqttStatus\": false}");
  50. }
  51. }
  52. void _wsParse(uint32_t client_id, uint8_t * payload, size_t length) {
  53. // Parse JSON input
  54. DynamicJsonBuffer jsonBuffer;
  55. JsonObject& root = jsonBuffer.parseObject((char *) payload);
  56. if (!root.success()) {
  57. DEBUG_MSG("[WEBSOCKET] Error parsing data\n");
  58. ws.text(client_id, "{\"message\": \"Error parsing data!\"}");
  59. return;
  60. }
  61. // Check actions
  62. if (root.containsKey("action")) {
  63. String action = root["action"];
  64. unsigned int relayID = 0;
  65. if (root.containsKey("relayID")) {
  66. String value = root["relayID"];
  67. relayID = value.toInt();
  68. }
  69. DEBUG_MSG("[WEBSOCKET] Requested action: %s\n", action.c_str());
  70. if (action.equals("reset")) ESP.reset();
  71. if (action.equals("restore") && root.containsKey("data")) {
  72. for (unsigned int i = EEPROM_DATA_END; i < SPI_FLASH_SEC_SIZE; i++) {
  73. EEPROM.write(i, 0xFF);
  74. }
  75. JsonObject& data = root["data"];
  76. for (auto element : data){
  77. setSetting(element.key, element.value.as<char*>());
  78. }
  79. saveSettings();
  80. ws.text(client_id, "{\"message\": \"Changes saved. You should reboot your board now.\"}");
  81. }
  82. if (action.equals("reconnect")) {
  83. // Let the HTTP request return and disconnect after 100ms
  84. deferred.once_ms(100, wifiDisconnect);
  85. }
  86. if (action.equals("on")) relayStatus(relayID, true);
  87. if (action.equals("off")) relayStatus(relayID, false);
  88. };
  89. // Check config
  90. if (root.containsKey("config") && root["config"].is<JsonArray&>()) {
  91. JsonArray& config = root["config"];
  92. DEBUG_MSG("[WEBSOCKET] Parsing configuration data\n");
  93. unsigned char webMode = WEB_MODE_NORMAL;
  94. bool save = false;
  95. bool changed = false;
  96. bool changedMQTT = false;
  97. bool apiEnabled = false;
  98. #if ENABLE_FAUXMO
  99. bool fauxmoEnabled = false;
  100. #endif
  101. unsigned int network = 0;
  102. unsigned int dczRelayIdx = 0;
  103. String adminPass;
  104. for (unsigned int i=0; i<config.size(); i++) {
  105. String key = config[i]["name"];
  106. String value = config[i]["value"];
  107. #if ENABLE_POW
  108. if (key == "powExpectedPower") {
  109. powSetExpectedActivePower(value.toInt());
  110. changed = true;
  111. }
  112. if (key == "powExpectedVoltage") {
  113. powSetExpectedVoltage(value.toInt());
  114. changed = true;
  115. }
  116. if (key == "powExpectedCurrent") {
  117. powSetExpectedCurrent(value.toInt());
  118. changed = true;
  119. }
  120. if (key == "powExpectedReset") {
  121. powReset();
  122. changed = true;
  123. }
  124. #endif
  125. if (key.startsWith("pow")) continue;
  126. #if ENABLE_DOMOTICZ
  127. if (key == "dczRelayIdx") {
  128. if (dczRelayIdx >= relayCount()) continue;
  129. key = key + String(dczRelayIdx);
  130. ++dczRelayIdx;
  131. }
  132. #else
  133. if (key.startsWith("dcz")) continue;
  134. #endif
  135. // Web portions
  136. if (key == "webPort") {
  137. if ((value.toInt() == 0) || (value.toInt() == 80)) {
  138. save = changed = true;
  139. delSetting(key);
  140. continue;
  141. }
  142. }
  143. if (key == "webMode") {
  144. webMode = value.toInt();
  145. continue;
  146. }
  147. // Check password
  148. if (key == "adminPass1") {
  149. adminPass = value;
  150. continue;
  151. }
  152. if (key == "adminPass2") {
  153. if (!value.equals(adminPass)) {
  154. ws.text(client_id, "{\"message\": \"Passwords do not match!\"}");
  155. return;
  156. }
  157. if (value.length() == 0) continue;
  158. ws.text(client_id, "{\"action\": \"reload\"}");
  159. key = String("adminPass");
  160. }
  161. // Checkboxes
  162. if (key == "apiEnabled") {
  163. apiEnabled = true;
  164. continue;
  165. }
  166. #if ENABLE_FAUXMO
  167. if (key == "fauxmoEnabled") {
  168. fauxmoEnabled = true;
  169. continue;
  170. }
  171. #endif
  172. if (key == "ssid") {
  173. key = key + String(network);
  174. }
  175. if (key == "pass") {
  176. key = key + String(network);
  177. }
  178. if (key == "ip") {
  179. key = key + String(network);
  180. }
  181. if (key == "gw") {
  182. key = key + String(network);
  183. }
  184. if (key == "mask") {
  185. key = key + String(network);
  186. }
  187. if (key == "dns") {
  188. key = key + String(network);
  189. ++network;
  190. }
  191. if (value != getSetting(key)) {
  192. //DEBUG_MSG("[WEBSOCKET] Storing %s = %s\n", key.c_str(), value.c_str());
  193. setSetting(key, value);
  194. save = changed = true;
  195. if (key.startsWith("mqtt")) changedMQTT = true;
  196. }
  197. }
  198. if (webMode == WEB_MODE_NORMAL) {
  199. // Checkboxes
  200. if (apiEnabled != (getSetting("apiEnabled").toInt() == 1)) {
  201. setSetting("apiEnabled", apiEnabled);
  202. save = changed = true;
  203. }
  204. #if ENABLE_FAUXMO
  205. if (fauxmoEnabled != (getSetting("fauxmoEnabled").toInt() == 1)) {
  206. setSetting("fauxmoEnabled", fauxmoEnabled);
  207. save = changed = true;
  208. }
  209. #endif
  210. // Clean wifi networks
  211. int i = 0;
  212. while (i < network) {
  213. if (getSetting("ssid" + String(i)).length() == 0) {
  214. delSetting("ssid" + String(i));
  215. break;
  216. }
  217. if (getSetting("pass" + String(i)).length() == 0) delSetting("pass" + String(i));
  218. if (getSetting("ip" + String(i)).length() == 0) delSetting("ip" + String(i));
  219. if (getSetting("gw" + String(i)).length() == 0) delSetting("gw" + String(i));
  220. if (getSetting("mask" + String(i)).length() == 0) delSetting("mask" + String(i));
  221. if (getSetting("dns" + String(i)).length() == 0) delSetting("dns" + String(i));
  222. ++i;
  223. }
  224. while (i < WIFI_MAX_NETWORKS) {
  225. if (getSetting("ssid" + String(i)).length() > 0) {
  226. save = changed = true;
  227. }
  228. delSetting("ssid" + String(i));
  229. delSetting("pass" + String(i));
  230. delSetting("ip" + String(i));
  231. delSetting("gw" + String(i));
  232. delSetting("mask" + String(i));
  233. delSetting("dns" + String(i));
  234. ++i;
  235. }
  236. }
  237. // Save settings
  238. if (save) {
  239. saveSettings();
  240. wifiConfigure();
  241. otaConfigure();
  242. #if ENABLE_FAUXMO
  243. fauxmoConfigure();
  244. #endif
  245. buildTopics();
  246. #if ENABLE_RF
  247. rfBuildCodes();
  248. #endif
  249. #if ENABLE_EMON
  250. setCurrentRatio(getSetting("emonRatio").toFloat());
  251. #endif
  252. // Check if we should reconfigure MQTT connection
  253. if (changedMQTT) {
  254. mqttDisconnect();
  255. }
  256. }
  257. if (changed) {
  258. ws.text(client_id, "{\"message\": \"Changes saved\"}");
  259. } else {
  260. ws.text(client_id, "{\"message\": \"No changes detected\"}");
  261. }
  262. }
  263. }
  264. void _wsStart(uint32_t client_id) {
  265. char chipid[6];
  266. sprintf(chipid, "%06X", ESP.getChipId());
  267. DynamicJsonBuffer jsonBuffer;
  268. JsonObject& root = jsonBuffer.createObject();
  269. bool changePassword = false;
  270. #if FORCE_CHANGE_PASS == 1
  271. String adminPass = getSetting("adminPass", ADMIN_PASS);
  272. if (adminPass.equals(ADMIN_PASS)) changePassword = true;
  273. #endif
  274. if (changePassword) {
  275. root["webMode"] = WEB_MODE_PASSWORD;
  276. } else {
  277. root["webMode"] = WEB_MODE_NORMAL;
  278. root["app"] = APP_NAME;
  279. root["version"] = APP_VERSION;
  280. root["buildDate"] = __DATE__;
  281. root["buildTime"] = __TIME__;
  282. root["manufacturer"] = String(MANUFACTURER);
  283. root["chipid"] = chipid;
  284. root["mac"] = WiFi.macAddress();
  285. root["device"] = String(DEVICE);
  286. root["hostname"] = getSetting("hostname", HOSTNAME);
  287. root["network"] = getNetwork();
  288. root["deviceip"] = getIP();
  289. root["mqttStatus"] = mqttConnected();
  290. root["mqttServer"] = getSetting("mqttServer", MQTT_SERVER);
  291. root["mqttPort"] = getSetting("mqttPort", MQTT_PORT);
  292. root["mqttUser"] = getSetting("mqttUser");
  293. root["mqttPassword"] = getSetting("mqttPassword");
  294. root["mqttTopic"] = getSetting("mqttTopic", MQTT_TOPIC);
  295. JsonArray& relay = root.createNestedArray("relayStatus");
  296. for (unsigned char relayID=0; relayID<relayCount(); relayID++) {
  297. relay.add(relayStatus(relayID));
  298. }
  299. root["relayMode"] = getSetting("relayMode", RELAY_MODE);
  300. root["relayPulseMode"] = getSetting("relayPulseMode", RELAY_PULSE_MODE);
  301. root["relayPulseTime"] = getSetting("relayPulseTime", RELAY_PULSE_TIME);
  302. if (relayCount() > 1) {
  303. root["multirelayVisible"] = 1;
  304. root["relaySync"] = getSetting("relaySync", RELAY_SYNC);
  305. }
  306. root["webPort"] = getSetting("webPort", WEBSERVER_PORT).toInt();
  307. root["apiEnabled"] = getSetting("apiEnabled").toInt() == 1;
  308. root["apiKey"] = getSetting("apiKey");
  309. root["tmpUnits"] = getSetting("tmpUnits", TMP_UNITS).toInt();
  310. #if ENABLE_DOMOTICZ
  311. root["dczVisible"] = 1;
  312. root["dczTopicIn"] = getSetting("dczTopicIn", DOMOTICZ_IN_TOPIC);
  313. root["dczTopicOut"] = getSetting("dczTopicOut", DOMOTICZ_OUT_TOPIC);
  314. JsonArray& dczRelayIdx = root.createNestedArray("dczRelayIdx");
  315. for (byte i=0; i<relayCount(); i++) {
  316. dczRelayIdx.add(relayToIdx(i));
  317. }
  318. #if ENABLE_DHT
  319. root["dczTmpIdx"] = getSetting("dczTmpIdx").toInt();
  320. root["dczHumIdx"] = getSetting("dczHumIdx").toInt();
  321. #endif
  322. #if ENABLE_DS18B20
  323. root["dczTmpIdx"] = getSetting("dczTmpIdx").toInt();
  324. #endif
  325. #if ENABLE_EMON
  326. root["dczPowIdx"] = getSetting("dczPowIdx").toInt();
  327. root["dczEnergyIdx"] = getSetting("dczEnergyIdx").toInt();
  328. root["dczCurrentIdx"] = getSetting("dczCurrentIdx").toInt();
  329. #endif
  330. #if ENABLE_POW
  331. root["dczPowIdx"] = getSetting("dczPowIdx").toInt();
  332. root["dczEnergyIdx"] = getSetting("dczEnergyIdx").toInt();
  333. root["dczVoltIdx"] = getSetting("dczVoltIdx").toInt();
  334. root["dczCurrentIdx"] = getSetting("dczCurrentIdx").toInt();
  335. #endif
  336. #endif
  337. #if ENABLE_FAUXMO
  338. root["fauxmoVisible"] = 1;
  339. root["fauxmoEnabled"] = getSetting("fauxmoEnabled", FAUXMO_ENABLED).toInt() == 1;
  340. #endif
  341. #if ENABLE_DS18B20
  342. root["dsVisible"] = 1;
  343. root["dsTmp"] = getDSTemperature();
  344. #endif
  345. #if ENABLE_DHT
  346. root["dhtVisible"] = 1;
  347. root["dhtTmp"] = getDHTTemperature();
  348. root["dhtHum"] = getDHTHumidity();
  349. #endif
  350. #if ENABLE_RF
  351. root["rfVisible"] = 1;
  352. root["rfChannel"] = getSetting("rfChannel", RF_CHANNEL);
  353. root["rfDevice"] = getSetting("rfDevice", RF_DEVICE);
  354. #endif
  355. #if ENABLE_EMON
  356. root["emonVisible"] = 1;
  357. root["emonPower"] = getPower();
  358. root["emonMains"] = getSetting("emonMains", EMON_MAINS_VOLTAGE);
  359. root["emonRatio"] = getSetting("emonRatio", EMON_CURRENT_RATIO);
  360. #endif
  361. #if ENABLE_POW
  362. root["powVisible"] = 1;
  363. root["powActivePower"] = getActivePower();
  364. root["powApparentPower"] = getApparentPower();
  365. root["powReactivePower"] = getReactivePower();
  366. root["powVoltage"] = getVoltage();
  367. root["powCurrent"] = getCurrent();
  368. root["powPowerFactor"] = getPowerFactor();
  369. #endif
  370. root["maxNetworks"] = WIFI_MAX_NETWORKS;
  371. JsonArray& wifi = root.createNestedArray("wifi");
  372. for (byte i=0; i<WIFI_MAX_NETWORKS; i++) {
  373. if (getSetting("ssid" + String(i)).length() == 0) break;
  374. JsonObject& network = wifi.createNestedObject();
  375. network["ssid"] = getSetting("ssid" + String(i));
  376. network["pass"] = getSetting("pass" + String(i));
  377. network["ip"] = getSetting("ip" + String(i));
  378. network["gw"] = getSetting("gw" + String(i));
  379. network["mask"] = getSetting("mask" + String(i));
  380. network["dns"] = getSetting("dns" + String(i));
  381. }
  382. }
  383. String output;
  384. root.printTo(output);
  385. ws.text(client_id, (char *) output.c_str());
  386. }
  387. bool _wsAuth(AsyncWebSocketClient * client) {
  388. IPAddress ip = client->remoteIP();
  389. unsigned long now = millis();
  390. unsigned short index = 0;
  391. for (index = 0; index < WS_BUFFER_SIZE; index++) {
  392. if ((_ticket[index].ip == ip) && (now - _ticket[index].timestamp < WS_TIMEOUT)) break;
  393. }
  394. if (index == WS_BUFFER_SIZE) {
  395. DEBUG_MSG("[WEBSOCKET] Validation check failed\n");
  396. ws.text(client->id(), "{\"message\": \"Session expired, please reload page...\"}");
  397. return false;
  398. }
  399. return true;
  400. }
  401. void _wsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){
  402. static uint8_t * message;
  403. // Authorize
  404. #ifndef NOWSAUTH
  405. if (!_wsAuth(client)) return;
  406. #endif
  407. if (type == WS_EVT_CONNECT) {
  408. IPAddress ip = client->remoteIP();
  409. 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());
  410. _wsStart(client->id());
  411. } else if(type == WS_EVT_DISCONNECT) {
  412. DEBUG_MSG("[WEBSOCKET] #%u disconnected\n", client->id());
  413. } else if(type == WS_EVT_ERROR) {
  414. DEBUG_MSG("[WEBSOCKET] #%u error(%u): %s\n", client->id(), *((uint16_t*)arg), (char*)data);
  415. } else if(type == WS_EVT_PONG) {
  416. DEBUG_MSG("[WEBSOCKET] #%u pong(%u): %s\n", client->id(), len, len ? (char*) data : "");
  417. } else if(type == WS_EVT_DATA) {
  418. AwsFrameInfo * info = (AwsFrameInfo*)arg;
  419. // First packet
  420. if (info->index == 0) {
  421. message = (uint8_t*) malloc(info->len);
  422. }
  423. // Store data
  424. memcpy(message + info->index, data, len);
  425. // Last packet
  426. if (info->index + len == info->len) {
  427. _wsParse(client->id(), message, info->len);
  428. free(message);
  429. }
  430. }
  431. }
  432. // -----------------------------------------------------------------------------
  433. // WEBSERVER
  434. // -----------------------------------------------------------------------------
  435. void webLogRequest(AsyncWebServerRequest *request) {
  436. DEBUG_MSG("[WEBSERVER] Request: %s %s\n", request->methodToString(), request->url().c_str());
  437. }
  438. bool _authenticate(AsyncWebServerRequest *request) {
  439. String password = getSetting("adminPass", ADMIN_PASS);
  440. char httpPassword[password.length() + 1];
  441. password.toCharArray(httpPassword, password.length() + 1);
  442. return request->authenticate(HTTP_USERNAME, httpPassword);
  443. }
  444. bool _authAPI(AsyncWebServerRequest *request) {
  445. if (getSetting("apiEnabled").toInt() == 0) {
  446. DEBUG_MSG("[WEBSERVER] HTTP API is not enabled\n");
  447. request->send(403);
  448. return false;
  449. }
  450. if (!request->hasParam("apikey", (request->method() == HTTP_PUT))) {
  451. DEBUG_MSG("[WEBSERVER] Missing apikey parameter\n");
  452. request->send(403);
  453. return false;
  454. }
  455. AsyncWebParameter* p = request->getParam("apikey", (request->method() == HTTP_PUT));
  456. if (!p->value().equals(getSetting("apiKey"))) {
  457. DEBUG_MSG("[WEBSERVER] Wrong apikey parameter\n");
  458. request->send(403);
  459. return false;
  460. }
  461. return true;
  462. }
  463. bool _asJson(AsyncWebServerRequest *request) {
  464. bool asJson = false;
  465. if (request->hasHeader("Accept")) {
  466. AsyncWebHeader* h = request->getHeader("Accept");
  467. asJson = h->value().equals("application/json");
  468. }
  469. return asJson;
  470. }
  471. ArRequestHandlerFunction _bindAPI(unsigned int apiID) {
  472. return [apiID](AsyncWebServerRequest *request) {
  473. webLogRequest(request);
  474. if (!_authAPI(request)) return;
  475. bool asJson = _asJson(request);
  476. web_api_t api = _apis[apiID];
  477. if (api.putFn != NULL) {
  478. if (request->hasParam("value", request->method() == HTTP_PUT)) {
  479. AsyncWebParameter* p = request->getParam("value", request->method() == HTTP_PUT);
  480. (api.putFn)((p->value()).c_str());
  481. }
  482. }
  483. char value[10];
  484. (api.getFn)(value, 10);
  485. // jump over leading spaces
  486. char *p = value;
  487. while ((unsigned char) *p == ' ') ++p;
  488. if (asJson) {
  489. char buffer[64];
  490. sprintf_P(buffer, PSTR("{ \"%s\": %s }"), api.key, p);
  491. request->send(200, "application/json", buffer);
  492. } else {
  493. request->send(200, "text/plain", p);
  494. }
  495. };
  496. }
  497. void apiRegister(const char * url, const char * key, apiGetCallbackFunction getFn, apiPutCallbackFunction putFn) {
  498. // Store it
  499. web_api_t api;
  500. api.url = strdup(url);
  501. api.key = strdup(key);
  502. api.getFn = getFn;
  503. api.putFn = putFn;
  504. _apis.push_back(api);
  505. // Bind call
  506. unsigned int methods = HTTP_GET;
  507. if (putFn != NULL) methods += HTTP_PUT;
  508. _server->on(url, methods, _bindAPI(_apis.size() - 1));
  509. }
  510. void _onAPIs(AsyncWebServerRequest *request) {
  511. webLogRequest(request);
  512. if (!_authAPI(request)) return;
  513. bool asJson = _asJson(request);
  514. String output;
  515. if (asJson) {
  516. DynamicJsonBuffer jsonBuffer;
  517. JsonObject& root = jsonBuffer.createObject();
  518. for (unsigned int i=0; i < _apis.size(); i++) {
  519. root[_apis[i].key] = _apis[i].url;
  520. }
  521. root.printTo(output);
  522. request->send(200, "application/json", output);
  523. } else {
  524. for (unsigned int i=0; i < _apis.size(); i++) {
  525. output += _apis[i].key + String(" -> ") + _apis[i].url + String("\n<br />");
  526. }
  527. request->send(200, "text/plain", output);
  528. }
  529. }
  530. void _onRPC(AsyncWebServerRequest *request) {
  531. webLogRequest(request);
  532. if (!_authAPI(request)) return;
  533. //bool asJson = _asJson(request);
  534. int response = 404;
  535. if (request->hasParam("action")) {
  536. AsyncWebParameter* p = request->getParam("action");
  537. String action = p->value();
  538. DEBUG_MSG("[RPC] Action: %s\n", action.c_str());
  539. if (action.equals("reset")) {
  540. response = 200;
  541. deferred.once_ms(100, []() { ESP.reset(); });
  542. }
  543. }
  544. request->send(response);
  545. }
  546. void _onAuth(AsyncWebServerRequest *request) {
  547. webLogRequest(request);
  548. if (!_authenticate(request)) return request->requestAuthentication();
  549. IPAddress ip = request->client()->remoteIP();
  550. unsigned long now = millis();
  551. unsigned short index;
  552. for (index = 0; index < WS_BUFFER_SIZE; index++) {
  553. if (_ticket[index].ip == ip) break;
  554. if (_ticket[index].timestamp == 0) break;
  555. if (now - _ticket[index].timestamp > WS_TIMEOUT) break;
  556. }
  557. if (index == WS_BUFFER_SIZE) {
  558. request->send(429);
  559. } else {
  560. _ticket[index].ip = ip;
  561. _ticket[index].timestamp = now;
  562. request->send(204);
  563. }
  564. }
  565. void _onGetConfig(AsyncWebServerRequest *request) {
  566. webLogRequest(request);
  567. if (!_authenticate(request)) return request->requestAuthentication();
  568. AsyncJsonResponse * response = new AsyncJsonResponse();
  569. JsonObject& root = response->getRoot();
  570. unsigned int size = settingsKeyCount();
  571. for (unsigned int i=0; i<size; i++) {
  572. String key = settingsKeyName(i);
  573. String value = getSetting(key);
  574. root[key] = value;
  575. }
  576. char buffer[100];
  577. sprintf(buffer, "attachment; filename=\"%s-backup.json\"", (char *) getSetting("hostname").c_str());
  578. response->addHeader("Content-Disposition", buffer);
  579. response->setLength();
  580. request->send(response);
  581. }
  582. #if EMBEDDED_WEB
  583. void _onHome(AsyncWebServerRequest *request) {
  584. webLogRequest(request);
  585. if (request->header("If-Modified-Since").equals(_last_modified)) {
  586. request->send(304);
  587. } else {
  588. AsyncWebServerResponse *response = request->beginResponse_P(200, "text/html", index_html_gz, index_html_gz_len);
  589. response->addHeader("Content-Encoding", "gzip");
  590. response->addHeader("Last-Modified", _last_modified);
  591. request->send(response);
  592. }
  593. }
  594. #endif
  595. void webSetup() {
  596. // Create server
  597. _server = new AsyncWebServer(getSetting("webPort", WEBSERVER_PORT).toInt());
  598. // Setup websocket
  599. ws.onEvent(_wsEvent);
  600. mqttRegister(wsMQTTCallback);
  601. // Cache the Last-Modifier header value
  602. sprintf(_last_modified, "%s %s GMT", __DATE__, __TIME__);
  603. // Setup webserver
  604. _server->addHandler(&ws);
  605. // Rewrites
  606. _server->rewrite("/", "/index.html");
  607. // Serve home (basic authentication protection)
  608. #if EMBEDDED_WEB
  609. _server->on("/index.html", HTTP_GET, _onHome);
  610. #endif
  611. _server->on("/config", HTTP_GET, _onGetConfig);
  612. _server->on("/auth", HTTP_GET, _onAuth);
  613. _server->on("/apis", HTTP_GET, _onAPIs);
  614. _server->on("/rpc", HTTP_GET, _onRPC);
  615. // Serve static files
  616. #if not EMBEDDED_WEB
  617. _server->serveStatic("/", SPIFFS, "/")
  618. .setLastModified(_last_modified)
  619. .setFilter([](AsyncWebServerRequest *request) -> bool {
  620. webLogRequest(request);
  621. return true;
  622. });
  623. #endif
  624. // 404
  625. _server->onNotFound([](AsyncWebServerRequest *request){
  626. request->send(404);
  627. });
  628. // Run server
  629. _server->begin();
  630. DEBUG_MSG("[WEBSERVER] Webserver running on port %d\n", getSetting("webPort", WEBSERVER_PORT).toInt());
  631. }