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.

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