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.

909 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
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.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["ntpStatus"] = ntpConnected();
  312. root["mqttStatus"] = mqttConnected();
  313. root["mqttServer"] = getSetting("mqttServer", MQTT_SERVER);
  314. root["mqttPort"] = getSetting("mqttPort", MQTT_PORT);
  315. root["mqttUser"] = getSetting("mqttUser");
  316. root["mqttPassword"] = getSetting("mqttPassword");
  317. root["mqttTopic"] = getSetting("mqttTopic", MQTT_TOPIC);
  318. JsonArray& relay = root.createNestedArray("relayStatus");
  319. for (unsigned char relayID=0; relayID<relayCount(); relayID++) {
  320. relay.add(relayStatus(relayID));
  321. }
  322. #if LIGHT_PROVIDER != LIGHT_PROVIDER_NONE
  323. root["colorVisible"] = 1;
  324. root["color"] = lightColor();
  325. #endif
  326. root["relayMode"] = getSetting("relayMode", RELAY_MODE);
  327. root["relayPulseMode"] = getSetting("relayPulseMode", RELAY_PULSE_MODE);
  328. root["relayPulseTime"] = getSetting("relayPulseTime", RELAY_PULSE_TIME);
  329. if (relayCount() > 1) {
  330. root["multirelayVisible"] = 1;
  331. root["relaySync"] = getSetting("relaySync", RELAY_SYNC);
  332. }
  333. root["webPort"] = getSetting("webPort", WEBSERVER_PORT).toInt();
  334. root["apiEnabled"] = getSetting("apiEnabled").toInt() == 1;
  335. root["apiKey"] = getSetting("apiKey");
  336. root["tmpUnits"] = getSetting("tmpUnits", TMP_UNITS).toInt();
  337. #if ENABLE_DOMOTICZ
  338. root["dczVisible"] = 1;
  339. root["dczTopicIn"] = getSetting("dczTopicIn", DOMOTICZ_IN_TOPIC);
  340. root["dczTopicOut"] = getSetting("dczTopicOut", DOMOTICZ_OUT_TOPIC);
  341. JsonArray& dczRelayIdx = root.createNestedArray("dczRelayIdx");
  342. for (byte i=0; i<relayCount(); i++) {
  343. dczRelayIdx.add(relayToIdx(i));
  344. }
  345. #if ENABLE_DHT
  346. root["dczTmpIdx"] = getSetting("dczTmpIdx").toInt();
  347. root["dczHumIdx"] = getSetting("dczHumIdx").toInt();
  348. #endif
  349. #if ENABLE_DS18B20
  350. root["dczTmpIdx"] = getSetting("dczTmpIdx").toInt();
  351. #endif
  352. #if ENABLE_EMON
  353. root["dczPowIdx"] = getSetting("dczPowIdx").toInt();
  354. root["dczEnergyIdx"] = getSetting("dczEnergyIdx").toInt();
  355. root["dczCurrentIdx"] = getSetting("dczCurrentIdx").toInt();
  356. #endif
  357. #if ENABLE_ANALOG
  358. root["dczAnaIdx"] = getSetting("dczAnaIdx").toInt();
  359. #endif
  360. #if ENABLE_POW
  361. root["dczPowIdx"] = getSetting("dczPowIdx").toInt();
  362. root["dczEnergyIdx"] = getSetting("dczEnergyIdx").toInt();
  363. root["dczVoltIdx"] = getSetting("dczVoltIdx").toInt();
  364. root["dczCurrentIdx"] = getSetting("dczCurrentIdx").toInt();
  365. #endif
  366. #endif
  367. #if ENABLE_FAUXMO
  368. root["fauxmoVisible"] = 1;
  369. root["fauxmoEnabled"] = getSetting("fauxmoEnabled", FAUXMO_ENABLED).toInt() == 1;
  370. #endif
  371. #if ENABLE_DS18B20
  372. root["dsVisible"] = 1;
  373. root["dsTmp"] = getDSTemperatureStr();
  374. #endif
  375. #if ENABLE_DHT
  376. root["dhtVisible"] = 1;
  377. root["dhtTmp"] = getDHTTemperature();
  378. root["dhtHum"] = getDHTHumidity();
  379. #endif
  380. #if ENABLE_RF
  381. root["rfVisible"] = 1;
  382. root["rfChannel"] = getSetting("rfChannel", RF_CHANNEL);
  383. root["rfDevice"] = getSetting("rfDevice", RF_DEVICE);
  384. #endif
  385. #if ENABLE_EMON
  386. root["emonVisible"] = 1;
  387. root["emonPower"] = getPower();
  388. root["emonMains"] = getSetting("emonMains", EMON_MAINS_VOLTAGE);
  389. root["emonRatio"] = getSetting("emonRatio", EMON_CURRENT_RATIO);
  390. #endif
  391. #if ENABLE_ANALOG
  392. root["analogVisible"] = 1;
  393. root["analogValue"] = getAnalog();
  394. #endif
  395. #if ENABLE_POW
  396. root["powVisible"] = 1;
  397. root["powActivePower"] = getActivePower();
  398. root["powApparentPower"] = getApparentPower();
  399. root["powReactivePower"] = getReactivePower();
  400. root["powVoltage"] = getVoltage();
  401. root["powCurrent"] = getCurrent();
  402. root["powPowerFactor"] = getPowerFactor();
  403. #endif
  404. root["maxNetworks"] = WIFI_MAX_NETWORKS;
  405. JsonArray& wifi = root.createNestedArray("wifi");
  406. for (byte i=0; i<WIFI_MAX_NETWORKS; i++) {
  407. if (getSetting("ssid" + String(i)).length() == 0) break;
  408. JsonObject& network = wifi.createNestedObject();
  409. network["ssid"] = getSetting("ssid" + String(i));
  410. network["pass"] = getSetting("pass" + String(i));
  411. network["ip"] = getSetting("ip" + String(i));
  412. network["gw"] = getSetting("gw" + String(i));
  413. network["mask"] = getSetting("mask" + String(i));
  414. network["dns"] = getSetting("dns" + String(i));
  415. }
  416. }
  417. String output;
  418. root.printTo(output);
  419. ws.text(client_id, (char *) output.c_str());
  420. }
  421. bool _wsAuth(AsyncWebSocketClient * client) {
  422. IPAddress ip = client->remoteIP();
  423. unsigned long now = millis();
  424. unsigned short index = 0;
  425. for (index = 0; index < WS_BUFFER_SIZE; index++) {
  426. if ((_ticket[index].ip == ip) && (now - _ticket[index].timestamp < WS_TIMEOUT)) break;
  427. }
  428. if (index == WS_BUFFER_SIZE) {
  429. DEBUG_MSG_P(PSTR("[WEBSOCKET] Validation check failed\n"));
  430. ws.text(client->id(), "{\"message\": \"Session expired, please reload page...\"}");
  431. return false;
  432. }
  433. return true;
  434. }
  435. void _wsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){
  436. static uint8_t * message;
  437. // Authorize
  438. #ifndef NOWSAUTH
  439. if (!_wsAuth(client)) return;
  440. #endif
  441. if (type == WS_EVT_CONNECT) {
  442. IPAddress ip = client->remoteIP();
  443. 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());
  444. _wsStart(client->id());
  445. } else if(type == WS_EVT_DISCONNECT) {
  446. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u disconnected\n"), client->id());
  447. } else if(type == WS_EVT_ERROR) {
  448. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u error(%u): %s\n"), client->id(), *((uint16_t*)arg), (char*)data);
  449. } else if(type == WS_EVT_PONG) {
  450. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u pong(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  451. } else if(type == WS_EVT_DATA) {
  452. AwsFrameInfo * info = (AwsFrameInfo*)arg;
  453. // First packet
  454. if (info->index == 0) {
  455. message = (uint8_t*) malloc(info->len);
  456. }
  457. // Store data
  458. memcpy(message + info->index, data, len);
  459. // Last packet
  460. if (info->index + len == info->len) {
  461. _wsParse(client->id(), message, info->len);
  462. free(message);
  463. }
  464. }
  465. }
  466. // -----------------------------------------------------------------------------
  467. // WEBSERVER
  468. // -----------------------------------------------------------------------------
  469. void webLogRequest(AsyncWebServerRequest *request) {
  470. DEBUG_MSG_P(PSTR("[WEBSERVER] Request: %s %s\n"), request->methodToString(), request->url().c_str());
  471. }
  472. bool _authenticate(AsyncWebServerRequest *request) {
  473. String password = getSetting("adminPass", ADMIN_PASS);
  474. char httpPassword[password.length() + 1];
  475. password.toCharArray(httpPassword, password.length() + 1);
  476. return request->authenticate(HTTP_USERNAME, httpPassword);
  477. }
  478. bool _authAPI(AsyncWebServerRequest *request) {
  479. if (getSetting("apiEnabled").toInt() == 0) {
  480. DEBUG_MSG_P(PSTR("[WEBSERVER] HTTP API is not enabled\n"));
  481. request->send(403);
  482. return false;
  483. }
  484. if (!request->hasParam("apikey", (request->method() == HTTP_PUT))) {
  485. DEBUG_MSG_P(PSTR("[WEBSERVER] Missing apikey parameter\n"));
  486. request->send(403);
  487. return false;
  488. }
  489. AsyncWebParameter* p = request->getParam("apikey", (request->method() == HTTP_PUT));
  490. if (!p->value().equals(getSetting("apiKey"))) {
  491. DEBUG_MSG_P(PSTR("[WEBSERVER] Wrong apikey parameter\n"));
  492. request->send(403);
  493. return false;
  494. }
  495. return true;
  496. }
  497. bool _asJson(AsyncWebServerRequest *request) {
  498. bool asJson = false;
  499. if (request->hasHeader("Accept")) {
  500. AsyncWebHeader* h = request->getHeader("Accept");
  501. asJson = h->value().equals("application/json");
  502. }
  503. return asJson;
  504. }
  505. ArRequestHandlerFunction _bindAPI(unsigned int apiID) {
  506. return [apiID](AsyncWebServerRequest *request) {
  507. webLogRequest(request);
  508. if (!_authAPI(request)) return;
  509. bool asJson = _asJson(request);
  510. web_api_t api = _apis[apiID];
  511. if (api.putFn != NULL) {
  512. if (request->hasParam("value", request->method() == HTTP_PUT)) {
  513. AsyncWebParameter* p = request->getParam("value", request->method() == HTTP_PUT);
  514. (api.putFn)((p->value()).c_str());
  515. }
  516. }
  517. char value[10];
  518. (api.getFn)(value, 10);
  519. // jump over leading spaces
  520. char *p = value;
  521. while ((unsigned char) *p == ' ') ++p;
  522. if (asJson) {
  523. char buffer[64];
  524. sprintf_P(buffer, PSTR("{ \"%s\": %s }"), api.key, p);
  525. request->send(200, "application/json", buffer);
  526. } else {
  527. request->send(200, "text/plain", p);
  528. }
  529. };
  530. }
  531. void apiRegister(const char * url, const char * key, apiGetCallbackFunction getFn, apiPutCallbackFunction putFn) {
  532. // Store it
  533. web_api_t api;
  534. char buffer[40];
  535. snprintf(buffer, 39, "/api/%s", url);
  536. api.url = strdup(buffer);
  537. api.key = strdup(key);
  538. api.getFn = getFn;
  539. api.putFn = putFn;
  540. _apis.push_back(api);
  541. // Bind call
  542. unsigned int methods = HTTP_GET;
  543. if (putFn != NULL) methods += HTTP_PUT;
  544. _server->on(buffer, methods, _bindAPI(_apis.size() - 1));
  545. }
  546. void _onAPIs(AsyncWebServerRequest *request) {
  547. webLogRequest(request);
  548. if (!_authAPI(request)) return;
  549. bool asJson = _asJson(request);
  550. String output;
  551. if (asJson) {
  552. DynamicJsonBuffer jsonBuffer;
  553. JsonObject& root = jsonBuffer.createObject();
  554. for (unsigned int i=0; i < _apis.size(); i++) {
  555. root[_apis[i].key] = _apis[i].url;
  556. }
  557. root.printTo(output);
  558. request->send(200, "application/json", output);
  559. } else {
  560. for (unsigned int i=0; i < _apis.size(); i++) {
  561. output += _apis[i].key + String(" -> ") + _apis[i].url + String("\n<br />");
  562. }
  563. request->send(200, "text/plain", output);
  564. }
  565. }
  566. void _onRPC(AsyncWebServerRequest *request) {
  567. webLogRequest(request);
  568. if (!_authAPI(request)) return;
  569. //bool asJson = _asJson(request);
  570. int response = 404;
  571. if (request->hasParam("action")) {
  572. AsyncWebParameter* p = request->getParam("action");
  573. String action = p->value();
  574. DEBUG_MSG_P(PSTR("[RPC] Action: %s\n"), action.c_str());
  575. if (action.equals("reset")) {
  576. response = 200;
  577. deferred.once_ms(100, []() { ESP.restart(); });
  578. }
  579. }
  580. request->send(response);
  581. }
  582. void _onAuth(AsyncWebServerRequest *request) {
  583. webLogRequest(request);
  584. if (!_authenticate(request)) return request->requestAuthentication();
  585. IPAddress ip = request->client()->remoteIP();
  586. unsigned long now = millis();
  587. unsigned short index;
  588. for (index = 0; index < WS_BUFFER_SIZE; index++) {
  589. if (_ticket[index].ip == ip) break;
  590. if (_ticket[index].timestamp == 0) break;
  591. if (now - _ticket[index].timestamp > WS_TIMEOUT) break;
  592. }
  593. if (index == WS_BUFFER_SIZE) {
  594. request->send(429);
  595. } else {
  596. _ticket[index].ip = ip;
  597. _ticket[index].timestamp = now;
  598. request->send(204);
  599. }
  600. }
  601. void _onGetConfig(AsyncWebServerRequest *request) {
  602. webLogRequest(request);
  603. if (!_authenticate(request)) return request->requestAuthentication();
  604. AsyncJsonResponse * response = new AsyncJsonResponse();
  605. JsonObject& root = response->getRoot();
  606. root["app"] = APP_NAME;
  607. root["version"] = APP_VERSION;
  608. unsigned int size = settingsKeyCount();
  609. for (unsigned int i=0; i<size; i++) {
  610. String key = settingsKeyName(i);
  611. String value = getSetting(key);
  612. root[key] = value;
  613. }
  614. char buffer[100];
  615. sprintf(buffer, "attachment; filename=\"%s-backup.json\"", (char *) getSetting("hostname").c_str());
  616. response->addHeader("Content-Disposition", buffer);
  617. response->setLength();
  618. request->send(response);
  619. }
  620. #if EMBEDDED_WEB
  621. void _onHome(AsyncWebServerRequest *request) {
  622. webLogRequest(request);
  623. if (request->header("If-Modified-Since").equals(_last_modified)) {
  624. request->send(304);
  625. } else {
  626. AsyncWebServerResponse *response = request->beginResponse_P(200, "text/html", index_html_gz, index_html_gz_len);
  627. response->addHeader("Content-Encoding", "gzip");
  628. response->addHeader("Last-Modified", _last_modified);
  629. request->send(response);
  630. }
  631. }
  632. #endif
  633. void _onUpgrade(AsyncWebServerRequest *request) {
  634. AsyncWebServerResponse *response = request->beginResponse(200, "text/plain", Update.hasError() ? "FAIL" : "OK");
  635. response->addHeader("Connection", "close");
  636. if (!Update.hasError()) {
  637. deferred.once_ms(100, []() {
  638. ESP.restart();
  639. });
  640. }
  641. request->send(response);
  642. }
  643. void _onUpgradeData(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final) {
  644. if (!index) {
  645. DEBUG_MSG_P(PSTR("[UPGRADE] Start: %s\n"), filename.c_str());
  646. Update.runAsync(true);
  647. if (!Update.begin((ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000)) {
  648. Update.printError(Serial);
  649. }
  650. }
  651. if (!Update.hasError()) {
  652. if (Update.write(data, len) != len) {
  653. Update.printError(Serial);
  654. }
  655. }
  656. if (final) {
  657. if (Update.end(true)){
  658. DEBUG_MSG_P(PSTR("[UPGRADE] Success: %u bytes\n"), index + len);
  659. } else {
  660. Update.printError(Serial);
  661. }
  662. } else {
  663. DEBUG_MSG_P(PSTR("[UPGRADE] Progress: %u bytes\r"), index + len);
  664. }
  665. }
  666. void webSetup() {
  667. // Create server
  668. _server = new AsyncWebServer(getSetting("webPort", WEBSERVER_PORT).toInt());
  669. // Setup websocket
  670. ws.onEvent(_wsEvent);
  671. mqttRegister(wsMQTTCallback);
  672. // Cache the Last-Modifier header value
  673. sprintf(_last_modified, "%s %s GMT", __DATE__, __TIME__);
  674. // Setup webserver
  675. _server->addHandler(&ws);
  676. // Rewrites
  677. _server->rewrite("/", "/index.html");
  678. // Serve home (basic authentication protection)
  679. #if EMBEDDED_WEB
  680. _server->on("/index.html", HTTP_GET, _onHome);
  681. #endif
  682. _server->on("/config", HTTP_GET, _onGetConfig);
  683. _server->on("/auth", HTTP_GET, _onAuth);
  684. _server->on("/apis", HTTP_GET, _onAPIs);
  685. _server->on("/rpc", HTTP_GET, _onRPC);
  686. _server->on("/upgrade", HTTP_POST, _onUpgrade, _onUpgradeData);
  687. // Serve static files
  688. #if not EMBEDDED_WEB
  689. _server->serveStatic("/", SPIFFS, "/")
  690. .setLastModified(_last_modified)
  691. .setFilter([](AsyncWebServerRequest *request) -> bool {
  692. webLogRequest(request);
  693. return true;
  694. });
  695. #endif
  696. // 404
  697. _server->onNotFound([](AsyncWebServerRequest *request){
  698. request->send(404);
  699. });
  700. // Run server
  701. _server->begin();
  702. DEBUG_MSG_P(PSTR("[WEBSERVER] Webserver running on port %d\n"), getSetting("webPort", WEBSERVER_PORT).toInt());
  703. }