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.

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