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.

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