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.

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