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.

907 lines
27 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 "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.toFloat());
  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. char buffer[40];
  534. snprintf(buffer, 39, "/api/%s", url);
  535. api.url = strdup(buffer);
  536. api.key = strdup(key);
  537. api.getFn = getFn;
  538. api.putFn = putFn;
  539. _apis.push_back(api);
  540. // Bind call
  541. unsigned int methods = HTTP_GET;
  542. if (putFn != NULL) methods += HTTP_PUT;
  543. _server->on(buffer, methods, _bindAPI(_apis.size() - 1));
  544. }
  545. void _onAPIs(AsyncWebServerRequest *request) {
  546. webLogRequest(request);
  547. if (!_authAPI(request)) return;
  548. bool asJson = _asJson(request);
  549. String output;
  550. if (asJson) {
  551. DynamicJsonBuffer jsonBuffer;
  552. JsonObject& root = jsonBuffer.createObject();
  553. for (unsigned int i=0; i < _apis.size(); i++) {
  554. root[_apis[i].key] = _apis[i].url;
  555. }
  556. root.printTo(output);
  557. request->send(200, "application/json", output);
  558. } else {
  559. for (unsigned int i=0; i < _apis.size(); i++) {
  560. output += _apis[i].key + String(" -> ") + _apis[i].url + String("\n<br />");
  561. }
  562. request->send(200, "text/plain", output);
  563. }
  564. }
  565. void _onRPC(AsyncWebServerRequest *request) {
  566. webLogRequest(request);
  567. if (!_authAPI(request)) return;
  568. //bool asJson = _asJson(request);
  569. int response = 404;
  570. if (request->hasParam("action")) {
  571. AsyncWebParameter* p = request->getParam("action");
  572. String action = p->value();
  573. DEBUG_MSG_P(PSTR("[RPC] Action: %s\n"), action.c_str());
  574. if (action.equals("reset")) {
  575. response = 200;
  576. deferred.once_ms(100, []() { ESP.restart(); });
  577. }
  578. }
  579. request->send(response);
  580. }
  581. void _onAuth(AsyncWebServerRequest *request) {
  582. webLogRequest(request);
  583. if (!_authenticate(request)) return request->requestAuthentication();
  584. IPAddress ip = request->client()->remoteIP();
  585. unsigned long now = millis();
  586. unsigned short index;
  587. for (index = 0; index < WS_BUFFER_SIZE; index++) {
  588. if (_ticket[index].ip == ip) break;
  589. if (_ticket[index].timestamp == 0) break;
  590. if (now - _ticket[index].timestamp > WS_TIMEOUT) break;
  591. }
  592. if (index == WS_BUFFER_SIZE) {
  593. request->send(429);
  594. } else {
  595. _ticket[index].ip = ip;
  596. _ticket[index].timestamp = now;
  597. request->send(204);
  598. }
  599. }
  600. void _onGetConfig(AsyncWebServerRequest *request) {
  601. webLogRequest(request);
  602. if (!_authenticate(request)) return request->requestAuthentication();
  603. AsyncJsonResponse * response = new AsyncJsonResponse();
  604. JsonObject& root = response->getRoot();
  605. root["app"] = APP_NAME;
  606. root["version"] = APP_VERSION;
  607. unsigned int size = settingsKeyCount();
  608. for (unsigned int i=0; i<size; i++) {
  609. String key = settingsKeyName(i);
  610. String value = getSetting(key);
  611. root[key] = value;
  612. }
  613. char buffer[100];
  614. sprintf(buffer, "attachment; filename=\"%s-backup.json\"", (char *) getSetting("hostname").c_str());
  615. response->addHeader("Content-Disposition", buffer);
  616. response->setLength();
  617. request->send(response);
  618. }
  619. #if EMBEDDED_WEB
  620. void _onHome(AsyncWebServerRequest *request) {
  621. webLogRequest(request);
  622. if (request->header("If-Modified-Since").equals(_last_modified)) {
  623. request->send(304);
  624. } else {
  625. AsyncWebServerResponse *response = request->beginResponse_P(200, "text/html", index_html_gz, index_html_gz_len);
  626. response->addHeader("Content-Encoding", "gzip");
  627. response->addHeader("Last-Modified", _last_modified);
  628. request->send(response);
  629. }
  630. }
  631. #endif
  632. void _onUpgrade(AsyncWebServerRequest *request) {
  633. AsyncWebServerResponse *response = request->beginResponse(200, "text/plain", Update.hasError() ? "FAIL" : "OK");
  634. response->addHeader("Connection", "close");
  635. if (!Update.hasError()) {
  636. deferred.once_ms(100, []() {
  637. ESP.restart();
  638. });
  639. }
  640. request->send(response);
  641. }
  642. void _onUpgradeData(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final) {
  643. if (!index) {
  644. DEBUG_MSG_P(PSTR("[UPGRADE] Start: %s\n"), filename.c_str());
  645. Update.runAsync(true);
  646. if (!Update.begin((ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000)) {
  647. Update.printError(Serial);
  648. }
  649. }
  650. if (!Update.hasError()) {
  651. if (Update.write(data, len) != len) {
  652. Update.printError(Serial);
  653. }
  654. }
  655. if (final) {
  656. if (Update.end(true)){
  657. DEBUG_MSG_P(PSTR("[UPGRADE] Success: %u bytes\n"), index + len);
  658. } else {
  659. Update.printError(Serial);
  660. }
  661. } else {
  662. DEBUG_MSG_P(PSTR("[UPGRADE] Progress: %u bytes\r"), index + len);
  663. }
  664. }
  665. void webSetup() {
  666. // Create server
  667. _server = new AsyncWebServer(getSetting("webPort", WEBSERVER_PORT).toInt());
  668. // Setup websocket
  669. ws.onEvent(_wsEvent);
  670. mqttRegister(wsMQTTCallback);
  671. // Cache the Last-Modifier header value
  672. sprintf(_last_modified, "%s %s GMT", __DATE__, __TIME__);
  673. // Setup webserver
  674. _server->addHandler(&ws);
  675. // Rewrites
  676. _server->rewrite("/", "/index.html");
  677. // Serve home (basic authentication protection)
  678. #if EMBEDDED_WEB
  679. _server->on("/index.html", HTTP_GET, _onHome);
  680. #endif
  681. _server->on("/config", HTTP_GET, _onGetConfig);
  682. _server->on("/auth", HTTP_GET, _onAuth);
  683. _server->on("/apis", HTTP_GET, _onAPIs);
  684. _server->on("/rpc", HTTP_GET, _onRPC);
  685. _server->on("/upgrade", HTTP_POST, _onUpgrade, _onUpgradeData);
  686. // Serve static files
  687. #if not EMBEDDED_WEB
  688. _server->serveStatic("/", SPIFFS, "/")
  689. .setLastModified(_last_modified)
  690. .setFilter([](AsyncWebServerRequest *request) -> bool {
  691. webLogRequest(request);
  692. return true;
  693. });
  694. #endif
  695. // 404
  696. _server->onNotFound([](AsyncWebServerRequest *request){
  697. request->send(404);
  698. });
  699. // Run server
  700. _server->begin();
  701. DEBUG_MSG_P(PSTR("[WEBSERVER] Webserver running on port %d\n"), getSetting("webPort", WEBSERVER_PORT).toInt());
  702. }