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.

966 lines
29 KiB

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