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.

946 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 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='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 5 characters, 1 lowercase and 1 uppercase or 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 (numReboot > 0) {
  114. var response = window.confirm("You have to reboot the board for the changes to take effect, do you want to do it now?");
  115. if (response == true) doReboot(false);
  116. } else if (numReconnect > 0) {
  117. var response = window.confirm("You have to reconnect to the WiFi 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. resetOriginals();
  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 doReboot(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 reboot the device?");
  190. if (response == false) return false;
  191. }
  192. websock.send(JSON.stringify({'action': 'reboot'}));
  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);
  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++);
  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 addRelayGroup() {
  322. var numGroups = $("#relayGroups > div").length;
  323. var tabindex = 200 + numGroups * 2;
  324. var template = $("#relayGroupTemplate").children();
  325. var line = $(template).clone();
  326. var element = $("span.relay_id", line);
  327. if (element.length) element.html(numGroups+1);
  328. $(line).find("input").each(function() {
  329. $(this).attr("tabindex", tabindex++);
  330. });
  331. line.appendTo("#relayGroups");
  332. return line;
  333. }
  334. function initColorRGB() {
  335. // check if already initialized
  336. var done = $("#colors > div").length;
  337. if (done > 0) return;
  338. // add template
  339. var template = $("#colorRGBTemplate").children();
  340. var line = $(template).clone();
  341. line.appendTo("#colors");
  342. // init color wheel
  343. $('input[name="color"]').wheelColorPicker({
  344. sliders: 'wrgbp'
  345. }).on('sliderup', function() {
  346. var value = $(this).wheelColorPicker('getValue', 'css');
  347. websock.send(JSON.stringify({'action': 'color', 'data' : {'rgb': value}}));
  348. });
  349. // init bright slider
  350. $('#brightness').on("change", function() {
  351. var value = $(this).val();
  352. var parent = $(this).parents(".pure-g");
  353. $("span", parent).html(value);
  354. websock.send(JSON.stringify({'action': 'color', 'data' : {'brightness': value}}));
  355. });
  356. }
  357. function initColorHSV() {
  358. // check if already initialized
  359. var done = $("#colors > div").length;
  360. if (done > 0) return;
  361. // add template
  362. var template = $("#colorHSVTemplate").children();
  363. var line = $(template).clone();
  364. line.appendTo("#colors");
  365. // init color wheel
  366. $('input[name="color"]').wheelColorPicker({
  367. sliders: 'whsvp'
  368. }).on('sliderup', function() {
  369. var color = $(this).wheelColorPicker('getColor');
  370. var value = parseInt(color.h * 360) + "," + parseInt(color.s * 100) + "," + parseInt(color.v * 100);
  371. websock.send(JSON.stringify({'action': 'color', 'data' : {'hsv': value}}));
  372. });
  373. }
  374. function initChannels(num) {
  375. // check if already initialized
  376. var done = $("#channels > div").length > 0;
  377. if (done) return;
  378. // does it have color channels?
  379. var colors = $("#colors > div").length > 0;
  380. // calculate channels to create
  381. var max = num;
  382. if (colors) {
  383. max = num % 3;
  384. if ((max > 0) & useWhite) max--;
  385. }
  386. var start = num - max;
  387. // add templates
  388. var template = $("#channelTemplate").children();
  389. for (var i=0; i<max; i++) {
  390. var channel_id = start + i;
  391. var line = $(template).clone();
  392. $("span.slider", line).attr("data", channel_id);
  393. $("input.slider", line).attr("data", channel_id).on("change", function() {
  394. var id = $(this).attr("data");
  395. var value = $(this).val();
  396. var parent = $(this).parents(".pure-g");
  397. $("span", parent).html(value);
  398. websock.send(JSON.stringify({'action': 'channel', 'data' : { 'id': id, 'value': value }}));
  399. });
  400. $("label", line).html("Channel " + (channel_id + 1));
  401. line.appendTo("#channels");
  402. }
  403. }
  404. function addRfbNode() {
  405. var numNodes = $("#rfbNodes > fieldset").length;
  406. var template = $("#rfbNodeTemplate").children();
  407. var line = $(template).clone();
  408. var status = true;
  409. $("span", line).html(numNodes+1);
  410. $(line).find("input").each(function() {
  411. $(this).attr("data-id", numNodes);
  412. $(this).attr("data-status", status ? 1 : 0);
  413. status = !status;
  414. });
  415. $(line).find(".button-rfb-learn").on('click', rfbLearn);
  416. $(line).find(".button-rfb-forget").on('click', rfbForget);
  417. $(line).find(".button-rfb-send").on('click', rfbSend);
  418. line.appendTo("#rfbNodes");
  419. return line;
  420. }
  421. function rfbLearn() {
  422. var parent = $(this).parents(".pure-g");
  423. var input = $("input", parent);
  424. websock.send(JSON.stringify({'action': 'rfblearn', 'data' : {'id' : input.attr("data-id"), 'status': input.attr("data-status")}}));
  425. }
  426. function rfbForget() {
  427. var parent = $(this).parents(".pure-g");
  428. var input = $("input", parent);
  429. websock.send(JSON.stringify({'action': 'rfbforget', 'data' : {'id' : input.attr("data-id"), 'status': input.attr("data-status")}}));
  430. }
  431. function rfbSend() {
  432. var parent = $(this).parents(".pure-g");
  433. var input = $("input", parent);
  434. websock.send(JSON.stringify({'action': 'rfbsend', 'data' : {'id' : input.attr("data-id"), 'status': input.attr("data-status"), 'data': input.val()}}));
  435. }
  436. // -----------------------------------------------------------------------------
  437. // Processing
  438. // -----------------------------------------------------------------------------
  439. function processData(data) {
  440. // title
  441. if ("app_name" in data) {
  442. var title = data.app_name;
  443. if ("app_version" in data) {
  444. title = title + " " + data.app_version;
  445. }
  446. $(".pure-menu-heading").html(title);
  447. if ("hostname" in data) {
  448. title = data.hostname + " - " + title;
  449. }
  450. document.title = title;
  451. }
  452. Object.keys(data).forEach(function(key) {
  453. // Web Modes
  454. if (key == "webMode") {
  455. password = data.webMode == 1;
  456. $("#layout").toggle(data.webMode == 0);
  457. $("#password").toggle(data.webMode == 1);
  458. }
  459. // Actions
  460. if (key == "action") {
  461. if (data.action == "reload") {
  462. doReload(1000);
  463. }
  464. if (data.action == "rfbLearn") {
  465. // Nothing to do?
  466. }
  467. if (data.action == "rfbTimeout") {
  468. // Nothing to do?
  469. }
  470. return;
  471. }
  472. if (key == "rfbCount") {
  473. for (var i=0; i<data.rfbCount; i++) addRfbNode();
  474. return;
  475. }
  476. if (key == "rfb") {
  477. var nodes = data.rfb;
  478. for (var i in nodes) {
  479. var node = nodes[i];
  480. var element = $("input[name=rfbcode][data-id=" + node["id"] + "][data-status=" + node["status"] + "]");
  481. if (element.length) element.val(node["data"]);
  482. }
  483. return;
  484. }
  485. if (key == "rgb") {
  486. initColorRGB();
  487. $("input[name='color']").wheelColorPicker('setValue', data[key], true);
  488. return;
  489. }
  490. if (key == "hsv") {
  491. initColorHSV();
  492. // wheelColorPicker expects HSV to be between 0 and 1 all of them
  493. var chunks = data[key].split(",");
  494. var obj = {};
  495. obj.h = chunks[0] / 360;
  496. obj.s = chunks[1] / 100;
  497. obj.v = chunks[2] / 100;
  498. $("input[name='color']").wheelColorPicker('setColor', obj);
  499. return;
  500. }
  501. if (key == "brightness") {
  502. var slider = $("#brightness");
  503. if (slider.length) slider.val(data[key]);
  504. var span = $("span.brightness");
  505. if (span.length) span.html(data[key]);
  506. return;
  507. }
  508. if (key == "channels") {
  509. var len = data[key].length;
  510. initChannels(len);
  511. for (var i=0; i<len; i++) {
  512. var slider = $("input.slider[data=" + i + "]");
  513. if (slider.length) slider.val(data[key][i]);
  514. var span = $("span.slider[data=" + i + "]");
  515. if (span.length) span.html(data[key][i]);
  516. }
  517. return;
  518. }
  519. if (key == "uptime") {
  520. var uptime = parseInt(data[key]);
  521. var seconds = uptime % 60; uptime = parseInt(uptime / 60);
  522. var minutes = uptime % 60; uptime = parseInt(uptime / 60);
  523. var hours = uptime % 24; uptime = parseInt(uptime / 24);
  524. var days = uptime;
  525. data[key] = days + 'd ' + zeroPad(hours, 2) + 'h ' + zeroPad(minutes, 2) + 'm ' + zeroPad(seconds, 2) + 's';
  526. }
  527. if (key == "useWhite") {
  528. useWhite = data[key];
  529. }
  530. if (key == "maxNetworks") {
  531. maxNetworks = parseInt(data.maxNetworks);
  532. return;
  533. }
  534. // Wifi
  535. if (key == "wifi") {
  536. var networks = data.wifi;
  537. for (var i in networks) {
  538. // add a new row
  539. var line = addNetwork();
  540. // fill in the blanks
  541. var wifi = data.wifi[i];
  542. Object.keys(wifi).forEach(function(key) {
  543. var element = $("input[name=" + key + "]", line);
  544. if (element.length) element.val(wifi[key]);
  545. });
  546. }
  547. return;
  548. }
  549. // Relay status
  550. if (key == "relayStatus") {
  551. var relays = data.relayStatus;
  552. createRelays(relays.length);
  553. for (var relayID in relays) {
  554. var element = $(".relayStatus[data=" + relayID + "]");
  555. if (element.length > 0) {
  556. element
  557. .prop("checked", relays[relayID])
  558. .iphoneStyle("refresh");
  559. }
  560. }
  561. return;
  562. }
  563. // Relay groups
  564. if (key == "relayGroups") {
  565. var groups = data.relayGroups;
  566. for (var i in groups) {
  567. // add a new row
  568. var line = addRelayGroup();
  569. // fill in the blanks
  570. var group = data.relayGroups[i];
  571. Object.keys(group).forEach(function(key) {
  572. var element = $("input[name=" + key + "]", line);
  573. if (element.length) element.val(group[key]);
  574. });
  575. }
  576. return;
  577. }
  578. // Domoticz
  579. if (key == "dczRelayIdx") {
  580. var idxs = data.dczRelayIdx;
  581. createIdxs(idxs.length);
  582. for (var i in idxs) {
  583. var element = $(".dczRelayIdx[data=" + i + "]");
  584. if (element.length > 0) element.val(idxs[i]);
  585. }
  586. return;
  587. }
  588. // Messages
  589. if (key == "message") {
  590. window.alert(messages[data.message]);
  591. return;
  592. }
  593. // Enable options
  594. if (key.endsWith("Visible")) {
  595. var module = key.slice(0,-7);
  596. $(".module-" + module).show();
  597. return;
  598. }
  599. // Pre-process
  600. if (key == "network") {
  601. data.network = data.network.toUpperCase();
  602. }
  603. if (key == "mqttStatus") {
  604. data.mqttStatus = data.mqttStatus ? "CONNECTED" : "NOT CONNECTED";
  605. }
  606. if (key == "ntpStatus") {
  607. data.ntpStatus = data.ntpStatus ? "SYNC'D" : "NOT SYNC'D";
  608. }
  609. if (key == "tmpUnits") {
  610. $("span[name='tmpUnits']").html(data[key] == 1 ? "ºF" : "ºC");
  611. }
  612. if (key == "dhtConnected" && !data[key]) {
  613. $("input[name='dhtTmp']").val("NOT CONNECTED");
  614. $("input[name='dhtHum']").val("NOT CONNECTED");
  615. }
  616. if (key == "dsConnected" && !data[key]) {
  617. $("input[name='dsTmp']").val("NOT CONNECTED");
  618. }
  619. // Look for INPUTs
  620. var element = $("input[name=" + key + "]");
  621. if (element.length > 0) {
  622. if (element.attr('type') == 'checkbox') {
  623. element
  624. .prop("checked", data[key])
  625. .iphoneStyle("refresh");
  626. } else if (element.attr('type') == 'radio') {
  627. element.val([data[key]]);
  628. } else {
  629. var pre = element.attr("pre") || "";
  630. var post = element.attr("post") || "";
  631. element.val(pre + data[key] + post);
  632. }
  633. return;
  634. }
  635. // Look for SPANs
  636. var element = $("span[name=" + key + "]");
  637. if (element.length > 0) {
  638. var pre = element.attr("pre") || "";
  639. var post = element.attr("post") || "";
  640. element.html(pre + data[key] + post);
  641. return;
  642. }
  643. // Look for SELECTs
  644. var element = $("select[name=" + key + "]");
  645. if (element.length > 0) {
  646. element.val(data[key]);
  647. return;
  648. }
  649. });
  650. // Auto generate an APIKey if none defined yet
  651. if ($("input[name='apiKey']").val() == "") {
  652. generateAPIKey();
  653. }
  654. resetOriginals();
  655. }
  656. function hasChanged() {
  657. var newValue, originalValue;
  658. if ($(this).attr('type') == 'checkbox') {
  659. newValue = $(this).prop("checked")
  660. originalValue = $(this).attr("original") == "true";
  661. } else {
  662. newValue = $(this).val();
  663. originalValue = $(this).attr("original");
  664. }
  665. var hasChanged = $(this).attr("hasChanged") || 0;
  666. var action = $(this).attr("action");
  667. if (typeof originalValue == 'undefined') return;
  668. if (action == 'none') return;
  669. if (newValue != originalValue) {
  670. if (hasChanged == 0) {
  671. ++numChanged;
  672. if (action == "reconnect") ++numReconnect;
  673. if (action == "reboot") ++numReboot;
  674. if (action == "reload") ++numReload;
  675. $(this).attr("hasChanged", 1);
  676. }
  677. } else {
  678. if (hasChanged == 1) {
  679. --numChanged;
  680. if (action == "reconnect") --numReconnect;
  681. if (action == "reboot") --numReboot;
  682. if (action == "reload") --numReload;
  683. $(this).attr("hasChanged", 0);
  684. }
  685. }
  686. }
  687. function resetOriginals() {
  688. $("input").each(function() {
  689. $(this).attr("original", $(this).val());
  690. })
  691. $("select").each(function() {
  692. $(this).attr("original", $(this).val());
  693. })
  694. numReboot = numReconnect = numReload = 0;
  695. }
  696. // -----------------------------------------------------------------------------
  697. // Init & connect
  698. // -----------------------------------------------------------------------------
  699. function connect(host) {
  700. if (typeof host === 'undefined') {
  701. host = window.location.href.replace('#', '');
  702. } else {
  703. if (!host.startsWith("http")) {
  704. host = 'http://' + host + '/';
  705. }
  706. }
  707. if (!host.startsWith("http")) return;
  708. webhost = host;
  709. wshost = host.replace('http', 'ws') + 'ws';
  710. if (websock) websock.close();
  711. websock = new WebSocket(wshost);
  712. websock.onopen = function(evt) {
  713. console.log("Connected");
  714. };
  715. websock.onclose = function(evt) {
  716. console.log("Disconnected");
  717. };
  718. websock.onerror = function(evt) {
  719. console.log("Error: ", evt);
  720. };
  721. websock.onmessage = function(evt) {
  722. var data = getJson(evt.data);
  723. if (data) processData(data);
  724. };
  725. }
  726. function init() {
  727. initMessages();
  728. $("#menuLink").on('click', toggleMenu);
  729. $(".pure-menu-link").on('click', showPanel);
  730. $('progress').attr({ value: 0, max: 100 });
  731. $(".button-update").on('click', doUpdate);
  732. $(".button-update-password").on('click', doUpdatePassword);
  733. $(".button-reboot").on('click', doReboot);
  734. $(".button-reconnect").on('click', doReconnect);
  735. $(".button-settings-backup").on('click', doBackup);
  736. $(".button-settings-restore").on('click', doRestore);
  737. $('#uploader').on('change', onFileUpload);
  738. $(".button-upgrade").on('click', doUpgrade);
  739. $(".button-apikey").on('click', generateAPIKey);
  740. $(".button-upgrade-browse").on('click', function() {
  741. $("input[name='upgrade']")[0].click();
  742. return false;
  743. });
  744. $("input[name='upgrade']").change(function (){
  745. var fileName = $(this).val();
  746. $("input[name='filename']").val(fileName.replace(/^.*[\\\/]/, ''));
  747. });
  748. $(".button-add-network").on('click', function() {
  749. $("div.more", addNetwork()).toggle();
  750. });
  751. $(document).on('change', 'input', hasChanged);
  752. $(document).on('change', 'select', hasChanged);
  753. connect();
  754. }
  755. $(init);