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.

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