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.

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