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.

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