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.

1256 lines
39 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((const char *) 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_name"] = APP_NAME;
  377. root["app_version"] = APP_VERSION;
  378. root["app_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["apiRealTime"] = getSetting("apiRealTime", API_REAL_TIME_VALUES).toInt() == 1;
  453. root["tmpUnits"] = getSetting("tmpUnits", TMP_UNITS).toInt();
  454. #if HOMEASSISTANT_SUPPORT
  455. root["haVisible"] = 1;
  456. root["haPrefix"] = getSetting("haPrefix", HOMEASSISTANT_PREFIX);
  457. #endif // HOMEASSISTANT_SUPPORT
  458. #if DOMOTICZ_SUPPORT
  459. root["dczVisible"] = 1;
  460. root["dczEnabled"] = getSetting("dczEnabled", DOMOTICZ_ENABLED).toInt() == 1;
  461. root["dczTopicIn"] = getSetting("dczTopicIn", DOMOTICZ_IN_TOPIC);
  462. root["dczTopicOut"] = getSetting("dczTopicOut", DOMOTICZ_OUT_TOPIC);
  463. JsonArray& dczRelayIdx = root.createNestedArray("dczRelayIdx");
  464. for (byte i=0; i<relayCount(); i++) {
  465. dczRelayIdx.add(domoticzIdx(i));
  466. }
  467. #if DHT_SUPPORT
  468. root["dczTmpIdx"] = getSetting("dczTmpIdx").toInt();
  469. root["dczHumIdx"] = getSetting("dczHumIdx").toInt();
  470. #endif
  471. #if DS18B20_SUPPORT
  472. root["dczTmpIdx"] = getSetting("dczTmpIdx").toInt();
  473. #endif
  474. #if ANALOG_SUPPORT
  475. root["dczAnaIdx"] = getSetting("dczAnaIdx").toInt();
  476. #endif
  477. #if POWER_PROVIDER != POWER_PROVIDER_NONE
  478. root["dczPowIdx"] = getSetting("dczPowIdx").toInt();
  479. root["dczEnergyIdx"] = getSetting("dczEnergyIdx").toInt();
  480. root["dczCurrentIdx"] = getSetting("dczCurrentIdx").toInt();
  481. #if POWER_HAS_ACTIVE
  482. root["dczVoltIdx"] = getSetting("dczVoltIdx").toInt();
  483. #endif
  484. #endif
  485. #endif
  486. #if INFLUXDB_SUPPORT
  487. root["idbVisible"] = 1;
  488. root["idbHost"] = getSetting("idbHost");
  489. root["idbPort"] = getSetting("idbPort", INFLUXDB_PORT).toInt();
  490. root["idbDatabase"] = getSetting("idbDatabase");
  491. root["idbUsername"] = getSetting("idbUsername");
  492. root["idbPassword"] = getSetting("idbPassword");
  493. #endif
  494. #if ALEXA_SUPPORT
  495. root["alexaVisible"] = 1;
  496. root["alexaEnabled"] = getSetting("alexaEnabled", ALEXA_ENABLED).toInt() == 1;
  497. #endif
  498. #if DS18B20_SUPPORT
  499. root["dsVisible"] = 1;
  500. root["dsTmp"] = getDSTemperatureStr();
  501. #endif
  502. #if DHT_SUPPORT
  503. root["dhtVisible"] = 1;
  504. root["dhtTmp"] = getDHTTemperature();
  505. root["dhtHum"] = getDHTHumidity();
  506. #endif
  507. #if RF_SUPPORT
  508. root["rfVisible"] = 1;
  509. root["rfChannel"] = getSetting("rfChannel", RF_CHANNEL);
  510. root["rfDevice"] = getSetting("rfDevice", RF_DEVICE);
  511. #endif
  512. #if ANALOG_SUPPORT
  513. root["analogVisible"] = 1;
  514. root["analogValue"] = getAnalog();
  515. #endif
  516. #if COUNTER_SUPPORT
  517. root["counterVisible"] = 1;
  518. root["counterValue"] = getCounter();
  519. #endif
  520. #if POWER_PROVIDER != POWER_PROVIDER_NONE
  521. root["pwrVisible"] = 1;
  522. root["pwrCurrent"] = getCurrent();
  523. root["pwrVoltage"] = getVoltage();
  524. root["pwrApparent"] = getApparentPower();
  525. root["pwrEnergy"] = getPowerEnergy();
  526. root["pwrReadEvery"] = powerReadInterval();
  527. root["pwrReportEvery"] = powerReportInterval();
  528. #if POWER_HAS_ACTIVE
  529. root["pwrActive"] = getActivePower();
  530. root["pwrReactive"] = getReactivePower();
  531. root["pwrFactor"] = int(100 * getPowerFactor());
  532. #endif
  533. #if (POWER_PROVIDER == POWER_PROVIDER_EMON_ANALOG) || (POWER_PROVIDER == POWER_PROVIDER_EMON_ADC121)
  534. root["emonVisible"] = 1;
  535. #endif
  536. #if POWER_PROVIDER == POWER_PROVIDER_HLW8012
  537. root["hlwVisible"] = 1;
  538. #endif
  539. #if POWER_PROVIDER == POWER_PROVIDER_V9261F
  540. root["v9261fVisible"] = 1;
  541. #endif
  542. #if POWER_PROVIDER == POWER_PROVIDER_ECH1560
  543. root["ech1560fVisible"] = 1;
  544. #endif
  545. #endif
  546. #if NOFUSS_SUPPORT
  547. root["nofussVisible"] = 1;
  548. root["nofussEnabled"] = getSetting("nofussEnabled", NOFUSS_ENABLED).toInt() == 1;
  549. root["nofussServer"] = getSetting("nofussServer", NOFUSS_SERVER);
  550. #endif
  551. #ifdef ITEAD_SONOFF_RFBRIDGE
  552. root["rfbVisible"] = 1;
  553. root["rfbCount"] = relayCount();
  554. JsonArray& rfb = root.createNestedArray("rfb");
  555. for (byte id=0; id<relayCount(); id++) {
  556. for (byte status=0; status<2; status++) {
  557. JsonObject& node = rfb.createNestedObject();
  558. node["id"] = id;
  559. node["status"] = status;
  560. node["data"] = rfbRetrieve(id, status == 1);
  561. }
  562. }
  563. #endif
  564. #if TELNET_SUPPORT
  565. root["telnetVisible"] = 1;
  566. root["telnetSTA"] = getSetting("telnetSTA", TELNET_STA).toInt() == 1;
  567. #endif
  568. root["maxNetworks"] = WIFI_MAX_NETWORKS;
  569. JsonArray& wifi = root.createNestedArray("wifi");
  570. for (byte i=0; i<WIFI_MAX_NETWORKS; i++) {
  571. if (getSetting("ssid" + String(i)).length() == 0) break;
  572. JsonObject& network = wifi.createNestedObject();
  573. network["ssid"] = getSetting("ssid" + String(i));
  574. network["pass"] = getSetting("pass" + String(i));
  575. network["ip"] = getSetting("ip" + String(i));
  576. network["gw"] = getSetting("gw" + String(i));
  577. network["mask"] = getSetting("mask" + String(i));
  578. network["dns"] = getSetting("dns" + String(i));
  579. }
  580. }
  581. String output;
  582. root.printTo(output);
  583. wsSend(client_id, (char *) output.c_str());
  584. }
  585. bool _wsAuth(AsyncWebSocketClient * client) {
  586. IPAddress ip = client->remoteIP();
  587. unsigned long now = millis();
  588. unsigned short index = 0;
  589. for (index = 0; index < WS_BUFFER_SIZE; index++) {
  590. if ((_ticket[index].ip == ip) && (now - _ticket[index].timestamp < WS_TIMEOUT)) break;
  591. }
  592. if (index == WS_BUFFER_SIZE) {
  593. DEBUG_MSG_P(PSTR("[WEBSOCKET] Validation check failed\n"));
  594. wsSend_P(client->id(), PSTR("{\"message\": 10}"));
  595. return false;
  596. }
  597. return true;
  598. }
  599. void _wsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){
  600. if (type == WS_EVT_CONNECT) {
  601. // Authorize
  602. #ifndef NOWSAUTH
  603. if (!_wsAuth(client)) return;
  604. #endif
  605. IPAddress ip = client->remoteIP();
  606. 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());
  607. _wsStart(client->id());
  608. client->_tempObject = new WebSocketIncommingBuffer(&_wsParse, true);
  609. wifiReconnectCheck();
  610. } else if(type == WS_EVT_DISCONNECT) {
  611. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u disconnected\n"), client->id());
  612. if (client->_tempObject) {
  613. delete (WebSocketIncommingBuffer *) client->_tempObject;
  614. }
  615. wifiReconnectCheck();
  616. } else if(type == WS_EVT_ERROR) {
  617. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u error(%u): %s\n"), client->id(), *((uint16_t*)arg), (char*)data);
  618. } else if(type == WS_EVT_PONG) {
  619. DEBUG_MSG_P(PSTR("[WEBSOCKET] #%u pong(%u): %s\n"), client->id(), len, len ? (char*) data : "");
  620. } else if(type == WS_EVT_DATA) {
  621. WebSocketIncommingBuffer *buffer = (WebSocketIncommingBuffer *)client->_tempObject;
  622. AwsFrameInfo * info = (AwsFrameInfo*)arg;
  623. buffer->data_event(client, info, data, len);
  624. }
  625. }
  626. // -----------------------------------------------------------------------------
  627. bool wsConnected() {
  628. return (_ws.count() > 0);
  629. }
  630. void wsSend(const char * payload) {
  631. if (_ws.count() > 0) {
  632. _ws.textAll(payload);
  633. }
  634. }
  635. void wsSend_P(PGM_P payload) {
  636. if (_ws.count() > 0) {
  637. char buffer[strlen_P(payload)];
  638. strcpy_P(buffer, payload);
  639. _ws.textAll(buffer);
  640. }
  641. }
  642. void wsSend(uint32_t client_id, const char * payload) {
  643. _ws.text(client_id, payload);
  644. }
  645. void wsSend_P(uint32_t client_id, PGM_P payload) {
  646. char buffer[strlen_P(payload)];
  647. strcpy_P(buffer, payload);
  648. _ws.text(client_id, buffer);
  649. }
  650. void wsSetup() {
  651. _ws.onEvent(_wsEvent);
  652. mqttRegister(_wsMQTTCallback);
  653. _server->addHandler(&_ws);
  654. _server->on("/auth", HTTP_GET, _onAuth);
  655. }
  656. // -----------------------------------------------------------------------------
  657. // API
  658. // -----------------------------------------------------------------------------
  659. bool _authAPI(AsyncWebServerRequest *request) {
  660. if (getSetting("apiEnabled", API_ENABLED).toInt() == 0) {
  661. DEBUG_MSG_P(PSTR("[WEBSERVER] HTTP API is not enabled\n"));
  662. request->send(403);
  663. return false;
  664. }
  665. if (!request->hasParam("apikey", (request->method() == HTTP_PUT))) {
  666. DEBUG_MSG_P(PSTR("[WEBSERVER] Missing apikey parameter\n"));
  667. request->send(403);
  668. return false;
  669. }
  670. AsyncWebParameter* p = request->getParam("apikey", (request->method() == HTTP_PUT));
  671. if (!p->value().equals(getSetting("apiKey"))) {
  672. DEBUG_MSG_P(PSTR("[WEBSERVER] Wrong apikey parameter\n"));
  673. request->send(403);
  674. return false;
  675. }
  676. return true;
  677. }
  678. bool _asJson(AsyncWebServerRequest *request) {
  679. bool asJson = false;
  680. if (request->hasHeader("Accept")) {
  681. AsyncWebHeader* h = request->getHeader("Accept");
  682. asJson = h->value().equals("application/json");
  683. }
  684. return asJson;
  685. }
  686. ArRequestHandlerFunction _bindAPI(unsigned int apiID) {
  687. return [apiID](AsyncWebServerRequest *request) {
  688. _webLog(request);
  689. if (!_authAPI(request)) return;
  690. web_api_t api = _apis[apiID];
  691. // Check if its a PUT
  692. if (api.putFn != NULL) {
  693. if (request->hasParam("value", request->method() == HTTP_PUT)) {
  694. AsyncWebParameter* p = request->getParam("value", request->method() == HTTP_PUT);
  695. (api.putFn)((p->value()).c_str());
  696. }
  697. }
  698. // Get response from callback
  699. char value[API_BUFFER_SIZE];
  700. (api.getFn)(value, API_BUFFER_SIZE);
  701. // The response will be a 404 NOT FOUND if the resource is not available
  702. if (!value) {
  703. DEBUG_MSG_P(PSTR("[API] Sending 404 response\n"));
  704. request->send(404);
  705. return;
  706. }
  707. DEBUG_MSG_P(PSTR("[API] Sending response '%s'\n"), value);
  708. // Format response according to the Accept header
  709. if (_asJson(request)) {
  710. char buffer[64];
  711. snprintf_P(buffer, sizeof(buffer), PSTR("{ \"%s\": %s }"), api.key, value);
  712. request->send(200, "application/json", buffer);
  713. } else {
  714. request->send(200, "text/plain", value);
  715. }
  716. };
  717. }
  718. void _onAPIs(AsyncWebServerRequest *request) {
  719. _webLog(request);
  720. if (!_authAPI(request)) return;
  721. bool asJson = _asJson(request);
  722. String output;
  723. if (asJson) {
  724. DynamicJsonBuffer jsonBuffer;
  725. JsonObject& root = jsonBuffer.createObject();
  726. for (unsigned int i=0; i < _apis.size(); i++) {
  727. root[_apis[i].key] = _apis[i].url;
  728. }
  729. root.printTo(output);
  730. request->send(200, "application/json", output);
  731. } else {
  732. for (unsigned int i=0; i < _apis.size(); i++) {
  733. output += _apis[i].key + String(" -> ") + _apis[i].url + String("\n");
  734. }
  735. request->send(200, "text/plain", output);
  736. }
  737. }
  738. void _onRPC(AsyncWebServerRequest *request) {
  739. _webLog(request);
  740. if (!_authAPI(request)) return;
  741. //bool asJson = _asJson(request);
  742. int response = 404;
  743. if (request->hasParam("action")) {
  744. AsyncWebParameter* p = request->getParam("action");
  745. String action = p->value();
  746. DEBUG_MSG_P(PSTR("[RPC] Action: %s\n"), action.c_str());
  747. if (action.equals("reset")) {
  748. response = 200;
  749. _web_defer.once_ms(100, []() {
  750. customReset(CUSTOM_RESET_RPC);
  751. ESP.restart();
  752. });
  753. }
  754. }
  755. request->send(response);
  756. }
  757. // -----------------------------------------------------------------------------
  758. void apiRegister(const char * url, const char * key, apiGetCallbackFunction getFn, apiPutCallbackFunction putFn) {
  759. // Store it
  760. web_api_t api;
  761. char buffer[40];
  762. snprintf_P(buffer, sizeof(buffer), PSTR("/api/%s"), url);
  763. api.url = strdup(buffer);
  764. api.key = strdup(key);
  765. api.getFn = getFn;
  766. api.putFn = putFn;
  767. _apis.push_back(api);
  768. // Bind call
  769. unsigned int methods = HTTP_GET;
  770. if (putFn != NULL) methods += HTTP_PUT;
  771. _server->on(buffer, methods, _bindAPI(_apis.size() - 1));
  772. }
  773. void apiSetup() {
  774. _server->on("/apis", HTTP_GET, _onAPIs);
  775. _server->on("/rpc", HTTP_GET, _onRPC);
  776. }
  777. // -----------------------------------------------------------------------------
  778. // WEBSERVER
  779. // -----------------------------------------------------------------------------
  780. void _webLog(AsyncWebServerRequest *request) {
  781. DEBUG_MSG_P(PSTR("[WEBSERVER] Request: %s %s\n"), request->methodToString(), request->url().c_str());
  782. }
  783. bool _authenticate(AsyncWebServerRequest *request) {
  784. String password = getSetting("adminPass", ADMIN_PASS);
  785. char httpPassword[password.length() + 1];
  786. password.toCharArray(httpPassword, password.length() + 1);
  787. return request->authenticate(WEB_USERNAME, httpPassword);
  788. }
  789. void _onAuth(AsyncWebServerRequest *request) {
  790. _webLog(request);
  791. if (!_authenticate(request)) return request->requestAuthentication();
  792. IPAddress ip = request->client()->remoteIP();
  793. unsigned long now = millis();
  794. unsigned short index;
  795. for (index = 0; index < WS_BUFFER_SIZE; index++) {
  796. if (_ticket[index].ip == ip) break;
  797. if (_ticket[index].timestamp == 0) break;
  798. if (now - _ticket[index].timestamp > WS_TIMEOUT) break;
  799. }
  800. if (index == WS_BUFFER_SIZE) {
  801. request->send(429);
  802. } else {
  803. _ticket[index].ip = ip;
  804. _ticket[index].timestamp = now;
  805. request->send(204);
  806. }
  807. }
  808. void _onGetConfig(AsyncWebServerRequest *request) {
  809. _webLog(request);
  810. if (!_authenticate(request)) return request->requestAuthentication();
  811. AsyncJsonResponse * response = new AsyncJsonResponse();
  812. JsonObject& root = response->getRoot();
  813. root["app"] = APP_NAME;
  814. root["version"] = APP_VERSION;
  815. unsigned int size = settingsKeyCount();
  816. for (unsigned int i=0; i<size; i++) {
  817. String key = settingsKeyName(i);
  818. String value = getSetting(key);
  819. root[key] = value;
  820. }
  821. char buffer[100];
  822. snprintf_P(buffer, sizeof(buffer), PSTR("attachment; filename=\"%s-backup.json\""), (char *) getSetting("hostname").c_str());
  823. response->addHeader("Content-Disposition", buffer);
  824. response->setLength();
  825. request->send(response);
  826. }
  827. #if WEB_EMBEDDED
  828. void _onHome(AsyncWebServerRequest *request) {
  829. _webLog(request);
  830. if (request->header("If-Modified-Since").equals(_last_modified)) {
  831. request->send(304);
  832. } else {
  833. #if ASYNC_TCP_SSL_ENABLED
  834. // Chunked response, we calculate the chunks based on free heap (in multiples of 32)
  835. // This is necessary when a TLS connection is open since it sucks too much memory
  836. DEBUG_MSG_P(PSTR("[MAIN] Free heap: %d bytes\n"), ESP.getFreeHeap());
  837. size_t max = (ESP.getFreeHeap() / 3) & 0xFFE0;
  838. AsyncWebServerResponse *response = request->beginChunkedResponse("text/html", [max](uint8_t *buffer, size_t maxLen, size_t index) -> size_t {
  839. // Get the chunk based on the index and maxLen
  840. size_t len = index_html_gz_len - index;
  841. if (len > maxLen) len = maxLen;
  842. if (len > max) len = max;
  843. if (len > 0) memcpy_P(buffer, index_html_gz + index, len);
  844. DEBUG_MSG_P(PSTR("[WEB] Sending %d%%%% (max chunk size: %4d)\r"), int(100 * index / index_html_gz_len), max);
  845. if (len == 0) DEBUG_MSG_P(PSTR("\n"));
  846. // Return the actual length of the chunk (0 for end of file)
  847. return len;
  848. });
  849. #else
  850. AsyncWebServerResponse *response = request->beginResponse_P(200, "text/html", index_html_gz, index_html_gz_len);
  851. #endif
  852. response->addHeader("Content-Encoding", "gzip");
  853. response->addHeader("Last-Modified", _last_modified);
  854. request->send(response);
  855. }
  856. }
  857. #endif
  858. #if ASYNC_TCP_SSL_ENABLED & WEB_SSL_ENABLED
  859. int _onCertificate(void * arg, const char *filename, uint8_t **buf) {
  860. #if WEB_EMBEDDED
  861. if (strcmp(filename, "server.cer") == 0) {
  862. uint8_t * nbuf = (uint8_t*) malloc(server_cer_len);
  863. memcpy_P(nbuf, server_cer, server_cer_len);
  864. *buf = nbuf;
  865. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - OK\n"), filename);
  866. return server_cer_len;
  867. }
  868. if (strcmp(filename, "server.key") == 0) {
  869. uint8_t * nbuf = (uint8_t*) malloc(server_key_len);
  870. memcpy_P(nbuf, server_key, server_key_len);
  871. *buf = nbuf;
  872. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - OK\n"), filename);
  873. return server_key_len;
  874. }
  875. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - ERROR\n"), filename);
  876. *buf = 0;
  877. return 0;
  878. #else
  879. File file = SPIFFS.open(filename, "r");
  880. if (file) {
  881. size_t size = file.size();
  882. uint8_t * nbuf = (uint8_t*) malloc(size);
  883. if (nbuf) {
  884. size = file.read(nbuf, size);
  885. file.close();
  886. *buf = nbuf;
  887. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - OK\n"), filename);
  888. return size;
  889. }
  890. file.close();
  891. }
  892. DEBUG_MSG_P(PSTR("[WEB] SSL File: %s - ERROR\n"), filename);
  893. *buf = 0;
  894. return 0;
  895. #endif
  896. }
  897. #endif
  898. void _onUpgrade(AsyncWebServerRequest *request) {
  899. char buffer[10];
  900. if (!Update.hasError()) {
  901. sprintf_P(buffer, PSTR("OK"));
  902. } else {
  903. sprintf_P(buffer, PSTR("ERROR %d"), Update.getError());
  904. }
  905. AsyncWebServerResponse *response = request->beginResponse(200, "text/plain", buffer);
  906. response->addHeader("Connection", "close");
  907. if (!Update.hasError()) {
  908. _web_defer.once_ms(100, []() {
  909. customReset(CUSTOM_RESET_UPGRADE);
  910. ESP.restart();
  911. });
  912. }
  913. request->send(response);
  914. }
  915. void _onUpgradeData(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final) {
  916. if (!index) {
  917. DEBUG_MSG_P(PSTR("[UPGRADE] Start: %s\n"), filename.c_str());
  918. Update.runAsync(true);
  919. if (!Update.begin((ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000)) {
  920. #ifdef DEBUG_PORT
  921. Update.printError(DEBUG_PORT);
  922. #endif
  923. }
  924. }
  925. if (!Update.hasError()) {
  926. if (Update.write(data, len) != len) {
  927. #ifdef DEBUG_PORT
  928. Update.printError(DEBUG_PORT);
  929. #endif
  930. }
  931. }
  932. if (final) {
  933. if (Update.end(true)){
  934. DEBUG_MSG_P(PSTR("[UPGRADE] Success: %u bytes\n"), index + len);
  935. } else {
  936. #ifdef DEBUG_PORT
  937. Update.printError(DEBUG_PORT);
  938. #endif
  939. }
  940. } else {
  941. DEBUG_MSG_P(PSTR("[UPGRADE] Progress: %u bytes\r"), index + len);
  942. }
  943. }
  944. // -----------------------------------------------------------------------------
  945. void webSetup() {
  946. // Cache the Last-Modifier header value
  947. snprintf_P(_last_modified, sizeof(_last_modified), PSTR("%s %s GMT"), __DATE__, __TIME__);
  948. // Create server
  949. #if ASYNC_TCP_SSL_ENABLED & WEB_SSL_ENABLED
  950. unsigned int port = 443;
  951. #else
  952. unsigned int port = getSetting("webPort", WEB_PORT).toInt();
  953. #endif
  954. _server = new AsyncWebServer(port);
  955. // Setup websocket
  956. wsSetup();
  957. // API setup
  958. apiSetup();
  959. // Rewrites
  960. _server->rewrite("/", "/index.html");
  961. // Serve home (basic authentication protection)
  962. #if WEB_EMBEDDED
  963. _server->on("/index.html", HTTP_GET, _onHome);
  964. #endif
  965. _server->on("/config", HTTP_GET, _onGetConfig);
  966. _server->on("/upgrade", HTTP_POST, _onUpgrade, _onUpgradeData);
  967. // Serve static files
  968. #if SPIFFS_SUPPORT
  969. _server->serveStatic("/", SPIFFS, "/")
  970. .setLastModified(_last_modified)
  971. .setFilter([](AsyncWebServerRequest *request) -> bool {
  972. _webLog(request);
  973. return true;
  974. });
  975. #endif
  976. // 404
  977. _server->onNotFound([](AsyncWebServerRequest *request){
  978. request->send(404);
  979. });
  980. // Run server
  981. #if ASYNC_TCP_SSL_ENABLED & WEB_SSL_ENABLED
  982. _server->onSslFileRequest(_onCertificate, NULL);
  983. _server->beginSecure("server.cer", "server.key", NULL);
  984. #else
  985. _server->begin();
  986. #endif
  987. DEBUG_MSG_P(PSTR("[WEBSERVER] Webserver running on port %d\n"), port);
  988. }
  989. #endif // WEB_SUPPORT