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.

977 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 initColor() {
  340. // check if already initialized
  341. var done = $("#colors > div").length;
  342. if (done > 0) return;
  343. // add template
  344. var template = $("#colorTemplate").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': 'color', '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_all = $(this).wheelColorPicker('getColor');
  383. var color_hsv ={};
  384. color_hsv.h =Math.floor(color_all.h * 255);
  385. color_hsv.s =Math.floor(color_all.s * 255);
  386. color_hsv.v =Math.floor(color_all.v * 255);
  387. websock.send(JSON.stringify({'action': 'color_hsv', 'data' : color_hsv}));
  388. });
  389. }
  390. function initColorsExtras() {
  391. // check if already initialized
  392. var done = $("#colorsExtras > div").length;
  393. if (done > 0) return;
  394. // add template
  395. var template = $("#colorsExtrasTemplate").children();
  396. var line = $(template).clone();
  397. line.appendTo("#colorsExtras");
  398. // init anim mode
  399. $("#animMode").on('change', function() {
  400. var select = this.value;
  401. websock.send(JSON.stringify( {'action': 'anim_mode', 'data' : select }));
  402. });
  403. // init anim speed slider
  404. noUiSlider.create($("#animSpeed").get(0), {
  405. start: 500,
  406. connect: [true, false],
  407. tooltips: true,
  408. format: {
  409. to: function (value) { return parseInt(value); },
  410. from: function (value) { return value; }
  411. },
  412. orientation: "horizontal",
  413. range: { 'min': 0, 'max': 1000}
  414. }).on("change", function() {
  415. var value = parseInt(this.get());
  416. websock.send(JSON.stringify({'action': 'anim_speed', 'data' : value}));
  417. });
  418. }
  419. function initChannels(num) {
  420. // check if already initialized
  421. var done = $("#channels > div").length > 0;
  422. if (done) return;
  423. // does it have color channels?
  424. var colors = $("#colors > div").length > 0;
  425. // calculate channels to create
  426. var max = num;
  427. if (colors) {
  428. max = num % 3;
  429. if ((max > 0) & useWhite) max--;
  430. }
  431. var start = num - max;
  432. // add templates
  433. var template = $("#channelTemplate").children();
  434. for (var i=0; i<max; i++) {
  435. var channel_id = start + i;
  436. var line = $(template).clone();
  437. $(".slider", line).attr("data", channel_id);
  438. $("label", line).html("Channel " + (channel_id + 1));
  439. noUiSlider.create($(".slider", line).get(0), {
  440. start: 0,
  441. connect: [true, false],
  442. tooltips: true,
  443. format: {
  444. to: function (value) { return parseInt(value); },
  445. from: function (value) { return value; }
  446. },
  447. orientation: "horizontal",
  448. range: { 'min': 0, 'max': 255 }
  449. }).on("change", function() {
  450. var id = $(this.target).attr("data");
  451. var value = parseInt(this.get());
  452. websock.send(JSON.stringify({'action': 'channel', 'data': { 'id': id, 'value': value }}));
  453. });
  454. line.appendTo("#channels");
  455. }
  456. }
  457. function addRfbNode() {
  458. var numNodes = $("#rfbNodes > fieldset").length;
  459. var template = $("#rfbNodeTemplate").children();
  460. var line = $(template).clone();
  461. var status = true;
  462. $("span", line).html(numNodes+1);
  463. $(line).find("input").each(function() {
  464. $(this).attr("data_id", numNodes);
  465. $(this).attr("data_status", status ? 1 : 0);
  466. status = !status;
  467. });
  468. $(line).find(".button-rfb-learn").on('click', rfbLearn);
  469. $(line).find(".button-rfb-forget").on('click', rfbForget);
  470. $(line).find(".button-rfb-send").on('click', rfbSend);
  471. line.appendTo("#rfbNodes");
  472. return line;
  473. }
  474. function rfbLearn() {
  475. var parent = $(this).parents(".pure-g");
  476. var input = $("input", parent);
  477. websock.send(JSON.stringify({'action': 'rfblearn', 'data' : {'id' : input.attr("data_id"), 'status': input.attr("data_status")}}));
  478. }
  479. function rfbForget() {
  480. var parent = $(this).parents(".pure-g");
  481. var input = $("input", parent);
  482. websock.send(JSON.stringify({'action': 'rfbforget', 'data' : {'id' : input.attr("data_id"), 'status': input.attr("data_status")}}));
  483. }
  484. function rfbSend() {
  485. var parent = $(this).parents(".pure-g");
  486. var input = $("input", parent);
  487. websock.send(JSON.stringify({'action': 'rfbsend', 'data' : {'id' : input.attr("data_id"), 'status': input.attr("data_status"), 'data': input.val()}}));
  488. }
  489. // -----------------------------------------------------------------------------
  490. // Processing
  491. // -----------------------------------------------------------------------------
  492. function processData(data) {
  493. // title
  494. if ("app_name" in data) {
  495. var title = data.app_name;
  496. if ("app_version" in data) {
  497. title = title + " " + data.app_version;
  498. }
  499. $(".pure-menu-heading").html(title);
  500. if ("hostname" in data) {
  501. title = data.hostname + " - " + title;
  502. }
  503. document.title = title;
  504. }
  505. Object.keys(data).forEach(function(key) {
  506. // Web Modes
  507. if (key == "webMode") {
  508. password = data.webMode == 1;
  509. $("#layout").toggle(data.webMode == 0);
  510. $("#password").toggle(data.webMode == 1);
  511. $("#credentials").hide();
  512. }
  513. // Actions
  514. if (key == "action") {
  515. if (data.action == "reload") {
  516. if (password) forgetCredentials();
  517. doReload(1000);
  518. }
  519. if (data.action == "rfbLearn") {
  520. // Nothing to do?
  521. }
  522. if (data.action == "rfbTimeout") {
  523. // Nothing to do?
  524. }
  525. return;
  526. }
  527. if (key == "rfbCount") {
  528. for (var i=0; i<data.rfbCount; i++) addRfbNode();
  529. return;
  530. }
  531. if (key == "rfb") {
  532. var nodes = data.rfb;
  533. for (var i in nodes) {
  534. var node = nodes[i];
  535. var element = $("input[name=rfbcode][data_id=" + node["id"] + "][data_status=" + node["status"] + "]");
  536. if (element.length) element.val(node["data"]).attr("original", node["data"]);
  537. }
  538. return;
  539. }
  540. if (key == "color") {
  541. initColor();
  542. $("input[name='color']").wheelColorPicker('setValue', data[key], true);
  543. return;
  544. }
  545. if (key == "color_hsv") {
  546. initColorHsv();
  547. var color_hsv ={};
  548. color_hsv.h = data[key]['h'] / 255;
  549. color_hsv.s = data[key]['s'] / 255;
  550. color_hsv.v = data[key]['v'] / 255;
  551. $("input[name='color']").wheelColorPicker('setColor', color_hsv);
  552. return;
  553. }
  554. if (key == "anim_mode") {
  555. initColorsExtras();
  556. $("[name='animation']").val(data[key]);
  557. return;
  558. }
  559. if (key == "anim_speed") {
  560. initColorsExtras();
  561. var slider = $("#animSpeed");
  562. if (slider.length) slider.get(0).noUiSlider.set(data[key]);
  563. return;
  564. }
  565. if (key == "brightness") {
  566. var slider = $("#brightness");
  567. if (slider.length) slider.get(0).noUiSlider.set(data[key]);
  568. return;
  569. }
  570. if (key == "channels") {
  571. var len = data[key].length;
  572. initChannels(len);
  573. for (var i=0; i<len; i++) {
  574. var slider = $("div.channels[data=" + i + "]");
  575. if (slider.length) slider.get(0).noUiSlider.set(data[key][i]);
  576. }
  577. return;
  578. }
  579. if (key == "uptime") {
  580. var uptime = parseInt(data[key]);
  581. var seconds = uptime % 60; uptime = parseInt(uptime / 60);
  582. var minutes = uptime % 60; uptime = parseInt(uptime / 60);
  583. var hours = uptime % 24; uptime = parseInt(uptime / 24);
  584. var days = uptime;
  585. data[key] = days + 'd ' + zeroPad(hours, 2) + 'h ' + zeroPad(minutes, 2) + 'm ' + zeroPad(seconds, 2) + 's';
  586. }
  587. if (key == "useWhite") {
  588. useWhite = data[key];
  589. }
  590. if (key == "maxNetworks") {
  591. maxNetworks = parseInt(data.maxNetworks);
  592. return;
  593. }
  594. // Wifi
  595. if (key == "wifi") {
  596. var networks = data.wifi;
  597. for (var i in networks) {
  598. // add a new row
  599. var line = addNetwork();
  600. // fill in the blanks
  601. var wifi = data.wifi[i];
  602. Object.keys(wifi).forEach(function(key) {
  603. var element = $("input[name=" + key + "]", line);
  604. if (element.length) element.val(wifi[key]).attr("original", wifi[key]);
  605. });
  606. }
  607. return;
  608. }
  609. // Relay status
  610. if (key == "relayStatus") {
  611. var relays = data.relayStatus;
  612. createRelays(relays.length);
  613. for (var relayID in relays) {
  614. var element = $(".relayStatus[data=" + relayID + "]");
  615. if (element.length > 0) {
  616. element
  617. .prop("checked", relays[relayID])
  618. .iphoneStyle("refresh");
  619. }
  620. }
  621. return;
  622. }
  623. // Domoticz
  624. if (key == "dczRelayIdx") {
  625. var idxs = data.dczRelayIdx;
  626. createIdxs(idxs.length);
  627. for (var i in idxs) {
  628. var element = $(".dczRelayIdx[data=" + i + "]");
  629. if (element.length > 0) element.val(idxs[i]).attr("original", idxs[i]);
  630. }
  631. return;
  632. }
  633. // Messages
  634. if (key == "message") {
  635. window.alert(messages[data.message]);
  636. return;
  637. }
  638. // Enable options
  639. if (key.endsWith("Visible")) {
  640. var module = key.slice(0,-7);
  641. $(".module-" + module).show();
  642. return;
  643. }
  644. // Pre-process
  645. if (key == "network") {
  646. data.network = data.network.toUpperCase();
  647. }
  648. if (key == "mqttStatus") {
  649. data.mqttStatus = data.mqttStatus ? "CONNECTED" : "NOT CONNECTED";
  650. }
  651. if (key == "ntpStatus") {
  652. data.ntpStatus = data.ntpStatus ? "SYNC'D" : "NOT SYNC'D";
  653. }
  654. if (key == "tmpUnits") {
  655. $("span#tmpUnit").html(data[key] == 1 ? "ºF" : "ºC");
  656. }
  657. // Look for INPUTs
  658. var element = $("input[name=" + key + "]");
  659. if (element.length > 0) {
  660. if (element.attr('type') == 'checkbox') {
  661. element
  662. .prop("checked", data[key])
  663. .iphoneStyle("refresh");
  664. } else if (element.attr('type') == 'radio') {
  665. element.val([data[key]]);
  666. } else {
  667. var pre = element.attr("pre") || "";
  668. var post = element.attr("post") || "";
  669. element.val(pre + data[key] + post).attr("original", data[key]);
  670. }
  671. return;
  672. }
  673. // Look for SPANs
  674. var element = $("span[name=" + key + "]");
  675. if (element.length > 0) {
  676. var pre = element.attr("pre") || "";
  677. var post = element.attr("post") || "";
  678. element.html(pre + data[key] + post);
  679. return;
  680. }
  681. // Look for SELECTs
  682. var element = $("select[name=" + key + "]");
  683. if (element.length > 0) {
  684. element.val(data[key]).attr("original", data[key]);
  685. return;
  686. }
  687. });
  688. // Auto generate an APIKey if none defined yet
  689. if ($("input[name='apiKey']").val() == "") {
  690. generateAPIKey();
  691. }
  692. }
  693. function hasChanged() {
  694. var newValue, originalValue;
  695. if ($(this).attr('type') == 'checkbox') {
  696. newValue = $(this).prop("checked")
  697. originalValue = $(this).attr("original") == "true";
  698. } else {
  699. newValue = $(this).val();
  700. originalValue = $(this).attr("original");
  701. }
  702. var hasChanged = $(this).attr("hasChanged") || 0;
  703. var action = $(this).attr("action");
  704. if (typeof originalValue == 'undefined') return;
  705. if (action == 'none') return;
  706. if (newValue != originalValue) {
  707. if (hasChanged == 0) {
  708. ++numChanged;
  709. if (action == "reconnect") ++numReconnect;
  710. if (action == "reset") ++numReset;
  711. if (action == "reload") ++numReload;
  712. $(this).attr("hasChanged", 1);
  713. }
  714. } else {
  715. if (hasChanged == 1) {
  716. --numChanged;
  717. if (action == "reconnect") --numReconnect;
  718. if (action == "reset") --numReset;
  719. if (action == "reload") --numReload;
  720. $(this).attr("hasChanged", 0);
  721. }
  722. }
  723. }
  724. // -----------------------------------------------------------------------------
  725. // Init & connect
  726. // -----------------------------------------------------------------------------
  727. function connect(host) {
  728. if (typeof host === 'undefined') {
  729. host = window.location.href.replace('#', '');
  730. } else {
  731. if (!host.startsWith("http")) {
  732. host = 'http://' + host + '/';
  733. }
  734. }
  735. webhost = host;
  736. wshost = host.replace('http', 'ws') + 'ws';
  737. if (websock) websock.close();
  738. websock = new WebSocket(wshost);
  739. websock.onopen = function(evt) {
  740. console.log("Connected");
  741. };
  742. websock.onclose = function(evt) {
  743. console.log("Disconnected");
  744. };
  745. websock.onerror = function(evt) {
  746. console.log("Error: ", evt);
  747. };
  748. websock.onmessage = function(evt) {
  749. var data = getJson(evt.data);
  750. if (data) processData(data);
  751. };
  752. }
  753. function init() {
  754. initMessages();
  755. $("#menuLink").on('click', toggleMenu);
  756. $(".pure-menu-link").on('click', showPanel);
  757. $('progress').attr({ value: 0, max: 100 });
  758. $(".button-update").on('click', doUpdate);
  759. $(".button-update-password").on('click', doUpdatePassword);
  760. $(".button-reset").on('click', doReset);
  761. $(".button-reconnect").on('click', doReconnect);
  762. $(".button-settings-backup").on('click', doBackup);
  763. $(".button-settings-restore").on('click', doRestore);
  764. $('#uploader').on('change', onFileUpload);
  765. $(".button-upgrade").on('click', doUpgrade);
  766. $(".button-apikey").on('click', generateAPIKey);
  767. $(".button-upgrade-browse").on('click', function() {
  768. $("input[name='upgrade']")[0].click();
  769. return false;
  770. });
  771. $("input[name='upgrade']").change(function (){
  772. var fileName = $(this).val();
  773. $("input[name='filename']").val(fileName.replace(/^.*[\\\/]/, ''));
  774. });
  775. $(".button-add-network").on('click', function() {
  776. $("div.more", addNetwork()).toggle();
  777. });
  778. $(".button-ha-add").on('click', function() {
  779. websock.send(JSON.stringify({'action': 'ha_add', 'data': $("input[name='haPrefix']").val()}));
  780. });
  781. $(".button-ha-del").on('click', function() {
  782. websock.send(JSON.stringify({'action': 'ha_del', 'data': $("input[name='haPrefix']").val()}));
  783. });
  784. $(document).on('change', 'input', hasChanged);
  785. $(document).on('change', 'select', hasChanged);
  786. $.ajax({
  787. 'method': 'GET',
  788. 'url': window.location.href + 'auth'
  789. }).done(function(data) {
  790. connect();
  791. }).fail(function(){
  792. $("#credentials").show();
  793. });
  794. }
  795. $(init);