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.

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