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.

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