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.

636 lines
19 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
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. #include <ESPAsyncTCP.h>
  6. #include <ESPAsyncWebServer.h>
  7. #include <ESP8266mDNS.h>
  8. #include <FS.h>
  9. #include <Hash.h>
  10. #include <AsyncJson.h>
  11. #include <ArduinoJson.h>
  12. #include <Ticker.h>
  13. AsyncWebServer server(80);
  14. AsyncWebSocket ws("/ws");
  15. typedef struct {
  16. IPAddress ip;
  17. unsigned long timestamp = 0;
  18. } ws_ticket_t;
  19. ws_ticket_t _ticket[WS_BUFFER_SIZE];
  20. Ticker deferred;
  21. // -----------------------------------------------------------------------------
  22. // WEBSOCKETS
  23. // -----------------------------------------------------------------------------
  24. bool wsSend(const char * payload) {
  25. DEBUG_MSG("[WEBSOCKET] Broadcasting '%s'\n", payload);
  26. ws.textAll(payload);
  27. }
  28. bool wsSend(uint32_t client_id, const char * payload) {
  29. DEBUG_MSG("[WEBSOCKET] Sending '%s' to #%ld\n", payload, client_id);
  30. ws.text(client_id, payload);
  31. }
  32. void wsMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  33. if (type == MQTT_CONNECT_EVENT) {
  34. wsSend("{\"mqttStatus\": true}");
  35. }
  36. if (type == MQTT_DISCONNECT_EVENT) {
  37. wsSend("{\"mqttStatus\": false}");
  38. }
  39. }
  40. void _wsParse(uint32_t client_id, uint8_t * payload, size_t length) {
  41. // Parse JSON input
  42. DynamicJsonBuffer jsonBuffer;
  43. JsonObject& root = jsonBuffer.parseObject((char *) payload);
  44. if (!root.success()) {
  45. DEBUG_MSG("[WEBSOCKET] Error parsing data\n");
  46. ws.text(client_id, "{\"message\": \"Error parsing data!\"}");
  47. return;
  48. }
  49. // Check actions
  50. if (root.containsKey("action")) {
  51. String action = root["action"];
  52. unsigned int relayID = 0;
  53. if (root.containsKey("relayID")) {
  54. String value = root["relayID"];
  55. relayID = value.toInt();
  56. }
  57. DEBUG_MSG("[WEBSOCKET] Requested action: %s\n", action.c_str());
  58. if (action.equals("reset")) ESP.reset();
  59. if (action.equals("reconnect")) {
  60. // Let the HTTP request return and disconnect after 100ms
  61. deferred.once_ms(100, wifiDisconnect);
  62. }
  63. if (action.equals("on")) relayStatus(relayID, true);
  64. if (action.equals("off")) relayStatus(relayID, false);
  65. };
  66. // Check config
  67. if (root.containsKey("config") && root["config"].is<JsonArray&>()) {
  68. JsonArray& config = root["config"];
  69. DEBUG_MSG("[WEBSOCKET] Parsing configuration data\n");
  70. bool save = false;
  71. bool changed = false;
  72. bool changedMQTT = false;
  73. bool apiEnabled = false;
  74. #if ENABLE_FAUXMO
  75. bool fauxmoEnabled = false;
  76. #endif
  77. unsigned int network = 0;
  78. unsigned int dczIdx = 0;
  79. String adminPass;
  80. for (unsigned int i=0; i<config.size(); i++) {
  81. String key = config[i]["name"];
  82. String value = config[i]["value"];
  83. #if ENABLE_POW
  84. if (key == "powExpectedPower") {
  85. powSetExpectedActivePower(value.toInt());
  86. changed = true;
  87. }
  88. if (key == "powExpectedVoltage") {
  89. powSetExpectedVoltage(value.toInt());
  90. changed = true;
  91. }
  92. if (key == "powExpectedCurrent") {
  93. powSetExpectedCurrent(value.toInt());
  94. changed = true;
  95. }
  96. if (key == "powExpectedReset") {
  97. powReset();
  98. changed = true;
  99. }
  100. #endif
  101. if (key.startsWith("pow")) continue;
  102. #if ENABLE_DOMOTICZ
  103. if (key == "dczIdx") {
  104. if (dczIdx >= relayCount()) continue;
  105. key = key + String(dczIdx);
  106. ++dczIdx;
  107. }
  108. #else
  109. if (key.startsWith("dcz")) continue;
  110. #endif
  111. // Check password
  112. if (key == "adminPass1") {
  113. adminPass = value;
  114. continue;
  115. }
  116. if (key == "adminPass2") {
  117. if (!value.equals(adminPass)) {
  118. ws.text(client_id, "{\"message\": \"Passwords do not match!\"}");
  119. return;
  120. }
  121. if (value.length() == 0) continue;
  122. ws.text(client_id, "{\"action\": \"reload\"}");
  123. key = String("adminPass");
  124. }
  125. // Checkboxes
  126. if (key == "apiEnabled") {
  127. apiEnabled = true;
  128. continue;
  129. }
  130. #if ENABLE_FAUXMO
  131. if (key == "fauxmoEnabled") {
  132. fauxmoEnabled = true;
  133. continue;
  134. }
  135. #endif
  136. if (key == "ssid") {
  137. key = key + String(network);
  138. }
  139. if (key == "pass") {
  140. key = key + String(network);
  141. }
  142. if (key == "ip") {
  143. key = key + String(network);
  144. }
  145. if (key == "gw") {
  146. key = key + String(network);
  147. }
  148. if (key == "mask") {
  149. key = key + String(network);
  150. }
  151. if (key == "dns") {
  152. key = key + String(network);
  153. ++network;
  154. }
  155. if (value != getSetting(key)) {
  156. //DEBUG_MSG("[WEBSOCKET] Storing %s = %s\n", key.c_str(), value.c_str());
  157. setSetting(key, value);
  158. save = changed = true;
  159. if (key.startsWith("mqtt")) changedMQTT = true;
  160. }
  161. }
  162. // Checkboxes
  163. if (apiEnabled != (getSetting("apiEnabled").toInt() == 1)) {
  164. setSetting("apiEnabled", apiEnabled);
  165. save = changed = true;
  166. }
  167. #if ENABLE_FAUXMO
  168. if (fauxmoEnabled != (getSetting("fauxmoEnabled").toInt() == 1)) {
  169. setSetting("fauxmoEnabled", fauxmoEnabled);
  170. save = changed = true;
  171. }
  172. #endif
  173. // Clean wifi networks
  174. for (int i = 0; i < network; i++) {
  175. if (getSetting("pass" + String(i)).length() == 0) delSetting("pass" + String(i));
  176. if (getSetting("ip" + String(i)).length() == 0) delSetting("ip" + String(i));
  177. if (getSetting("gw" + String(i)).length() == 0) delSetting("gw" + String(i));
  178. if (getSetting("mask" + String(i)).length() == 0) delSetting("mask" + String(i));
  179. if (getSetting("dns" + String(i)).length() == 0) delSetting("dns" + String(i));
  180. }
  181. for (int i = network; i<WIFI_MAX_NETWORKS; i++) {
  182. if (getSetting("ssid" + String(i)).length() > 0) {
  183. save = changed = true;
  184. }
  185. delSetting("ssid" + String(i));
  186. delSetting("pass" + String(i));
  187. delSetting("ip" + String(i));
  188. delSetting("gw" + String(i));
  189. delSetting("mask" + String(i));
  190. delSetting("dns" + String(i));
  191. }
  192. // Save settings
  193. if (save) {
  194. saveSettings();
  195. wifiConfigure();
  196. otaConfigure();
  197. #if ENABLE_FAUXMO
  198. fauxmoConfigure();
  199. #endif
  200. buildTopics();
  201. #if ENABLE_RF
  202. rfBuildCodes();
  203. #endif
  204. #if ENABLE_EMON
  205. setCurrentRatio(getSetting("emonRatio").toFloat());
  206. #endif
  207. #if ITEAD_1CH_INCHING
  208. byte relayPulseMode = getSetting("relayPulseMode", String(RELAY_PULSE_MODE)).toInt();
  209. digitalWrite(LED_PULSE, relayPulseMode != RELAY_PULSE_NONE);
  210. #endif
  211. // Check if we should reconfigure MQTT connection
  212. if (changedMQTT) {
  213. mqttDisconnect();
  214. }
  215. }
  216. if (changed) {
  217. ws.text(client_id, "{\"message\": \"Changes saved\"}");
  218. } else {
  219. ws.text(client_id, "{\"message\": \"No changes detected\"}");
  220. }
  221. }
  222. }
  223. void _wsStart(uint32_t client_id) {
  224. char chipid[6];
  225. sprintf(chipid, "%06X", ESP.getChipId());
  226. DynamicJsonBuffer jsonBuffer;
  227. JsonObject& root = jsonBuffer.createObject();
  228. root["app"] = APP_NAME;
  229. root["version"] = APP_VERSION;
  230. root["buildDate"] = __DATE__;
  231. root["buildTime"] = __TIME__;
  232. root["manufacturer"] = String(MANUFACTURER);
  233. root["chipid"] = chipid;
  234. root["mac"] = WiFi.macAddress();
  235. root["device"] = String(DEVICE);
  236. root["hostname"] = getSetting("hostname", HOSTNAME);
  237. root["network"] = getNetwork();
  238. root["deviceip"] = getIP();
  239. root["mqttStatus"] = mqttConnected();
  240. root["mqttServer"] = getSetting("mqttServer", MQTT_SERVER);
  241. root["mqttPort"] = getSetting("mqttPort", MQTT_PORT);
  242. root["mqttUser"] = getSetting("mqttUser");
  243. root["mqttPassword"] = getSetting("mqttPassword");
  244. root["mqttTopic"] = getSetting("mqttTopic", MQTT_TOPIC);
  245. JsonArray& relay = root.createNestedArray("relayStatus");
  246. for (unsigned char relayID=0; relayID<relayCount(); relayID++) {
  247. relay.add(relayStatus(relayID));
  248. }
  249. root["relayMode"] = getSetting("relayMode", RELAY_MODE);
  250. root["relayPulseMode"] = getSetting("relayPulseMode", RELAY_PULSE_MODE);
  251. root["relayPulseTime"] = getSetting("relayPulseTime", RELAY_PULSE_TIME);
  252. if (relayCount() > 1) {
  253. root["multirelayVisible"] = 1;
  254. root["relaySync"] = getSetting("relaySync", RELAY_SYNC);
  255. }
  256. root["apiEnabled"] = getSetting("apiEnabled").toInt() == 1;
  257. root["apiKey"] = getSetting("apiKey");
  258. #if ENABLE_DOMOTICZ
  259. root["dczVisible"] = 1;
  260. root["dczTopicIn"] = getSetting("dczTopicIn", DOMOTICZ_IN_TOPIC);
  261. root["dczTopicOut"] = getSetting("dczTopicOut", DOMOTICZ_OUT_TOPIC);
  262. JsonArray& dczIdx = root.createNestedArray("dczIdx");
  263. for (byte i=0; i<relayCount(); i++) {
  264. dczIdx.add(domoticzIdx(i));
  265. }
  266. #endif
  267. #if ENABLE_FAUXMO
  268. root["fauxmoVisible"] = 1;
  269. root["fauxmoEnabled"] = getSetting("fauxmoEnabled", FAUXMO_ENABLED).toInt() == 1;
  270. #endif
  271. #if ENABLE_DS18B20
  272. root["dsVisible"] = 1;
  273. root["dsTmp"] = getDSTemperature();
  274. #endif
  275. #if ENABLE_DHT
  276. root["dhtVisible"] = 1;
  277. root["dhtTmp"] = getDHTTemperature();
  278. root["dhtHum"] = getDHTHumidity();
  279. #endif
  280. #if ENABLE_RF
  281. root["rfVisible"] = 1;
  282. root["rfChannel"] = getSetting("rfChannel", RF_CHANNEL);
  283. root["rfDevice"] = getSetting("rfDevice", RF_DEVICE);
  284. #endif
  285. #if ENABLE_EMON
  286. root["emonVisible"] = 1;
  287. root["emonPower"] = getPower();
  288. root["emonMains"] = getSetting("emonMains", EMON_MAINS_VOLTAGE);
  289. root["emonRatio"] = getSetting("emonRatio", EMON_CURRENT_RATIO);
  290. #endif
  291. #if ENABLE_POW
  292. root["powVisible"] = 1;
  293. root["powActivePower"] = getActivePower();
  294. root["powApparentPower"] = getApparentPower();
  295. root["powReactivePower"] = getReactivePower();
  296. root["powVoltage"] = getVoltage();
  297. root["powCurrent"] = getCurrent();
  298. root["powPowerFactor"] = getPowerFactor();
  299. #endif
  300. root["maxNetworks"] = WIFI_MAX_NETWORKS;
  301. JsonArray& wifi = root.createNestedArray("wifi");
  302. for (byte i=0; i<WIFI_MAX_NETWORKS; i++) {
  303. if (getSetting("ssid" + String(i)).length() == 0) break;
  304. JsonObject& network = wifi.createNestedObject();
  305. network["ssid"] = getSetting("ssid" + String(i));
  306. network["pass"] = getSetting("pass" + String(i));
  307. network["ip"] = getSetting("ip" + String(i));
  308. network["gw"] = getSetting("gw" + String(i));
  309. network["mask"] = getSetting("mask" + String(i));
  310. network["dns"] = getSetting("dns" + String(i));
  311. }
  312. String output;
  313. root.printTo(output);
  314. ws.text(client_id, (char *) output.c_str());
  315. }
  316. bool _wsAuth(AsyncWebSocketClient * client) {
  317. IPAddress ip = client->remoteIP();
  318. unsigned long now = millis();
  319. unsigned short index = 0;
  320. for (index = 0; index < WS_BUFFER_SIZE; index++) {
  321. if ((_ticket[index].ip == ip) && (now - _ticket[index].timestamp < WS_TIMEOUT)) break;
  322. }
  323. if (index == WS_BUFFER_SIZE) {
  324. DEBUG_MSG("[WEBSOCKET] Validation check failed\n");
  325. ws.text(client->id(), "{\"message\": \"Session expired, please reload page...\"}");
  326. return false;
  327. }
  328. return true;
  329. }
  330. void _wsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){
  331. static uint8_t * message;
  332. // Authorize
  333. #ifndef NOWSAUTH
  334. if (!_wsAuth(client)) return;
  335. #endif
  336. if (type == WS_EVT_CONNECT) {
  337. IPAddress ip = client->remoteIP();
  338. DEBUG_MSG("[WEBSOCKET] #%u connected, ip: %d.%d.%d.%d, url: %s\n", client->id(), ip[0], ip[1], ip[2], ip[3], server->url());
  339. _wsStart(client->id());
  340. } else if(type == WS_EVT_DISCONNECT) {
  341. DEBUG_MSG("[WEBSOCKET] #%u disconnected\n", client->id());
  342. } else if(type == WS_EVT_ERROR) {
  343. DEBUG_MSG("[WEBSOCKET] #%u error(%u): %s\n", client->id(), *((uint16_t*)arg), (char*)data);
  344. } else if(type == WS_EVT_PONG) {
  345. DEBUG_MSG("[WEBSOCKET] #%u pong(%u): %s\n", client->id(), len, len ? (char*) data : "");
  346. } else if(type == WS_EVT_DATA) {
  347. AwsFrameInfo * info = (AwsFrameInfo*)arg;
  348. // First packet
  349. if (info->index == 0) {
  350. //Serial.printf("Before malloc: %d\n", ESP.getFreeHeap());
  351. message = (uint8_t*) malloc(info->len);
  352. //Serial.printf("After malloc: %d\n", ESP.getFreeHeap());
  353. }
  354. // Store data
  355. memcpy(message + info->index, data, len);
  356. // Last packet
  357. if (info->index + len == info->len) {
  358. _wsParse(client->id(), message, info->len);
  359. //Serial.printf("Before free: %d\n", ESP.getFreeHeap());
  360. free(message);
  361. //Serial.printf("After free: %d\n", ESP.getFreeHeap());
  362. }
  363. }
  364. }
  365. // -----------------------------------------------------------------------------
  366. // WEBSERVER
  367. // -----------------------------------------------------------------------------
  368. void _logRequest(AsyncWebServerRequest *request) {
  369. DEBUG_MSG("[WEBSERVER] Request: %s %s\n", request->methodToString(), request->url().c_str());
  370. }
  371. bool _authenticate(AsyncWebServerRequest *request) {
  372. String password = getSetting("adminPass", ADMIN_PASS);
  373. char httpPassword[password.length() + 1];
  374. password.toCharArray(httpPassword, password.length() + 1);
  375. return request->authenticate(HTTP_USERNAME, httpPassword);
  376. }
  377. void _onAuth(AsyncWebServerRequest *request) {
  378. _logRequest(request);
  379. if (!_authenticate(request)) return request->requestAuthentication();
  380. IPAddress ip = request->client()->remoteIP();
  381. unsigned long now = millis();
  382. unsigned short index;
  383. for (index = 0; index < WS_BUFFER_SIZE; index++) {
  384. if (_ticket[index].ip == ip) break;
  385. if (_ticket[index].timestamp == 0) break;
  386. if (now - _ticket[index].timestamp > WS_TIMEOUT) break;
  387. }
  388. if (index == WS_BUFFER_SIZE) {
  389. request->send(423);
  390. } else {
  391. _ticket[index].ip = ip;
  392. _ticket[index].timestamp = now;
  393. request->send(204);
  394. }
  395. }
  396. void _onHome(AsyncWebServerRequest *request) {
  397. _logRequest(request);
  398. if (!_authenticate(request)) return request->requestAuthentication();
  399. String password = getSetting("adminPass", ADMIN_PASS);
  400. if (password.equals(ADMIN_PASS)) {
  401. request->send(SPIFFS, "/password.html");
  402. } else {
  403. request->send(SPIFFS, "/index.html");
  404. }
  405. }
  406. bool _apiAuth(AsyncWebServerRequest *request) {
  407. if (getSetting("apiEnabled").toInt() == 0) {
  408. DEBUG_MSG("[WEBSERVER] HTTP API is not enabled\n");
  409. request->send(403);
  410. return false;
  411. }
  412. if (!request->hasParam("apikey", (request->method() == HTTP_PUT))) {
  413. DEBUG_MSG("[WEBSERVER] Missing apikey parameter\n");
  414. request->send(403);
  415. return false;
  416. }
  417. AsyncWebParameter* p = request->getParam("apikey", (request->method() == HTTP_PUT));
  418. if (!p->value().equals(getSetting("apiKey"))) {
  419. DEBUG_MSG("[WEBSERVER] Wrong apikey parameter\n");
  420. request->send(403);
  421. return false;
  422. }
  423. return true;
  424. }
  425. void _onRelay(AsyncWebServerRequest *request) {
  426. _logRequest(request);
  427. if (!_apiAuth(request)) return;
  428. bool asJson = false;
  429. if (request->hasHeader("Accept")) {
  430. AsyncWebHeader* h = request->getHeader("Accept");
  431. asJson = h->value().equals("application/json");
  432. }
  433. String output;
  434. if (asJson) {
  435. output = relayString();
  436. request->send(200, "application/json", output);
  437. } else {
  438. for (unsigned int i=0; i<relayCount(); i++) {
  439. output += "Relay #" + String(i) + String(": ") + String(relayStatus(i) ? "1" : "0") + "\n";
  440. }
  441. request->send(200, "text/plain", output);
  442. }
  443. };
  444. ArRequestHandlerFunction _onRelayStatusWrapper(unsigned int relayID) {
  445. return [relayID](AsyncWebServerRequest *request) {
  446. _logRequest(request);
  447. if (!_apiAuth(request)) return;
  448. if (request->method() == HTTP_PUT) {
  449. if (request->hasParam("status", true)) {
  450. AsyncWebParameter* p = request->getParam("status", true);
  451. unsigned int value = p->value().toInt();
  452. if (value == 2) {
  453. relayToggle(relayID);
  454. } else {
  455. relayStatus(relayID, value == 1);
  456. }
  457. }
  458. }
  459. bool asJson = false;
  460. if (request->hasHeader("Accept")) {
  461. AsyncWebHeader* h = request->getHeader("Accept");
  462. asJson = h->value().equals("application/json");
  463. }
  464. String output;
  465. if (asJson) {
  466. output = String("{\"relayStatus\": ") + String(relayStatus(relayID) ? "1" : "0") + "}";
  467. request->send(200, "application/json", output);
  468. } else {
  469. request->send(200, "text/plain", relayStatus(relayID) ? "1" : "0");
  470. }
  471. };
  472. }
  473. void webSetup() {
  474. // Setup websocket
  475. ws.onEvent(_wsEvent);
  476. mqttRegister(wsMQTTCallback);
  477. // Setup webserver
  478. server.addHandler(&ws);
  479. // Serve home (basic authentication protection)
  480. server.on("/", HTTP_GET, _onHome);
  481. server.on("/index.html", HTTP_GET, _onHome);
  482. server.on("/auth", HTTP_GET, _onAuth);
  483. // API entry points (protected with apikey)
  484. for (unsigned int relayID=0; relayID<relayCount(); relayID++) {
  485. char buffer[15];
  486. sprintf(buffer, "/api/relay/%d", relayID);
  487. server.on(buffer, HTTP_GET + HTTP_PUT, _onRelayStatusWrapper(relayID));
  488. }
  489. server.on("/api/relay", HTTP_GET, _onRelay);
  490. // Serve static files
  491. char lastModified[50];
  492. sprintf(lastModified, "%s %s GMT", __DATE__, __TIME__);
  493. server.serveStatic("/", SPIFFS, "/").setLastModified(lastModified);
  494. // 404
  495. server.onNotFound([](AsyncWebServerRequest *request){
  496. request->send(404);
  497. });
  498. // Run server
  499. server.begin();
  500. }