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.

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