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.

954 lines
27 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 = [
  54. "ssid", "pass", "gw", "mask", "ip", "dns",
  55. "relayBoot", "relayPulse", "relayTime",
  56. "mqttGroup", "mqttGroupInv",
  57. "dczRelayIdx",
  58. "ledMode",
  59. "ntpServer",
  60. "adminPass"
  61. ];
  62. function getData(form) {
  63. var data = {};
  64. // Populate data
  65. $("input,select", form).each(function() {
  66. var name = $(this).attr("name");
  67. if (name) {
  68. if ($(this).attr('type') == 'checkbox') {
  69. value = $(this).is(':checked') ? 1 : 0;
  70. } else if ($(this).attr('type') == 'radio') {
  71. if (!$(this).is(':checked')) return;
  72. value = $(this).val();
  73. } else {
  74. value = $(this).val();
  75. }
  76. if (name in data) {
  77. data[name].push(value);
  78. } else if (is_group.indexOf(name) >= 0) {
  79. data[name] = [value];
  80. } else {
  81. data[name] = value;
  82. }
  83. }
  84. });
  85. // Delete unwanted fields
  86. delete(data["filename"]);
  87. return data;
  88. }
  89. function randomString(length, chars) {
  90. var mask = '';
  91. if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz';
  92. if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  93. if (chars.indexOf('#') > -1) mask += '0123456789';
  94. if (chars.indexOf('@') > -1) mask += 'ABCDEF';
  95. if (chars.indexOf('!') > -1) mask += '~`!@#$%^&*()_+-={}[]:";\'<>?,./|\\';
  96. var result = '';
  97. for (var i = length; i > 0; --i) result += mask[Math.round(Math.random() * (mask.length - 1))];
  98. return result;
  99. }
  100. function generateAPIKey() {
  101. var apikey = randomString(16, '@#');
  102. $("input[name=\"apiKey\"]").val(apikey);
  103. return false;
  104. }
  105. function getJson(str) {
  106. try {
  107. return JSON.parse(str);
  108. } catch (e) {
  109. return false;
  110. }
  111. }
  112. // -----------------------------------------------------------------------------
  113. // Actions
  114. // -----------------------------------------------------------------------------
  115. function doReload(milliseconds) {
  116. milliseconds = (typeof milliseconds == 'undefined') ? 0 : parseInt(milliseconds);
  117. setTimeout(function() {
  118. window.location.reload();
  119. }, milliseconds);
  120. }
  121. function doUpdate() {
  122. var form = $("#formSave");
  123. if (validateForm(form)) {
  124. // Get data
  125. var data = getData(form);
  126. websock.send(JSON.stringify({'config': data}));
  127. // Empty special fields
  128. $(".pwrExpected").val(0);
  129. $("input[name='pwrResetCalibration']")
  130. .prop("checked", false)
  131. .iphoneStyle("refresh");
  132. // Change handling
  133. numChanged = 0;
  134. setTimeout(function() {
  135. if (numReboot > 0) {
  136. var response = window.confirm("You have to reboot the board for the changes to take effect, do you want to do it now?");
  137. if (response == true) doReboot(false);
  138. } else if (numReconnect > 0) {
  139. var response = window.confirm("You have to reconnect to the WiFi for the changes to take effect, do you want to do it now?");
  140. if (response == true) doReconnect(false);
  141. } else if (numReload > 0) {
  142. var response = window.confirm("You have to reload the page to see the latest changes, do you want to do it now?");
  143. if (response == true) doReload();
  144. }
  145. resetOriginals();
  146. }, 1000);
  147. }
  148. return false;
  149. }
  150. function doUpgrade() {
  151. var contents = $("input[name='upgrade']")[0].files[0];
  152. if (typeof contents == 'undefined') {
  153. alert("First you have to select a file from your computer.");
  154. return false;
  155. }
  156. var filename = $("input[name='upgrade']").val().split('\\').pop();
  157. var data = new FormData();
  158. data.append('upgrade', contents, filename);
  159. $.ajax({
  160. // Your server script to process the upload
  161. url: webhost + 'upgrade',
  162. type: 'POST',
  163. // Form data
  164. data: data,
  165. // Tell jQuery not to process data or worry about content-type
  166. // You *must* include these options!
  167. cache: false,
  168. contentType: false,
  169. processData: false,
  170. success: function(data, text) {
  171. $("#upgrade-progress").hide();
  172. if (data == 'OK') {
  173. alert("Firmware image uploaded, board rebooting. This page will be refreshed in 5 seconds.");
  174. doReload(5000);
  175. } else {
  176. alert("There was an error trying to upload the new image, please try again (" + data + ").");
  177. }
  178. },
  179. // Custom XMLHttpRequest
  180. xhr: function() {
  181. $("#upgrade-progress").show();
  182. var myXhr = $.ajaxSettings.xhr();
  183. if (myXhr.upload) {
  184. // For handling the progress of the upload
  185. myXhr.upload.addEventListener('progress', function(e) {
  186. if (e.lengthComputable) {
  187. $('progress').attr({ value: e.loaded, max: e.total });
  188. }
  189. } , false);
  190. }
  191. return myXhr;
  192. },
  193. });
  194. return false;
  195. }
  196. function doUpdatePassword() {
  197. var form = $("#formPassword");
  198. if (validateForm(form)) {
  199. var data = getData(form);
  200. websock.send(JSON.stringify({'config': data}));
  201. }
  202. return false;
  203. }
  204. function doReboot(ask) {
  205. ask = (typeof ask == 'undefined') ? true : ask;
  206. if (numChanged > 0) {
  207. var response = window.confirm("Some changes have not been saved yet, do you want to save them first?");
  208. if (response == true) return doUpdate();
  209. }
  210. if (ask) {
  211. var response = window.confirm("Are you sure you want to reboot the device?");
  212. if (response == false) return false;
  213. }
  214. websock.send(JSON.stringify({'action': 'reboot'}));
  215. doReload(5000);
  216. return false;
  217. }
  218. function doReconnect(ask) {
  219. ask = (typeof ask == 'undefined') ? true : ask;
  220. if (numChanged > 0) {
  221. var response = window.confirm("Some changes have not been saved yet, do you want to save them first?");
  222. if (response == true) return doUpdate();
  223. }
  224. if (ask) {
  225. var response = window.confirm("Are you sure you want to disconnect from the current WIFI network?");
  226. if (response == false) return false;
  227. }
  228. websock.send(JSON.stringify({'action': 'reconnect'}));
  229. doReload(5000);
  230. return false;
  231. }
  232. function doBackup() {
  233. document.getElementById('downloader').src = webhost + 'config';
  234. return false;
  235. }
  236. function onFileUpload(event) {
  237. var inputFiles = this.files;
  238. if (inputFiles == undefined || inputFiles.length == 0) return false;
  239. var inputFile = inputFiles[0];
  240. this.value = "";
  241. var response = window.confirm("Previous settings will be overwritten. Are you sure you want to restore this settings?");
  242. if (response == false) return false;
  243. var reader = new FileReader();
  244. reader.onload = function(e) {
  245. var data = getJson(e.target.result);
  246. if (data) {
  247. websock.send(JSON.stringify({'action': 'restore', 'data': data}));
  248. } else {
  249. alert(messages[4]);
  250. }
  251. };
  252. reader.readAsText(inputFile);
  253. return false;
  254. }
  255. function doRestore() {
  256. if (typeof window.FileReader !== 'function') {
  257. alert("The file API isn't supported on this browser yet.");
  258. } else {
  259. $("#uploader").click();
  260. }
  261. return false;
  262. }
  263. function doToggle(element, value) {
  264. var relayID = parseInt(element.attr("data"));
  265. websock.send(JSON.stringify({'action': 'relay', 'data': { 'id': relayID, 'status': value ? 1 : 0 }}));
  266. return false;
  267. }
  268. // -----------------------------------------------------------------------------
  269. // Visualization
  270. // -----------------------------------------------------------------------------
  271. function showPanel() {
  272. $(".panel").hide();
  273. $("#" + $(this).attr("data")).show();
  274. if ($("#layout").hasClass('active')) toggleMenu();
  275. $("input[type='checkbox']").iphoneStyle("calculateDimensions").iphoneStyle("refresh");
  276. };
  277. function toggleMenu() {
  278. $("#layout").toggleClass('active');
  279. $("#menu").toggleClass('active');
  280. $("#menuLink").toggleClass('active');
  281. }
  282. // -----------------------------------------------------------------------------
  283. // Templates
  284. // -----------------------------------------------------------------------------
  285. function createRelays(count) {
  286. var current = $("#relays > div").length;
  287. if (current > 0) return;
  288. var template = $("#relayTemplate .pure-g")[0];
  289. for (var relayID=0; relayID<count; relayID++) {
  290. var line = $(template).clone();
  291. $(line).find("input").each(function() {
  292. $(this).attr("data", relayID);
  293. });
  294. if (count > 1) $(".relay_id", line).html(" " + (relayID+1));
  295. line.appendTo("#relays");
  296. $(":checkbox", line).iphoneStyle({
  297. onChange: doToggle,
  298. resizeContainer: true,
  299. resizeHandle: true,
  300. checkedLabel: 'ON',
  301. uncheckedLabel: 'OFF'
  302. });
  303. }
  304. }
  305. function initRelayConfig(data) {
  306. var current = $("#relayConfig > div").length;
  307. if (current > 0) return;
  308. var template = $("#relayConfigTemplate").children();
  309. for (var i=0; i < data.length; i++) {
  310. var line = $(template).clone();
  311. $("span.gpio", line).html(data[i].gpio);
  312. $("span.id", line).html(i+1);
  313. $("select[name='relayBoot']", line).val(data[i].boot);
  314. $("select[name='relayPulse']", line).val(data[i].pulse);
  315. $("input[name='relayTime']", line).val(data[i].pulse_ms);
  316. $("intut[name='mqttGroup']", line).val(data[i].group || 0);
  317. $("select[name='mqttGroupInv']", line).val(data[i].group_inv || 0);
  318. line.appendTo("#relayConfig");
  319. }
  320. }
  321. function createIdxs(count) {
  322. var current = $("#idxs > div").length;
  323. if (current > 0) return;
  324. var template = $("#idxTemplate .pure-g")[0];
  325. for (var id=0; id<count; id++) {
  326. var line = $(template).clone();
  327. $(line).find("input").each(function() {
  328. $(this).attr("data", id).attr("tabindex", 40+id);
  329. });
  330. if (count > 1) $(".id", line).html(" " + id);
  331. line.appendTo("#idxs");
  332. }
  333. }
  334. function delNetwork() {
  335. var parent = $(this).parents(".pure-g");
  336. $(parent).remove();
  337. }
  338. function moreNetwork() {
  339. var parent = $(this).parents(".pure-g");
  340. $("div.more", parent).toggle();
  341. }
  342. function addNetwork() {
  343. var numNetworks = $("#networks > div").length;
  344. if (numNetworks >= maxNetworks) {
  345. alert("Max number of networks reached");
  346. return;
  347. }
  348. var tabindex = 200 + numNetworks * 10;
  349. var template = $("#networkTemplate").children();
  350. var line = $(template).clone();
  351. $(line).find("input").each(function() {
  352. $(this).attr("tabindex", tabindex++);
  353. });
  354. $(line).find(".button-del-network").on('click', delNetwork);
  355. $(line).find(".button-more-network").on('click', moreNetwork);
  356. line.appendTo("#networks");
  357. return line;
  358. }
  359. function initColorRGB() {
  360. // check if already initialized
  361. var done = $("#colors > div").length;
  362. if (done > 0) return;
  363. // add template
  364. var template = $("#colorRGBTemplate").children();
  365. var line = $(template).clone();
  366. line.appendTo("#colors");
  367. // init color wheel
  368. $('input[name="color"]').wheelColorPicker({
  369. sliders: 'wrgbp'
  370. }).on('sliderup', function() {
  371. var value = $(this).wheelColorPicker('getValue', 'css');
  372. websock.send(JSON.stringify({'action': 'color', 'data' : {'rgb': value}}));
  373. });
  374. // init bright slider
  375. $('#brightness').on("change", function() {
  376. var value = $(this).val();
  377. var parent = $(this).parents(".pure-g");
  378. $("span", parent).html(value);
  379. websock.send(JSON.stringify({'action': 'color', 'data' : {'brightness': value}}));
  380. });
  381. }
  382. function initColorHSV() {
  383. // check if already initialized
  384. var done = $("#colors > div").length;
  385. if (done > 0) return;
  386. // add template
  387. var template = $("#colorHSVTemplate").children();
  388. var line = $(template).clone();
  389. line.appendTo("#colors");
  390. // init color wheel
  391. $('input[name="color"]').wheelColorPicker({
  392. sliders: 'whsvp'
  393. }).on('sliderup', function() {
  394. var color = $(this).wheelColorPicker('getColor');
  395. var value = parseInt(color.h * 360) + "," + parseInt(color.s * 100) + "," + parseInt(color.v * 100);
  396. websock.send(JSON.stringify({'action': 'color', 'data' : {'hsv': value}}));
  397. });
  398. }
  399. function initChannels(num) {
  400. // check if already initialized
  401. var done = $("#channels > div").length > 0;
  402. if (done) return;
  403. // does it have color channels?
  404. var colors = $("#colors > div").length > 0;
  405. // calculate channels to create
  406. var max = num;
  407. if (colors) {
  408. max = num % 3;
  409. if ((max > 0) & useWhite) max--;
  410. }
  411. var start = num - max;
  412. // add templates
  413. var template = $("#channelTemplate").children();
  414. for (var i=0; i<max; i++) {
  415. var channel_id = start + i;
  416. var line = $(template).clone();
  417. $("span.slider", line).attr("data", channel_id);
  418. $("input.slider", line).attr("data", channel_id).on("change", function() {
  419. var id = $(this).attr("data");
  420. var value = $(this).val();
  421. var parent = $(this).parents(".pure-g");
  422. $("span", parent).html(value);
  423. websock.send(JSON.stringify({'action': 'channel', 'data' : { 'id': id, 'value': value }}));
  424. });
  425. $("label", line).html("Channel " + (channel_id + 1));
  426. line.appendTo("#channels");
  427. }
  428. }
  429. function addRfbNode() {
  430. var numNodes = $("#rfbNodes > fieldset").length;
  431. var template = $("#rfbNodeTemplate").children();
  432. var line = $(template).clone();
  433. var status = true;
  434. $("span", line).html(numNodes+1);
  435. $(line).find("input").each(function() {
  436. $(this).attr("data-id", numNodes);
  437. $(this).attr("data-status", status ? 1 : 0);
  438. status = !status;
  439. });
  440. $(line).find(".button-rfb-learn").on('click', rfbLearn);
  441. $(line).find(".button-rfb-forget").on('click', rfbForget);
  442. $(line).find(".button-rfb-send").on('click', rfbSend);
  443. line.appendTo("#rfbNodes");
  444. return line;
  445. }
  446. function rfbLearn() {
  447. var parent = $(this).parents(".pure-g");
  448. var input = $("input", parent);
  449. websock.send(JSON.stringify({'action': 'rfblearn', 'data' : {'id' : input.attr("data-id"), 'status': input.attr("data-status")}}));
  450. }
  451. function rfbForget() {
  452. var parent = $(this).parents(".pure-g");
  453. var input = $("input", parent);
  454. websock.send(JSON.stringify({'action': 'rfbforget', 'data' : {'id' : input.attr("data-id"), 'status': input.attr("data-status")}}));
  455. }
  456. function rfbSend() {
  457. var parent = $(this).parents(".pure-g");
  458. var input = $("input", parent);
  459. websock.send(JSON.stringify({'action': 'rfbsend', 'data' : {'id' : input.attr("data-id"), 'status': input.attr("data-status"), 'data': input.val()}}));
  460. }
  461. // -----------------------------------------------------------------------------
  462. // Processing
  463. // -----------------------------------------------------------------------------
  464. function processData(data) {
  465. // title
  466. if ("app_name" in data) {
  467. var title = data.app_name;
  468. if ("app_version" in data) {
  469. title = title + " " + data.app_version;
  470. }
  471. $(".pure-menu-heading").html(title);
  472. if ("hostname" in data) {
  473. title = data.hostname + " - " + title;
  474. }
  475. document.title = title;
  476. }
  477. Object.keys(data).forEach(function(key) {
  478. // Web Modes
  479. if (key == "webMode") {
  480. password = data.webMode == 1;
  481. $("#layout").toggle(data.webMode == 0);
  482. $("#password").toggle(data.webMode == 1);
  483. }
  484. // Actions
  485. if (key == "action") {
  486. if (data.action == "reload") {
  487. doReload(1000);
  488. }
  489. if (data.action == "rfbLearn") {
  490. // Nothing to do?
  491. }
  492. if (data.action == "rfbTimeout") {
  493. // Nothing to do?
  494. }
  495. return;
  496. }
  497. if (key == "rfbCount") {
  498. for (var i=0; i<data.rfbCount; i++) addRfbNode();
  499. return;
  500. }
  501. if (key == "rfb") {
  502. var nodes = data.rfb;
  503. for (var i in nodes) {
  504. var node = nodes[i];
  505. var element = $("input[name=rfbcode][data-id=" + node["id"] + "][data-status=" + node["status"] + "]");
  506. if (element.length) element.val(node["data"]);
  507. }
  508. return;
  509. }
  510. if (key == "rgb") {
  511. initColorRGB();
  512. $("input[name='color']").wheelColorPicker('setValue', data[key], true);
  513. return;
  514. }
  515. if (key == "hsv") {
  516. initColorHSV();
  517. // wheelColorPicker expects HSV to be between 0 and 1 all of them
  518. var chunks = data[key].split(",");
  519. var obj = {};
  520. obj.h = chunks[0] / 360;
  521. obj.s = chunks[1] / 100;
  522. obj.v = chunks[2] / 100;
  523. $("input[name='color']").wheelColorPicker('setColor', obj);
  524. return;
  525. }
  526. if (key == "brightness") {
  527. var slider = $("#brightness");
  528. if (slider.length) slider.val(data[key]);
  529. var span = $("span.brightness");
  530. if (span.length) span.html(data[key]);
  531. return;
  532. }
  533. if (key == "channels") {
  534. var len = data[key].length;
  535. initChannels(len);
  536. for (var i=0; i<len; i++) {
  537. var slider = $("input.slider[data=" + i + "]");
  538. if (slider.length) slider.val(data[key][i]);
  539. var span = $("span.slider[data=" + i + "]");
  540. if (span.length) span.html(data[key][i]);
  541. }
  542. return;
  543. }
  544. if (key == "uptime") {
  545. var uptime = parseInt(data[key]);
  546. var seconds = uptime % 60; uptime = parseInt(uptime / 60);
  547. var minutes = uptime % 60; uptime = parseInt(uptime / 60);
  548. var hours = uptime % 24; uptime = parseInt(uptime / 24);
  549. var days = uptime;
  550. data[key] = days + 'd ' + zeroPad(hours, 2) + 'h ' + zeroPad(minutes, 2) + 'm ' + zeroPad(seconds, 2) + 's';
  551. }
  552. if (key == "useWhite") {
  553. useWhite = data[key];
  554. }
  555. if (key == "maxNetworks") {
  556. maxNetworks = parseInt(data.maxNetworks);
  557. return;
  558. }
  559. // Wifi
  560. if (key == "wifi") {
  561. var networks = data.wifi;
  562. for (var i in networks) {
  563. // add a new row
  564. var line = addNetwork();
  565. // fill in the blanks
  566. var wifi = data.wifi[i];
  567. Object.keys(wifi).forEach(function(key) {
  568. var element = $("input[name=" + key + "]", line);
  569. if (element.length) element.val(wifi[key]);
  570. });
  571. }
  572. return;
  573. }
  574. // Relay status
  575. if (key == "relayStatus") {
  576. var relays = data.relayStatus;
  577. createRelays(relays.length);
  578. for (var relayID in relays) {
  579. var element = $(".relayStatus[data=" + relayID + "]");
  580. if (element.length > 0) {
  581. element
  582. .prop("checked", relays[relayID])
  583. .iphoneStyle("refresh");
  584. }
  585. }
  586. return;
  587. }
  588. // Relay configuration
  589. if (key == "relayConfig") {
  590. initRelayConfig(data[key]);
  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);