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.

1245 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. wifiReconnectCheck();
  600. } else if(type == WS_EVT_DISCONNECT) {
  601. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u disconnected\n"), client->id());
  602. if (client->_tempObject) {
  603. delete (WebSocketIncommingBuffer *) client->_tempObject;
  604. }
  605. wifiReconnectCheck();
  606. } else if(type == WS_EVT_ERROR) {
  607. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u error(%u): %s\n"), client->id(), *((uint16_t*)arg), (char*)data);
  608. } else if(type == WS_EVT_PONG) {
  609. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u pong(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  610. } else if(type == WS_EVT_DATA) {
  611. WebSocketIncommingBuffer *buffer = (WebSocketIncommingBuffer *)client->_tempObject;
  612. AwsFrameInfo * info = (AwsFrameInfo*)arg;
  613. buffer->data_event(client, info, data, len);
  614. }
  615. }
  616. // -----------------------------------------------------------------------------
  617. bool wsConnected() {
  618. return (_ws.count() > 0);
  619. }
  620. void wsSend(const char * payload) {
  621. if (_ws.count() > 0) {
  622. _ws.textAll(payload);
  623. }
  624. }
  625. void wsSend_P(PGM_P payload) {
  626. if (_ws.count() > 0) {
  627. char buffer[strlen_P(payload)];
  628. strcpy_P(buffer, payload);
  629. _ws.textAll(buffer);
  630. }
  631. }
  632. void wsSend(uint32_t client_id, const char * payload) {
  633. _ws.text(client_id, payload);
  634. }
  635. void wsSend_P(uint32_t client_id, PGM_P payload) {
  636. char buffer[strlen_P(payload)];
  637. strcpy_P(buffer, payload);
  638. _ws.text(client_id, buffer);
  639. }
  640. void wsSetup() {
  641. _ws.onEvent(_wsEvent);
  642. mqttRegister(_wsMQTTCallback);
  643. _server->addHandler(&_ws);
  644. _server->on("/auth", HTTP_GET, _onAuth);
  645. }
  646. // -----------------------------------------------------------------------------
  647. // API
  648. // -----------------------------------------------------------------------------
  649. bool _authAPI(AsyncWebServerRequest *request) {
  650. if (getSetting("apiEnabled", API_ENABLED).toInt() == 0) {
  651. DEBUG_MSG_P(PSTR("[WEBSERVER] HTTP API is not enabled\n"));
  652. request->send(403);
  653. return false;
  654. }
  655. if (!request->hasParam("apikey", (request->method() == HTTP_PUT))) {
  656. DEBUG_MSG_P(PSTR("[WEBSERVER] Missing apikey parameter\n"));
  657. request->send(403);
  658. return false;
  659. }
  660. AsyncWebParameter* p = request->getParam("apikey", (request->method() == HTTP_PUT));
  661. if (!p->value().equals(getSetting("apiKey"))) {
  662. DEBUG_MSG_P(PSTR("[WEBSERVER] Wrong apikey parameter\n"));
  663. request->send(403);
  664. return false;
  665. }
  666. return true;
  667. }
  668. bool _asJson(AsyncWebServerRequest *request) {
  669. bool asJson = false;
  670. if (request->hasHeader("Accept")) {
  671. AsyncWebHeader* h = request->getHeader("Accept");
  672. asJson = h->value().equals("application/json");
  673. }
  674. return asJson;
  675. }
  676. ArRequestHandlerFunction _bindAPI(unsigned int apiID) {
  677. return [apiID](AsyncWebServerRequest *request) {
  678. _webLog(request);
  679. if (!_authAPI(request)) return;
  680. web_api_t api = _apis[apiID];
  681. // Check if its a PUT
  682. if (api.putFn != NULL) {
  683. if (request->hasParam("value", request->method() == HTTP_PUT)) {
  684. AsyncWebParameter* p = request->getParam("value", request->method() == HTTP_PUT);
  685. (api.putFn)((p->value()).c_str());
  686. }
  687. }
  688. // Get response from callback
  689. char value[API_BUFFER_SIZE];
  690. (api.getFn)(value, API_BUFFER_SIZE);
  691. // The response will be a 404 NOT FOUND if the resource is not available
  692. if (!value) {
  693. DEBUG_MSG_P(PSTR("[API] Sending 404 response\n"));
  694. request->send(404);
  695. return;
  696. }
  697. DEBUG_MSG_P(PSTR("[API] Sending response '%s'\n"), value);
  698. // Format response according to the Accept header
  699. if (_asJson(request)) {
  700. char buffer[64];
  701. snprintf_P(buffer, sizeof(buffer), PSTR("{ \"%s\": %s }"), api.key, value);
  702. request->send(200, "application/json", buffer);
  703. } else {
  704. request->send(200, "text/plain", value);
  705. }
  706. };
  707. }
  708. void _onAPIs(AsyncWebServerRequest *request) {
  709. _webLog(request);
  710. if (!_authAPI(request)) return;
  711. bool asJson = _asJson(request);
  712. String output;
  713. if (asJson) {
  714. DynamicJsonBuffer jsonBuffer;
  715. JsonObject& root = jsonBuffer.createObject();
  716. for (unsigned int i=0; i < _apis.size(); i++) {
  717. root[_apis[i].key] = _apis[i].url;
  718. }
  719. root.printTo(output);
  720. request->send(200, "application/json", output);
  721. } else {
  722. for (unsigned int i=0; i < _apis.size(); i++) {
  723. output += _apis[i].key + String(" -> ") + _apis[i].url + String("\n");
  724. }
  725. request->send(200, "text/plain", output);
  726. }
  727. }
  728. void _onRPC(AsyncWebServerRequest *request) {
  729. _webLog(request);
  730. if (!_authAPI(request)) return;
  731. //bool asJson = _asJson(request);
  732. int response = 404;
  733. if (request->hasParam("action")) {
  734. AsyncWebParameter* p = request->getParam("action");
  735. String action = p->value();
  736. DEBUG_MSG_P(PSTR("[RPC] Action: %s\n"), action.c_str());
  737. if (action.equals("reset")) {
  738. response = 200;
  739. _web_defer.once_ms(100, []() {
  740. customReset(CUSTOM_RESET_RPC);
  741. ESP.restart();
  742. });
  743. }
  744. }
  745. request->send(response);
  746. }
  747. // -----------------------------------------------------------------------------
  748. void apiRegister(const char * url, const char * key, apiGetCallbackFunction getFn, apiPutCallbackFunction putFn) {
  749. // Store it
  750. web_api_t api;
  751. char buffer[40];
  752. snprintf_P(buffer, sizeof(buffer), PSTR("/api/%s"), url);
  753. api.url = strdup(buffer);
  754. api.key = strdup(key);
  755. api.getFn = getFn;
  756. api.putFn = putFn;
  757. _apis.push_back(api);
  758. // Bind call
  759. unsigned int methods = HTTP_GET;
  760. if (putFn != NULL) methods += HTTP_PUT;
  761. _server->on(buffer, methods, _bindAPI(_apis.size() - 1));
  762. }
  763. void apiSetup() {
  764. _server->on("/apis", HTTP_GET, _onAPIs);
  765. _server->on("/rpc", HTTP_GET, _onRPC);
  766. }
  767. // -----------------------------------------------------------------------------
  768. // WEBSERVER
  769. // -----------------------------------------------------------------------------
  770. void _webLog(AsyncWebServerRequest *request) {
  771. DEBUG_MSG_P(PSTR("[WEBSERVER] Request: %s %s\n"), request->methodToString(), request->url().c_str());
  772. }
  773. bool _authenticate(AsyncWebServerRequest *request) {
  774. String password = getSetting("adminPass", ADMIN_PASS);
  775. char httpPassword[password.length() + 1];
  776. password.toCharArray(httpPassword, password.length() + 1);
  777. return request->authenticate(WEB_USERNAME, httpPassword);
  778. }
  779. void _onAuth(AsyncWebServerRequest *request) {
  780. _webLog(request);
  781. if (!_authenticate(request)) return request->requestAuthentication();
  782. IPAddress ip = request->client()->remoteIP();
  783. unsigned long now = millis();
  784. unsigned short index;
  785. for (index = 0; index < WS_BUFFER_SIZE; index++) {
  786. if (_ticket[index].ip == ip) break;
  787. if (_ticket[index].timestamp == 0) break;
  788. if (now - _ticket[index].timestamp > WS_TIMEOUT) break;
  789. }
  790. if (index == WS_BUFFER_SIZE) {
  791. request->send(429);
  792. } else {
  793. _ticket[index].ip = ip;
  794. _ticket[index].timestamp = now;
  795. request->send(204);
  796. }
  797. }
  798. void _onGetConfig(AsyncWebServerRequest *request) {
  799. _webLog(request);
  800. if (!_authenticate(request)) return request->requestAuthentication();
  801. AsyncJsonResponse * response = new AsyncJsonResponse();
  802. JsonObject& root = response->getRoot();
  803. root["app"] = APP_NAME;
  804. root["version"] = APP_VERSION;
  805. unsigned int size = settingsKeyCount();
  806. for (unsigned int i=0; i<size; i++) {
  807. String key = settingsKeyName(i);
  808. String value = getSetting(key);
  809. root[key] = value;
  810. }
  811. char buffer[100];
  812. snprintf_P(buffer, sizeof(buffer), PSTR("attachment; filename=\"%s-backup.json\""), (char *) getSetting("hostname").c_str());
  813. response->addHeader("Content-Disposition", buffer);
  814. response->setLength();
  815. request->send(response);
  816. }
  817. #if WEB_EMBEDDED
  818. void _onHome(AsyncWebServerRequest *request) {
  819. _webLog(request);
  820. if (request->header("If-Modified-Since").equals(_last_modified)) {
  821. request->send(304);
  822. } else {
  823. #if ASYNC_TCP_SSL_ENABLED
  824. // Chunked response, we calculate the chunks based on free heap (in multiples of 32)
  825. // This is necessary when a TLS connection is open since it sucks too much memory
  826. DEBUG_MSG_P(PSTR("[MAIN] Free heap: %d bytes\n"), ESP.getFreeHeap());
  827. size_t max = (ESP.getFreeHeap() / 3) & 0xFFE0;
  828. AsyncWebServerResponse *response = request->beginChunkedResponse("text/html", [max](uint8_t *buffer, size_t maxLen, size_t index) -> size_t {
  829. // Get the chunk based on the index and maxLen
  830. size_t len = index_html_gz_len - index;
  831. if (len > maxLen) len = maxLen;
  832. if (len > max) len = max;
  833. if (len > 0) memcpy_P(buffer, index_html_gz + index, len);
  834. DEBUG_MSG_P(PSTR("[WEB] Sending %d%%%% (max chunk size: %4d)\r"), int(100 * index / index_html_gz_len), max);
  835. if (len == 0) DEBUG_MSG_P(PSTR("\n"));
  836. // Return the actual length of the chunk (0 for end of file)
  837. return len;
  838. });
  839. #else
  840. AsyncWebServerResponse *response = request->beginResponse_P(200, "text/html", index_html_gz, index_html_gz_len);
  841. #endif
  842. response->addHeader("Content-Encoding", "gzip");
  843. response->addHeader("Last-Modified", _last_modified);
  844. request->send(response);
  845. }
  846. }
  847. #endif
  848. #if ASYNC_TCP_SSL_ENABLED & WEB_SSL_ENABLED
  849. int _onCertificate(void * arg, const char *filename, uint8_t **buf) {
  850. #if WEB_EMBEDDED
  851. if (strcmp(filename, "server.cer") == 0) {
  852. uint8_t * nbuf = (uint8_t*) malloc(server_cer_len);
  853. memcpy_P(nbuf, server_cer, server_cer_len);
  854. *buf = nbuf;
  855. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - OK\n"), filename);
  856. return server_cer_len;
  857. }
  858. if (strcmp(filename, "server.key") == 0) {
  859. uint8_t * nbuf = (uint8_t*) malloc(server_key_len);
  860. memcpy_P(nbuf, server_key, server_key_len);
  861. *buf = nbuf;
  862. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - OK\n"), filename);
  863. return server_key_len;
  864. }
  865. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - ERROR\n"), filename);
  866. *buf = 0;
  867. return 0;
  868. #else
  869. File file = SPIFFS.open(filename, "r");
  870. if (file) {
  871. size_t size = file.size();
  872. uint8_t * nbuf = (uint8_t*) malloc(size);
  873. if (nbuf) {
  874. size = file.read(nbuf, size);
  875. file.close();
  876. *buf = nbuf;
  877. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - OK\n"), filename);
  878. return size;
  879. }
  880. file.close();
  881. }
  882. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - ERROR\n"), filename);
  883. *buf = 0;
  884. return 0;
  885. #endif
  886. }
  887. #endif
  888. void _onUpgrade(AsyncWebServerRequest *request) {
  889. char buffer[10];
  890. if (!Update.hasError()) {
  891. sprintf_P(buffer, PSTR("OK"));
  892. } else {
  893. sprintf_P(buffer, PSTR("ERROR %d"), Update.getError());
  894. }
  895. AsyncWebServerResponse *response = request->beginResponse(200, "text/plain", buffer);
  896. response->addHeader("Connection", "close");
  897. if (!Update.hasError()) {
  898. _web_defer.once_ms(100, []() {
  899. customReset(CUSTOM_RESET_UPGRADE);
  900. ESP.restart();
  901. });
  902. }
  903. request->send(response);
  904. }
  905. void _onUpgradeData(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final) {
  906. if (!index) {
  907. DEBUG_MSG_P(PSTR("[UPGRADE] Start: %s\n"), filename.c_str());
  908. Update.runAsync(true);
  909. if (!Update.begin((ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000)) {
  910. #ifdef DEBUG_PORT
  911. Update.printError(DEBUG_PORT);
  912. #endif
  913. }
  914. }
  915. if (!Update.hasError()) {
  916. if (Update.write(data, len) != len) {
  917. #ifdef DEBUG_PORT
  918. Update.printError(DEBUG_PORT);
  919. #endif
  920. }
  921. }
  922. if (final) {
  923. if (Update.end(true)){
  924. DEBUG_MSG_P(PSTR("[UPGRADE] Success: %u bytes\n"), index + len);
  925. } else {
  926. #ifdef DEBUG_PORT
  927. Update.printError(DEBUG_PORT);
  928. #endif
  929. }
  930. } else {
  931. DEBUG_MSG_P(PSTR("[UPGRADE] Progress: %u bytes\r"), index + len);
  932. }
  933. }
  934. // -----------------------------------------------------------------------------
  935. void webSetup() {
  936. // Cache the Last-Modifier header value
  937. snprintf_P(_last_modified, sizeof(_last_modified), PSTR("%s %s GMT"), __DATE__, __TIME__);
  938. // Create server
  939. #if ASYNC_TCP_SSL_ENABLED & WEB_SSL_ENABLED
  940. unsigned int port = 443;
  941. #else
  942. unsigned int port = getSetting("webPort", WEB_PORT).toInt();
  943. #endif
  944. _server = new AsyncWebServer(port);
  945. // Setup websocket
  946. wsSetup();
  947. // API setup
  948. apiSetup();
  949. // Rewrites
  950. _server->rewrite("/", "/index.html");
  951. // Serve home (basic authentication protection)
  952. #if WEB_EMBEDDED
  953. _server->on("/index.html", HTTP_GET, _onHome);
  954. #endif
  955. _server->on("/config", HTTP_GET, _onGetConfig);
  956. _server->on("/upgrade", HTTP_POST, _onUpgrade, _onUpgradeData);
  957. // Serve static files
  958. #if SPIFFS_SUPPORT
  959. _server->serveStatic("/", SPIFFS, "/")
  960. .setLastModified(_last_modified)
  961. .setFilter([](AsyncWebServerRequest *request) -> bool {
  962. _webLog(request);
  963. return true;
  964. });
  965. #endif
  966. // 404
  967. _server->onNotFound([](AsyncWebServerRequest *request){
  968. request->send(404);
  969. });
  970. // Run server
  971. #if ASYNC_TCP_SSL_ENABLED & WEB_SSL_ENABLED
  972. _server->onSslFileRequest(_onCertificate, NULL);
  973. _server->beginSecure("server.cer", "server.key", NULL);
  974. #else
  975. _server->begin();
  976. #endif
  977. DEBUG_MSG_P(PSTR("[WEBSERVER] Webserver running on port %d\n"), port);
  978. }
  979. #endif // WEB_SUPPORT