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.

1200 lines
36 KiB

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