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.

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