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.

1238 lines
38 KiB

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