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.

1198 lines
36 KiB

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