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.

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