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.

1005 lines
30 KiB

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