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.

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