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.

1141 lines
35 KiB

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