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.

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