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.

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