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