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.

903 lines
26 KiB

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