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.

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