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.

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