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.

964 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
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. 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["webPort"] = getSetting("webPort", WEBSERVER_PORT).toInt();
  368. root["apiEnabled"] = getSetting("apiEnabled").toInt() == 1;
  369. root["apiKey"] = getSetting("apiKey");
  370. root["tmpUnits"] = getSetting("tmpUnits", TMP_UNITS).toInt();
  371. #if ENABLE_DOMOTICZ
  372. root["dczVisible"] = 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(relayToIdx(i));
  378. }
  379. #if ENABLE_DHT
  380. root["dczTmpIdx"] = getSetting("dczTmpIdx").toInt();
  381. root["dczHumIdx"] = getSetting("dczHumIdx").toInt();
  382. #endif
  383. #if ENABLE_DS18B20
  384. root["dczTmpIdx"] = getSetting("dczTmpIdx").toInt();
  385. #endif
  386. #if ENABLE_EMON
  387. root["dczPowIdx"] = getSetting("dczPowIdx").toInt();
  388. root["dczEnergyIdx"] = getSetting("dczEnergyIdx").toInt();
  389. root["dczCurrentIdx"] = getSetting("dczCurrentIdx").toInt();
  390. #endif
  391. #if ENABLE_ANALOG
  392. root["dczAnaIdx"] = getSetting("dczAnaIdx").toInt();
  393. #endif
  394. #if ENABLE_HLW8012
  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 ENABLE_INFLUXDB
  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 ENABLE_FAUXMO
  410. root["fauxmoVisible"] = 1;
  411. root["fauxmoEnabled"] = getSetting("fauxmoEnabled", FAUXMO_ENABLED).toInt() == 1;
  412. #endif
  413. #if ENABLE_DS18B20
  414. root["dsVisible"] = 1;
  415. root["dsTmp"] = getDSTemperatureStr();
  416. #endif
  417. #if ENABLE_DHT
  418. root["dhtVisible"] = 1;
  419. root["dhtTmp"] = getDHTTemperature();
  420. root["dhtHum"] = getDHTHumidity();
  421. #endif
  422. #if ENABLE_RF
  423. root["rfVisible"] = 1;
  424. root["rfChannel"] = getSetting("rfChannel", RF_CHANNEL);
  425. root["rfDevice"] = getSetting("rfDevice", RF_DEVICE);
  426. #endif
  427. #if ENABLE_EMON
  428. root["emonVisible"] = 1;
  429. root["emonPower"] = getPower();
  430. root["emonMains"] = getSetting("emonMains", EMON_MAINS_VOLTAGE);
  431. root["emonRatio"] = getSetting("emonRatio", EMON_CURRENT_RATIO);
  432. #endif
  433. #if ENABLE_ANALOG
  434. root["analogVisible"] = 1;
  435. root["analogValue"] = getAnalog();
  436. #endif
  437. #if ENABLE_HLW8012
  438. root["powVisible"] = 1;
  439. root["powActivePower"] = getActivePower();
  440. root["powApparentPower"] = getApparentPower();
  441. root["powReactivePower"] = getReactivePower();
  442. root["powVoltage"] = getVoltage();
  443. root["powCurrent"] = String(getCurrent(), 3);
  444. root["powPowerFactor"] = String(getPowerFactor(), 2);
  445. #endif
  446. root["maxNetworks"] = WIFI_MAX_NETWORKS;
  447. JsonArray& wifi = root.createNestedArray("wifi");
  448. for (byte i=0; i<WIFI_MAX_NETWORKS; i++) {
  449. if (getSetting("ssid" + String(i)).length() == 0) break;
  450. JsonObject& network = wifi.createNestedObject();
  451. network["ssid"] = getSetting("ssid" + String(i));
  452. network["pass"] = getSetting("pass" + String(i));
  453. network["ip"] = getSetting("ip" + String(i));
  454. network["gw"] = getSetting("gw" + String(i));
  455. network["mask"] = getSetting("mask" + String(i));
  456. network["dns"] = getSetting("dns" + String(i));
  457. }
  458. }
  459. String output;
  460. root.printTo(output);
  461. ws.text(client_id, (char *) output.c_str());
  462. }
  463. bool _wsAuth(AsyncWebSocketClient * client) {
  464. IPAddress ip = client->remoteIP();
  465. unsigned long now = millis();
  466. unsigned short index = 0;
  467. for (index = 0; index < WS_BUFFER_SIZE; index++) {
  468. if ((_ticket[index].ip == ip) && (now - _ticket[index].timestamp < WS_TIMEOUT)) break;
  469. }
  470. if (index == WS_BUFFER_SIZE) {
  471. DEBUG_MSG_P(PSTR("[WEBSOCKET] Validation check failed\n"));
  472. ws.text(client->id(), "{\"message\": \"Session expired, please reload page...\"}");
  473. return false;
  474. }
  475. return true;
  476. }
  477. void _wsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){
  478. static uint8_t * message;
  479. // Authorize
  480. #ifndef NOWSAUTH
  481. if (!_wsAuth(client)) return;
  482. #endif
  483. if (type == WS_EVT_CONNECT) {
  484. IPAddress ip = client->remoteIP();
  485. 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());
  486. _wsStart(client->id());
  487. } else if(type == WS_EVT_DISCONNECT) {
  488. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u disconnected\n"), client->id());
  489. } else if(type == WS_EVT_ERROR) {
  490. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u error(%u): %s\n"), client->id(), *((uint16_t*)arg), (char*)data);
  491. } else if(type == WS_EVT_PONG) {
  492. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u pong(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  493. } else if(type == WS_EVT_DATA) {
  494. AwsFrameInfo * info = (AwsFrameInfo*)arg;
  495. // First packet
  496. if (info->index == 0) {
  497. message = (uint8_t*) malloc(info->len);
  498. }
  499. // Store data
  500. memcpy(message + info->index, data, len);
  501. // Last packet
  502. if (info->index + len == info->len) {
  503. _wsParse(client->id(), message, info->len);
  504. free(message);
  505. }
  506. }
  507. }
  508. // -----------------------------------------------------------------------------
  509. // WEBSERVER
  510. // -----------------------------------------------------------------------------
  511. void webLogRequest(AsyncWebServerRequest *request) {
  512. DEBUG_MSG_P(PSTR("[WEBSERVER] Request: %s %s\n"), request->methodToString(), request->url().c_str());
  513. }
  514. bool _authenticate(AsyncWebServerRequest *request) {
  515. String password = getSetting("adminPass", ADMIN_PASS);
  516. char httpPassword[password.length() + 1];
  517. password.toCharArray(httpPassword, password.length() + 1);
  518. return request->authenticate(HTTP_USERNAME, httpPassword);
  519. }
  520. bool _authAPI(AsyncWebServerRequest *request) {
  521. if (getSetting("apiEnabled").toInt() == 0) {
  522. DEBUG_MSG_P(PSTR("[WEBSERVER] HTTP API is not enabled\n"));
  523. request->send(403);
  524. return false;
  525. }
  526. if (!request->hasParam("apikey", (request->method() == HTTP_PUT))) {
  527. DEBUG_MSG_P(PSTR("[WEBSERVER] Missing apikey parameter\n"));
  528. request->send(403);
  529. return false;
  530. }
  531. AsyncWebParameter* p = request->getParam("apikey", (request->method() == HTTP_PUT));
  532. if (!p->value().equals(getSetting("apiKey"))) {
  533. DEBUG_MSG_P(PSTR("[WEBSERVER] Wrong apikey parameter\n"));
  534. request->send(403);
  535. return false;
  536. }
  537. return true;
  538. }
  539. bool _asJson(AsyncWebServerRequest *request) {
  540. bool asJson = false;
  541. if (request->hasHeader("Accept")) {
  542. AsyncWebHeader* h = request->getHeader("Accept");
  543. asJson = h->value().equals("application/json");
  544. }
  545. return asJson;
  546. }
  547. ArRequestHandlerFunction _bindAPI(unsigned int apiID) {
  548. return [apiID](AsyncWebServerRequest *request) {
  549. webLogRequest(request);
  550. if (!_authAPI(request)) return;
  551. bool asJson = _asJson(request);
  552. web_api_t api = _apis[apiID];
  553. if (api.putFn != NULL) {
  554. if (request->hasParam("value", request->method() == HTTP_PUT)) {
  555. AsyncWebParameter* p = request->getParam("value", request->method() == HTTP_PUT);
  556. (api.putFn)((p->value()).c_str());
  557. }
  558. }
  559. char value[10];
  560. (api.getFn)(value, 10);
  561. // jump over leading spaces
  562. char *p = value;
  563. while ((unsigned char) *p == ' ') ++p;
  564. if (asJson) {
  565. char buffer[64];
  566. sprintf_P(buffer, PSTR("{ \"%s\": %s }"), api.key, p);
  567. request->send(200, "application/json", buffer);
  568. } else {
  569. request->send(200, "text/plain", p);
  570. }
  571. };
  572. }
  573. void apiRegister(const char * url, const char * key, apiGetCallbackFunction getFn, apiPutCallbackFunction putFn) {
  574. // Store it
  575. web_api_t api;
  576. char buffer[40];
  577. snprintf(buffer, 39, "/api/%s", url);
  578. api.url = strdup(buffer);
  579. api.key = strdup(key);
  580. api.getFn = getFn;
  581. api.putFn = putFn;
  582. _apis.push_back(api);
  583. // Bind call
  584. unsigned int methods = HTTP_GET;
  585. if (putFn != NULL) methods += HTTP_PUT;
  586. _server->on(buffer, methods, _bindAPI(_apis.size() - 1));
  587. }
  588. void _onAPIs(AsyncWebServerRequest *request) {
  589. webLogRequest(request);
  590. if (!_authAPI(request)) return;
  591. bool asJson = _asJson(request);
  592. String output;
  593. if (asJson) {
  594. DynamicJsonBuffer jsonBuffer;
  595. JsonObject& root = jsonBuffer.createObject();
  596. for (unsigned int i=0; i < _apis.size(); i++) {
  597. root[_apis[i].key] = _apis[i].url;
  598. }
  599. root.printTo(output);
  600. request->send(200, "application/json", output);
  601. } else {
  602. for (unsigned int i=0; i < _apis.size(); i++) {
  603. output += _apis[i].key + String(" -> ") + _apis[i].url + String("\n<br />");
  604. }
  605. request->send(200, "text/plain", output);
  606. }
  607. }
  608. void _onRPC(AsyncWebServerRequest *request) {
  609. webLogRequest(request);
  610. if (!_authAPI(request)) return;
  611. //bool asJson = _asJson(request);
  612. int response = 404;
  613. if (request->hasParam("action")) {
  614. AsyncWebParameter* p = request->getParam("action");
  615. String action = p->value();
  616. DEBUG_MSG_P(PSTR("[RPC] Action: %s\n"), action.c_str());
  617. if (action.equals("reset")) {
  618. response = 200;
  619. deferred.once_ms(100, []() {
  620. customReset(CUSTOM_RESET_RPC);
  621. ESP.restart();
  622. });
  623. }
  624. }
  625. request->send(response);
  626. }
  627. void _onAuth(AsyncWebServerRequest *request) {
  628. webLogRequest(request);
  629. if (!_authenticate(request)) return request->requestAuthentication();
  630. IPAddress ip = request->client()->remoteIP();
  631. unsigned long now = millis();
  632. unsigned short index;
  633. for (index = 0; index < WS_BUFFER_SIZE; index++) {
  634. if (_ticket[index].ip == ip) break;
  635. if (_ticket[index].timestamp == 0) break;
  636. if (now - _ticket[index].timestamp > WS_TIMEOUT) break;
  637. }
  638. if (index == WS_BUFFER_SIZE) {
  639. request->send(429);
  640. } else {
  641. _ticket[index].ip = ip;
  642. _ticket[index].timestamp = now;
  643. request->send(204);
  644. }
  645. }
  646. void _onGetConfig(AsyncWebServerRequest *request) {
  647. webLogRequest(request);
  648. if (!_authenticate(request)) return request->requestAuthentication();
  649. AsyncJsonResponse * response = new AsyncJsonResponse();
  650. JsonObject& root = response->getRoot();
  651. root["app"] = APP_NAME;
  652. root["version"] = APP_VERSION;
  653. unsigned int size = settingsKeyCount();
  654. for (unsigned int i=0; i<size; i++) {
  655. String key = settingsKeyName(i);
  656. String value = getSetting(key);
  657. root[key] = value;
  658. }
  659. char buffer[100];
  660. sprintf(buffer, "attachment; filename=\"%s-backup.json\"", (char *) getSetting("hostname").c_str());
  661. response->addHeader("Content-Disposition", buffer);
  662. response->setLength();
  663. request->send(response);
  664. }
  665. #if EMBEDDED_WEB
  666. void _onHome(AsyncWebServerRequest *request) {
  667. webLogRequest(request);
  668. if (request->header("If-Modified-Since").equals(_last_modified)) {
  669. request->send(304);
  670. } else {
  671. AsyncWebServerResponse *response = request->beginResponse_P(200, "text/html", index_html_gz, index_html_gz_len);
  672. response->addHeader("Content-Encoding", "gzip");
  673. response->addHeader("Last-Modified", _last_modified);
  674. request->send(response);
  675. }
  676. }
  677. #endif
  678. void _onUpgrade(AsyncWebServerRequest *request) {
  679. AsyncWebServerResponse *response = request->beginResponse(200, "text/plain", Update.hasError() ? "FAIL" : "OK");
  680. response->addHeader("Connection", "close");
  681. if (!Update.hasError()) {
  682. deferred.once_ms(100, []() {
  683. customReset(CUSTOM_RESET_UPGRADE);
  684. ESP.restart();
  685. });
  686. }
  687. request->send(response);
  688. }
  689. void _onUpgradeData(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final) {
  690. if (!index) {
  691. DEBUG_MSG_P(PSTR("[UPGRADE] Start: %s\n"), filename.c_str());
  692. Update.runAsync(true);
  693. if (!Update.begin((ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000)) {
  694. #ifdef DEBUG_PORT
  695. Update.printError(DEBUG_PORT);
  696. #endif
  697. }
  698. }
  699. if (!Update.hasError()) {
  700. if (Update.write(data, len) != len) {
  701. #ifdef DEBUG_PORT
  702. Update.printError(DEBUG_PORT);
  703. #endif
  704. }
  705. }
  706. if (final) {
  707. if (Update.end(true)){
  708. DEBUG_MSG_P(PSTR("[UPGRADE] Success: %u bytes\n"), index + len);
  709. } else {
  710. #ifdef DEBUG_PORT
  711. Update.printError(DEBUG_PORT);
  712. #endif
  713. }
  714. } else {
  715. DEBUG_MSG_P(PSTR("[UPGRADE] Progress: %u bytes\r"), index + len);
  716. }
  717. }
  718. void webSetup() {
  719. // Create server
  720. _server = new AsyncWebServer(getSetting("webPort", WEBSERVER_PORT).toInt());
  721. // Setup websocket
  722. ws.onEvent(_wsEvent);
  723. mqttRegister(wsMQTTCallback);
  724. // Cache the Last-Modifier header value
  725. sprintf(_last_modified, "%s %s GMT", __DATE__, __TIME__);
  726. // Setup webserver
  727. _server->addHandler(&ws);
  728. // Rewrites
  729. _server->rewrite("/", "/index.html");
  730. // Serve home (basic authentication protection)
  731. #if EMBEDDED_WEB
  732. _server->on("/index.html", HTTP_GET, _onHome);
  733. #endif
  734. _server->on("/config", HTTP_GET, _onGetConfig);
  735. _server->on("/auth", HTTP_GET, _onAuth);
  736. _server->on("/apis", HTTP_GET, _onAPIs);
  737. _server->on("/rpc", HTTP_GET, _onRPC);
  738. _server->on("/upgrade", HTTP_POST, _onUpgrade, _onUpgradeData);
  739. // Serve static files
  740. #if not EMBEDDED_WEB
  741. _server->serveStatic("/", SPIFFS, "/")
  742. .setLastModified(_last_modified)
  743. .setFilter([](AsyncWebServerRequest *request) -> bool {
  744. webLogRequest(request);
  745. return true;
  746. });
  747. #endif
  748. // 404
  749. _server->onNotFound([](AsyncWebServerRequest *request){
  750. request->send(404);
  751. });
  752. // Run server
  753. _server->begin();
  754. DEBUG_MSG_P(PSTR("[WEBSERVER] Webserver running on port %d\n"), getSetting("webPort", WEBSERVER_PORT).toInt());
  755. }