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.

942 lines
27 KiB

8 years ago
7 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 messages = [];
  5. var webhost;
  6. var numChanged = 0;
  7. var numReset = 0;
  8. var numReconnect = 0;
  9. var numReload = 0;
  10. var useWhite = false;
  11. // -----------------------------------------------------------------------------
  12. // Messages
  13. // -----------------------------------------------------------------------------
  14. function initMessages() {
  15. messages[01] = "Remote update started";
  16. messages[02] = "OTA update started";
  17. messages[03] = "Error parsing data!";
  18. messages[04] = "The file does not look like a valid configuration backup or is corrupted";
  19. messages[05] = "Changes saved. You should reboot your board now";
  20. messages[07] = "Passwords do not match!";
  21. messages[08] = "Changes saved";
  22. messages[09] = "No changes detected";
  23. messages[10] = "Session expired, please reload page...";
  24. }
  25. // -----------------------------------------------------------------------------
  26. // Utils
  27. // -----------------------------------------------------------------------------
  28. // http://www.the-art-of-web.com/javascript/validate-password/
  29. function checkPassword(str) {
  30. // at least one number, one lowercase and one uppercase letter
  31. // at least eight characters that are letters, numbers or the underscore
  32. var re = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])\w{8,}$/;
  33. return re.test(str);
  34. }
  35. function zeroPad(number, positions) {
  36. return ("0".repeat(positions) + number).slice(-positions);
  37. }
  38. function validateForm(form) {
  39. // password
  40. var adminPass1 = $("input[name='adminPass1']", form).val();
  41. if (adminPass1.length > 0 && !checkPassword(adminPass1)) {
  42. alert("The password you have entered is not valid, it must have at least 8 characters, 1 lower and 1 uppercase and 1 number!");
  43. return false;
  44. }
  45. var adminPass2 = $("input[name='adminPass2']", form).val();
  46. if (adminPass1 != adminPass2) {
  47. alert("Passwords are different!");
  48. return false;
  49. }
  50. return true;
  51. }
  52. function valueSet(data, name, value) {
  53. for (var i in data) {
  54. if (data[i]['name'] == name) {
  55. data[i]['value'] = value;
  56. return;
  57. }
  58. }
  59. data.push({'name': name, 'value': value});
  60. }
  61. function randomString(length, chars) {
  62. var mask = '';
  63. if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz';
  64. if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  65. if (chars.indexOf('#') > -1) mask += '0123456789';
  66. if (chars.indexOf('@') > -1) mask += 'ABCDEF';
  67. if (chars.indexOf('!') > -1) mask += '~`!@#$%^&*()_+-={}[]:";\'<>?,./|\\';
  68. var result = '';
  69. for (var i = length; i > 0; --i) result += mask[Math.round(Math.random() * (mask.length - 1))];
  70. return result;
  71. }
  72. function generateAPIKey() {
  73. var apikey = randomString(16, '@#');
  74. $("input[name=\"apiKey\"]").val(apikey);
  75. return false;
  76. }
  77. function getJson(str) {
  78. try {
  79. return JSON.parse(str);
  80. } catch (e) {
  81. return false;
  82. }
  83. }
  84. // -----------------------------------------------------------------------------
  85. // Actions
  86. // -----------------------------------------------------------------------------
  87. function doReload(milliseconds) {
  88. milliseconds = (typeof milliseconds == 'undefined') ? 0 : parseInt(milliseconds);
  89. setTimeout(function() {
  90. window.location.reload();
  91. }, milliseconds);
  92. }
  93. function doUpdate() {
  94. var form = $("#formSave");
  95. if (validateForm(form)) {
  96. // Get data
  97. var data = form.serializeArray();
  98. // Post-process
  99. delete(data['filename']);
  100. $("input[type='checkbox']").each(function() {
  101. var name = $(this).attr("name");
  102. if (name) {
  103. valueSet(data, name, $(this).is(':checked') ? 1 : 0);
  104. }
  105. });
  106. websock.send(JSON.stringify({'config': data}));
  107. $(".pwrExpected").val(0);
  108. $("input[name='pwrResetCalibration']")
  109. .prop("checked", false)
  110. .iphoneStyle("refresh");
  111. numChanged = 0;
  112. setTimeout(function() {
  113. if (numReset > 0) {
  114. var response = window.confirm("You have to reset the board for the changes to take effect, do you want to do it now?");
  115. if (response == true) doReset(false);
  116. } else if (numReconnect > 0) {
  117. var response = window.confirm("You have to reset the wifi connection for the changes to take effect, do you want to do it now?");
  118. if (response == true) doReconnect(false);
  119. } else if (numReload > 0) {
  120. var response = window.confirm("You have to reload the page to see the latest changes, do you want to do it now?");
  121. if (response == true) doReload();
  122. }
  123. numReset = numReconnect = numReload = 0;
  124. }, 1000);
  125. }
  126. return false;
  127. }
  128. function doUpgrade() {
  129. var contents = $("input[name='upgrade']")[0].files[0];
  130. if (typeof contents == 'undefined') {
  131. alert("First you have to select a file from your computer.");
  132. return false;
  133. }
  134. var filename = $("input[name='upgrade']").val().split('\\').pop();
  135. var data = new FormData();
  136. data.append('upgrade', contents, filename);
  137. $.ajax({
  138. // Your server script to process the upload
  139. url: webhost + 'upgrade',
  140. type: 'POST',
  141. // Form data
  142. data: data,
  143. // Tell jQuery not to process data or worry about content-type
  144. // You *must* include these options!
  145. cache: false,
  146. contentType: false,
  147. processData: false,
  148. success: function(data, text) {
  149. $("#upgrade-progress").hide();
  150. if (data == 'OK') {
  151. alert("Firmware image uploaded, board rebooting. This page will be refreshed in 5 seconds.");
  152. doReload(5000);
  153. } else {
  154. alert("There was an error trying to upload the new image, please try again (" + data + ").");
  155. }
  156. },
  157. // Custom XMLHttpRequest
  158. xhr: function() {
  159. $("#upgrade-progress").show();
  160. var myXhr = $.ajaxSettings.xhr();
  161. if (myXhr.upload) {
  162. // For handling the progress of the upload
  163. myXhr.upload.addEventListener('progress', function(e) {
  164. if (e.lengthComputable) {
  165. $('progress').attr({ value: e.loaded, max: e.total });
  166. }
  167. } , false);
  168. }
  169. return myXhr;
  170. },
  171. });
  172. return false;
  173. }
  174. function doUpdatePassword() {
  175. var form = $("#formPassword");
  176. if (validateForm(form)) {
  177. var data = form.serializeArray();
  178. websock.send(JSON.stringify({'config': data}));
  179. }
  180. return false;
  181. }
  182. function doReset(ask) {
  183. ask = (typeof ask == 'undefined') ? true : ask;
  184. if (numChanged > 0) {
  185. var response = window.confirm("Some changes have not been saved yet, do you want to save them first?");
  186. if (response == true) return doUpdate();
  187. }
  188. if (ask) {
  189. var response = window.confirm("Are you sure you want to reset the device?");
  190. if (response == false) return false;
  191. }
  192. websock.send(JSON.stringify({'action': 'reset'}));
  193. doReload(5000);
  194. return false;
  195. }
  196. function doReconnect(ask) {
  197. ask = (typeof ask == 'undefined') ? true : ask;
  198. if (numChanged > 0) {
  199. var response = window.confirm("Some changes have not been saved yet, do you want to save them first?");
  200. if (response == true) return doUpdate();
  201. }
  202. if (ask) {
  203. var response = window.confirm("Are you sure you want to disconnect from the current WIFI network?");
  204. if (response == false) return false;
  205. }
  206. websock.send(JSON.stringify({'action': 'reconnect'}));
  207. doReload(5000);
  208. return false;
  209. }
  210. function doBackup() {
  211. document.getElementById('downloader').src = webhost + 'config';
  212. return false;
  213. }
  214. function onFileUpload(event) {
  215. var inputFiles = this.files;
  216. if (inputFiles == undefined || inputFiles.length == 0) return false;
  217. var inputFile = inputFiles[0];
  218. this.value = "";
  219. var response = window.confirm("Previous settings will be overwritten. Are you sure you want to restore this settings?");
  220. if (response == false) return false;
  221. var reader = new FileReader();
  222. reader.onload = function(e) {
  223. var data = getJson(e.target.result);
  224. if (data) {
  225. websock.send(JSON.stringify({'action': 'restore', 'data': data}));
  226. } else {
  227. alert(messages[4]);
  228. }
  229. };
  230. reader.readAsText(inputFile);
  231. return false;
  232. }
  233. function doRestore() {
  234. if (typeof window.FileReader !== 'function') {
  235. alert("The file API isn't supported on this browser yet.");
  236. } else {
  237. $("#uploader").click();
  238. }
  239. return false;
  240. }
  241. function doToggle(element, value) {
  242. var relayID = parseInt(element.attr("data"));
  243. websock.send(JSON.stringify({'action': 'relay', 'data': { 'id': relayID, 'status': value ? 1 : 0 }}));
  244. return false;
  245. }
  246. // -----------------------------------------------------------------------------
  247. // Visualization
  248. // -----------------------------------------------------------------------------
  249. function showPanel() {
  250. $(".panel").hide();
  251. $("#" + $(this).attr("data")).show();
  252. if ($("#layout").hasClass('active')) toggleMenu();
  253. $("input[type='checkbox']").iphoneStyle("calculateDimensions").iphoneStyle("refresh");
  254. };
  255. function toggleMenu() {
  256. $("#layout").toggleClass('active');
  257. $("#menu").toggleClass('active');
  258. $("#menuLink").toggleClass('active');
  259. }
  260. // -----------------------------------------------------------------------------
  261. // Templates
  262. // -----------------------------------------------------------------------------
  263. function createRelays(count) {
  264. var current = $("#relays > div").length;
  265. if (current > 0) return;
  266. var template = $("#relayTemplate .pure-g")[0];
  267. for (var relayID=0; relayID<count; relayID++) {
  268. var line = $(template).clone();
  269. $(line).find("input").each(function() {
  270. $(this).attr("data", relayID);
  271. });
  272. if (count > 1) $(".relay_id", line).html(" " + (relayID+1));
  273. line.appendTo("#relays");
  274. $(":checkbox", line).iphoneStyle({
  275. onChange: doToggle,
  276. resizeContainer: true,
  277. resizeHandle: true,
  278. checkedLabel: 'ON',
  279. uncheckedLabel: 'OFF'
  280. });
  281. }
  282. }
  283. function createIdxs(count) {
  284. var current = $("#idxs > div").length;
  285. if (current > 0) return;
  286. var template = $("#idxTemplate .pure-g")[0];
  287. for (var id=0; id<count; id++) {
  288. var line = $(template).clone();
  289. $(line).find("input").each(function() {
  290. $(this).attr("data", id).attr("tabindex", 40+id).attr("original", "");
  291. });
  292. if (count > 1) $(".id", line).html(" " + id);
  293. line.appendTo("#idxs");
  294. }
  295. }
  296. function delNetwork() {
  297. var parent = $(this).parents(".pure-g");
  298. $(parent).remove();
  299. }
  300. function moreNetwork() {
  301. var parent = $(this).parents(".pure-g");
  302. $("div.more", parent).toggle();
  303. }
  304. function addNetwork() {
  305. var numNetworks = $("#networks > div").length;
  306. if (numNetworks >= maxNetworks) {
  307. alert("Max number of networks reached");
  308. return;
  309. }
  310. var tabindex = 200 + numNetworks * 10;
  311. var template = $("#networkTemplate").children();
  312. var line = $(template).clone();
  313. $(line).find("input").each(function() {
  314. $(this).attr("tabindex", tabindex++).attr("original", "");
  315. });
  316. $(line).find(".button-del-network").on('click', delNetwork);
  317. $(line).find(".button-more-network").on('click', moreNetwork);
  318. line.appendTo("#networks");
  319. return line;
  320. }
  321. function initColorRGB() {
  322. // check if already initialized
  323. var done = $("#colors > div").length;
  324. if (done > 0) return;
  325. // add template
  326. var template = $("#colorRGBTemplate").children();
  327. var line = $(template).clone();
  328. line.appendTo("#colors");
  329. // init color wheel
  330. $('input[name="color"]').wheelColorPicker({
  331. sliders: 'wrgbp'
  332. }).on('sliderup', function() {
  333. var value = $(this).wheelColorPicker('getValue', 'css');
  334. websock.send(JSON.stringify({'action': 'rgb', 'data' : value}));
  335. });
  336. // init bright slider
  337. noUiSlider.create($("#brightness").get(0), {
  338. start: 255,
  339. connect: [true, false],
  340. tooltips: true,
  341. format: {
  342. to: function (value) { return parseInt(value); },
  343. from: function (value) { return value; }
  344. },
  345. orientation: "horizontal",
  346. range: { 'min': 0, 'max': 255}
  347. }).on("change", function() {
  348. var value = parseInt(this.get());
  349. websock.send(JSON.stringify({'action': 'brightness', 'data' : value}));
  350. });
  351. }
  352. function initColorHSV() {
  353. // check if already initialized
  354. var done = $("#colors > div").length;
  355. if (done > 0) return;
  356. // add template
  357. var template = $("#colorHSVTemplate").children();
  358. var line = $(template).clone();
  359. line.appendTo("#colors");
  360. // init color wheel
  361. $('input[name="color"]').wheelColorPicker({
  362. sliders: 'whsvp'
  363. }).on('sliderup', function() {
  364. var color = $(this).wheelColorPicker('getColor');
  365. var value = parseInt(color.h * 360) + "," + parseInt(color.s * 100) + "," + parseInt(color.v * 100);
  366. websock.send(JSON.stringify({'action': 'hsv', 'data': value}));
  367. });
  368. }
  369. function initColorsExtras() {
  370. // check if already initialized
  371. var done = $("#colorsExtras > div").length;
  372. if (done > 0) return;
  373. // add template
  374. var template = $("#colorsExtrasTemplate").children();
  375. var line = $(template).clone();
  376. line.appendTo("#colorsExtras");
  377. // init anim mode
  378. $("#animMode").on('change', function() {
  379. var select = this.value;
  380. websock.send(JSON.stringify( {'action': 'anim_mode', 'data' : select }));
  381. });
  382. // init anim speed slider
  383. noUiSlider.create($("#animSpeed").get(0), {
  384. start: 500,
  385. connect: [true, false],
  386. tooltips: true,
  387. format: {
  388. to: function (value) { return parseInt(value); },
  389. from: function (value) { return value; }
  390. },
  391. orientation: "horizontal",
  392. range: { 'min': 0, 'max': 1000}
  393. }).on("change", function() {
  394. var value = parseInt(this.get());
  395. websock.send(JSON.stringify({'action': 'anim_speed', 'data' : value}));
  396. });
  397. }
  398. function initChannels(num) {
  399. // check if already initialized
  400. var done = $("#channels > div").length > 0;
  401. if (done) return;
  402. // does it have color channels?
  403. var colors = $("#colors > div").length > 0;
  404. // calculate channels to create
  405. var max = num;
  406. if (colors) {
  407. max = num % 3;
  408. if ((max > 0) & useWhite) max--;
  409. }
  410. var start = num - max;
  411. // add templates
  412. var template = $("#channelTemplate").children();
  413. for (var i=0; i<max; i++) {
  414. var channel_id = start + i;
  415. var line = $(template).clone();
  416. $(".slider", line).attr("data", channel_id);
  417. $("label", line).html("Channel " + (channel_id + 1));
  418. noUiSlider.create($(".slider", line).get(0), {
  419. start: 0,
  420. connect: [true, false],
  421. tooltips: true,
  422. format: {
  423. to: function (value) { return parseInt(value); },
  424. from: function (value) { return value; }
  425. },
  426. orientation: "horizontal",
  427. range: { 'min': 0, 'max': 255 }
  428. }).on("change", function() {
  429. var id = $(this.target).attr("data");
  430. var value = parseInt(this.get());
  431. websock.send(JSON.stringify({'action': 'channel', 'data': { 'id': id, 'value': value }}));
  432. });
  433. line.appendTo("#channels");
  434. }
  435. }
  436. function addRfbNode() {
  437. var numNodes = $("#rfbNodes > fieldset").length;
  438. var template = $("#rfbNodeTemplate").children();
  439. var line = $(template).clone();
  440. var status = true;
  441. $("span", line).html(numNodes+1);
  442. $(line).find("input").each(function() {
  443. $(this).attr("data_id", numNodes);
  444. $(this).attr("data_status", status ? 1 : 0);
  445. status = !status;
  446. });
  447. $(line).find(".button-rfb-learn").on('click', rfbLearn);
  448. $(line).find(".button-rfb-forget").on('click', rfbForget);
  449. $(line).find(".button-rfb-send").on('click', rfbSend);
  450. line.appendTo("#rfbNodes");
  451. return line;
  452. }
  453. function rfbLearn() {
  454. var parent = $(this).parents(".pure-g");
  455. var input = $("input", parent);
  456. websock.send(JSON.stringify({'action': 'rfblearn', 'data' : {'id' : input.attr("data_id"), 'status': input.attr("data_status")}}));
  457. }
  458. function rfbForget() {
  459. var parent = $(this).parents(".pure-g");
  460. var input = $("input", parent);
  461. websock.send(JSON.stringify({'action': 'rfbforget', 'data' : {'id' : input.attr("data_id"), 'status': input.attr("data_status")}}));
  462. }
  463. function rfbSend() {
  464. var parent = $(this).parents(".pure-g");
  465. var input = $("input", parent);
  466. websock.send(JSON.stringify({'action': 'rfbsend', 'data' : {'id' : input.attr("data_id"), 'status': input.attr("data_status"), 'data': input.val()}}));
  467. }
  468. // -----------------------------------------------------------------------------
  469. // Processing
  470. // -----------------------------------------------------------------------------
  471. function processData(data) {
  472. // title
  473. if ("app_name" in data) {
  474. var title = data.app_name;
  475. if ("app_version" in data) {
  476. title = title + " " + data.app_version;
  477. }
  478. $(".pure-menu-heading").html(title);
  479. if ("hostname" in data) {
  480. title = data.hostname + " - " + title;
  481. }
  482. document.title = title;
  483. }
  484. Object.keys(data).forEach(function(key) {
  485. // Web Modes
  486. if (key == "webMode") {
  487. password = data.webMode == 1;
  488. $("#layout").toggle(data.webMode == 0);
  489. $("#password").toggle(data.webMode == 1);
  490. }
  491. // Actions
  492. if (key == "action") {
  493. if (data.action == "reload") {
  494. doReload(1000);
  495. }
  496. if (data.action == "rfbLearn") {
  497. // Nothing to do?
  498. }
  499. if (data.action == "rfbTimeout") {
  500. // Nothing to do?
  501. }
  502. return;
  503. }
  504. if (key == "rfbCount") {
  505. for (var i=0; i<data.rfbCount; i++) addRfbNode();
  506. return;
  507. }
  508. if (key == "rfb") {
  509. var nodes = data.rfb;
  510. for (var i in nodes) {
  511. var node = nodes[i];
  512. var element = $("input[name=rfbcode][data_id=" + node["id"] + "][data_status=" + node["status"] + "]");
  513. if (element.length) element.val(node["data"]).attr("original", node["data"]);
  514. }
  515. return;
  516. }
  517. if (key == "rgb") {
  518. initColorRGB();
  519. $("input[name='color']").wheelColorPicker('setValue', data[key], true);
  520. return;
  521. }
  522. if (key == "hsv") {
  523. initColorHSV();
  524. // wheelColorPicker expects HSV to be between 0 and 1 all of them
  525. var chunks = data[key].split(",");
  526. var obj = {};
  527. obj.h = chunks[0] / 360;
  528. obj.s = chunks[1] / 100;
  529. obj.v = chunks[2] / 100;
  530. $("input[name='color']").wheelColorPicker('setColor', obj);
  531. return;
  532. }
  533. if (key == "anim_mode") {
  534. initColorsExtras();
  535. $("[name='animation']").val(data[key]);
  536. return;
  537. }
  538. if (key == "anim_speed") {
  539. initColorsExtras();
  540. var slider = $("#animSpeed");
  541. if (slider.length) slider.get(0).noUiSlider.set(data[key]);
  542. return;
  543. }
  544. if (key == "brightness") {
  545. var slider = $("#brightness");
  546. if (slider.length) slider.get(0).noUiSlider.set(data[key]);
  547. return;
  548. }
  549. if (key == "channels") {
  550. var len = data[key].length;
  551. initChannels(len);
  552. for (var i=0; i<len; i++) {
  553. var slider = $("div.channels[data=" + i + "]");
  554. if (slider.length) slider.get(0).noUiSlider.set(data[key][i]);
  555. }
  556. return;
  557. }
  558. if (key == "uptime") {
  559. var uptime = parseInt(data[key]);
  560. var seconds = uptime % 60; uptime = parseInt(uptime / 60);
  561. var minutes = uptime % 60; uptime = parseInt(uptime / 60);
  562. var hours = uptime % 24; uptime = parseInt(uptime / 24);
  563. var days = uptime;
  564. data[key] = days + 'd ' + zeroPad(hours, 2) + 'h ' + zeroPad(minutes, 2) + 'm ' + zeroPad(seconds, 2) + 's';
  565. }
  566. if (key == "useWhite") {
  567. useWhite = data[key];
  568. }
  569. if (key == "maxNetworks") {
  570. maxNetworks = parseInt(data.maxNetworks);
  571. return;
  572. }
  573. // Wifi
  574. if (key == "wifi") {
  575. var networks = data.wifi;
  576. for (var i in networks) {
  577. // add a new row
  578. var line = addNetwork();
  579. // fill in the blanks
  580. var wifi = data.wifi[i];
  581. Object.keys(wifi).forEach(function(key) {
  582. var element = $("input[name=" + key + "]", line);
  583. if (element.length) element.val(wifi[key]).attr("original", wifi[key]);
  584. });
  585. }
  586. return;
  587. }
  588. // Relay status
  589. if (key == "relayStatus") {
  590. var relays = data.relayStatus;
  591. createRelays(relays.length);
  592. for (var relayID in relays) {
  593. var element = $(".relayStatus[data=" + relayID + "]");
  594. if (element.length > 0) {
  595. element
  596. .prop("checked", relays[relayID])
  597. .iphoneStyle("refresh");
  598. }
  599. }
  600. return;
  601. }
  602. // Domoticz
  603. if (key == "dczRelayIdx") {
  604. var idxs = data.dczRelayIdx;
  605. createIdxs(idxs.length);
  606. for (var i in idxs) {
  607. var element = $(".dczRelayIdx[data=" + i + "]");
  608. if (element.length > 0) element.val(idxs[i]).attr("original", idxs[i]);
  609. }
  610. return;
  611. }
  612. // Messages
  613. if (key == "message") {
  614. window.alert(messages[data.message]);
  615. return;
  616. }
  617. // Enable options
  618. if (key.endsWith("Visible")) {
  619. var module = key.slice(0,-7);
  620. $(".module-" + module).show();
  621. return;
  622. }
  623. // Pre-process
  624. if (key == "network") {
  625. data.network = data.network.toUpperCase();
  626. }
  627. if (key == "mqttStatus") {
  628. data.mqttStatus = data.mqttStatus ? "CONNECTED" : "NOT CONNECTED";
  629. }
  630. if (key == "ntpStatus") {
  631. data.ntpStatus = data.ntpStatus ? "SYNC'D" : "NOT SYNC'D";
  632. }
  633. if (key == "tmpUnits") {
  634. $("span#tmpUnit").html(data[key] == 1 ? "ºF" : "ºC");
  635. }
  636. // Look for INPUTs
  637. var element = $("input[name=" + key + "]");
  638. if (element.length > 0) {
  639. if (element.attr('type') == 'checkbox') {
  640. element
  641. .prop("checked", data[key])
  642. .iphoneStyle("refresh");
  643. } else if (element.attr('type') == 'radio') {
  644. element.val([data[key]]);
  645. } else {
  646. var pre = element.attr("pre") || "";
  647. var post = element.attr("post") || "";
  648. element.val(pre + data[key] + post).attr("original", data[key]);
  649. }
  650. return;
  651. }
  652. // Look for SPANs
  653. var element = $("span[name=" + key + "]");
  654. if (element.length > 0) {
  655. var pre = element.attr("pre") || "";
  656. var post = element.attr("post") || "";
  657. element.html(pre + data[key] + post);
  658. return;
  659. }
  660. // Look for SELECTs
  661. var element = $("select[name=" + key + "]");
  662. if (element.length > 0) {
  663. element.val(data[key]).attr("original", data[key]);
  664. return;
  665. }
  666. });
  667. // Auto generate an APIKey if none defined yet
  668. if ($("input[name='apiKey']").val() == "") {
  669. generateAPIKey();
  670. }
  671. }
  672. function hasChanged() {
  673. var newValue, originalValue;
  674. if ($(this).attr('type') == 'checkbox') {
  675. newValue = $(this).prop("checked")
  676. originalValue = $(this).attr("original") == "true";
  677. } else {
  678. newValue = $(this).val();
  679. originalValue = $(this).attr("original");
  680. }
  681. var hasChanged = $(this).attr("hasChanged") || 0;
  682. var action = $(this).attr("action");
  683. if (typeof originalValue == 'undefined') return;
  684. if (action == 'none') return;
  685. if (newValue != originalValue) {
  686. if (hasChanged == 0) {
  687. ++numChanged;
  688. if (action == "reconnect") ++numReconnect;
  689. if (action == "reset") ++numReset;
  690. if (action == "reload") ++numReload;
  691. $(this).attr("hasChanged", 1);
  692. }
  693. } else {
  694. if (hasChanged == 1) {
  695. --numChanged;
  696. if (action == "reconnect") --numReconnect;
  697. if (action == "reset") --numReset;
  698. if (action == "reload") --numReload;
  699. $(this).attr("hasChanged", 0);
  700. }
  701. }
  702. }
  703. // -----------------------------------------------------------------------------
  704. // Init & connect
  705. // -----------------------------------------------------------------------------
  706. function connect(host) {
  707. if (typeof host === 'undefined') {
  708. host = window.location.href.replace('#', '');
  709. } else {
  710. if (!host.startsWith("http")) {
  711. host = 'http://' + host + '/';
  712. }
  713. }
  714. webhost = host;
  715. wshost = host.replace('http', 'ws') + 'ws';
  716. if (websock) websock.close();
  717. websock = new WebSocket(wshost);
  718. websock.onopen = function(evt) {
  719. console.log("Connected");
  720. };
  721. websock.onclose = function(evt) {
  722. console.log("Disconnected");
  723. };
  724. websock.onerror = function(evt) {
  725. console.log("Error: ", evt);
  726. };
  727. websock.onmessage = function(evt) {
  728. var data = getJson(evt.data);
  729. if (data) processData(data);
  730. };
  731. }
  732. function init() {
  733. initMessages();
  734. $("#menuLink").on('click', toggleMenu);
  735. $(".pure-menu-link").on('click', showPanel);
  736. $('progress').attr({ value: 0, max: 100 });
  737. $(".button-update").on('click', doUpdate);
  738. $(".button-update-password").on('click', doUpdatePassword);
  739. $(".button-reset").on('click', doReset);
  740. $(".button-reconnect").on('click', doReconnect);
  741. $(".button-settings-backup").on('click', doBackup);
  742. $(".button-settings-restore").on('click', doRestore);
  743. $('#uploader').on('change', onFileUpload);
  744. $(".button-upgrade").on('click', doUpgrade);
  745. $(".button-apikey").on('click', generateAPIKey);
  746. $(".button-upgrade-browse").on('click', function() {
  747. $("input[name='upgrade']")[0].click();
  748. return false;
  749. });
  750. $("input[name='upgrade']").change(function (){
  751. var fileName = $(this).val();
  752. $("input[name='filename']").val(fileName.replace(/^.*[\\\/]/, ''));
  753. });
  754. $(".button-add-network").on('click', function() {
  755. $("div.more", addNetwork()).toggle();
  756. });
  757. $(document).on('change', 'input', hasChanged);
  758. $(document).on('change', 'select', hasChanged);
  759. connect();
  760. }
  761. $(init);