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.

744 lines
20 KiB

8 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 host;
  5. var port;
  6. var useWhite = false;
  7. // http://www.the-art-of-web.com/javascript/validate-password/
  8. function checkPassword(str) {
  9. // at least one number, one lowercase and one uppercase letter
  10. // at least eight characters that are letters, numbers or the underscore
  11. var re = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])\w{8,}$/;
  12. return re.test(str);
  13. }
  14. function validateForm(form) {
  15. // password
  16. var adminPass1 = $("input[name='adminPass1']", form).val();
  17. if (adminPass1.length > 0 && !checkPassword(adminPass1)) {
  18. alert("The password you have entered is not valid, it must have at least 8 characters, 1 lower and 1 uppercase and 1 number!");
  19. return false;
  20. }
  21. var adminPass2 = $("input[name='adminPass2']", form).val();
  22. if (adminPass1 != adminPass2) {
  23. alert("Passwords are different!");
  24. return false;
  25. }
  26. return true;
  27. }
  28. function valueSet(data, name, value) {
  29. for (var i in data) {
  30. if (data[i]['name'] == name) {
  31. data[i]['value'] = value;
  32. return;
  33. }
  34. }
  35. data.push({'name': name, 'value': value});
  36. }
  37. function doUpdate() {
  38. var form = $("#formSave");
  39. if (validateForm(form)) {
  40. // Get data
  41. var data = form.serializeArray();
  42. // Post-process
  43. delete(data['filename']);
  44. $("input[type='checkbox']").each(function() {
  45. var name = $(this).attr("name");
  46. if (name) {
  47. valueSet(data, name, $(this).is(':checked') ? 1 : 0);
  48. }
  49. });
  50. websock.send(JSON.stringify({'config': data}));
  51. $(".powExpected").val(0);
  52. $("input[name='powExpectedReset']")
  53. .prop("checked", false)
  54. .iphoneStyle("refresh");
  55. }
  56. return false;
  57. }
  58. function doUpgrade() {
  59. var contents = $("input[name='upgrade']")[0].files[0];
  60. if (typeof contents == 'undefined') {
  61. alert("First you have to select a file from your computer.");
  62. return false;
  63. }
  64. var filename = $("input[name='upgrade']").val().split('\\').pop();
  65. var data = new FormData();
  66. data.append('upgrade', contents, filename);
  67. $.ajax({
  68. // Your server script to process the upload
  69. url: 'http://' + host + ':' + port + '/upgrade',
  70. type: 'POST',
  71. // Form data
  72. data: data,
  73. // Tell jQuery not to process data or worry about content-type
  74. // You *must* include these options!
  75. cache: false,
  76. contentType: false,
  77. processData: false,
  78. success: function(data, text) {
  79. $("#upgrade-progress").hide();
  80. if (data == 'OK') {
  81. alert("Firmware image uploaded, board rebooting. This page will be refreshed in 5 seconds.");
  82. setTimeout(function() {
  83. window.location = "/";
  84. }, 5000);
  85. } else {
  86. alert("There was an error trying to upload the new image, please try again.");
  87. }
  88. },
  89. // Custom XMLHttpRequest
  90. xhr: function() {
  91. $("#upgrade-progress").show();
  92. var myXhr = $.ajaxSettings.xhr();
  93. if (myXhr.upload) {
  94. // For handling the progress of the upload
  95. myXhr.upload.addEventListener('progress', function(e) {
  96. if (e.lengthComputable) {
  97. $('progress').attr({ value: e.loaded, max: e.total });
  98. }
  99. } , false);
  100. }
  101. return myXhr;
  102. },
  103. });
  104. return false;
  105. }
  106. function doUpdatePassword() {
  107. var form = $("#formPassword");
  108. if (validateForm(form)) {
  109. var data = form.serializeArray();
  110. websock.send(JSON.stringify({'config': data}));
  111. }
  112. return false;
  113. }
  114. function doReset() {
  115. var response = window.confirm("Are you sure you want to reset the device?");
  116. if (response == false) return false;
  117. websock.send(JSON.stringify({'action': 'reset'}));
  118. return false;
  119. }
  120. function doReconnect() {
  121. var response = window.confirm("Are you sure you want to disconnect from the current WIFI network?");
  122. if (response == false) return false;
  123. websock.send(JSON.stringify({'action': 'reconnect'}));
  124. return false;
  125. }
  126. function doToggle(element, value) {
  127. var relayID = parseInt(element.attr("data"));
  128. websock.send(JSON.stringify({'action': 'relay', 'data': { 'id': relayID, 'status': value ? 1 : 0 }}));
  129. return false;
  130. }
  131. function backupSettings() {
  132. document.getElementById('downloader').src = 'http://' + host + ':' + port + '/config';
  133. return false;
  134. }
  135. function onFileUpload(event) {
  136. var inputFiles = this.files;
  137. if (inputFiles == undefined || inputFiles.length == 0) return false;
  138. var inputFile = inputFiles[0];
  139. this.value = "";
  140. var response = window.confirm("Previous settings will be overwritten. Are you sure you want to restore this settings?");
  141. if (response == false) return false;
  142. var reader = new FileReader();
  143. reader.onload = function(e) {
  144. var data = getJson(e.target.result);
  145. if (data) {
  146. websock.send(JSON.stringify({'action': 'restore', 'data': data}));
  147. } else {
  148. alert("The file is not a configuration backup or is corrupted");
  149. }
  150. };
  151. reader.readAsText(inputFile);
  152. return false;
  153. }
  154. function restoreSettings() {
  155. if (typeof window.FileReader !== 'function') {
  156. alert("The file API isn't supported on this browser yet.");
  157. } else {
  158. $("#uploader").click();
  159. }
  160. return false;
  161. }
  162. function randomString(length, chars) {
  163. var mask = '';
  164. if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz';
  165. if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  166. if (chars.indexOf('#') > -1) mask += '0123456789';
  167. if (chars.indexOf('@') > -1) mask += 'ABCDEF';
  168. if (chars.indexOf('!') > -1) mask += '~`!@#$%^&*()_+-={}[]:";\'<>?,./|\\';
  169. var result = '';
  170. for (var i = length; i > 0; --i) result += mask[Math.round(Math.random() * (mask.length - 1))];
  171. return result;
  172. }
  173. function doGenerateAPIKey() {
  174. var apikey = randomString(16, '@#');
  175. $("input[name=\"apiKey\"]").val(apikey);
  176. return false;
  177. }
  178. function showPanel() {
  179. $(".panel").hide();
  180. $("#" + $(this).attr("data")).show();
  181. if ($("#layout").hasClass('active')) toggleMenu();
  182. $("input[type='checkbox']").iphoneStyle("calculateDimensions").iphoneStyle("refresh");
  183. };
  184. function toggleMenu() {
  185. $("#layout").toggleClass('active');
  186. $("#menu").toggleClass('active');
  187. $("#menuLink").toggleClass('active');
  188. }
  189. function createRelays(count) {
  190. var current = $("#relays > div").length;
  191. if (current > 0) return;
  192. var template = $("#relayTemplate .pure-g")[0];
  193. for (var relayID=0; relayID<count; relayID++) {
  194. var line = $(template).clone();
  195. $(line).find("input").each(function() {
  196. $(this).attr("data", relayID);
  197. });
  198. if (count > 1) $(".relay_id", line).html(" " + (relayID+1));
  199. line.appendTo("#relays");
  200. $(":checkbox", line).iphoneStyle({
  201. onChange: doToggle,
  202. resizeContainer: true,
  203. resizeHandle: true,
  204. checkedLabel: 'ON',
  205. uncheckedLabel: 'OFF'
  206. });
  207. }
  208. }
  209. function createIdxs(count) {
  210. var current = $("#idxs > div").length;
  211. if (current > 0) return;
  212. var template = $("#idxTemplate .pure-g")[0];
  213. for (var id=0; id<count; id++) {
  214. var line = $(template).clone();
  215. $(line).find("input").each(function() {
  216. $(this).attr("data", id).attr("tabindex", 40+id);
  217. });
  218. if (count > 1) $(".id", line).html(" " + id);
  219. line.appendTo("#idxs");
  220. }
  221. }
  222. function delNetwork() {
  223. var parent = $(this).parents(".pure-g");
  224. $(parent).remove();
  225. }
  226. function moreNetwork() {
  227. var parent = $(this).parents(".pure-g");
  228. $("div.more", parent).toggle();
  229. }
  230. function addNetwork() {
  231. var numNetworks = $("#networks > div").length;
  232. if (numNetworks >= maxNetworks) {
  233. alert("Max number of networks reached");
  234. return;
  235. }
  236. var tabindex = 200 + numNetworks * 10;
  237. var template = $("#networkTemplate").children();
  238. var line = $(template).clone();
  239. $(line).find("input").each(function() {
  240. $(this).attr("tabindex", tabindex++);
  241. });
  242. $(line).find(".button-del-network").on('click', delNetwork);
  243. $(line).find(".button-more-network").on('click', moreNetwork);
  244. line.appendTo("#networks");
  245. return line;
  246. }
  247. function initColor() {
  248. // check if already initialized
  249. var done = $("#colors > div").length;
  250. if (done > 0) return;
  251. // add template
  252. var template = $("#colorTemplate").children();
  253. var line = $(template).clone();
  254. line.appendTo("#colors");
  255. // init color wheel
  256. $('input[name="color"]').wheelColorPicker({
  257. sliders: 'wrgbp'
  258. }).on('sliderup', function() {
  259. var value = $(this).wheelColorPicker('getValue', 'css');
  260. websock.send(JSON.stringify({'action': 'color', 'data' : value}));
  261. });
  262. // init bright slider
  263. noUiSlider.create($("#brightness").get(0), {
  264. start: 255,
  265. connect: [true, false],
  266. tooltips: true,
  267. format: {
  268. to: function (value) { return parseInt(value); },
  269. from: function (value) { return value; }
  270. },
  271. orientation: "horizontal",
  272. range: { 'min': 0, 'max': 255}
  273. }).on("change", function() {
  274. var value = parseInt(this.get());
  275. websock.send(JSON.stringify({'action': 'brightness', 'data' : value}));
  276. });
  277. }
  278. function initChannels(num) {
  279. // check if already initialized
  280. var done = $("#channels > div").length > 0;
  281. if (done) return;
  282. // does it have color channels?
  283. var colors = $("#colors > div").length > 0;
  284. // calculate channels to create
  285. var max = num;
  286. if (colors) {
  287. max = num % 3;
  288. if ((max > 0) & useWhite) max--;
  289. }
  290. var start = num - max;
  291. // add templates
  292. var template = $("#channelTemplate").children();
  293. for (var i=0; i<max; i++) {
  294. var channel_id = start + i;
  295. var line = $(template).clone();
  296. $(".slider", line).attr("data", channel_id);
  297. $("label", line).html("Channel " + (channel_id + 1));
  298. noUiSlider.create($(".slider", line).get(0), {
  299. start: 0,
  300. connect: [true, false],
  301. tooltips: true,
  302. format: {
  303. to: function (value) { return parseInt(value); },
  304. from: function (value) { return value; }
  305. },
  306. orientation: "horizontal",
  307. range: { 'min': 0, 'max': 255 }
  308. }).on("change", function() {
  309. var id = $(this.target).attr("data");
  310. var value = parseInt(this.get());
  311. websock.send(JSON.stringify({'action': 'channel', 'data': { 'id': id, 'value': value }}));
  312. });
  313. line.appendTo("#channels");
  314. }
  315. }
  316. function addRfbNode() {
  317. var numNodes = $("#rfbNodes > fieldset").length;
  318. var template = $("#rfbNodeTemplate").children();
  319. var line = $(template).clone();
  320. var status = true;
  321. $("span", line).html(numNodes+1);
  322. $(line).find("input").each(function() {
  323. $(this).attr("data_id", numNodes);
  324. $(this).attr("data_status", status ? 1 : 0);
  325. status = !status;
  326. });
  327. $(line).find(".button-rfb-learn").on('click', rfbLearn);
  328. $(line).find(".button-rfb-forget").on('click', rfbForget);
  329. $(line).find(".button-rfb-send").on('click', rfbSend);
  330. line.appendTo("#rfbNodes");
  331. return line;
  332. }
  333. function rfbLearn() {
  334. var parent = $(this).parents(".pure-g");
  335. var input = $("input", parent);
  336. websock.send(JSON.stringify({'action': 'rfblearn', 'data' : {'id' : input.attr("data_id"), 'status': input.attr("data_status")}}));
  337. }
  338. function rfbForget() {
  339. var parent = $(this).parents(".pure-g");
  340. var input = $("input", parent);
  341. websock.send(JSON.stringify({'action': 'rfbforget', 'data' : {'id' : input.attr("data_id"), 'status': input.attr("data_status")}}));
  342. }
  343. function rfbSend() {
  344. var parent = $(this).parents(".pure-g");
  345. var input = $("input", parent);
  346. websock.send(JSON.stringify({'action': 'rfbsend', 'data' : {'id' : input.attr("data_id"), 'status': input.attr("data_status"), 'data': input.val()}}));
  347. }
  348. function forgetCredentials() {
  349. $.ajax({
  350. 'method': 'GET',
  351. 'url': '/',
  352. 'async': false,
  353. 'username': "logmeout",
  354. 'password': "123456",
  355. 'headers': { "Authorization": "Basic xxx" }
  356. }).done(function(data) {
  357. return false;
  358. // If we don't get an error, we actually got an error as we expect an 401!
  359. }).fail(function(){
  360. // We expect to get an 401 Unauthorized error! In this case we are successfully
  361. // logged out and we redirect the user.
  362. return true;
  363. });
  364. }
  365. function processData(data) {
  366. // title
  367. if ("app" in data) {
  368. var title = data.app;
  369. if ("version" in data) {
  370. title = title + " " + data.version;
  371. }
  372. $(".pure-menu-heading").html(title);
  373. if ("hostname" in data) {
  374. title = data.hostname + " - " + title;
  375. }
  376. document.title = title;
  377. }
  378. Object.keys(data).forEach(function(key) {
  379. // Web Modes
  380. if (key == "webMode") {
  381. password = data.webMode == 1;
  382. $("#layout").toggle(data.webMode == 0);
  383. $("#password").toggle(data.webMode == 1);
  384. $("#credentials").hide();
  385. }
  386. // Actions
  387. if (key == "action") {
  388. if (data.action == "reload") {
  389. if (password) forgetCredentials();
  390. setTimeout(function() {
  391. window.location = "/";
  392. }, 1000);
  393. }
  394. if (data.action == "rfbLearn") {
  395. // Nothing to do?
  396. }
  397. if (data.action == "rfbTimeout") {
  398. // Nothing to do?
  399. }
  400. return;
  401. }
  402. if (key == "rfbCount") {
  403. for (var i=0; i<data.rfbCount; i++) addRfbNode();
  404. return;
  405. }
  406. if (key == "rfb") {
  407. var nodes = data.rfb;
  408. for (var i in nodes) {
  409. var node = nodes[i];
  410. var element = $("input[name=rfbcode][data_id=" + node["id"] + "][data_status=" + node["status"] + "]");
  411. if (element.length) element.val(node["data"]);
  412. }
  413. return;
  414. }
  415. if (key == "color") {
  416. initColor();
  417. $("input[name='color']").wheelColorPicker('setValue', data[key], true);
  418. return;
  419. }
  420. if (key == "brightness") {
  421. var slider = $("#brightness");
  422. if (slider.length) slider.get(0).noUiSlider.set(data[key]);
  423. return;
  424. }
  425. if (key == "channels") {
  426. var len = data[key].length;
  427. initChannels(len);
  428. for (var i=0; i<len; i++) {
  429. var slider = $("div.channels[data=" + i + "]");
  430. if (slider.length) slider.get(0).noUiSlider.set(data[key][i]);
  431. }
  432. return;
  433. }
  434. if (key == "useWhite") {
  435. useWhite = data[key];
  436. }
  437. if (key == "maxNetworks") {
  438. maxNetworks = parseInt(data.maxNetworks);
  439. return;
  440. }
  441. // Wifi
  442. if (key == "wifi") {
  443. var networks = data.wifi;
  444. for (var i in networks) {
  445. // add a new row
  446. var line = addNetwork();
  447. // fill in the blanks
  448. var wifi = data.wifi[i];
  449. Object.keys(wifi).forEach(function(key) {
  450. var element = $("input[name=" + key + "]", line);
  451. if (element.length) element.val(wifi[key]);
  452. });
  453. }
  454. return;
  455. }
  456. // Relay status
  457. if (key == "relayStatus") {
  458. var relays = data.relayStatus;
  459. createRelays(relays.length);
  460. for (var relayID in relays) {
  461. var element = $(".relayStatus[data=" + relayID + "]");
  462. if (element.length > 0) {
  463. element
  464. .prop("checked", relays[relayID])
  465. .iphoneStyle("refresh");
  466. }
  467. }
  468. return;
  469. }
  470. // Domoticz
  471. if (key == "dczRelayIdx") {
  472. var idxs = data.dczRelayIdx;
  473. createIdxs(idxs.length);
  474. for (var i in idxs) {
  475. var element = $(".dczRelayIdx[data=" + i + "]");
  476. if (element.length > 0) element.val(idxs[i]);
  477. }
  478. return;
  479. }
  480. // Messages
  481. if (key == "message") {
  482. window.alert(data.message);
  483. return;
  484. }
  485. // Enable options
  486. if (key.endsWith("Visible")) {
  487. var module = key.slice(0,-7);
  488. $(".module-" + module).show();
  489. return;
  490. }
  491. // Pre-process
  492. if (key == "network") {
  493. data.network = data.network.toUpperCase();
  494. }
  495. if (key == "mqttStatus") {
  496. data.mqttStatus = data.mqttStatus ? "CONNECTED" : "NOT CONNECTED";
  497. }
  498. if (key == "ntpStatus") {
  499. data.ntpStatus = data.ntpStatus ? "SYNC'D" : "NOT SYNC'D";
  500. }
  501. if (key == "tmpUnits") {
  502. $("span#tmpUnit").html(data[key] == 1 ? "ºF" : "ºC");
  503. }
  504. // Look for INPUTs
  505. var element = $("input[name=" + key + "]");
  506. if (element.length > 0) {
  507. if (element.attr('type') == 'checkbox') {
  508. element
  509. .prop("checked", data[key])
  510. .iphoneStyle("refresh");
  511. } else if (element.attr('type') == 'radio') {
  512. element.val([data[key]]);
  513. } else {
  514. var pre = element.attr("pre") || "";
  515. var post = element.attr("post") || "";
  516. element.val(pre + data[key] + post);
  517. }
  518. return;
  519. }
  520. // Look for SPANs
  521. var element = $("span[name=" + key + "]");
  522. if (element.length > 0) {
  523. var pre = element.attr("pre") || "";
  524. var post = element.attr("post") || "";
  525. element.html(pre + data[key] + post);
  526. return;
  527. }
  528. // Look for SELECTs
  529. var element = $("select[name=" + key + "]");
  530. if (element.length > 0) {
  531. element.val(data[key]);
  532. return;
  533. }
  534. });
  535. // Auto generate an APIKey if none defined yet
  536. if ($("input[name='apiKey']").val() == "") {
  537. doGenerateAPIKey();
  538. }
  539. }
  540. function getJson(str) {
  541. try {
  542. return JSON.parse(str);
  543. } catch (e) {
  544. return false;
  545. }
  546. }
  547. function connect(h, p) {
  548. if (typeof h === 'undefined') {
  549. h = window.location.hostname;
  550. }
  551. if (typeof p === 'undefined') {
  552. p = location.port;
  553. }
  554. host = h;
  555. port = p;
  556. if (websock) websock.close();
  557. websock = new WebSocket('ws://' + host + ':' + port + '/ws');
  558. websock.onopen = function(evt) {
  559. console.log("Connected");
  560. };
  561. websock.onclose = function(evt) {
  562. console.log("Disconnected");
  563. };
  564. websock.onerror = function(evt) {
  565. console.log("Error: ", evt);
  566. };
  567. websock.onmessage = function(evt) {
  568. var data = getJson(evt.data);
  569. if (data) processData(data);
  570. };
  571. }
  572. function init() {
  573. $("#menuLink").on('click', toggleMenu);
  574. $(".button-update").on('click', doUpdate);
  575. $(".button-update-password").on('click', doUpdatePassword);
  576. $(".button-reset").on('click', doReset);
  577. $(".button-reconnect").on('click', doReconnect);
  578. $(".button-settings-backup").on('click', backupSettings);
  579. $(".button-settings-restore").on('click', restoreSettings);
  580. $('#uploader').on('change', onFileUpload);
  581. $(".button-apikey").on('click', doGenerateAPIKey);
  582. $(".button-upgrade").on('click', doUpgrade);
  583. $(".button-upgrade-browse").on('click', function() {
  584. $("input[name='upgrade']")[0].click();
  585. return false;
  586. });
  587. $("input[name='upgrade']").change(function (){
  588. var fileName = $(this).val();
  589. $("input[name='filename']").val(fileName.replace(/^.*[\\\/]/, ''));
  590. });
  591. $('progress').attr({ value: 0, max: 100 });
  592. $(".pure-menu-link").on('click', showPanel);
  593. $(".button-add-network").on('click', function() {
  594. $("div.more", addNetwork()).toggle();
  595. });
  596. var host = window.location.hostname;
  597. var port = location.port;
  598. $.ajax({
  599. 'method': 'GET',
  600. 'url': 'http://' + host + ':' + port + '/auth'
  601. }).done(function(data) {
  602. connect();
  603. }).fail(function(){
  604. $("#credentials").show();
  605. });
  606. }
  607. $(init);