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.

1252 lines
39 KiB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
7 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
  1. /*
  2. WEBSERVER MODULE
  3. Copyright (C) 2016-2017 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #if WEB_SUPPORT
  6. #include <ESPAsyncTCP.h>
  7. #include <ESPAsyncWebServer.h>
  8. #include <Hash.h>
  9. #include <FS.h>
  10. #include <AsyncJson.h>
  11. #include <ArduinoJson.h>
  12. #include <Ticker.h>
  13. #include <vector>
  14. #include "web.h"
  15. #if WEB_EMBEDDED
  16. #include "static/index.html.gz.h"
  17. #endif // WEB_EMBEDDED
  18. #if ASYNC_TCP_SSL_ENABLED & WEB_SSL_ENABLED
  19. #include "static/server.cer.h"
  20. #include "static/server.key.h"
  21. #endif // ASYNC_TCP_SSL_ENABLED & WEB_SSL_ENABLED
  22. // -----------------------------------------------------------------------------
  23. AsyncWebServer * _server;
  24. char _last_modified[50];
  25. Ticker _web_defer;
  26. // -----------------------------------------------------------------------------
  27. AsyncWebSocket _ws("/ws");
  28. typedef struct {
  29. IPAddress ip;
  30. unsigned long timestamp = 0;
  31. } ws_ticket_t;
  32. ws_ticket_t _ticket[WS_BUFFER_SIZE];
  33. // -----------------------------------------------------------------------------
  34. typedef struct {
  35. char * url;
  36. char * key;
  37. apiGetCallbackFunction getFn = NULL;
  38. apiPutCallbackFunction putFn = NULL;
  39. } web_api_t;
  40. std::vector<web_api_t> _apis;
  41. // -----------------------------------------------------------------------------
  42. // WEBSOCKETS
  43. // -----------------------------------------------------------------------------
  44. void _wsMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  45. if (type == MQTT_CONNECT_EVENT) {
  46. wsSend_P(PSTR("{\"mqttStatus\": true}"));
  47. }
  48. if (type == MQTT_DISCONNECT_EVENT) {
  49. wsSend_P(PSTR("{\"mqttStatus\": false}"));
  50. }
  51. }
  52. void _wsParse(AsyncWebSocketClient *client, uint8_t * payload, size_t length) {
  53. // Get client ID
  54. uint32_t client_id = client->id();
  55. // Parse JSON input
  56. DynamicJsonBuffer jsonBuffer;
  57. JsonObject& root = jsonBuffer.parseObject((char *) payload);
  58. if (!root.success()) {
  59. DEBUG_MSG_P(PSTR("[WEBSOCKET] Error parsing data\n"));
  60. wsSend_P(client_id, PSTR("{\"message\": 3}"));
  61. return;
  62. }
  63. // Check actions
  64. if (root.containsKey("action")) {
  65. String action = root["action"];
  66. DEBUG_MSG_P(PSTR("[WEBSOCKET] Requested action: %s\n"), action.c_str());
  67. if (action.equals("reset")) {
  68. customReset(CUSTOM_RESET_WEB);
  69. ESP.restart();
  70. }
  71. #ifdef ITEAD_SONOFF_RFBRIDGE
  72. if (action.equals("rfblearn") && root.containsKey("data")) {
  73. JsonObject& data = root["data"];
  74. rfbLearn(data["id"], data["status"]);
  75. }
  76. if (action.equals("rfbforget") && root.containsKey("data")) {
  77. JsonObject& data = root["data"];
  78. rfbForget(data["id"], data["status"]);
  79. }
  80. if (action.equals("rfbsend") && root.containsKey("data")) {
  81. JsonObject& data = root["data"];
  82. rfbStore(data["id"], data["status"], data["data"].as<const char*>());
  83. }
  84. #endif
  85. if (action.equals("restore") && root.containsKey("data")) {
  86. JsonObject& data = root["data"];
  87. if (!data.containsKey("app") || (data["app"] != APP_NAME)) {
  88. wsSend_P(client_id, PSTR("{\"message\": 4}"));
  89. return;
  90. }
  91. for (unsigned int i = EEPROM_DATA_END; i < SPI_FLASH_SEC_SIZE; i++) {
  92. EEPROM.write(i, 0xFF);
  93. }
  94. for (auto element : data) {
  95. if (strcmp(element.key, "app") == 0) continue;
  96. if (strcmp(element.key, "version") == 0) continue;
  97. setSetting(element.key, element.value.as<char*>());
  98. }
  99. saveSettings();
  100. wsSend_P(client_id, PSTR("{\"message\": 5}"));
  101. }
  102. if (action.equals("reconnect")) {
  103. // Let the HTTP request return and disconnect after 100ms
  104. _web_defer.once_ms(100, wifiDisconnect);
  105. }
  106. if (action.equals("relay") && root.containsKey("data")) {
  107. JsonObject& data = root["data"];
  108. if (data.containsKey("status")) {
  109. unsigned char value = relayParsePayload(data["status"]);
  110. if (value == 3) {
  111. relayWS();
  112. } else if (value < 3) {
  113. unsigned int relayID = 0;
  114. if (data.containsKey("id")) {
  115. String value = data["id"];
  116. relayID = value.toInt();
  117. }
  118. // Action to perform
  119. if (value == 0) {
  120. relayStatus(relayID, false);
  121. } else if (value == 1) {
  122. relayStatus(relayID, true);
  123. } else if (value == 2) {
  124. relayToggle(relayID);
  125. }
  126. }
  127. }
  128. }
  129. #if HOMEASSISTANT_SUPPORT
  130. if (action.equals("ha_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. if (lightHasColor()) {
  145. if (action.equals("rgb") && root.containsKey("data")) {
  146. lightColor((const char *) root["data"], true);
  147. lightUpdate(true, true);
  148. }
  149. if (action.equals("brightness") && root.containsKey("data")) {
  150. lightBrightness(root["data"]);
  151. lightUpdate(true, true);
  152. }
  153. if (action.equals("hsv") && root.containsKey("data")) {
  154. lightColor((const char *) root["data"], false);
  155. lightUpdate(true, true);
  156. }
  157. }
  158. if (action.equals("channel") && root.containsKey("data")) {
  159. JsonObject& data = root["data"];
  160. if (data.containsKey("id") && data.containsKey("value")) {
  161. lightChannel(data["id"], data["value"]);
  162. lightUpdate(true, true);
  163. }
  164. }
  165. #ifdef LIGHT_PROVIDER_EXPERIMENTAL_RGB_ONLY_HSV_IR
  166. if (action.equals("anim_mode") && root.containsKey("data")) {
  167. lightAnimMode(root["data"]);
  168. lightUpdate(true, true);
  169. }
  170. if (action.equals("anim_speed") && root.containsKey("data")) {
  171. lightAnimSpeed(root["data"]);
  172. lightUpdate(true, true);
  173. }
  174. #endif //LIGHT_PROVIDER_EXPERIMENTAL_RGB_ONLY_HSV_IR
  175. #endif //LIGHT_PROVIDER != LIGHT_PROVIDER_NONE
  176. };
  177. // Check config
  178. if (root.containsKey("config") && root["config"].is<JsonArray&>()) {
  179. JsonArray& config = root["config"];
  180. DEBUG_MSG_P(PSTR("[WEBSOCKET] Parsing configuration data\n"));
  181. unsigned char webMode = WEB_MODE_NORMAL;
  182. bool save = false;
  183. bool changed = false;
  184. bool changedMQTT = false;
  185. bool changedNTP = false;
  186. unsigned int network = 0;
  187. unsigned int dczRelayIdx = 0;
  188. String adminPass;
  189. for (unsigned int i=0; i<config.size(); i++) {
  190. String key = config[i]["name"];
  191. String value = config[i]["value"];
  192. // Skip firmware filename
  193. if (key.equals("filename")) continue;
  194. #if POWER_PROVIDER != POWER_PROVIDER_NONE
  195. if (key == "pwrExpectedP") {
  196. powerCalibrate(POWER_MAGNITUDE_ACTIVE, value.toFloat());
  197. changed = true;
  198. continue;
  199. }
  200. if (key == "pwrExpectedV") {
  201. powerCalibrate(POWER_MAGNITUDE_VOLTAGE, value.toFloat());
  202. changed = true;
  203. continue;
  204. }
  205. if (key == "pwrExpectedC") {
  206. powerCalibrate(POWER_MAGNITUDE_CURRENT, value.toFloat());
  207. changed = true;
  208. continue;
  209. }
  210. if (key == "pwrExpectedF") {
  211. powerCalibrate(POWER_MAGNITUDE_POWER_FACTOR, value.toFloat());
  212. changed = true;
  213. continue;
  214. }
  215. if (key == "pwrResetCalibration") {
  216. if (value.toInt() == 1) {
  217. powerResetCalibration();
  218. changed = true;
  219. }
  220. continue;
  221. }
  222. #endif
  223. #if DOMOTICZ_SUPPORT
  224. if (key == "dczRelayIdx") {
  225. if (dczRelayIdx >= relayCount()) continue;
  226. key = key + String(dczRelayIdx);
  227. ++dczRelayIdx;
  228. }
  229. #else
  230. if (key.startsWith("dcz")) continue;
  231. #endif
  232. // Web portions
  233. if (key == "webPort") {
  234. if ((value.toInt() == 0) || (value.toInt() == 80)) {
  235. save = changed = true;
  236. delSetting(key);
  237. continue;
  238. }
  239. }
  240. if (key == "webMode") {
  241. webMode = value.toInt();
  242. continue;
  243. }
  244. // Check password
  245. if (key == "adminPass1") {
  246. adminPass = value;
  247. continue;
  248. }
  249. if (key == "adminPass2") {
  250. if (!value.equals(adminPass)) {
  251. wsSend_P(client_id, PSTR("{\"message\": 7}"));
  252. return;
  253. }
  254. if (value.length() == 0) continue;
  255. wsSend_P(client_id, PSTR("{\"action\": \"reload\"}"));
  256. key = String("adminPass");
  257. }
  258. if (key == "ssid") {
  259. key = key + String(network);
  260. }
  261. if (key == "pass") {
  262. key = key + String(network);
  263. }
  264. if (key == "ip") {
  265. key = key + String(network);
  266. }
  267. if (key == "gw") {
  268. key = key + String(network);
  269. }
  270. if (key == "mask") {
  271. key = key + String(network);
  272. }
  273. if (key == "dns") {
  274. key = key + String(network);
  275. ++network;
  276. }
  277. if (value != getSetting(key)) {
  278. //DEBUG_MSG_P(PSTR("[WEBSOCKET] Storing %s = %s\n", key.c_str(), value.c_str()));
  279. setSetting(key, value);
  280. save = changed = true;
  281. if (key.startsWith("mqtt")) changedMQTT = true;
  282. #if NTP_SUPPORT
  283. if (key.startsWith("ntp")) changedNTP = true;
  284. #endif
  285. }
  286. }
  287. if (webMode == WEB_MODE_NORMAL) {
  288. // Clean wifi networks
  289. int i = 0;
  290. while (i < network) {
  291. if (getSetting("ssid" + String(i)).length() == 0) {
  292. delSetting("ssid" + String(i));
  293. break;
  294. }
  295. if (getSetting("pass" + String(i)).length() == 0) delSetting("pass" + String(i));
  296. if (getSetting("ip" + String(i)).length() == 0) delSetting("ip" + String(i));
  297. if (getSetting("gw" + String(i)).length() == 0) delSetting("gw" + String(i));
  298. if (getSetting("mask" + String(i)).length() == 0) delSetting("mask" + String(i));
  299. if (getSetting("dns" + String(i)).length() == 0) delSetting("dns" + String(i));
  300. ++i;
  301. }
  302. while (i < WIFI_MAX_NETWORKS) {
  303. if (getSetting("ssid" + String(i)).length() > 0) {
  304. save = changed = true;
  305. }
  306. delSetting("ssid" + String(i));
  307. delSetting("pass" + String(i));
  308. delSetting("ip" + String(i));
  309. delSetting("gw" + String(i));
  310. delSetting("mask" + String(i));
  311. delSetting("dns" + String(i));
  312. ++i;
  313. }
  314. }
  315. // Save settings
  316. if (save) {
  317. saveSettings();
  318. wifiConfigure();
  319. otaConfigure();
  320. if (changedMQTT) {
  321. mqttConfigure();
  322. mqttDisconnect();
  323. }
  324. #if ALEXA_SUPPORT
  325. alexaConfigure();
  326. #endif
  327. #if INFLUXDB_SUPPORT
  328. influxDBConfigure();
  329. #endif
  330. #if DOMOTICZ_SUPPORT
  331. domoticzConfigure();
  332. #endif
  333. #if NOFUSS_SUPPORT
  334. nofussConfigure();
  335. #endif
  336. #if RF_SUPPORT
  337. rfBuildCodes();
  338. #endif
  339. #if POWER_PROVIDER != POWER_PROVIDER_NONE
  340. powerConfigure();
  341. #endif
  342. #if LIGHT_PROVIDER != LIGHT_PROVIDER_NONE
  343. #if LIGHT_SAVE_ENABLED == 0
  344. lightSave();
  345. #endif
  346. #endif
  347. #if NTP_SUPPORT
  348. if (changedNTP) ntpConfigure();
  349. #endif
  350. }
  351. if (changed) {
  352. wsSend_P(client_id, PSTR("{\"message\": 8}"));
  353. } else {
  354. wsSend_P(client_id, PSTR("{\"message\": 9}"));
  355. }
  356. }
  357. }
  358. void _wsStart(uint32_t client_id) {
  359. char chipid[7];
  360. snprintf_P(chipid, sizeof(chipid), PSTR("%06X"), ESP.getChipId());
  361. DynamicJsonBuffer jsonBuffer;
  362. JsonObject& root = jsonBuffer.createObject();
  363. bool changePassword = false;
  364. #if WEB_FORCE_PASS_CHANGE
  365. String adminPass = getSetting("adminPass", ADMIN_PASS);
  366. if (adminPass.equals(ADMIN_PASS)) changePassword = true;
  367. #endif
  368. if (changePassword) {
  369. root["webMode"] = WEB_MODE_PASSWORD;
  370. } else {
  371. root["webMode"] = WEB_MODE_NORMAL;
  372. root["app_name"] = APP_NAME;
  373. root["app_version"] = APP_VERSION;
  374. root["app_build"] = buildTime();
  375. root["manufacturer"] = String(MANUFACTURER);
  376. root["chipid"] = chipid;
  377. root["mac"] = WiFi.macAddress();
  378. root["device"] = String(DEVICE);
  379. root["hostname"] = getSetting("hostname");
  380. root["network"] = getNetwork();
  381. root["deviceip"] = getIP();
  382. root["time"] = ntpDateTime();
  383. root["uptime"] = getUptime();
  384. root["heap"] = ESP.getFreeHeap();
  385. root["sketch_size"] = ESP.getSketchSize();
  386. root["free_size"] = ESP.getFreeSketchSpace();
  387. #if NTP_SUPPORT
  388. root["ntpVisible"] = 1;
  389. root["ntpStatus"] = ntpConnected();
  390. root["ntpServer1"] = getSetting("ntpServer1", NTP_SERVER);
  391. root["ntpServer2"] = getSetting("ntpServer2");
  392. root["ntpServer3"] = getSetting("ntpServer3");
  393. root["ntpOffset"] = getSetting("ntpOffset", NTP_TIME_OFFSET).toInt();
  394. root["ntpDST"] = getSetting("ntpDST", NTP_DAY_LIGHT).toInt() == 1;
  395. #endif
  396. root["mqttStatus"] = mqttConnected();
  397. root["mqttEnabled"] = mqttEnabled();
  398. root["mqttServer"] = getSetting("mqttServer", MQTT_SERVER);
  399. root["mqttPort"] = getSetting("mqttPort", MQTT_PORT);
  400. root["mqttUser"] = getSetting("mqttUser");
  401. root["mqttPassword"] = getSetting("mqttPassword");
  402. #if ASYNC_TCP_SSL_ENABLED
  403. root["mqttsslVisible"] = 1;
  404. root["mqttUseSSL"] = getSetting("mqttUseSSL", 0).toInt() == 1;
  405. root["mqttFP"] = getSetting("mqttFP");
  406. #endif
  407. root["mqttTopic"] = getSetting("mqttTopic", MQTT_TOPIC);
  408. root["mqttUseJson"] = getSetting("mqttUseJson", MQTT_USE_JSON).toInt() == 1;
  409. JsonArray& relay = root.createNestedArray("relayStatus");
  410. for (unsigned char relayID=0; relayID<relayCount(); relayID++) {
  411. relay.add(relayStatus(relayID));
  412. }
  413. #if LIGHT_PROVIDER != LIGHT_PROVIDER_NONE
  414. root["colorVisible"] = 1;
  415. root["useColor"] = getSetting("useColor", LIGHT_USE_COLOR).toInt() == 1;
  416. root["useWhite"] = getSetting("useWhite", LIGHT_USE_WHITE).toInt() == 1;
  417. root["useGamma"] = getSetting("useGamma", LIGHT_USE_GAMMA).toInt() == 1;
  418. root["useCSS"] = getSetting("useCSS", LIGHT_USE_CSS).toInt() == 1;
  419. bool useRGB = getSetting("useRGB", LIGHT_USE_RGB).toInt() == 1;
  420. root["useRGB"] = useRGB;
  421. if (lightHasColor()) {
  422. if (useRGB) {
  423. root["rgb"] = lightColor(true);
  424. root["brightness"] = lightBrightness();
  425. } else {
  426. root["hsv"] = lightColor(false);
  427. }
  428. #ifdef LIGHT_PROVIDER_EXPERIMENTAL_RGB_ONLY_HSV_IR
  429. root["anim_mode"] = lightAnimMode();
  430. root["anim_speed"] = lightAnimSpeed();
  431. #endif // LIGHT_PROVIDER_EXPERIMENTAL_RGB_ONLY_HSV_IR
  432. }
  433. JsonArray& channels = root.createNestedArray("channels");
  434. for (unsigned char id=0; id < lightChannels(); id++) {
  435. channels.add(lightChannel(id));
  436. }
  437. #endif
  438. root["relayMode"] = getSetting("relayMode", RELAY_MODE);
  439. root["relayPulseMode"] = getSetting("relayPulseMode", RELAY_PULSE_MODE);
  440. root["relayPulseTime"] = getSetting("relayPulseTime", RELAY_PULSE_TIME).toFloat();
  441. if (relayCount() > 1) {
  442. root["multirelayVisible"] = 1;
  443. root["relaySync"] = getSetting("relaySync", RELAY_SYNC);
  444. }
  445. root["btnDelay"] = getSetting("btnDelay", BUTTON_DBLCLICK_DELAY).toInt();
  446. root["webPort"] = getSetting("webPort", WEB_PORT).toInt();
  447. root["apiEnabled"] = getSetting("apiEnabled", API_ENABLED).toInt() == 1;
  448. root["apiKey"] = getSetting("apiKey");
  449. root["apiRealTime"] = getSetting("apiRealTime", API_REAL_TIME_VALUES).toInt() == 1;
  450. root["tmpUnits"] = getSetting("tmpUnits", TMP_UNITS).toInt();
  451. #if HOMEASSISTANT_SUPPORT
  452. root["haVisible"] = 1;
  453. root["haPrefix"] = getSetting("haPrefix", HOMEASSISTANT_PREFIX);
  454. #endif // HOMEASSISTANT_SUPPORT
  455. #if DOMOTICZ_SUPPORT
  456. root["dczVisible"] = 1;
  457. root["dczEnabled"] = getSetting("dczEnabled", DOMOTICZ_ENABLED).toInt() == 1;
  458. root["dczTopicIn"] = getSetting("dczTopicIn", DOMOTICZ_IN_TOPIC);
  459. root["dczTopicOut"] = getSetting("dczTopicOut", DOMOTICZ_OUT_TOPIC);
  460. JsonArray& dczRelayIdx = root.createNestedArray("dczRelayIdx");
  461. for (byte i=0; i<relayCount(); i++) {
  462. dczRelayIdx.add(domoticzIdx(i));
  463. }
  464. #if DHT_SUPPORT
  465. root["dczTmpIdx"] = getSetting("dczTmpIdx").toInt();
  466. root["dczHumIdx"] = getSetting("dczHumIdx").toInt();
  467. #endif
  468. #if DS18B20_SUPPORT
  469. root["dczTmpIdx"] = getSetting("dczTmpIdx").toInt();
  470. #endif
  471. #if ANALOG_SUPPORT
  472. root["dczAnaIdx"] = getSetting("dczAnaIdx").toInt();
  473. #endif
  474. #if POWER_PROVIDER != POWER_PROVIDER_NONE
  475. root["dczPowIdx"] = getSetting("dczPowIdx").toInt();
  476. root["dczEnergyIdx"] = getSetting("dczEnergyIdx").toInt();
  477. root["dczCurrentIdx"] = getSetting("dczCurrentIdx").toInt();
  478. #if POWER_HAS_ACTIVE
  479. root["dczVoltIdx"] = getSetting("dczVoltIdx").toInt();
  480. #endif
  481. #endif
  482. #endif
  483. #if INFLUXDB_SUPPORT
  484. root["idbVisible"] = 1;
  485. root["idbHost"] = getSetting("idbHost");
  486. root["idbPort"] = getSetting("idbPort", INFLUXDB_PORT).toInt();
  487. root["idbDatabase"] = getSetting("idbDatabase");
  488. root["idbUsername"] = getSetting("idbUsername");
  489. root["idbPassword"] = getSetting("idbPassword");
  490. #endif
  491. #if ALEXA_SUPPORT
  492. root["alexaVisible"] = 1;
  493. root["alexaEnabled"] = getSetting("alexaEnabled", ALEXA_ENABLED).toInt() == 1;
  494. #endif
  495. #if DS18B20_SUPPORT
  496. root["dsVisible"] = 1;
  497. root["dsTmp"] = getDSTemperatureStr();
  498. #endif
  499. #if DHT_SUPPORT
  500. root["dhtVisible"] = 1;
  501. root["dhtTmp"] = getDHTTemperature();
  502. root["dhtHum"] = getDHTHumidity();
  503. #endif
  504. #if RF_SUPPORT
  505. root["rfVisible"] = 1;
  506. root["rfChannel"] = getSetting("rfChannel", RF_CHANNEL);
  507. root["rfDevice"] = getSetting("rfDevice", RF_DEVICE);
  508. #endif
  509. #if ANALOG_SUPPORT
  510. root["analogVisible"] = 1;
  511. root["analogValue"] = getAnalog();
  512. #endif
  513. #if COUNTER_SUPPORT
  514. root["counterVisible"] = 1;
  515. root["counterValue"] = getCounter();
  516. #endif
  517. #if POWER_PROVIDER != POWER_PROVIDER_NONE
  518. root["pwrVisible"] = 1;
  519. root["pwrCurrent"] = getCurrent();
  520. root["pwrVoltage"] = getVoltage();
  521. root["pwrApparent"] = getApparentPower();
  522. root["pwrEnergy"] = getPowerEnergy();
  523. root["pwrReadEvery"] = powerReadInterval();
  524. root["pwrReportEvery"] = powerReportInterval();
  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