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.

1020 lines
31 KiB

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