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.

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