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