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.

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