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.

2387 lines
67 KiB

8 years ago
7 years ago
providers: relays, lights and buttons refactoring (#2414) - gpio module now tracks the known providers (right now, hardware and mcp expander) - refactored relay struct to use 'Provider' implementing setup,notify,change,boot instead of just BasePin actions - refactored button module to use gpio provider instead of referencing types itself - removed dual & stm code from buttons, migrate both to relay module - added status notify and change callbacks for relayStatus (i.e. 'notify' when relay status was called, but not changed. and 'changed' when it did) - relays runtime configuration keys - relay command now shows configured relays and current & target statuses - refactor the code using relayStatus(0, blah) under LIGHT_PROVIDER check to use lightState instead - remove rfbridge code form relay module. implement through a basic state listener in the rfbridge module, depend on RELAY_SUPPORT - allow to bind rf codes to real relays - drop tuya-specific lights provider, remove tuya code from relays and lights modules - integrate tuya via relay listeners and providers, use lights custom provider - implement channel transitions for tuya. disabled by default, and transition time and step are overridden to 2000 + 100. needs to be set to some value below the total time (i.e. `total transition time / step time == number of steps`, we need to figure out a correct time that serial comms could handle) - lights custom provider (global, not per-pin) and state listeners - remove lights code from relay module. implement through providers & listeners in the lights module, depend on RELAY_SUPPORT - lights per-channel relay provider (unused atm), depend on RELAY_SUPPORT - refactored channel transition - calculate step only once, make sure time + step values are sane, generate quick transitions with very small delay (10ms hardcoded) for transitions during OFF state i.e. we no longer waste 500ms (or whatever transition time is set to) on boot doing nothing - transition time + step parameter for the lightUpdate - report mask parameter for the lightUpdate - minor fixes across the board resolve #2222
3 years ago
providers: relays, lights and buttons refactoring (#2414) - gpio module now tracks the known providers (right now, hardware and mcp expander) - refactored relay struct to use 'Provider' implementing setup,notify,change,boot instead of just BasePin actions - refactored button module to use gpio provider instead of referencing types itself - removed dual & stm code from buttons, migrate both to relay module - added status notify and change callbacks for relayStatus (i.e. 'notify' when relay status was called, but not changed. and 'changed' when it did) - relays runtime configuration keys - relay command now shows configured relays and current & target statuses - refactor the code using relayStatus(0, blah) under LIGHT_PROVIDER check to use lightState instead - remove rfbridge code form relay module. implement through a basic state listener in the rfbridge module, depend on RELAY_SUPPORT - allow to bind rf codes to real relays - drop tuya-specific lights provider, remove tuya code from relays and lights modules - integrate tuya via relay listeners and providers, use lights custom provider - implement channel transitions for tuya. disabled by default, and transition time and step are overridden to 2000 + 100. needs to be set to some value below the total time (i.e. `total transition time / step time == number of steps`, we need to figure out a correct time that serial comms could handle) - lights custom provider (global, not per-pin) and state listeners - remove lights code from relay module. implement through providers & listeners in the lights module, depend on RELAY_SUPPORT - lights per-channel relay provider (unused atm), depend on RELAY_SUPPORT - refactored channel transition - calculate step only once, make sure time + step values are sane, generate quick transitions with very small delay (10ms hardcoded) for transitions during OFF state i.e. we no longer waste 500ms (or whatever transition time is set to) on boot doing nothing - transition time + step parameter for the lightUpdate - report mask parameter for the lightUpdate - minor fixes across the board resolve #2222
3 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
providers: relays, lights and buttons refactoring (#2414) - gpio module now tracks the known providers (right now, hardware and mcp expander) - refactored relay struct to use 'Provider' implementing setup,notify,change,boot instead of just BasePin actions - refactored button module to use gpio provider instead of referencing types itself - removed dual & stm code from buttons, migrate both to relay module - added status notify and change callbacks for relayStatus (i.e. 'notify' when relay status was called, but not changed. and 'changed' when it did) - relays runtime configuration keys - relay command now shows configured relays and current & target statuses - refactor the code using relayStatus(0, blah) under LIGHT_PROVIDER check to use lightState instead - remove rfbridge code form relay module. implement through a basic state listener in the rfbridge module, depend on RELAY_SUPPORT - allow to bind rf codes to real relays - drop tuya-specific lights provider, remove tuya code from relays and lights modules - integrate tuya via relay listeners and providers, use lights custom provider - implement channel transitions for tuya. disabled by default, and transition time and step are overridden to 2000 + 100. needs to be set to some value below the total time (i.e. `total transition time / step time == number of steps`, we need to figure out a correct time that serial comms could handle) - lights custom provider (global, not per-pin) and state listeners - remove lights code from relay module. implement through providers & listeners in the lights module, depend on RELAY_SUPPORT - lights per-channel relay provider (unused atm), depend on RELAY_SUPPORT - refactored channel transition - calculate step only once, make sure time + step values are sane, generate quick transitions with very small delay (10ms hardcoded) for transitions during OFF state i.e. we no longer waste 500ms (or whatever transition time is set to) on boot doing nothing - transition time + step parameter for the lightUpdate - report mask parameter for the lightUpdate - minor fixes across the board resolve #2222
3 years ago
6 years ago
6 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
8 years ago
8 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
providers: relays, lights and buttons refactoring (#2414) - gpio module now tracks the known providers (right now, hardware and mcp expander) - refactored relay struct to use 'Provider' implementing setup,notify,change,boot instead of just BasePin actions - refactored button module to use gpio provider instead of referencing types itself - removed dual & stm code from buttons, migrate both to relay module - added status notify and change callbacks for relayStatus (i.e. 'notify' when relay status was called, but not changed. and 'changed' when it did) - relays runtime configuration keys - relay command now shows configured relays and current & target statuses - refactor the code using relayStatus(0, blah) under LIGHT_PROVIDER check to use lightState instead - remove rfbridge code form relay module. implement through a basic state listener in the rfbridge module, depend on RELAY_SUPPORT - allow to bind rf codes to real relays - drop tuya-specific lights provider, remove tuya code from relays and lights modules - integrate tuya via relay listeners and providers, use lights custom provider - implement channel transitions for tuya. disabled by default, and transition time and step are overridden to 2000 + 100. needs to be set to some value below the total time (i.e. `total transition time / step time == number of steps`, we need to figure out a correct time that serial comms could handle) - lights custom provider (global, not per-pin) and state listeners - remove lights code from relay module. implement through providers & listeners in the lights module, depend on RELAY_SUPPORT - lights per-channel relay provider (unused atm), depend on RELAY_SUPPORT - refactored channel transition - calculate step only once, make sure time + step values are sane, generate quick transitions with very small delay (10ms hardcoded) for transitions during OFF state i.e. we no longer waste 500ms (or whatever transition time is set to) on boot doing nothing - transition time + step parameter for the lightUpdate - report mask parameter for the lightUpdate - minor fixes across the board resolve #2222
3 years ago
providers: relays, lights and buttons refactoring (#2414) - gpio module now tracks the known providers (right now, hardware and mcp expander) - refactored relay struct to use 'Provider' implementing setup,notify,change,boot instead of just BasePin actions - refactored button module to use gpio provider instead of referencing types itself - removed dual & stm code from buttons, migrate both to relay module - added status notify and change callbacks for relayStatus (i.e. 'notify' when relay status was called, but not changed. and 'changed' when it did) - relays runtime configuration keys - relay command now shows configured relays and current & target statuses - refactor the code using relayStatus(0, blah) under LIGHT_PROVIDER check to use lightState instead - remove rfbridge code form relay module. implement through a basic state listener in the rfbridge module, depend on RELAY_SUPPORT - allow to bind rf codes to real relays - drop tuya-specific lights provider, remove tuya code from relays and lights modules - integrate tuya via relay listeners and providers, use lights custom provider - implement channel transitions for tuya. disabled by default, and transition time and step are overridden to 2000 + 100. needs to be set to some value below the total time (i.e. `total transition time / step time == number of steps`, we need to figure out a correct time that serial comms could handle) - lights custom provider (global, not per-pin) and state listeners - remove lights code from relay module. implement through providers & listeners in the lights module, depend on RELAY_SUPPORT - lights per-channel relay provider (unused atm), depend on RELAY_SUPPORT - refactored channel transition - calculate step only once, make sure time + step values are sane, generate quick transitions with very small delay (10ms hardcoded) for transitions during OFF state i.e. we no longer waste 500ms (or whatever transition time is set to) on boot doing nothing - transition time + step parameter for the lightUpdate - report mask parameter for the lightUpdate - minor fixes across the board resolve #2222
3 years ago
providers: relays, lights and buttons refactoring (#2414) - gpio module now tracks the known providers (right now, hardware and mcp expander) - refactored relay struct to use 'Provider' implementing setup,notify,change,boot instead of just BasePin actions - refactored button module to use gpio provider instead of referencing types itself - removed dual & stm code from buttons, migrate both to relay module - added status notify and change callbacks for relayStatus (i.e. 'notify' when relay status was called, but not changed. and 'changed' when it did) - relays runtime configuration keys - relay command now shows configured relays and current & target statuses - refactor the code using relayStatus(0, blah) under LIGHT_PROVIDER check to use lightState instead - remove rfbridge code form relay module. implement through a basic state listener in the rfbridge module, depend on RELAY_SUPPORT - allow to bind rf codes to real relays - drop tuya-specific lights provider, remove tuya code from relays and lights modules - integrate tuya via relay listeners and providers, use lights custom provider - implement channel transitions for tuya. disabled by default, and transition time and step are overridden to 2000 + 100. needs to be set to some value below the total time (i.e. `total transition time / step time == number of steps`, we need to figure out a correct time that serial comms could handle) - lights custom provider (global, not per-pin) and state listeners - remove lights code from relay module. implement through providers & listeners in the lights module, depend on RELAY_SUPPORT - lights per-channel relay provider (unused atm), depend on RELAY_SUPPORT - refactored channel transition - calculate step only once, make sure time + step values are sane, generate quick transitions with very small delay (10ms hardcoded) for transitions during OFF state i.e. we no longer waste 500ms (or whatever transition time is set to) on boot doing nothing - transition time + step parameter for the lightUpdate - report mask parameter for the lightUpdate - minor fixes across the board resolve #2222
3 years ago
6 years ago
6 years ago
6 years ago
6 years ago
providers: relays, lights and buttons refactoring (#2414) - gpio module now tracks the known providers (right now, hardware and mcp expander) - refactored relay struct to use 'Provider' implementing setup,notify,change,boot instead of just BasePin actions - refactored button module to use gpio provider instead of referencing types itself - removed dual & stm code from buttons, migrate both to relay module - added status notify and change callbacks for relayStatus (i.e. 'notify' when relay status was called, but not changed. and 'changed' when it did) - relays runtime configuration keys - relay command now shows configured relays and current & target statuses - refactor the code using relayStatus(0, blah) under LIGHT_PROVIDER check to use lightState instead - remove rfbridge code form relay module. implement through a basic state listener in the rfbridge module, depend on RELAY_SUPPORT - allow to bind rf codes to real relays - drop tuya-specific lights provider, remove tuya code from relays and lights modules - integrate tuya via relay listeners and providers, use lights custom provider - implement channel transitions for tuya. disabled by default, and transition time and step are overridden to 2000 + 100. needs to be set to some value below the total time (i.e. `total transition time / step time == number of steps`, we need to figure out a correct time that serial comms could handle) - lights custom provider (global, not per-pin) and state listeners - remove lights code from relay module. implement through providers & listeners in the lights module, depend on RELAY_SUPPORT - lights per-channel relay provider (unused atm), depend on RELAY_SUPPORT - refactored channel transition - calculate step only once, make sure time + step values are sane, generate quick transitions with very small delay (10ms hardcoded) for transitions during OFF state i.e. we no longer waste 500ms (or whatever transition time is set to) on boot doing nothing - transition time + step parameter for the lightUpdate - report mask parameter for the lightUpdate - minor fixes across the board resolve #2222
3 years ago
6 years ago
6 years ago
6 years ago
8 years ago
6 years ago
8 years ago
6 years ago
8 years ago
8 years ago
8 years ago
8 years ago
6 years ago
8 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
8 years ago
  1. var debug = false;
  2. var websock;
  3. var password = false;
  4. var maxNetworks;
  5. var free_size = 0;
  6. var urls = {};
  7. var numChanged = 0;
  8. var numReboot = 0;
  9. var numReconnect = 0;
  10. var numReload = 0;
  11. var configurationSaved = false;
  12. var ws_pingpong;
  13. //removeIf(!light)
  14. var colorPicker;
  15. var useWhite = false;
  16. var useCCT = false;
  17. //endRemoveIf(!light)
  18. var now = 0;
  19. var ago = 0;
  20. //removeIf(!rfm69)
  21. var packets;
  22. var filters = [];
  23. //endRemoveIf(!rfm69)
  24. //removeIf(!sensor)
  25. var Magnitudes = [];
  26. var MagnitudeErrors = {};
  27. var MagnitudeNames = {};
  28. var MagnitudeTypePrefixes = {};
  29. var MagnitudePrefixTypes = {};
  30. //endRemoveIf(!sensor)
  31. // -----------------------------------------------------------------------------
  32. // Utils
  33. // -----------------------------------------------------------------------------
  34. $.fn.enterKey = function (fnc) {
  35. return this.each(function () {
  36. $(this).keypress(function (ev) {
  37. var keycode = parseInt(ev.keyCode ? ev.keyCode : ev.which, 10);
  38. if (13 === keycode) {
  39. return fnc.call(this, ev);
  40. }
  41. });
  42. });
  43. };
  44. function followScroll(id, threshold) {
  45. if (threshold === undefined) {
  46. threshold = 90;
  47. }
  48. var elem = document.getElementById(id);
  49. var offset = (elem.scrollTop + elem.offsetHeight) / elem.scrollHeight * 100;
  50. if (offset > threshold) {
  51. elem.scrollTop = elem.scrollHeight;
  52. }
  53. }
  54. function fromSchema(source, schema) {
  55. if (schema.length !== source.length) {
  56. throw `Schema mismatch! Expected length ${schema.length} vs. ${source.length}`;
  57. }
  58. var target = {};
  59. schema.forEach(function(key, index) {
  60. target[key] = source[index];
  61. });
  62. return target;
  63. }
  64. function keepTime() {
  65. $("span[name='ago']").html(ago);
  66. ago++;
  67. if (0 === now) { return; }
  68. var date = new Date(now * 1000);
  69. var text = date.toISOString().substring(0, 19).replace("T", " ");
  70. $("input[name='now']").val(text);
  71. $("span[name='now']").html(text);
  72. now++;
  73. }
  74. function zeroPad(number, positions) {
  75. return number.toString().padStart(positions, "0");
  76. }
  77. function validatePassword(password) {
  78. // http://www.the-art-of-web.com/javascript/validate-password/
  79. // at least one lowercase and one uppercase letter or number
  80. // at least eight characters (letters, numbers or special characters)
  81. // MUST be 8..63 printable ASCII characters. See:
  82. // https://en.wikipedia.org/wiki/Wi-Fi_Protected_Access#Target_users_(authentication_key_distribution)
  83. // https://github.com/xoseperez/espurna/issues/1151
  84. var re_password = /^(?=.*[A-Z\d])(?=.*[a-z])[\w~!@#$%^&*\(\)<>,.\?;:{}\[\]\\|]{8,63}$/;
  85. return (
  86. (password !== undefined)
  87. && (typeof password === "string")
  88. && (password.length > 0)
  89. && re_password.test(password)
  90. );
  91. }
  92. function validateFormPasswords(form) {
  93. var passwords = $("input[name='adminPass0'],input[name='adminPass1']", form);
  94. var adminPass1 = passwords.first().val(),
  95. adminPass2 = passwords.last().val();
  96. var formValidity = passwords.first()[0].checkValidity();
  97. if (formValidity && (adminPass1.length === 0) && (adminPass2.length === 0)) {
  98. return true;
  99. }
  100. var validPass1 = validatePassword(adminPass1),
  101. validPass2 = validatePassword(adminPass2);
  102. if (formValidity && validPass1 && validPass2) {
  103. return true;
  104. }
  105. if (!formValidity || (adminPass1.length > 0 && !validPass1)) {
  106. alert("The password you have entered is not valid, it must be 8..63 characters and have at least 1 lowercase and 1 uppercase / number!");
  107. }
  108. if (adminPass1 !== adminPass2) {
  109. alert("Passwords are different!");
  110. }
  111. return false;
  112. }
  113. function validateFormHostname(form) {
  114. // RFCs mandate that a hostname's labels may contain only
  115. // the ASCII letters 'a' through 'z' (case-insensitive),
  116. // the digits '0' through '9', and the hyphen.
  117. // Hostname labels cannot begin or end with a hyphen.
  118. // No other symbols, punctuation characters, or blank spaces are permitted.
  119. // Negative lookbehind does not work in Javascript
  120. // var re_hostname = new RegExp('^(?!-)[A-Za-z0-9-]{1,32}(?<!-)$');
  121. var re_hostname = new RegExp('^(?!-)[A-Za-z0-9-]{0,31}[A-Za-z0-9]$');
  122. var hostname = $("input[name='hostname']", form);
  123. if ("true" !== hostname.attr("hasChanged")) {
  124. return true;
  125. }
  126. if (re_hostname.test(hostname.val())) {
  127. return true;
  128. }
  129. alert("Hostname cannot be empty and may only contain the ASCII letters ('A' through 'Z' and 'a' through 'z'), the digits '0' through '9', and the hyphen ('-')! They can neither start or end with an hyphen.");
  130. return false;
  131. }
  132. function validateForm(form) {
  133. return validateFormPasswords(form) && validateFormHostname(form);
  134. }
  135. // Observe all group settings to selectively update originals based on the current data
  136. var groupSettingsObserver = new MutationObserver(function(mutations) {
  137. mutations.forEach(function(mutation) {
  138. // If any new elements are added, set "settings-target" element as changed to forcibly send the data
  139. var targets = $(mutation.target).attr("data-settings-target");
  140. if (targets !== undefined) {
  141. mutation.addedNodes.forEach(function(node) {
  142. var overrides = [];
  143. targets.split(" ").forEach(function(target) {
  144. var elem = $("[name='" + target + "']", node);
  145. if (!elem.length) return;
  146. var value = getValue(elem);
  147. if ((value === null) || (value === elem[0].defaultValue)) {
  148. overrides.push(elem);
  149. }
  150. });
  151. setOriginalsFromValues($("input,select", node));
  152. overrides.forEach(function(elem) {
  153. elem.attr("hasChanged", "true");
  154. if (elem.prop("tagName") === "SELECT") {
  155. elem.prop("value", 0);
  156. }
  157. });
  158. });
  159. }
  160. // If anything was removed, forcibly send **all** of the group to avoid having any outdated keys
  161. // TODO: hide instead of remove?
  162. var changed = $(mutation.target).attr("hasChanged") === "true";
  163. if (changed || mutation.removedNodes.length) {
  164. $(mutation.target).attr("hasChanged", "true");
  165. $("input,select", mutation.target.childNodes).attr("hasChanged", "true");
  166. }
  167. });
  168. });
  169. function bitsetToValues(bitset) {
  170. var values = [];
  171. for (var index = 0; index < 31; ++index) {
  172. if (bitset & (1 << index)) {
  173. values.push(String(index));
  174. }
  175. }
  176. return values;
  177. }
  178. function valuesToBitset(values) {
  179. var result = 0;
  180. for (var value of values) {
  181. result |= 1 << parseInt(value);
  182. }
  183. return result;
  184. }
  185. function getValue(element) {
  186. if ($(element).attr("type") === "checkbox") {
  187. return $(element).prop("checked") ? 1 : 0;
  188. } else if ($(element).attr("type") === "radio") {
  189. if (!$(element).prop("checked")) {
  190. return null;
  191. }
  192. } else if ($(element).attr("multiple") !== undefined) {
  193. return valuesToBitset($(element).val());
  194. }
  195. return $(element).val();
  196. }
  197. function getData(form, changed, cleanup) {
  198. // Populate two sets of data, ones that had been changed and ones that stayed the same
  199. var data = {};
  200. var changed_data = [];
  201. if (cleanup === undefined) {
  202. cleanup = true;
  203. }
  204. if (changed === undefined) {
  205. changed = true;
  206. }
  207. $("input,select", form).each(function() {
  208. if ($(this).attr("data-settings-ignore") === "true") {
  209. return;
  210. }
  211. var name = $(this).attr("name");
  212. if (name === undefined) {
  213. return;
  214. }
  215. var real_name = $(this).attr("data-settings-real-name");
  216. if (real_name !== undefined) {
  217. name = real_name;
  218. }
  219. var value = getValue(this);
  220. if (null !== value) {
  221. var haschanged = ("true" === $(this).attr("hasChanged"));
  222. var indexed = changed_data.indexOf(name) >= 0;
  223. if ((haschanged || !changed) && !indexed) {
  224. changed_data.push(name);
  225. }
  226. // make sure to group keys from templates (or, manually flagged as such)
  227. var is_group = $(this).attr("data-settings-group") !== undefined;
  228. if (is_group) {
  229. if (name in data) {
  230. data[name].push(value);
  231. } else {
  232. data[name] = [value];
  233. }
  234. } else {
  235. data[name] = value;
  236. }
  237. }
  238. });
  239. // Finally, filter out only fields that had changed.
  240. // Note: We need to preserve dynamic lists like schedules, wifi etc.
  241. // so we don't accidentally break when user deletes entry in the middle
  242. var resulting_data = {};
  243. for (var value in data) {
  244. if (changed_data.indexOf(value) >= 0) {
  245. resulting_data[value] = data[value];
  246. }
  247. }
  248. // Hack: clean-up leftover arrays.
  249. // When empty, the receiving side will prune all keys greater than the current one.
  250. if (cleanup) {
  251. $(".settings-group").each(function() {
  252. var haschanged = ("true" === $(this).attr("hasChanged"));
  253. if (haschanged && !this.children.length) {
  254. var targets = this.dataset.settingsTarget;
  255. if (targets === undefined) return;
  256. targets.split(" ").forEach(function(target) {
  257. resulting_data[target] = [];
  258. });
  259. }
  260. });
  261. }
  262. return resulting_data;
  263. }
  264. function randomString(length, args) {
  265. if (typeof args === "undefined") {
  266. args = {
  267. lowercase: true,
  268. uppercase: true,
  269. numbers: true,
  270. special: true
  271. }
  272. }
  273. var mask = "";
  274. if (args.lowercase) { mask += "abcdefghijklmnopqrstuvwxyz"; }
  275. if (args.uppercase) { mask += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; }
  276. if (args.numbers || args.hex) { mask += "0123456789"; }
  277. if (args.hex) { mask += "ABCDEF"; }
  278. if (args.special) { mask += "~`!@#$%^&*()_+-={}[]:\";'<>?,./|\\"; }
  279. var source = new Uint32Array(length);
  280. var result = new Array(length);
  281. window.crypto.getRandomValues(source).forEach(function(value, i) {
  282. result[i] = mask[value % mask.length];
  283. });
  284. return result.join("");
  285. }
  286. function generateAPIKey() {
  287. var apikey = randomString(16, {hex: true});
  288. $("input[name='apiKey']")
  289. .val(apikey)
  290. .attr("original", "-".repeat(16))
  291. .attr("haschanged", "true");
  292. return false;
  293. }
  294. function generatePassword() {
  295. var password = "";
  296. do {
  297. password = randomString(10);
  298. } while (!validatePassword(password));
  299. return password;
  300. }
  301. function toggleVisiblePassword() {
  302. var elem = this.previousElementSibling;
  303. if (elem.type === "password") {
  304. elem.type = "text";
  305. } else {
  306. elem.type = "password";
  307. }
  308. return false;
  309. }
  310. function doGeneratePassword() {
  311. var elems = $("input", $("#formPassword"));
  312. elems
  313. .val(generatePassword())
  314. .attr("haschanged", "true")
  315. .each(function() {
  316. this.type = "text";
  317. });
  318. return false;
  319. }
  320. function moduleVisible(module) {
  321. if (module == "sch") {
  322. $("li.module-" + module).css("display", "inherit");
  323. $("div.module-" + module).css("display", "flex");
  324. return;
  325. }
  326. $(".module-" + module).css("display", "inherit");
  327. }
  328. //removeIf(!thermostat)
  329. function checkTempRangeMin() {
  330. var min = parseInt($("#tempRangeMinInput").val(), 10);
  331. var max = parseInt($("#tempRangeMaxInput").val(), 10);
  332. if (min > max - 1) {
  333. $("#tempRangeMinInput").val(max - 1);
  334. }
  335. }
  336. function checkTempRangeMax() {
  337. var min = parseInt($("#tempRangeMinInput").val(), 10);
  338. var max = parseInt($("#tempRangeMaxInput").val(), 10);
  339. if (max < min + 1) {
  340. $("#tempRangeMaxInput").val(min + 1);
  341. }
  342. }
  343. function doResetThermostatCounters(ask) {
  344. var question = (typeof ask === "undefined" || false === ask) ?
  345. null :
  346. "Are you sure you want to reset burning counters?";
  347. return doAction(question, "thermostat_reset_counters");
  348. }
  349. //endRemoveIf(!thermostat)
  350. function initSelectGPIO(select) {
  351. // TODO: properly lock used GPIOs via locking and apply the mask here
  352. var mapping = [
  353. [153, "NONE"],
  354. [0, "0 (FLASH)"],
  355. [1, "1 (U0TXD)"],
  356. [2, "2 (U1TXD)"],
  357. [3, "3 (U0RXD)"],
  358. [4, "4 (SDA)"],
  359. [5, "5 (SCL)"],
  360. [9, "9 (SDD2)"],
  361. [10, "10 (SDD3)"],
  362. [12, "12 (MTDI)"],
  363. [13, "13 (MTCK)"],
  364. [14, "14 (MTMS)"],
  365. [15, "15 (MTDO)"],
  366. [16, "16 (WAKE)"],
  367. ];
  368. for (n in mapping) {
  369. var elem = $('<option value="' + mapping[n][0] + '">');
  370. elem.html(mapping[n][1]);
  371. elem.appendTo(select);
  372. }
  373. }
  374. function fillTemplateLineFromCfg(line, id, cfg) {
  375. for (var [key, value] of Object.entries(cfg)) {
  376. var span = $(`span.${key}`, line);
  377. if (span.length) {
  378. span.html(cfg[key]);
  379. continue;
  380. }
  381. var input = $(`input[name='${key}']`, line);
  382. if (input.length) {
  383. if (input.is("[type='checkbox']")) {
  384. var realId = key + id;
  385. input.prop("checked", cfg[key])
  386. .attr("id", realId)
  387. .attr("name", realId)
  388. .next().attr("for", realId);
  389. } else {
  390. input.val(cfg[key]);
  391. }
  392. continue;
  393. }
  394. var select = $(`select[name='${key}']`, line);
  395. if (select.length) {
  396. select.prop("value", cfg[key]);
  397. continue;
  398. }
  399. }
  400. setOriginalsFromValues($("input,select", line));
  401. }
  402. // -----------------------------------------------------------------------------
  403. // Actions
  404. // -----------------------------------------------------------------------------
  405. function send(json) {
  406. if (debug) console.log(json);
  407. websock.send(json);
  408. }
  409. function sendAction(action, data) {
  410. send(JSON.stringify({action: action, data: data}));
  411. }
  412. function sendConfig(data) {
  413. send(JSON.stringify({config: data}));
  414. }
  415. function setOriginalsFromValues(elems) {
  416. if (typeof elems == "undefined") {
  417. elems = $("input,select");
  418. }
  419. elems.each(function() {
  420. var value;
  421. if ($(this).attr("type") === "checkbox") {
  422. value = $(this).prop("checked");
  423. } else {
  424. value = $(this).val();
  425. }
  426. $(this).attr("original", value);
  427. hasChanged.call(this);
  428. });
  429. }
  430. function resetOriginals() {
  431. setOriginalsFromValues();
  432. $(".settings-group").attr("haschanged", "false")
  433. numReboot = numReconnect = numReload = 0;
  434. configurationSaved = false;
  435. }
  436. function doReload(milliseconds) {
  437. setTimeout(function() {
  438. window.location.reload();
  439. }, parseInt(milliseconds, 10));
  440. }
  441. /**
  442. * Check a file object to see if it is a valid firmware image
  443. * The file first byte should be 0xE9
  444. * @param {file} file File object
  445. * @param {Function} callback Function to call back with the result
  446. */
  447. function checkFirmware(file, callback) {
  448. var reader = new FileReader();
  449. reader.onloadend = function(evt) {
  450. if (FileReader.DONE === evt.target.readyState) {
  451. var magic = evt.target.result.charCodeAt(0);
  452. if ((0x1F === magic) && (0x8B === evt.target.result.charCodeAt(1))) {
  453. callback(true);
  454. return;
  455. }
  456. if (0xE9 !== magic) {
  457. alert("Binary image does not start with a magic byte");
  458. callback(false);
  459. return;
  460. }
  461. var modes = ['QIO', 'QOUT', 'DIO', 'DOUT'];
  462. var flash_mode = evt.target.result.charCodeAt(2);
  463. if (0x03 !== flash_mode) {
  464. var response = window.confirm("Binary image is using " + modes[flash_mode] + " flash mode! Make sure that the device supports it before proceeding.");
  465. callback(response);
  466. } else {
  467. callback(true);
  468. }
  469. }
  470. };
  471. var blob = file.slice(0, 3);
  472. reader.readAsBinaryString(blob);
  473. }
  474. function doUpgrade() {
  475. var file = $("input[name='upgrade']")[0].files[0];
  476. if (typeof file === "undefined") {
  477. alert("First you have to select a file from your computer.");
  478. return false;
  479. }
  480. if (file.size > free_size) {
  481. alert("Image it too large to fit in the available space for OTA. Consider doing a two-step update.");
  482. return false;
  483. }
  484. checkFirmware(file, function(ok) {
  485. if (!ok) {
  486. return;
  487. }
  488. var data = new FormData();
  489. data.append("upgrade", file, file.name);
  490. var xhr = new XMLHttpRequest();
  491. var msg_ok = "Firmware image uploaded, board rebooting. This page will be refreshed in 5 seconds.";
  492. var msg_err = "There was an error trying to upload the new image, please try again: ";
  493. var network_error = function(e) {
  494. alert(msg_err + " xhr request " + e.type);
  495. };
  496. xhr.addEventListener("error", network_error, false);
  497. xhr.addEventListener("abort", network_error, false);
  498. xhr.addEventListener("load", function(e) {
  499. $("#upgrade-progress").hide();
  500. if ("OK" === xhr.responseText) {
  501. alert(msg_ok);
  502. doReload(5000);
  503. } else {
  504. alert(msg_err + xhr.status.toString() + " " + xhr.statusText + ", " + xhr.responseText);
  505. }
  506. }, false);
  507. xhr.upload.addEventListener("progress", function(e) {
  508. $("#upgrade-progress").show();
  509. if (e.lengthComputable) {
  510. $("progress").attr({ value: e.loaded, max: e.total });
  511. }
  512. }, false);
  513. xhr.open("POST", urls.upgrade.href);
  514. xhr.send(data);
  515. });
  516. return false;
  517. }
  518. function doUpdatePassword() {
  519. var form = $("#formPassword");
  520. if (validateFormPasswords(form)) {
  521. sendConfig(getData(form, true, false));
  522. }
  523. return false;
  524. }
  525. function checkChanges() {
  526. if (numChanged > 0) {
  527. var response = window.confirm("Some changes have not been saved yet, do you want to save them first?");
  528. if (response) {
  529. doUpdate();
  530. }
  531. }
  532. }
  533. function doAction(question, action) {
  534. checkChanges();
  535. if (question) {
  536. var response = window.confirm(question);
  537. if (false === response) {
  538. return false;
  539. }
  540. }
  541. sendAction(action, {});
  542. doReload(5000);
  543. return false;
  544. }
  545. function doReboot(ask) {
  546. var question = (typeof ask === "undefined" || false === ask) ?
  547. null :
  548. "Are you sure you want to reboot the device?";
  549. return doAction(question, "reboot");
  550. }
  551. function doReconnect(ask) {
  552. var question = (typeof ask === "undefined" || false === ask) ?
  553. null :
  554. "Are you sure you want to disconnect from the current WIFI network?";
  555. return doAction(question, "reconnect");
  556. }
  557. function doCheckOriginals() {
  558. var response;
  559. if (numReboot > 0) {
  560. response = window.confirm("You have to reboot the board for the changes to take effect, do you want to do it now?");
  561. if (response) { doReboot(false); }
  562. } else if (numReconnect > 0) {
  563. response = window.confirm("You have to reconnect to the WiFi for the changes to take effect, do you want to do it now?");
  564. if (response) { doReconnect(false); }
  565. } else if (numReload > 0) {
  566. response = window.confirm("You have to reload the page to see the latest changes, do you want to do it now?");
  567. if (response) { doReload(0); }
  568. }
  569. resetOriginals();
  570. }
  571. function waitForSave(){
  572. if (!configurationSaved) {
  573. setTimeout(waitForSave, 1000);
  574. } else {
  575. doCheckOriginals();
  576. }
  577. }
  578. function doUpdate() {
  579. // Since we have 2-page config, make sure we select the active one
  580. var forms = $(".form-settings");
  581. if (validateForm(forms)) {
  582. sendConfig(getData(forms));
  583. //removeIf(!sensor)
  584. // Energy reset is handled via these keys
  585. // TODO: replace these with actions, not settings
  586. $(".pwrExpected").val(0);
  587. $("input[name='snsResetCalibration']").prop("checked", false);
  588. $("input[name='pwrResetCalibration']").prop("checked", false);
  589. $("input[name='pwrResetE']").prop("checked", false);
  590. //endRemoveIf(!sensor)
  591. numChanged = 0;
  592. waitForSave();
  593. }
  594. return false;
  595. }
  596. function doBackup() {
  597. document.getElementById("downloader").src = urls.config.href;
  598. return false;
  599. }
  600. function onFileUpload(event) {
  601. var inputFiles = this.files;
  602. if (typeof inputFiles === "undefined" || inputFiles.length === 0) {
  603. return false;
  604. }
  605. var inputFile = inputFiles[0];
  606. this.value = "";
  607. var response = window.confirm("Previous settings will be overwritten. Are you sure you want to restore this settings?");
  608. if (!response) {
  609. return false;
  610. }
  611. var reader = new FileReader();
  612. reader.onload = function(e) {
  613. try {
  614. var data = JSON.parse(e.target.result);
  615. sendAction("restore", data);
  616. } catch (e) {
  617. window.alert(e);
  618. }
  619. };
  620. reader.readAsText(inputFile);
  621. return false;
  622. }
  623. function doRestore() {
  624. if (typeof window.FileReader !== "function") {
  625. alert("The file API isn't supported on this browser yet.");
  626. } else {
  627. $("#uploader").click();
  628. }
  629. return false;
  630. }
  631. function doFactoryReset() {
  632. var response = window.confirm("Are you sure you want to restore to factory settings?");
  633. if (!response) {
  634. return false;
  635. }
  636. sendAction("factory_reset", {});
  637. doReload(5000);
  638. return false;
  639. }
  640. function doToggle(id, value) {
  641. sendAction("relay", {id: id, status: value ? 1 : 0 });
  642. return false;
  643. }
  644. function doScan() {
  645. $("#scanResult").html("");
  646. $("div.scan.loading").show();
  647. $("#button-wifi-scan").attr("disabled", true);
  648. sendAction("scan", {});
  649. return false;
  650. }
  651. function doDebugCommand() {
  652. var el = $("input[name='dbgcmd']");
  653. var command = el.val();
  654. el.val("");
  655. sendAction("dbgcmd", {command: command});
  656. followScroll("weblog", 0);
  657. return false;
  658. }
  659. function doDebugClear() {
  660. $("#weblog").text("");
  661. return false;
  662. }
  663. //removeIf(!rfm69)
  664. function doClearCounts() {
  665. sendAction("clear-counts", {});
  666. return false;
  667. }
  668. function doClearMessages() {
  669. packets.clear().draw(false);
  670. return false;
  671. }
  672. function doFilter(e) {
  673. var index = packets.cell(this).index();
  674. if (index == 'undefined') return;
  675. var c = index.column;
  676. var column = packets.column(c);
  677. if (filters[c]) {
  678. filters[c] = false;
  679. column.search("");
  680. $(column.header()).removeClass("filtered");
  681. } else {
  682. filters[c] = true;
  683. var data = packets.row(this).data();
  684. if (e.which == 1) {
  685. column.search('^' + data[c] + '$', true, false );
  686. } else {
  687. column.search('^((?!(' + data[c] + ')).)*$', true, false );
  688. }
  689. $(column.header()).addClass("filtered");
  690. }
  691. column.draw();
  692. return false;
  693. }
  694. function doClearFilters() {
  695. for (var i = 0; i < packets.columns()[0].length; i++) {
  696. if (filters[i]) {
  697. filters[i] = false;
  698. var column = packets.column(i);
  699. column.search("");
  700. $(column.header()).removeClass("filtered");
  701. column.draw();
  702. }
  703. }
  704. return false;
  705. }
  706. //endRemoveIf(!rfm69)
  707. function delParent() {
  708. var parent = $(this).parent().parent();
  709. $(parent).remove();
  710. }
  711. // -----------------------------------------------------------------------------
  712. // Visualization
  713. // -----------------------------------------------------------------------------
  714. function toggleMenu() {
  715. $("#layout").toggleClass("active");
  716. $("#menu").toggleClass("active");
  717. $("#menuLink").toggleClass("active");
  718. }
  719. function showPanel() {
  720. $(".panel").hide();
  721. if ($("#layout").hasClass("active")) { toggleMenu(); }
  722. $("#" + $(this).attr("data")).show();
  723. }
  724. function loadTemplate(name) {
  725. let template = $(`#${name}.template`);
  726. let clone = $(template).clone();
  727. return clone.children();
  728. }
  729. function loadConfigTemplate(name) {
  730. let template = loadTemplate(name);
  731. $("input,select", template)
  732. .attr("data-settings-group", "");
  733. return template;
  734. }
  735. // -----------------------------------------------------------------------------
  736. // Relays & magnitudes mapping
  737. // -----------------------------------------------------------------------------
  738. function createRelayList(data, container, template_name) {
  739. var current = $("#" + container + " > div").length;
  740. if (current > 0) { return; }
  741. var template = loadConfigTemplate(template_name);
  742. for (var i in data) {
  743. var line = $(template).clone();
  744. $("label", line).html("Switch #" + i);
  745. setOriginalsFromValues($("input", line));
  746. line.appendTo("#" + container);
  747. }
  748. }
  749. //removeIf(!sensor)
  750. function createMagnitudeList(data, container, template_name) {
  751. var current = $("#" + container + " > div").length;
  752. if (current > 0) { return; }
  753. var template = loadConfigTemplate(template_name);
  754. var size = data.size;
  755. for (var i=0; i<size; ++i) {
  756. var line = $(template).clone();
  757. $("label", line).html(MagnitudeNames[data.type[i]] + " #" + parseInt(data.index[i], 10));
  758. $("div.hint", line).html(Magnitudes[i].description);
  759. setOriginalsFromValues($("input", line));
  760. line.appendTo("#" + container);
  761. }
  762. }
  763. //endRemoveIf(!sensor)
  764. function addFromTemplate(template, target) {
  765. var line = loadConfigTemplate(template);
  766. $("button", line)
  767. .on('click', delParent);
  768. setOriginalsFromValues($("input", line));
  769. line.appendTo("#" + target);
  770. }
  771. // -----------------------------------------------------------------------------
  772. // RPN Rules
  773. // -----------------------------------------------------------------------------
  774. function addRPNRule() {
  775. addFromTemplate("rpnRuleTemplate", "rpnRules");
  776. }
  777. function addRPNTopic() {
  778. addFromTemplate("rpnRuleTemplate", "rpnTopics");
  779. }
  780. // -----------------------------------------------------------------------------
  781. // RFM69
  782. // -----------------------------------------------------------------------------
  783. //removeIf(!rfm69)
  784. function addMapping() {
  785. addFromTemplate("nodeTemplate", "mapping");
  786. }
  787. //endRemoveIf(!rfm69)
  788. // -----------------------------------------------------------------------------
  789. // Wifi
  790. // -----------------------------------------------------------------------------
  791. function numNetworks() {
  792. return $("#networks > div").length;
  793. }
  794. function delNetwork() {
  795. var parent = $(this).parents(".pure-g");
  796. $(parent).remove();
  797. }
  798. function moreNetwork() {
  799. var parent = $(this).parents(".pure-g");
  800. $(".more", parent).toggle();
  801. }
  802. function addNetwork(network) {
  803. var number = numNetworks();
  804. if (number >= maxNetworks) {
  805. alert("Max number of networks reached");
  806. return null;
  807. }
  808. if (network === undefined) {
  809. network = {};
  810. }
  811. var line = loadConfigTemplate("networkTemplate");
  812. $(".password-reveal", line).on("click", toggleVisiblePassword);
  813. $(line).find(".button-del-network").on("click", delNetwork);
  814. $(line).find(".button-more-network").on("click", moreNetwork);
  815. Object.entries(network).forEach(function(pair) {
  816. // XXX: UI deleting this network will only re-use stored values.
  817. var key = pair[0],
  818. val = pair[1];
  819. if (key === "stored") {
  820. $(line).find(".button-del-network").prop("disabled", val);
  821. return;
  822. }
  823. $("input[name='" + key + "']", line).val(val);
  824. });
  825. line.appendTo("#networks");
  826. return line;
  827. }
  828. // -----------------------------------------------------------------------------
  829. // Relays scheduler
  830. // -----------------------------------------------------------------------------
  831. function addLed(id, cfg, payload) {
  832. var line = loadConfigTemplate("ledConfigTemplate");
  833. fillTemplateLineFromCfg(line, id, cfg);
  834. $("span.id", line)
  835. .html(id);
  836. line.appendTo("#ledConfig");
  837. }
  838. // -----------------------------------------------------------------------------
  839. // Relays scheduler
  840. // -----------------------------------------------------------------------------
  841. function numSchedules() {
  842. return $("#schedules > div").length;
  843. }
  844. function maxSchedules() {
  845. var value = $("#schedules").attr("data-settings-max");
  846. return parseInt(value === undefined ? 0 : value, 10);
  847. }
  848. function delSchedule() {
  849. var parent = $(this).parents(".pure-g");
  850. $(parent).remove();
  851. }
  852. function moreSchedule() {
  853. var parent = $(this).parents(".pure-g");
  854. $("div.more", parent).toggle();
  855. }
  856. function addSchedule(cfg, payload) {
  857. var id = numSchedules();
  858. if (id >= maxSchedules()) {
  859. alert("Max number of schedules reached");
  860. return null;
  861. }
  862. if (cfg === undefined) {
  863. return null;
  864. }
  865. if (payload === undefined) {
  866. payload = {};
  867. }
  868. var line = loadConfigTemplate("scheduleTemplate");
  869. var type = "none";
  870. switch(cfg.schType) {
  871. case 1:
  872. type = "switch";
  873. break;
  874. case 2:
  875. type = "light";
  876. break;
  877. case 3:
  878. type = "curtain";
  879. break;
  880. }
  881. $("#schActionDiv", line)
  882. .append(loadConfigTemplate(type + "ActionTemplate"));
  883. $(".button-del-schedule", line)
  884. .on("click", delSchedule);
  885. $(".button-more-schedule", line)
  886. .on("click", moreSchedule);
  887. $("input[type='checkbox']", line)
  888. .prop("checked", false);
  889. fillTemplateLineFromCfg(line, id, cfg);
  890. line.appendTo("#schedules");
  891. return line;
  892. }
  893. // -----------------------------------------------------------------------------
  894. // Relays
  895. // -----------------------------------------------------------------------------
  896. function initRelay(id, cfg, payload) {
  897. var line = loadConfigTemplate("relayTemplate");
  898. $("span.relayName", line)
  899. .text(cfg.relayName)
  900. .attr("data-id", id)
  901. .attr("title", payload["desc"][id]);
  902. $("input[type='checkbox']", line)
  903. .prop('checked', false)
  904. .prop('disabled', true)
  905. .attr("data-id", id)
  906. .prop("id", "relay" + id)
  907. .on("change", function (event) {
  908. var target= parseInt($(event.target).attr("data-id"), 10);
  909. var status = $(event.target).prop("checked");
  910. doToggle(target, status);
  911. });
  912. $("label.toggle", line)
  913. .prop("for", "relay" + id);
  914. line.appendTo("#relays");
  915. }
  916. function updateRelays(data) {
  917. var size = data.size;
  918. for (var i=0; i<size; ++i) {
  919. var elem = $("input[name='relay'][data-id='" + i + "']");
  920. elem.prop("checked", data.status[i]);
  921. var lock = {
  922. 0: false,
  923. 1: !data.status[i],
  924. 2: data.status[i]
  925. };
  926. elem.prop("disabled", lock[data.lock[i]]); // RELAY_LOCK_DISABLED=0
  927. }
  928. }
  929. function createCheckboxes() {
  930. $("input[type='checkbox']").each(function() {
  931. let name = $(this).prop("name")
  932. if ($(this).prop("name")) {
  933. $(this).prop("id", $(this).prop("name"));
  934. }
  935. $(this)
  936. .parent().addClass("toggleWrapper");
  937. $(this)
  938. .after('<label for="' + $(this).prop("name") + '" class="toggle"><span class="toggle__handler"></span></label>')
  939. });
  940. }
  941. function initRelayConfig(id, cfg, payload) {
  942. var line = loadConfigTemplate("relayConfigTemplate");
  943. fillTemplateLineFromCfg(line, id, cfg);
  944. line.appendTo("#relayConfig");
  945. // Populate the relay SELECTs on the configuration panel
  946. $("select.isrelay").append(
  947. $("<option></option>")
  948. .attr("value", id)
  949. .text(name)
  950. );
  951. }
  952. // -----------------------------------------------------------------------------
  953. // Sensors & Magnitudes
  954. // -----------------------------------------------------------------------------
  955. //removeIf(!sensor)
  956. function initMagnitudes(data) {
  957. // check if already initialized (each magnitude is inside div.pure-g)
  958. var done = $("#magnitudes > div").length;
  959. if (done > 0) { return; }
  960. var size = data.size;
  961. for (var i=0; i<size; ++i) {
  962. var magnitude = {
  963. "name": MagnitudeNames[data.type[i]] + " #" + parseInt(data.index[i], 10),
  964. "units": data.units[i],
  965. "description": data.description[i]
  966. };
  967. Magnitudes.push(magnitude);
  968. var line = loadConfigTemplate("magnitudeTemplate");
  969. $("label", line).html(magnitude.name);
  970. $("input", line).attr("data", i);
  971. $("div.sns-desc", line).html(magnitude.description);
  972. $("div.sns-info", line).hide();
  973. line.appendTo("#magnitudes");
  974. }
  975. }
  976. //endRemoveIf(!sensor)
  977. // -----------------------------------------------------------------------------
  978. // Curtains
  979. // -----------------------------------------------------------------------------
  980. //removeIf(!curtain)
  981. //Create the controls for one curtain. It is called when curtain is updated (so created the first time)
  982. //Let this there as we plan to have more than one curtain per switch
  983. function initCurtain(data) {
  984. var current = $("#curtains > div").length;
  985. if (current > 0) { return; }
  986. // add and init curtain template, prepare multi switches
  987. var line = loadConfigTemplate("curtainTemplate");
  988. $(line).find(".button-curtain-open").on("click", function() {
  989. sendAction("curtainAction", {button: 1});
  990. $(this).css('background', 'red');
  991. });
  992. $(line).find(".button-curtain-pause").on("click", function() {
  993. sendAction("curtainAction", {button: 0});
  994. $(this).css('background', 'red');
  995. });
  996. $(line).find(".button-curtain-close").on("click", function() {
  997. sendAction("curtainAction", {button: 2});
  998. $(this).css('background', 'red');
  999. });
  1000. line.appendTo("#curtains");
  1001. // init curtain slider
  1002. $("#curtainSet").on("change", function() {
  1003. var value = $(this).val();
  1004. var parent = $(this).parents(".pure-g");
  1005. $("span", parent).html(value);
  1006. sendAction("curtainAction", {position: value});
  1007. });
  1008. }
  1009. function initCurtainConfig(data) {
  1010. var current = $("#curtainConfig > legend").length; // there is a legend per relay
  1011. if (current > 0) { return; }
  1012. // Populate the curtain select
  1013. $("select.iscurtain").append(
  1014. $("<option></option>")
  1015. .attr("value", "0")
  1016. .text("Curtain #" + "0")
  1017. );
  1018. }
  1019. //endRemoveIf(!curtain)
  1020. // -----------------------------------------------------------------------------
  1021. // Lights
  1022. // -----------------------------------------------------------------------------
  1023. //removeIf(!light)
  1024. function colorToHsvString(color) {
  1025. var h = String(Math.round(color.hsv.h));
  1026. var s = String(Math.round(color.hsv.s));
  1027. var v = String(Math.round(color.hsv.v));
  1028. return h + "," + s + "," + v;
  1029. }
  1030. function hsvStringToColor(hsv) {
  1031. var parts = hsv.split(",");
  1032. return {
  1033. h: parseInt(parts[0]),
  1034. s: parseInt(parts[1]),
  1035. v: parseInt(parts[2])
  1036. };
  1037. }
  1038. function colorSlider(type) {
  1039. return {component: iro.ui.Slider, options: {sliderType: type}};
  1040. }
  1041. function colorWheel() {
  1042. return {component: iro.ui.Wheel, options: {}};
  1043. }
  1044. function colorBox() {
  1045. return {component: iro.ui.Box, options: {}};
  1046. }
  1047. function updateColor(mode, value) {
  1048. if (colorPicker) {
  1049. if (mode === "rgb") {
  1050. colorPicker.color.hexString = value;
  1051. } else if (mode === "hsv") {
  1052. colorPicker.color.hsv = hsvStringToColor(value);
  1053. }
  1054. return;
  1055. }
  1056. // TODO: useRGB -> ltWheel?
  1057. // TODO: always show wheel + sliders like before?
  1058. var layout = []
  1059. if (mode === "rgb") {
  1060. layout.push(colorWheel());
  1061. layout.push(colorSlider("value"));
  1062. } else if (mode === "hsv") {
  1063. layout.push(colorBox());
  1064. layout.push(colorSlider("hue"));
  1065. }
  1066. var options = {
  1067. color: (mode === "rgb") ? value : hsvStringToColor(value),
  1068. layout: layout
  1069. };
  1070. colorPicker = new iro.ColorPicker("#color", options);
  1071. colorPicker.on("input:change", function(color) {
  1072. if (mode === "rgb") {
  1073. sendAction("color", {rgb: color.hexString});
  1074. } else if (mode === "hsv") {
  1075. sendAction("color", {hsv: colorToHsvString(color)});
  1076. }
  1077. });
  1078. }
  1079. function initCCT() {
  1080. // check if already initialized
  1081. var done = $("#cct > div").length;
  1082. if (done > 0) { return; }
  1083. $("#miredsTemplate").children().clone().appendTo("#cct");
  1084. $("#mireds").on("change", function() {
  1085. var value = $(this).val();
  1086. var parent = $(this).parents(".pure-g");
  1087. $("span", parent).html(value);
  1088. sendAction("mireds", {mireds: value});
  1089. });
  1090. }
  1091. function initChannels(num) {
  1092. // check if already initialized
  1093. var done = $("#channels > div").length > 0;
  1094. if (done) { return; }
  1095. // calculate channels to create
  1096. var max = num;
  1097. if (colorPicker) {
  1098. max = num % 3;
  1099. if ((max > 0) & useWhite) {
  1100. max--;
  1101. if (useCCT) {
  1102. max--;
  1103. }
  1104. }
  1105. }
  1106. var start = num - max;
  1107. var onChannelSliderChange = function() {
  1108. var id = $(this).attr("data");
  1109. var value = $(this).val();
  1110. var parent = $(this).parents(".pure-g");
  1111. $("span", parent).html(value);
  1112. sendAction("channel", {id: id, value: value});
  1113. };
  1114. // add channel templates
  1115. var i = 0;
  1116. for (i=0; i<max; i++) {
  1117. var channel_id = start + i;
  1118. var line = loadTemplate("channelTemplate");
  1119. $("span.slider", line).attr("data", channel_id);
  1120. $("input.slider", line).attr("data", channel_id).on("change", onChannelSliderChange);
  1121. $("label", line).html("Channel #" + channel_id);
  1122. line.appendTo("#channels");
  1123. }
  1124. // Init channel dropdowns
  1125. for (i=0; i<num; i++) {
  1126. $("select.islight").append(
  1127. $("<option></option>").attr("value",i).text("Channel #" + i));
  1128. }
  1129. // add brightness template
  1130. var line = loadTemplate("brightnessTemplate");
  1131. line.appendTo("#channels");
  1132. // init bright slider
  1133. $("#brightness").on("change", function() {
  1134. var value = $(this).val();
  1135. var parent = $(this).parents(".pure-g");
  1136. $("span", parent).html(value);
  1137. sendAction("brightness", {value: value});
  1138. });
  1139. }
  1140. //endRemoveIf(!light)
  1141. // -----------------------------------------------------------------------------
  1142. // RFBridge
  1143. // -----------------------------------------------------------------------------
  1144. //removeIf(!rfbridge)
  1145. function rfbLearn() {
  1146. var parent = $(this).parents(".pure-g");
  1147. var input = $("input", parent);
  1148. sendAction("rfblearn", {id: input.attr("data-id"), status: input.attr("data-status")});
  1149. }
  1150. function rfbForget() {
  1151. var parent = $(this).parents(".pure-g");
  1152. var input = $("input", parent);
  1153. sendAction("rfbforget", {id: input.attr("data-id"), status: input.attr("data-status")});
  1154. }
  1155. function rfbSend() {
  1156. var parent = $(this).parents(".pure-g");
  1157. var input = $("input", parent);
  1158. sendAction("rfbsend", {id: input.attr("data-id"), status: input.attr("data-status"), data: input.val()});
  1159. }
  1160. function addRfbNode() {
  1161. var numNodes = $("#rfbNodes > legend").length;
  1162. var line = loadTemplate("rfbNodeTemplate");
  1163. $("span", line).html(numNodes);
  1164. $(line).find("input").each(function() {
  1165. this.dataset["id"] = numNodes;
  1166. });
  1167. $(line).find(".button-rfb-learn").on("click", rfbLearn);
  1168. $(line).find(".button-rfb-forget").on("click", rfbForget);
  1169. $(line).find(".button-rfb-send").on("click", rfbSend);
  1170. line.appendTo("#rfbNodes");
  1171. return line;
  1172. }
  1173. //endRemoveIf(!rfbridge)
  1174. // -----------------------------------------------------------------------------
  1175. // LightFox
  1176. // -----------------------------------------------------------------------------
  1177. //removeIf(!lightfox)
  1178. function lightfoxLearn() {
  1179. sendAction("lightfoxLearn", {});
  1180. }
  1181. function lightfoxClear() {
  1182. sendAction("lightfoxClear", {});
  1183. }
  1184. function initLightfox(data, relayCount) {
  1185. var numNodes = data.length;
  1186. var i, j;
  1187. for (i=0; i<numNodes; i++) {
  1188. var $line = loadTemplate("lightfoxNodeTemplate");
  1189. $line.find("label > span").text(data[i]["id"]);
  1190. $line.find("select").each(function() {
  1191. $(this).attr("name", "btnRelay" + data[i]["id"]);
  1192. for (j=0; j < relayCount; j++) {
  1193. $(this).append($("<option >").attr("value", j).text("Switch #" + j));
  1194. }
  1195. $(this).val(data[i]["relay"]);
  1196. status = !status;
  1197. });
  1198. setOriginalsFromValues($("input,select", $line));
  1199. $line.appendTo("#lightfoxNodes");
  1200. }
  1201. var $panel = $("#panel-lightfox")
  1202. $(".button-lightfox-learn").off("click").click(lightfoxLearn);
  1203. $(".button-lightfox-clear").off("click").click(lightfoxClear);
  1204. }
  1205. //endRemoveIf(!lightfox)
  1206. // -----------------------------------------------------------------------------
  1207. // Processing
  1208. // -----------------------------------------------------------------------------
  1209. function processData(data) {
  1210. if (debug) console.log(data);
  1211. // title
  1212. if ("app_name" in data) {
  1213. var title = data.app_name;
  1214. if ("app_version" in data) {
  1215. $("span[name=title]").html(data.app_version);
  1216. title = title + " " + data.app_version;
  1217. }
  1218. if ("hostname" in data) {
  1219. title = data.hostname + " - " + title;
  1220. }
  1221. document.title = title;
  1222. }
  1223. Object.keys(data).forEach(function(key) {
  1224. var i;
  1225. var value = data[key];
  1226. // ---------------------------------------------------------------------
  1227. // Web mode
  1228. // ---------------------------------------------------------------------
  1229. if ("webMode" === key) {
  1230. password = (1 === value);
  1231. $("#layout").toggle(!password);
  1232. $("#password").toggle(password);
  1233. }
  1234. // ---------------------------------------------------------------------
  1235. // Actions
  1236. // ---------------------------------------------------------------------
  1237. if ("action" === key) {
  1238. if ("reload" === data.action) {
  1239. doReload(1000);
  1240. }
  1241. return;
  1242. }
  1243. // ---------------------------------------------------------------------
  1244. // RFBridge
  1245. // ---------------------------------------------------------------------
  1246. //removeIf(!rfbridge)
  1247. if ("rfbCount" === key) {
  1248. for (i=0; i<data.rfbCount; i++) { addRfbNode(); }
  1249. return;
  1250. }
  1251. if ("rfb" === key) {
  1252. var rfb = data.rfb;
  1253. var size = rfb.size;
  1254. var start = rfb.start;
  1255. var processOn = ((rfb.on !== undefined) && (rfb.on.length > 0));
  1256. var processOff = ((rfb.off !== undefined) && (rfb.off.length > 0));
  1257. for (let i = 0; i < size; ++i) {
  1258. let selector = template`input[name='rfbcode'][data-id='${id}'][data-status='${status}']`;
  1259. let id = i + start;
  1260. if (processOn) {
  1261. $(selector({"id": id, "status": 1}))
  1262. .val(rfb.on[i]);
  1263. }
  1264. if (processOff) {
  1265. $(selector({"id": id, "status": 0}))
  1266. .val(rfb.off[i]);
  1267. }
  1268. }
  1269. return;
  1270. }
  1271. //endRemoveIf(!rfbridge)
  1272. // ---------------------------------------------------------------------
  1273. // LightFox
  1274. // ---------------------------------------------------------------------
  1275. //removeIf(!lightfox)
  1276. if ("lightfoxButtons" === key) {
  1277. initLightfox(data["lightfoxButtons"], data["lightfoxRelayCount"]);
  1278. return;
  1279. }
  1280. //endRemoveIf(!lightfox)
  1281. // ---------------------------------------------------------------------
  1282. // RFM69
  1283. // ---------------------------------------------------------------------
  1284. //removeIf(!rfm69)
  1285. if (key == "packet") {
  1286. var packet = data.packet;
  1287. var d = new Date();
  1288. packets.row.add([
  1289. d.toLocaleTimeString('en-US', { hour12: false }),
  1290. packet.senderID,
  1291. packet.packetID,
  1292. packet.targetID,
  1293. packet.key,
  1294. packet.value,
  1295. packet.rssi,
  1296. packet.duplicates,
  1297. packet.missing,
  1298. ]).draw(false);
  1299. return;
  1300. }
  1301. if (key == "mapping") {
  1302. for (var i in data.mapping) {
  1303. // add a new row
  1304. addMapping();
  1305. // get group
  1306. var line = $("#mapping .pure-g")[i];
  1307. // fill in the blanks
  1308. var mapping = data.mapping[i];
  1309. Object.keys(mapping).forEach(function(key) {
  1310. var id = "input[name=" + key + "]";
  1311. if ($(id, line).length) $(id, line).val(mapping[key]);
  1312. });
  1313. setOriginalsFromValues($("input", line));
  1314. }
  1315. return;
  1316. }
  1317. //endRemoveIf(!rfm69)
  1318. // ---------------------------------------------------------------------
  1319. // RPN Rules
  1320. // ---------------------------------------------------------------------
  1321. if (key == "rpnRules") {
  1322. for (var i in data.rpnRules) {
  1323. // add a new row
  1324. addRPNRule();
  1325. // get group
  1326. var line = $("#rpnRules .pure-g")[i];
  1327. // fill in the blanks
  1328. var rule = data.rpnRules[i];
  1329. $("input", line).val(rule);
  1330. setOriginalsFromValues($("input", line));
  1331. }
  1332. return;
  1333. }
  1334. if (key == "rpnTopics") {
  1335. for (var i in data.rpnTopics) {
  1336. // add a new row
  1337. addRPNTopic();
  1338. // get group
  1339. var line = $("#rpnTopics .pure-g")[i];
  1340. // fill in the blanks
  1341. var topic = data.rpnTopics[i];
  1342. var name = data.rpnNames[i];
  1343. $("input[name='rpnTopic']", line).val(topic);
  1344. $("input[name='rpnName']", line).val(name);
  1345. setOriginalsFromValues($("input", line));
  1346. }
  1347. return;
  1348. }
  1349. if (key == "rpnNames") return;
  1350. // ---------------------------------------------------------------------
  1351. // Curtains
  1352. // ---------------------------------------------------------------------
  1353. //removeIf(!curtain)
  1354. function applyCurtain(a, b) {
  1355. $("#curtainGetPicture").css('background', 'linear-gradient(' + a + ', black ' + b + '%, #a0d6ff ' + b + '%)');
  1356. }
  1357. if ("curtainState" === key) {
  1358. initCurtain();
  1359. switch(value.type) {
  1360. case '0': //Roller
  1361. default:
  1362. applyCurtain('180deg', value.get);
  1363. break;
  1364. case '1': //One side left to right
  1365. applyCurtain('90deg', value.get);
  1366. break;
  1367. case '2': //One side right to left
  1368. applyCurtain('270deg', value.get);
  1369. break;
  1370. case '3': //Two sides
  1371. $("#curtainGetPicture").css('background', 'linear-gradient(90deg, black ' + value.get/2 + '%, #a0d6ff ' + value.get/2 + '% ' + (100 - value.get/2) + '%, black ' + (100 - value.get/2) + '%)');
  1372. break;
  1373. }
  1374. $("#curtainSet").val(value.set);
  1375. if(!value.moving) {
  1376. $("button.curtain-button").css('background', 'rgb(66, 184, 221)');
  1377. } else {
  1378. if(!value.button)
  1379. $("button.button-curtain-pause").css('background', 'rgb(192, 0, 0)');
  1380. else if(value.button == 1) {
  1381. $("button.button-curtain-close").css('background', 'rgb(66, 184, 221)');
  1382. $("button.button-curtain-open").css('background', 'rgb(192, 0, 0)');
  1383. }
  1384. else if(value.button == 2) {
  1385. $("button.button-curtain-open").css('background', 'rgb(66, 184, 221)');
  1386. $("button.button-curtain-close").css('background', 'rgb(192, 0, 0)');
  1387. }
  1388. }
  1389. return;
  1390. }
  1391. //endRemoveIf(!curtain)
  1392. // ---------------------------------------------------------------------
  1393. // Lights
  1394. // ---------------------------------------------------------------------
  1395. //removeIf(!light)
  1396. if ("lightstate" === key) {
  1397. $("#color").toggle(value);
  1398. return;
  1399. }
  1400. if (("rgb" === key) || ("hsv" === key)) {
  1401. updateColor(key, value);
  1402. return;
  1403. }
  1404. if ("brightness" === key) {
  1405. $("#brightness").val(value);
  1406. $("span.brightness").html(value);
  1407. return;
  1408. }
  1409. if ("channels" === key) {
  1410. var len = value.length;
  1411. initChannels(len);
  1412. for (i in value) {
  1413. var ch = value[i];
  1414. $("input.slider[data=" + i + "]").val(ch);
  1415. $("span.slider[data=" + i + "]").html(ch);
  1416. }
  1417. return;
  1418. }
  1419. if ("mireds" === key) {
  1420. $("#mireds").attr("min", value["cold"]);
  1421. $("#mireds").attr("max", value["warm"]);
  1422. $("#mireds").val(value["value"]);
  1423. $("span.mireds").html(value["value"]);
  1424. return;
  1425. }
  1426. if ("useWhite" === key) {
  1427. useWhite = value;
  1428. }
  1429. if ("useCCT" === key) {
  1430. initCCT();
  1431. useCCT = value;
  1432. }
  1433. //endRemoveIf(!light)
  1434. // ---------------------------------------------------------------------
  1435. // Sensors & Magnitudes
  1436. // ---------------------------------------------------------------------
  1437. //removeIf(!sensor)
  1438. if ("snsErrors" === key) {
  1439. for (var index in value) {
  1440. var type = value[index][0];
  1441. var name = value[index][1];
  1442. MagnitudeErrors[type] = name;
  1443. }
  1444. return;
  1445. }
  1446. if ("snsMagnitudes" === key) {
  1447. for (var index in value) {
  1448. var type = value[index][0];
  1449. var prefix = value[index][1];
  1450. var name = value[index][2];
  1451. MagnitudeNames[type] = name;
  1452. MagnitudeTypePrefixes[type] = prefix;
  1453. MagnitudePrefixTypes[prefix] = type;
  1454. moduleVisible(prefix);
  1455. }
  1456. return;
  1457. }
  1458. if ("magnitudesConfig" === key) {
  1459. initMagnitudes(value);
  1460. return;
  1461. }
  1462. if ("magnitudes" === key) {
  1463. for (var i=0; i<value.size; ++i) {
  1464. var inputElem = $("input[name='magnitude'][data='" + i + "']");
  1465. var infoElem = inputElem.parent().parent().find("div.sns-info");
  1466. var error = value.error[i] || 0;
  1467. var text = (0 === error)
  1468. ? value.value[i] + Magnitudes[i].units
  1469. : MagnitudeErrors[error];
  1470. inputElem.val(text);
  1471. if (value.info !== undefined) {
  1472. var info = value.info[i] || 0;
  1473. infoElem.toggle(info != 0);
  1474. infoElem.text(info);
  1475. }
  1476. }
  1477. return;
  1478. }
  1479. if ("pzemVisible" === key) {
  1480. $("input[name='snsSave']").prop("disabled", true);
  1481. $("input[name='snsSave']")
  1482. .parent().parent().find(".hint")
  1483. .text("PZEM004 module saves the energy data on it's own")
  1484. return;
  1485. }
  1486. //endRemoveIf(!sensor)
  1487. // ---------------------------------------------------------------------
  1488. // WiFi
  1489. // ---------------------------------------------------------------------
  1490. if ("wifi" === key) {
  1491. maxNetworks = parseInt(value["max"], 10);
  1492. value["networks"].forEach(function(network) {
  1493. addNetwork(fromSchema(network, value.schema));
  1494. });
  1495. return;
  1496. }
  1497. if ("scanResult" === key) {
  1498. $("div.scan.loading").hide();
  1499. $("#button-wifi-scan").attr("disabled", false);
  1500. $("#scanResult").show();
  1501. }
  1502. // -----------------------------------------------------------------------------
  1503. // Relays scheduler
  1504. // -----------------------------------------------------------------------------
  1505. if ("schConfig" === key) {
  1506. $("#schedules")
  1507. .attr("data-settings-max", value.max);
  1508. let schema = value.schema;
  1509. value["schedules"].forEach((entries, id) => {
  1510. let cfg = fromSchema(entries, schema);
  1511. addSchedule(cfg, value);
  1512. });
  1513. return;
  1514. }
  1515. // ---------------------------------------------------------------------
  1516. // Relays
  1517. // ---------------------------------------------------------------------
  1518. if ("relayConfig" === key) {
  1519. if ($("#relays > div").length) {
  1520. return;
  1521. }
  1522. if ($("#relayConfig > legend").length) {
  1523. return;
  1524. }
  1525. let schema = value.schema;
  1526. value["relays"].forEach((entries, id) => {
  1527. let cfg = fromSchema(entries, schema);
  1528. var name = cfg["relayName"];
  1529. if (!cfg.relayName.length) {
  1530. cfg.relayName = "Switch #" + id;
  1531. }
  1532. initRelay(id, cfg, value);
  1533. initRelayConfig(id, cfg, value);
  1534. });
  1535. return;
  1536. }
  1537. if ("relayState" === key) {
  1538. updateRelays(value);
  1539. return;
  1540. }
  1541. // ---------------------------------------------------------------------
  1542. // Curtain(s)
  1543. // ---------------------------------------------------------------------
  1544. //removeIf(!curtain)
  1545. // Relay configuration
  1546. if ("curtainConfig" === key) {
  1547. initCurtainConfig(value);
  1548. return;
  1549. }
  1550. //endRemoveIf(!curtain)
  1551. // ---------------------------------------------------------------------
  1552. // LEDs
  1553. // ---------------------------------------------------------------------
  1554. if ("ledConfig" === key) {
  1555. if ($("#ledConfig > div").length > 0) {
  1556. return;
  1557. }
  1558. let schema = value["schema"];
  1559. value["leds"].forEach((entries, id) => {
  1560. addLed(id, fromSchema(entries, schema), value);
  1561. });
  1562. return;
  1563. }
  1564. // ---------------------------------------------------------------------
  1565. // Domoticz
  1566. // ---------------------------------------------------------------------
  1567. // Domoticz - Relays
  1568. if ("dczRelays" === key) {
  1569. createRelayList(value, "dczRelays", "dczRelayTemplate");
  1570. return;
  1571. }
  1572. // Domoticz - Magnitudes
  1573. //removeIf(!sensor)
  1574. if ("dczMagnitudes" === key) {
  1575. createMagnitudeList(value, "dczMagnitudes", "dczMagnitudeTemplate");
  1576. return;
  1577. }
  1578. //endRemoveIf(!sensor)
  1579. // ---------------------------------------------------------------------
  1580. // Thingspeak
  1581. // ---------------------------------------------------------------------
  1582. // Thingspeak - Relays
  1583. if ("tspkRelays" === key) {
  1584. createRelayList(value, "tspkRelays", "tspkRelayTemplate");
  1585. return;
  1586. }
  1587. // Thingspeak - Magnitudes
  1588. //removeIf(!sensor)
  1589. if ("tspkMagnitudes" === key) {
  1590. createMagnitudeList(value, "tspkMagnitudes", "tspkMagnitudeTemplate");
  1591. return;
  1592. }
  1593. //endRemoveIf(!sensor)
  1594. // ---------------------------------------------------------------------
  1595. // HTTP API
  1596. // ---------------------------------------------------------------------
  1597. // Auto generate an APIKey if none defined yet
  1598. if ("apiVisible" === key) {
  1599. if (data.apiKey === undefined || data.apiKey === "") {
  1600. generateAPIKey();
  1601. }
  1602. }
  1603. // ---------------------------------------------------------------------
  1604. // General
  1605. // ---------------------------------------------------------------------
  1606. if ("saved" === key) {
  1607. configurationSaved = value;
  1608. return;
  1609. }
  1610. if ("message" === key) {
  1611. window.alert(value);
  1612. return;
  1613. }
  1614. // Web log
  1615. if ("weblog" === key) {
  1616. send("{}");
  1617. var msg = value["msg"];
  1618. var pre = value["pre"];
  1619. for (var i=0; i < msg.length; ++i) {
  1620. if (pre[i]) {
  1621. $("#weblog").append(new Text(pre[i]));
  1622. }
  1623. $("#weblog").append(new Text(msg[i]));
  1624. }
  1625. followScroll("weblog");
  1626. return;
  1627. }
  1628. // Enable options
  1629. var position = key.indexOf("Visible");
  1630. if (position > 0 && position === key.length - 7) {
  1631. var module = key.slice(0,-7);
  1632. moduleVisible(module);
  1633. return;
  1634. }
  1635. if ("deviceip" === key) {
  1636. var a_href = $("span[name='" + key + "']").parent();
  1637. a_href.attr("href", "//" + value);
  1638. a_href.next().attr("href", "telnet://" + value);
  1639. }
  1640. if ("now" === key) {
  1641. now = parseInt(value, 10);
  1642. return;
  1643. }
  1644. if ("free_size" === key) {
  1645. free_size = parseInt(value, 10);
  1646. }
  1647. // Pre-process
  1648. if ("mqttStatus" === key) {
  1649. value = value ? "CONNECTED" : "NOT CONNECTED";
  1650. }
  1651. if ("ntpStatus" === key) {
  1652. value = value ? "SYNC'D" : "NOT SYNC'D";
  1653. }
  1654. if ("uptime" === key) {
  1655. ago = 0;
  1656. var uptime = parseInt(value, 10);
  1657. var seconds = uptime % 60; uptime = parseInt(uptime / 60, 10);
  1658. var minutes = uptime % 60; uptime = parseInt(uptime / 60, 10);
  1659. var hours = uptime % 24; uptime = parseInt(uptime / 24, 10);
  1660. var days = uptime;
  1661. value = days + "d " + zeroPad(hours, 2) + "h " + zeroPad(minutes, 2) + "m " + zeroPad(seconds, 2) + "s";
  1662. }
  1663. //removeIf(!thermostat)
  1664. if ("tmpUnits" == key) {
  1665. $("span.tmpUnit").html(data[key] == 3 ? "ºF" : "ºC");
  1666. }
  1667. //endRemoveIf(!thermostat)
  1668. // ---------------------------------------------------------------------
  1669. // Matching
  1670. // ---------------------------------------------------------------------
  1671. var elems = [];
  1672. var pre;
  1673. var post;
  1674. // Look for INPUTs
  1675. var input = $("input[name='" + key + "']");
  1676. if (input.length > 0) {
  1677. if (input.attr("type") === "checkbox") {
  1678. input.prop("checked", value);
  1679. } else if (input.attr("type") === "radio") {
  1680. input.val([value]);
  1681. } else {
  1682. pre = input.attr("pre") || "";
  1683. post = input.attr("post") || "";
  1684. input.val(pre + value + post);
  1685. }
  1686. elems.push(input);
  1687. }
  1688. // Look for SPANs
  1689. var span = $("span[name='" + key + "']");
  1690. if (span.length > 0) {
  1691. if (Array.isArray(value)) {
  1692. value.forEach(function(elem) {
  1693. span.append(elem);
  1694. span.append('</br>');
  1695. elems.push(span);
  1696. });
  1697. } else {
  1698. pre = span.attr("pre") || "";
  1699. post = span.attr("post") || "";
  1700. span.html(pre + value + post);
  1701. elems.push(span);
  1702. }
  1703. }
  1704. // Look for SELECTs
  1705. var select = $("select[name='" + key + "']");
  1706. if (select.length > 0) {
  1707. if (select.attr("multiple") !== undefined) {
  1708. select.val(bitsetToValues(value));
  1709. } else {
  1710. select.val(value);
  1711. }
  1712. elems.push(select);
  1713. }
  1714. setOriginalsFromValues($(elems));
  1715. });
  1716. }
  1717. function hasChanged() {
  1718. var newValue, originalValue;
  1719. if ($(this).attr("type") === "checkbox") {
  1720. newValue = $(this).prop("checked");
  1721. originalValue = ($(this).attr("original") === "true");
  1722. } else {
  1723. newValue = $(this).val();
  1724. originalValue = $(this).attr("original");
  1725. }
  1726. if ($(this).attr("multiple") !== undefined) {
  1727. newValue = newValue.join(",");
  1728. }
  1729. var hasChanged = ("true" === $(this).attr("hasChanged"));
  1730. var action = $(this).attr("action");
  1731. if (typeof originalValue === "undefined") { return; }
  1732. if ("none" === action) { return; }
  1733. if (newValue !== originalValue) {
  1734. if (!hasChanged) {
  1735. ++numChanged;
  1736. if ("reconnect" === action) { ++numReconnect; }
  1737. if ("reboot" === action) { ++numReboot; }
  1738. if ("reload" === action) { ++numReload; }
  1739. }
  1740. $(this).attr("hasChanged", true);
  1741. } else {
  1742. if (hasChanged) {
  1743. --numChanged;
  1744. if ("reconnect" === action) { --numReconnect; }
  1745. if ("reboot" === action) { --numReboot; }
  1746. if ("reload" === action) { --numReload; }
  1747. }
  1748. $(this).attr("hasChanged", false);
  1749. }
  1750. }
  1751. // -----------------------------------------------------------------------------
  1752. // Init & connect
  1753. // -----------------------------------------------------------------------------
  1754. function initUrls(root) {
  1755. var paths = ["ws", "upgrade", "config", "auth"];
  1756. urls["root"] = root;
  1757. paths.forEach(function(path) {
  1758. urls[path] = new URL(path, root);
  1759. urls[path].protocol = root.protocol;
  1760. });
  1761. if (root.protocol == "https:") {
  1762. urls.ws.protocol = "wss:";
  1763. } else {
  1764. urls.ws.protocol = "ws:";
  1765. }
  1766. }
  1767. function connectToURL(url) {
  1768. initUrls(url);
  1769. fetch(urls.auth.href, {
  1770. 'method': 'GET',
  1771. 'cors': true,
  1772. 'credentials': 'same-origin'
  1773. }).then(function(response) {
  1774. // Nothing to do, reload page and retry
  1775. if (response.status != 200) {
  1776. doReload(5000);
  1777. return;
  1778. }
  1779. // update websock object
  1780. if (websock) { websock.close(); }
  1781. websock = new WebSocket(urls.ws.href);
  1782. websock.onmessage = function(evt) {
  1783. var data = {};
  1784. try {
  1785. data = JSON.parse(evt.data
  1786. .replace(/\n/g, "\\n")
  1787. .replace(/\r/g, "\\r")
  1788. .replace(/\t/g, "\\t"));
  1789. } catch (e) {
  1790. console.log(e);
  1791. }
  1792. processData(data);
  1793. };
  1794. websock.onclose = function(evt) {
  1795. clearInterval(ws_pingpong);
  1796. if (window.confirm("Connection lost with the device, click OK to refresh the page")) {
  1797. $("#layout").toggle(false);
  1798. window.location.reload();
  1799. }
  1800. }
  1801. websock.onopen = function(evt) {
  1802. ws_pingpong = setInterval(function() { sendAction("ping", {}); }, 5000);
  1803. }
  1804. }).catch(function(error) {
  1805. console.log(error);
  1806. doReload(5000);
  1807. });
  1808. }
  1809. function connect(host) {
  1810. if (!host.startsWith("http:") && !host.startsWith("https:")) {
  1811. host = "http://" + host;
  1812. }
  1813. connectToURL(new URL(host));
  1814. }
  1815. function connectToCurrentURL() {
  1816. connectToURL(new URL(window.location));
  1817. }
  1818. $(function() {
  1819. // most of the time, we want this unconditionally for all <a href="..."></a>
  1820. $("a.external")
  1821. .attr("target", "_blank")
  1822. .attr("rel", "noopener")
  1823. .attr("tabindex", "-1");
  1824. createCheckboxes();
  1825. setInterval(function() { keepTime(); }, 1000);
  1826. $(".password-reveal").on("click", toggleVisiblePassword);
  1827. $("#menuLink").on("click", toggleMenu);
  1828. $(".pure-menu-link").on("click", showPanel);
  1829. $("progress").attr({ value: 0, max: 100 });
  1830. $("#button-wifi-scan").on("click", doScan);
  1831. $(".button-update").on("click", doUpdate);
  1832. $(".button-update-password").on("click", doUpdatePassword);
  1833. $(".button-generate-password").on("click", doGeneratePassword);
  1834. $(".button-reboot").on("click", doReboot);
  1835. $(".button-reconnect").on("click", doReconnect);
  1836. $(".button-dbgcmd").on("click", doDebugCommand);
  1837. $("input[name='dbgcmd']").enterKey(doDebugCommand);
  1838. $(".button-dbg-clear").on("click", doDebugClear);
  1839. $(".button-settings-backup").on("click", doBackup);
  1840. $(".button-settings-restore").on("click", doRestore);
  1841. $(".button-settings-factory").on("click", doFactoryReset);
  1842. $("#uploader").on("change", onFileUpload);
  1843. $(".button-upgrade").on("click", doUpgrade);
  1844. //removeIf(!garland)
  1845. $(".checkbox-garland-enable").on("change", function() {
  1846. sendAction("garland_switch", {status: $(this).prop("checked") ? 1 : 0});
  1847. });
  1848. $(".slider-garland-brightness").on("change", function() {
  1849. sendAction("garland_set_brightness", {brightness: $(this)[0].value});
  1850. });
  1851. $(".slider-garland-speed").on("change", function() {
  1852. sendAction("garland_set_speed", {speed: $(this)[0].value});
  1853. });
  1854. $(".button-garland-set-default").on("click", function() {
  1855. sendAction("garland_set_default", {});
  1856. });
  1857. //endRemoveIf(!garland)
  1858. //removeIf(!thermostat)
  1859. $(".button-thermostat-reset-counters").on('click', doResetThermostatCounters);
  1860. //endRemoveIf(!thermostat)
  1861. $(".button-apikey").on("click", generateAPIKey);
  1862. $(".button-upgrade-browse").on("click", function() {
  1863. $("input[name='upgrade']")[0].click();
  1864. return false;
  1865. });
  1866. $("input[name='upgrade']").change(function (){
  1867. var file = this.files[0];
  1868. $("input[name='filename']").val(file.name);
  1869. });
  1870. $(".button-add-network").on("click", function() {
  1871. $(".more", addNetwork()).toggle();
  1872. });
  1873. $(".button-add-switch-schedule").on("click", function() {
  1874. addSchedule({schType: 1, schSwitch: -1});
  1875. });
  1876. //removeIf(!light)
  1877. $(".button-add-light-schedule").on("click", function() {
  1878. addSchedule({schType: 2, schSwitch: -1});
  1879. });
  1880. //endRemoveIf(!light)
  1881. //removeIf(!curtain)
  1882. $(".button-add-curtain-schedule").on("click", function() {
  1883. addSchedule({schType: 3, schSwitch: -1});
  1884. });
  1885. //endRemoveIf(!curtain)
  1886. $(".button-add-rpnrule").on('click', addRPNRule);
  1887. $(".button-add-rpntopic").on('click', addRPNTopic);
  1888. $(".button-del-parent").on('click', delParent);
  1889. //removeIf(!rfm69)
  1890. $(".button-add-mapping").on('click', addMapping);
  1891. $(".button-clear-counts").on('click', doClearCounts);
  1892. $(".button-clear-messages").on('click', doClearMessages);
  1893. $(".button-clear-filters").on('click', doClearFilters);
  1894. $('#packets tbody').on('mousedown', 'td', doFilter);
  1895. packets = $('#packets').DataTable({
  1896. "paging": false
  1897. });
  1898. for (var i = 0; i < packets.columns()[0].length; i++) {
  1899. filters[i] = false;
  1900. }
  1901. //endRemoveIf(!rfm69)
  1902. $(".gpio-select").each(function(_, elem) {
  1903. initSelectGPIO(elem)
  1904. });
  1905. $(document).on("change", "input", hasChanged);
  1906. $(document).on("change", "select", hasChanged);
  1907. $("textarea").on("dblclick", function() { this.select(); });
  1908. resetOriginals();
  1909. $(".settings-group").each(function() {
  1910. groupSettingsObserver.observe(this, {childList: true});
  1911. });
  1912. // don't autoconnect when opening from filesystem
  1913. if (window.location.protocol === "file:") {
  1914. processData({"webMode": 0});
  1915. return;
  1916. }
  1917. // Check host param in query string
  1918. var search = new URLSearchParams(window.location.search),
  1919. host = search.get("host");
  1920. if (host !== null) {
  1921. connect(host);
  1922. } else {
  1923. connectToCurrentURL();
  1924. }
  1925. });