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.

458 lines
12 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
  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 doUpdate() {
  28. var form = $("#formSave");
  29. if (validateForm(form)) {
  30. var data = form.serializeArray();
  31. websock.send(JSON.stringify({'config': data}));
  32. $(".powExpected").val(0);
  33. $("input[name='powExpectedReset']")
  34. .prop("checked", false)
  35. .iphoneStyle("refresh");
  36. }
  37. return false;
  38. }
  39. function doUpdatePassword() {
  40. var form = $("#formPassword");
  41. if (validateForm(form)) {
  42. var data = form.serializeArray();
  43. websock.send(JSON.stringify({'config': data}));
  44. }
  45. return false;
  46. }
  47. function doReset() {
  48. var response = window.confirm("Are you sure you want to reset the device?");
  49. if (response == false) return false;
  50. websock.send(JSON.stringify({'action': 'reset'}));
  51. return false;
  52. }
  53. function doReconnect() {
  54. var response = window.confirm("Are you sure you want to disconnect from the current WIFI network?");
  55. if (response == false) return false;
  56. websock.send(JSON.stringify({'action': 'reconnect'}));
  57. return false;
  58. }
  59. function doToggle(element, value) {
  60. var relayID = parseInt(element.attr("data"));
  61. websock.send(JSON.stringify({'action': value ? 'on' : 'off', 'relayID': relayID}));
  62. return false;
  63. }
  64. function backupSettings() {
  65. document.getElementById('downloader').src = 'http://' + host + ':' + port + '/config';
  66. return false;
  67. }
  68. function onFileUpload(event) {
  69. var inputFiles = this.files;
  70. if (inputFiles == undefined || inputFiles.length == 0) return false;
  71. var inputFile = inputFiles[0];
  72. var response = window.confirm("Previous settings will be overwritten. Are you sure you want to restore this settings?");
  73. if (response == false) return false;
  74. var reader = new FileReader();
  75. reader.onload = function(e) {
  76. var data = getJson(e.target.result);
  77. if (data) {
  78. websock.send(JSON.stringify({'action': 'restore', 'data': data}));
  79. } else {
  80. alert("The file is not a configuration backup or is corrupted");
  81. }
  82. };
  83. reader.readAsText(inputFile);
  84. return false;
  85. }
  86. function restoreSettings() {
  87. if (typeof window.FileReader !== 'function') {
  88. alert("The file API isn't supported on this browser yet.");
  89. } else {
  90. $("#uploader").click();
  91. }
  92. return false;
  93. }
  94. function randomString(length, chars) {
  95. var mask = '';
  96. if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz';
  97. if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  98. if (chars.indexOf('#') > -1) mask += '0123456789';
  99. if (chars.indexOf('@') > -1) mask += 'ABCDEF';
  100. if (chars.indexOf('!') > -1) mask += '~`!@#$%^&*()_+-={}[]:";\'<>?,./|\\';
  101. var result = '';
  102. for (var i = length; i > 0; --i) result += mask[Math.round(Math.random() * (mask.length - 1))];
  103. return result;
  104. }
  105. function doGenerateAPIKey() {
  106. var apikey = randomString(16, '@#');
  107. $("input[name=\"apiKey\"]").val(apikey);
  108. return false;
  109. }
  110. function showPanel() {
  111. $(".panel").hide();
  112. $("#" + $(this).attr("data")).show();
  113. if ($("#layout").hasClass('active')) toggleMenu();
  114. $("input[type='checkbox']").iphoneStyle("calculateDimensions").iphoneStyle("refresh");
  115. };
  116. function toggleMenu() {
  117. $("#layout").toggleClass('active');
  118. $("#menu").toggleClass('active');
  119. $("#menuLink").toggleClass('active');
  120. }
  121. function createRelays(count) {
  122. var current = $("#relays > div").length;
  123. if (current > 0) return;
  124. var template = $("#relayTemplate .pure-g")[0];
  125. for (var relayID=0; relayID<count; relayID++) {
  126. var line = $(template).clone();
  127. $(line).find("input").each(function() {
  128. $(this).attr("data", relayID);
  129. });
  130. if (count > 1) $(".relay_id", line).html(" " + (relayID+1));
  131. line.appendTo("#relays");
  132. $(":checkbox", line).iphoneStyle({
  133. onChange: doToggle,
  134. resizeContainer: true,
  135. resizeHandle: true,
  136. checkedLabel: 'ON',
  137. uncheckedLabel: 'OFF'
  138. });
  139. }
  140. }
  141. function createIdxs(count) {
  142. var current = $("#idxs > div").length;
  143. if (current > 0) return;
  144. var template = $("#idxTemplate .pure-g")[0];
  145. for (var id=0; id<count; id++) {
  146. var line = $(template).clone();
  147. $(line).find("input").each(function() {
  148. $(this).attr("data", id).attr("tabindex", 40+id);
  149. });
  150. if (count > 1) $(".id", line).html(" " + id);
  151. line.appendTo("#idxs");
  152. }
  153. }
  154. function delNetwork() {
  155. var parent = $(this).parents(".pure-g");
  156. $(parent).remove();
  157. }
  158. function moreNetwork() {
  159. var parent = $(this).parents(".pure-g");
  160. $("div.more", parent).toggle();
  161. }
  162. function addNetwork() {
  163. var numNetworks = $("#networks > div").length;
  164. if (numNetworks >= maxNetworks) {
  165. alert("Max number of networks reached");
  166. return;
  167. }
  168. var tabindex = 200 + numNetworks * 10;
  169. var template = $("#networkTemplate").children();
  170. var line = $(template).clone();
  171. $(line).find("input").each(function() {
  172. $(this).attr("tabindex", tabindex++);
  173. });
  174. $(line).find(".button-del-network").on('click', delNetwork);
  175. $(line).find(".button-more-network").on('click', moreNetwork);
  176. line.appendTo("#networks");
  177. return line;
  178. }
  179. function forgetCredentials() {
  180. $.ajax({
  181. 'method': 'GET',
  182. 'url': '/',
  183. 'async': false,
  184. 'username': "logmeout",
  185. 'password': "123456",
  186. 'headers': { "Authorization": "Basic xxx" }
  187. }).done(function(data) {
  188. return false;
  189. // If we don't get an error, we actually got an error as we expect an 401!
  190. }).fail(function(){
  191. // We expect to get an 401 Unauthorized error! In this case we are successfully
  192. // logged out and we redirect the user.
  193. return true;
  194. });
  195. }
  196. function processData(data) {
  197. // title
  198. if ("app" in data) {
  199. var title = data.app;
  200. if ("version" in data) {
  201. title = title + " " + data.version;
  202. }
  203. $(".pure-menu-heading").html(title);
  204. if ("hostname" in data) {
  205. title = data.hostname + " - " + title;
  206. }
  207. document.title = title;
  208. }
  209. Object.keys(data).forEach(function(key) {
  210. // Web Modes
  211. if (key == "webMode") {
  212. password = data.webMode == 1;
  213. $("#layout").toggle(data.webMode == 0);
  214. $("#password").toggle(data.webMode == 1);
  215. $("#credentials").hide();
  216. }
  217. // Actions
  218. if (key == "action") {
  219. if (data.action == "reload") {
  220. if (password) forgetCredentials();
  221. setTimeout(function() {
  222. window.location = "/";
  223. }, 1000);
  224. }
  225. return;
  226. }
  227. if (key == "maxNetworks") {
  228. maxNetworks = parseInt(data.maxNetworks);
  229. return;
  230. }
  231. // Wifi
  232. if (key == "wifi") {
  233. var networks = data.wifi;
  234. for (var i in networks) {
  235. // add a new row
  236. var line = addNetwork();
  237. // fill in the blanks
  238. var wifi = data.wifi[i];
  239. Object.keys(wifi).forEach(function(key) {
  240. var element = $("input[name=" + key + "]", line);
  241. if (element.length) element.val(wifi[key]);
  242. });
  243. }
  244. return;
  245. }
  246. // Relay status
  247. if (key == "relayStatus") {
  248. var relays = data.relayStatus;
  249. createRelays(relays.length);
  250. for (var relayID in relays) {
  251. var element = $(".relayStatus[data=" + relayID + "]");
  252. if (element.length > 0) {
  253. element
  254. .prop("checked", relays[relayID])
  255. .iphoneStyle("refresh");
  256. }
  257. }
  258. return;
  259. }
  260. // Domoticz
  261. if (key == "dczRelayIdx") {
  262. var idxs = data.dczRelayIdx;
  263. createIdxs(idxs.length);
  264. for (var i in idxs) {
  265. var element = $(".dczRelayIdx[data=" + i + "]");
  266. if (element.length > 0) element.val(idxs[i]);
  267. }
  268. return;
  269. }
  270. // Messages
  271. if (key == "message") {
  272. window.alert(data.message);
  273. return;
  274. }
  275. // Enable options
  276. if (key.endsWith("Visible")) {
  277. var module = key.slice(0,-7);
  278. $(".module-" + module).show();
  279. return;
  280. }
  281. // Pre-process
  282. if (key == "network") {
  283. data.network = data.network.toUpperCase();
  284. }
  285. if (key == "mqttStatus") {
  286. data.mqttStatus = data.mqttStatus ? "CONNECTED" : "NOT CONNECTED";
  287. }
  288. if (key == "tmpUnits") {
  289. $("span#tmpUnit").html(data[key] == 1 ? "ºF" : "ºC");
  290. }
  291. // Look for INPUTs
  292. var element = $("input[name=" + key + "]");
  293. if (element.length > 0) {
  294. if (element.attr('type') == 'checkbox') {
  295. element
  296. .prop("checked", data[key])
  297. .iphoneStyle("refresh");
  298. } else if (element.attr('type') == 'radio') {
  299. element.val([data[key]]);
  300. } else {
  301. element.val(data[key]);
  302. }
  303. return;
  304. }
  305. // Look for SELECTs
  306. var element = $("select[name=" + key + "]");
  307. if (element.length > 0) {
  308. element.val(data[key]);
  309. return;
  310. }
  311. });
  312. // Auto generate an APIKey if none defined yet
  313. if ($("input[name='apiKey']").val() == "") {
  314. doGenerateAPIKey();
  315. }
  316. }
  317. function getJson(str) {
  318. try {
  319. return JSON.parse(str);
  320. } catch (e) {
  321. return false;
  322. }
  323. }
  324. function connect(h, p) {
  325. if (typeof h === 'undefined') {
  326. h = window.location.hostname;
  327. }
  328. if (typeof p === 'undefined') {
  329. p = location.port;
  330. }
  331. host = h;
  332. port = p;
  333. if (websock) websock.close();
  334. websock = new WebSocket('ws://' + host + ':' + port + '/ws');
  335. websock.onopen = function(evt) {
  336. console.log("Connected");
  337. };
  338. websock.onclose = function(evt) {
  339. console.log("Disconnected");
  340. };
  341. websock.onerror = function(evt) {
  342. console.log("Error: ", evt);
  343. };
  344. websock.onmessage = function(evt) {
  345. var data = getJson(evt.data);
  346. if (data) processData(data);
  347. };
  348. }
  349. function init() {
  350. $("#menuLink").on('click', toggleMenu);
  351. $(".button-update").on('click', doUpdate);
  352. $(".button-update-password").on('click', doUpdatePassword);
  353. $(".button-reset").on('click', doReset);
  354. $(".button-reconnect").on('click', doReconnect);
  355. $(".button-settings-backup").on('click', backupSettings);
  356. $(".button-settings-restore").on('click', restoreSettings);
  357. $('#uploader').on('change', onFileUpload);
  358. $(".button-apikey").on('click', doGenerateAPIKey);
  359. $(".pure-menu-link").on('click', showPanel);
  360. $(".button-add-network").on('click', function() {
  361. $("div.more", addNetwork()).toggle();
  362. });
  363. var host = window.location.hostname;
  364. var port = location.port;
  365. $.ajax({
  366. 'method': 'GET',
  367. 'url': 'http://' + host + ':' + port + '/auth'
  368. }).done(function(data) {
  369. connect();
  370. }).fail(function(){
  371. $("#credentials").show();
  372. });
  373. }
  374. $(init);