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.

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