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.

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