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.

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