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.

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