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.

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