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.

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