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.

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