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.

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