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.

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