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.

656 lines
18 KiB

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