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.

749 lines
21 KiB

8 years ago
7 years ago
7 years ago
8 years ago
8 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 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. var websock;
  2. var password = false;
  3. var maxNetworks;
  4. var protocol;
  5. var host;
  6. var port;
  7. var useWhite = false;
  8. // http://www.the-art-of-web.com/javascript/validate-password/
  9. function checkPassword(str) {
  10. // at least one number, one lowercase and one uppercase letter
  11. // at least eight characters that are letters, numbers or the underscore
  12. var re = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])\w{8,}$/;
  13. return re.test(str);
  14. }
  15. function validateForm(form) {
  16. // password
  17. var adminPass1 = $("input[name='adminPass1']", form).val();
  18. if (adminPass1.length > 0 && !checkPassword(adminPass1)) {
  19. alert("The password you have entered is not valid, it must have at least 8 characters, 1 lower and 1 uppercase and 1 number!");
  20. return false;
  21. }
  22. var adminPass2 = $("input[name='adminPass2']", form).val();
  23. if (adminPass1 != adminPass2) {
  24. alert("Passwords are different!");
  25. return false;
  26. }
  27. return true;
  28. }
  29. function valueSet(data, name, value) {
  30. for (var i in data) {
  31. if (data[i]['name'] == name) {
  32. data[i]['value'] = value;
  33. return;
  34. }
  35. }
  36. data.push({'name': name, 'value': value});
  37. }
  38. function doUpdate() {
  39. var form = $("#formSave");
  40. if (validateForm(form)) {
  41. // Get data
  42. var data = form.serializeArray();
  43. // Post-process
  44. delete(data['filename']);
  45. $("input[type='checkbox']").each(function() {
  46. var name = $(this).attr("name");
  47. if (name) {
  48. valueSet(data, name, $(this).is(':checked') ? 1 : 0);
  49. }
  50. });
  51. websock.send(JSON.stringify({'config': data}));
  52. $(".powExpected").val(0);
  53. $("input[name='powExpectedReset']")
  54. .prop("checked", false)
  55. .iphoneStyle("refresh");
  56. }
  57. return false;
  58. }
  59. function doUpgrade() {
  60. var contents = $("input[name='upgrade']")[0].files[0];
  61. if (typeof contents == 'undefined') {
  62. alert("First you have to select a file from your computer.");
  63. return false;
  64. }
  65. var filename = $("input[name='upgrade']").val().split('\\').pop();
  66. var data = new FormData();
  67. data.append('upgrade', contents, filename);
  68. $.ajax({
  69. // Your server script to process the upload
  70. url: protocol + '//' + host + ':' + port + '/upgrade',
  71. type: 'POST',
  72. // Form data
  73. data: data,
  74. // Tell jQuery not to process data or worry about content-type
  75. // You *must* include these options!
  76. cache: false,
  77. contentType: false,
  78. processData: false,
  79. success: function(data, text) {
  80. $("#upgrade-progress").hide();
  81. if (data == 'OK') {
  82. alert("Firmware image uploaded, board rebooting. This page will be refreshed in 5 seconds.");
  83. setTimeout(function() {
  84. window.location = "/";
  85. }, 5000);
  86. } else {
  87. alert("There was an error trying to upload the new image, please try again.");
  88. }
  89. },
  90. // Custom XMLHttpRequest
  91. xhr: function() {
  92. $("#upgrade-progress").show();
  93. var myXhr = $.ajaxSettings.xhr();
  94. if (myXhr.upload) {
  95. // For handling the progress of the upload
  96. myXhr.upload.addEventListener('progress', function(e) {
  97. if (e.lengthComputable) {
  98. $('progress').attr({ value: e.loaded, max: e.total });
  99. }
  100. } , false);
  101. }
  102. return myXhr;
  103. },
  104. });
  105. return false;
  106. }
  107. function doUpdatePassword() {
  108. var form = $("#formPassword");
  109. if (validateForm(form)) {
  110. var data = form.serializeArray();
  111. websock.send(JSON.stringify({'config': data}));
  112. }
  113. return false;
  114. }
  115. function doReset() {
  116. var response = window.confirm("Are you sure you want to reset the device?");
  117. if (response == false) return false;
  118. websock.send(JSON.stringify({'action': 'reset'}));
  119. return false;
  120. }
  121. function doReconnect() {
  122. var response = window.confirm("Are you sure you want to disconnect from the current WIFI network?");
  123. if (response == false) return false;
  124. websock.send(JSON.stringify({'action': 'reconnect'}));
  125. return false;
  126. }
  127. function doToggle(element, value) {
  128. var relayID = parseInt(element.attr("data"));
  129. websock.send(JSON.stringify({'action': 'relay', 'data': { 'id': relayID, 'status': value ? 1 : 0 }}));
  130. return false;
  131. }
  132. function backupSettings() {
  133. document.getElementById('downloader').src = protocol + '//' + host + ':' + port + '/config';
  134. return false;
  135. }
  136. function onFileUpload(event) {
  137. var inputFiles = this.files;
  138. if (inputFiles == undefined || inputFiles.length == 0) return false;
  139. var inputFile = inputFiles[0];
  140. this.value = "";
  141. var response = window.confirm("Previous settings will be overwritten. Are you sure you want to restore this settings?");
  142. if (response == false) return false;
  143. var reader = new FileReader();
  144. reader.onload = function(e) {
  145. var data = getJson(e.target.result);
  146. if (data) {
  147. websock.send(JSON.stringify({'action': 'restore', 'data': data}));
  148. } else {
  149. alert("The file is not a configuration backup or is corrupted");
  150. }
  151. };
  152. reader.readAsText(inputFile);
  153. return false;
  154. }
  155. function restoreSettings() {
  156. if (typeof window.FileReader !== 'function') {
  157. alert("The file API isn't supported on this browser yet.");
  158. } else {
  159. $("#uploader").click();
  160. }
  161. return false;
  162. }
  163. function randomString(length, chars) {
  164. var mask = '';
  165. if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz';
  166. if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  167. if (chars.indexOf('#') > -1) mask += '0123456789';
  168. if (chars.indexOf('@') > -1) mask += 'ABCDEF';
  169. if (chars.indexOf('!') > -1) mask += '~`!@#$%^&*()_+-={}[]:";\'<>?,./|\\';
  170. var result = '';
  171. for (var i = length; i > 0; --i) result += mask[Math.round(Math.random() * (mask.length - 1))];
  172. return result;
  173. }
  174. function doGenerateAPIKey() {
  175. var apikey = randomString(16, '@#');
  176. $("input[name=\"apiKey\"]").val(apikey);
  177. return false;
  178. }
  179. function showPanel() {
  180. $(".panel").hide();
  181. $("#" + $(this).attr("data")).show();
  182. if ($("#layout").hasClass('active')) toggleMenu();
  183. $("input[type='checkbox']").iphoneStyle("calculateDimensions").iphoneStyle("refresh");
  184. };
  185. function toggleMenu() {
  186. $("#layout").toggleClass('active');
  187. $("#menu").toggleClass('active');
  188. $("#menuLink").toggleClass('active');
  189. }
  190. function createRelays(count) {
  191. var current = $("#relays > div").length;
  192. if (current > 0) return;
  193. var template = $("#relayTemplate .pure-g")[0];
  194. for (var relayID=0; relayID<count; relayID++) {
  195. var line = $(template).clone();
  196. $(line).find("input").each(function() {
  197. $(this).attr("data", relayID);
  198. });
  199. if (count > 1) $(".relay_id", line).html(" " + (relayID+1));
  200. line.appendTo("#relays");
  201. $(":checkbox", line).iphoneStyle({
  202. onChange: doToggle,
  203. resizeContainer: true,
  204. resizeHandle: true,
  205. checkedLabel: 'ON',
  206. uncheckedLabel: 'OFF'
  207. });
  208. }
  209. }
  210. function createIdxs(count) {
  211. var current = $("#idxs > div").length;
  212. if (current > 0) return;
  213. var template = $("#idxTemplate .pure-g")[0];
  214. for (var id=0; id<count; id++) {
  215. var line = $(template).clone();
  216. $(line).find("input").each(function() {
  217. $(this).attr("data", id).attr("tabindex", 40+id);
  218. });
  219. if (count > 1) $(".id", line).html(" " + id);
  220. line.appendTo("#idxs");
  221. }
  222. }
  223. function delNetwork() {
  224. var parent = $(this).parents(".pure-g");
  225. $(parent).remove();
  226. }
  227. function moreNetwork() {
  228. var parent = $(this).parents(".pure-g");
  229. $("div.more", parent).toggle();
  230. }
  231. function addNetwork() {
  232. var numNetworks = $("#networks > div").length;
  233. if (numNetworks >= maxNetworks) {
  234. alert("Max number of networks reached");
  235. return;
  236. }
  237. var tabindex = 200 + numNetworks * 10;
  238. var template = $("#networkTemplate").children();
  239. var line = $(template).clone();
  240. $(line).find("input").each(function() {
  241. $(this).attr("tabindex", tabindex++);
  242. });
  243. $(line).find(".button-del-network").on('click', delNetwork);
  244. $(line).find(".button-more-network").on('click', moreNetwork);
  245. line.appendTo("#networks");
  246. return line;
  247. }
  248. function initColor() {
  249. // check if already initialized
  250. var done = $("#colors > div").length;
  251. if (done > 0) return;
  252. // add template
  253. var template = $("#colorTemplate").children();
  254. var line = $(template).clone();
  255. line.appendTo("#colors");
  256. // init color wheel
  257. $('input[name="color"]').wheelColorPicker({
  258. sliders: 'wrgbp'
  259. }).on('sliderup', function() {
  260. var value = $(this).wheelColorPicker('getValue', 'css');
  261. websock.send(JSON.stringify({'action': 'color', 'data' : value}));
  262. });
  263. // init bright slider
  264. noUiSlider.create($("#brightness").get(0), {
  265. start: 255,
  266. connect: [true, false],
  267. tooltips: true,
  268. format: {
  269. to: function (value) { return parseInt(value); },
  270. from: function (value) { return value; }
  271. },
  272. orientation: "horizontal",
  273. range: { 'min': 0, 'max': 255}
  274. }).on("change", function() {
  275. var value = parseInt(this.get());
  276. websock.send(JSON.stringify({'action': 'brightness', 'data' : value}));
  277. });
  278. }
  279. function initChannels(num) {
  280. // check if already initialized
  281. var done = $("#channels > div").length > 0;
  282. if (done) return;
  283. // does it have color channels?
  284. var colors = $("#colors > div").length > 0;
  285. // calculate channels to create
  286. var max = num;
  287. if (colors) {
  288. max = num % 3;
  289. if ((max > 0) & useWhite) max--;
  290. }
  291. var start = num - max;
  292. // add templates
  293. var template = $("#channelTemplate").children();
  294. for (var i=0; i<max; i++) {
  295. var channel_id = start + i;
  296. var line = $(template).clone();
  297. $(".slider", line).attr("data", channel_id);
  298. $("label", line).html("Channel " + (channel_id + 1));
  299. noUiSlider.create($(".slider", line).get(0), {
  300. start: 0,
  301. connect: [true, false],
  302. tooltips: true,
  303. format: {
  304. to: function (value) { return parseInt(value); },
  305. from: function (value) { return value; }
  306. },
  307. orientation: "horizontal",
  308. range: { 'min': 0, 'max': 255 }
  309. }).on("change", function() {
  310. var id = $(this.target).attr("data");
  311. var value = parseInt(this.get());
  312. websock.send(JSON.stringify({'action': 'channel', 'data': { 'id': id, 'value': value }}));
  313. });
  314. line.appendTo("#channels");
  315. }
  316. }
  317. function addRfbNode() {
  318. var numNodes = $("#rfbNodes > fieldset").length;
  319. var template = $("#rfbNodeTemplate").children();
  320. var line = $(template).clone();
  321. var status = true;
  322. $("span", line).html(numNodes+1);
  323. $(line).find("input").each(function() {
  324. $(this).attr("data_id", numNodes);
  325. $(this).attr("data_status", status ? 1 : 0);
  326. status = !status;
  327. });
  328. $(line).find(".button-rfb-learn").on('click', rfbLearn);
  329. $(line).find(".button-rfb-forget").on('click', rfbForget);
  330. $(line).find(".button-rfb-send").on('click', rfbSend);
  331. line.appendTo("#rfbNodes");
  332. return line;
  333. }
  334. function rfbLearn() {
  335. var parent = $(this).parents(".pure-g");
  336. var input = $("input", parent);
  337. websock.send(JSON.stringify({'action': 'rfblearn', 'data' : {'id' : input.attr("data_id"), 'status': input.attr("data_status")}}));
  338. }
  339. function rfbForget() {
  340. var parent = $(this).parents(".pure-g");
  341. var input = $("input", parent);
  342. websock.send(JSON.stringify({'action': 'rfbforget', 'data' : {'id' : input.attr("data_id"), 'status': input.attr("data_status")}}));
  343. }
  344. function rfbSend() {
  345. var parent = $(this).parents(".pure-g");
  346. var input = $("input", parent);
  347. websock.send(JSON.stringify({'action': 'rfbsend', 'data' : {'id' : input.attr("data_id"), 'status': input.attr("data_status"), 'data': input.val()}}));
  348. }
  349. function forgetCredentials() {
  350. $.ajax({
  351. 'method': 'GET',
  352. 'url': '/',
  353. 'async': false,
  354. 'username': "logmeout",
  355. 'password': "123456",
  356. 'headers': { "Authorization": "Basic xxx" }
  357. }).done(function(data) {
  358. return false;
  359. // If we don't get an error, we actually got an error as we expect an 401!
  360. }).fail(function(){
  361. // We expect to get an 401 Unauthorized error! In this case we are successfully
  362. // logged out and we redirect the user.
  363. return true;
  364. });
  365. }
  366. function processData(data) {
  367. // title
  368. if ("app" in data) {
  369. var title = data.app;
  370. if ("version" in data) {
  371. title = title + " " + data.version;
  372. }
  373. $(".pure-menu-heading").html(title);
  374. if ("hostname" in data) {
  375. title = data.hostname + " - " + title;
  376. }
  377. document.title = title;
  378. }
  379. Object.keys(data).forEach(function(key) {
  380. // Web Modes
  381. if (key == "webMode") {
  382. password = data.webMode == 1;
  383. $("#layout").toggle(data.webMode == 0);
  384. $("#password").toggle(data.webMode == 1);
  385. $("#credentials").hide();
  386. }
  387. // Actions
  388. if (key == "action") {
  389. if (data.action == "reload") {
  390. if (password) forgetCredentials();
  391. setTimeout(function() {
  392. window.location = "/";
  393. }, 1000);
  394. }
  395. if (data.action == "rfbLearn") {
  396. // Nothing to do?
  397. }
  398. if (data.action == "rfbTimeout") {
  399. // Nothing to do?
  400. }
  401. return;
  402. }
  403. if (key == "rfbCount") {
  404. for (var i=0; i<data.rfbCount; i++) addRfbNode();
  405. return;
  406. }
  407. if (key == "rfb") {
  408. var nodes = data.rfb;
  409. for (var i in nodes) {
  410. var node = nodes[i];
  411. var element = $("input[name=rfbcode][data_id=" + node["id"] + "][data_status=" + node["status"] + "]");
  412. if (element.length) element.val(node["data"]);
  413. }
  414. return;
  415. }
  416. if (key == "color") {
  417. initColor();
  418. $("input[name='color']").wheelColorPicker('setValue', data[key], true);
  419. return;
  420. }
  421. if (key == "brightness") {
  422. var slider = $("#brightness");
  423. if (slider.length) slider.get(0).noUiSlider.set(data[key]);
  424. return;
  425. }
  426. if (key == "channels") {
  427. var len = data[key].length;
  428. initChannels(len);
  429. for (var i=0; i<len; i++) {
  430. var slider = $("div.channels[data=" + i + "]");
  431. if (slider.length) slider.get(0).noUiSlider.set(data[key][i]);
  432. }
  433. return;
  434. }
  435. if (key == "useWhite") {
  436. useWhite = data[key];
  437. }
  438. if (key == "maxNetworks") {
  439. maxNetworks = parseInt(data.maxNetworks);
  440. return;
  441. }
  442. // Wifi
  443. if (key == "wifi") {
  444. var networks = data.wifi;
  445. for (var i in networks) {
  446. // add a new row
  447. var line = addNetwork();
  448. // fill in the blanks
  449. var wifi = data.wifi[i];
  450. Object.keys(wifi).forEach(function(key) {
  451. var element = $("input[name=" + key + "]", line);
  452. if (element.length) element.val(wifi[key]);
  453. });
  454. }
  455. return;
  456. }
  457. // Relay status
  458. if (key == "relayStatus") {
  459. var relays = data.relayStatus;
  460. createRelays(relays.length);
  461. for (var relayID in relays) {
  462. var element = $(".relayStatus[data=" + relayID + "]");
  463. if (element.length > 0) {
  464. element
  465. .prop("checked", relays[relayID])
  466. .iphoneStyle("refresh");
  467. }
  468. }
  469. return;
  470. }
  471. // Domoticz
  472. if (key == "dczRelayIdx") {
  473. var idxs = data.dczRelayIdx;
  474. createIdxs(idxs.length);
  475. for (var i in idxs) {
  476. var element = $(".dczRelayIdx[data=" + i + "]");
  477. if (element.length > 0) element.val(idxs[i]);
  478. }
  479. return;
  480. }
  481. // Messages
  482. if (key == "message") {
  483. window.alert(data.message);
  484. return;
  485. }
  486. // Enable options
  487. if (key.endsWith("Visible")) {
  488. var module = key.slice(0,-7);
  489. $(".module-" + module).show();
  490. return;
  491. }
  492. // Pre-process
  493. if (key == "network") {
  494. data.network = data.network.toUpperCase();
  495. }
  496. if (key == "mqttStatus") {
  497. data.mqttStatus = data.mqttStatus ? "CONNECTED" : "NOT CONNECTED";
  498. }
  499. if (key == "ntpStatus") {
  500. data.ntpStatus = data.ntpStatus ? "SYNC'D" : "NOT SYNC'D";
  501. }
  502. if (key == "tmpUnits") {
  503. $("span#tmpUnit").html(data[key] == 1 ? "ºF" : "ºC");
  504. }
  505. // Look for INPUTs
  506. var element = $("input[name=" + key + "]");
  507. if (element.length > 0) {
  508. if (element.attr('type') == 'checkbox') {
  509. element
  510. .prop("checked", data[key])
  511. .iphoneStyle("refresh");
  512. } else if (element.attr('type') == 'radio') {
  513. element.val([data[key]]);
  514. } else {
  515. var pre = element.attr("pre") || "";
  516. var post = element.attr("post") || "";
  517. element.val(pre + data[key] + post);
  518. }
  519. return;
  520. }
  521. // Look for SPANs
  522. var element = $("span[name=" + key + "]");
  523. if (element.length > 0) {
  524. var pre = element.attr("pre") || "";
  525. var post = element.attr("post") || "";
  526. element.html(pre + data[key] + post);
  527. return;
  528. }
  529. // Look for SELECTs
  530. var element = $("select[name=" + key + "]");
  531. if (element.length > 0) {
  532. element.val(data[key]);
  533. return;
  534. }
  535. });
  536. // Auto generate an APIKey if none defined yet
  537. if ($("input[name='apiKey']").val() == "") {
  538. doGenerateAPIKey();
  539. }
  540. }
  541. function getJson(str) {
  542. try {
  543. return JSON.parse(str);
  544. } catch (e) {
  545. return false;
  546. }
  547. }
  548. function connect(h, p) {
  549. if (typeof h === 'undefined') {
  550. h = window.location.hostname;
  551. }
  552. if (typeof p === 'undefined') {
  553. p = location.port;
  554. }
  555. host = h;
  556. port = p;
  557. protocol = location.protocol;
  558. wsproto = (protocol == 'https:') ? 'wss:' : 'ws:';
  559. if (websock) websock.close();
  560. websock = new WebSocket(wsproto + '//' + host + ':' + port + '/ws');
  561. websock.onopen = function(evt) {
  562. console.log("Connected");
  563. };
  564. websock.onclose = function(evt) {
  565. console.log("Disconnected");
  566. };
  567. websock.onerror = function(evt) {
  568. console.log("Error: ", evt);
  569. };
  570. websock.onmessage = function(evt) {
  571. var data = getJson(evt.data);
  572. if (data) processData(data);
  573. };
  574. }
  575. function init() {
  576. $("#menuLink").on('click', toggleMenu);
  577. $(".button-update").on('click', doUpdate);
  578. $(".button-update-password").on('click', doUpdatePassword);
  579. $(".button-reset").on('click', doReset);
  580. $(".button-reconnect").on('click', doReconnect);
  581. $(".button-settings-backup").on('click', backupSettings);
  582. $(".button-settings-restore").on('click', restoreSettings);
  583. $('#uploader').on('change', onFileUpload);
  584. $(".button-apikey").on('click', doGenerateAPIKey);
  585. $(".button-upgrade").on('click', doUpgrade);
  586. $(".button-upgrade-browse").on('click', function() {
  587. $("input[name='upgrade']")[0].click();
  588. return false;
  589. });
  590. $("input[name='upgrade']").change(function (){
  591. var fileName = $(this).val();
  592. $("input[name='filename']").val(fileName.replace(/^.*[\\\/]/, ''));
  593. });
  594. $('progress').attr({ value: 0, max: 100 });
  595. $(".pure-menu-link").on('click', showPanel);
  596. $(".button-add-network").on('click', function() {
  597. $("div.more", addNetwork()).toggle();
  598. });
  599. var protocol = location.protocol;
  600. var host = window.location.hostname;
  601. var port = location.port;
  602. $.ajax({
  603. 'method': 'GET',
  604. 'url': protocol + '//' + host + ':' + port + '/auth'
  605. }).done(function(data) {
  606. connect();
  607. }).fail(function(){
  608. $("#credentials").show();
  609. });
  610. }
  611. $(init);