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.

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