Fork of the espurna firmware for `mhsw` switches
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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