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.

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