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.

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