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.

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