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.

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