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.

955 lines
28 KiB

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