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.

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