From b2bf9ba767050ec1581dd3641885fe1132ac45aa Mon Sep 17 00:00:00 2001 From: Jan Scheiper Date: Sun, 16 Feb 2020 17:36:29 +0100 Subject: [PATCH] added some utility functions from various plugins --- index.js | 1 + package.json | 2 +- utils.js | 75 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 77 insertions(+), 1 deletion(-) create mode 100644 utils.js diff --git a/index.js b/index.js index 0ac3e31..caaacf7 100644 --- a/index.js +++ b/index.js @@ -3,4 +3,5 @@ module.exports = { HCSwitch: require('./SwitchBase'), HCFogmachine: require('./FogmachineBase'), StateUpdateManager: require('./StateUpdateManager'), + utils: require('./utils'), }; \ No newline at end of file diff --git a/package.json b/package.json index ad53446..67eb602 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "homecontrol-control-base", - "version": "1.1.0", + "version": "1.2.0", "description": "Base class which all hc-controls inherit from", "main": "index.js", "scripts": { diff --git a/utils.js b/utils.js new file mode 100644 index 0000000..794594c --- /dev/null +++ b/utils.js @@ -0,0 +1,75 @@ +function fillPartialHSL(newcolor, oldcolor) { + //console.log(newcolor, oldcolor); + let color = {}; + color.hue = (newcolor.hue != null) ? newcolor.hue : oldcolor.hue; + color.sat = (newcolor.sat != null) ? newcolor.sat : oldcolor.sat; + color.l = (newcolor.l != null) ? newcolor.l : oldcolor.l; + return color; +} + +function clamp(value, min, max) { + return Math.min(max, Math.max(min, value)); +} + +function HSL_to_RGB(hsl) { + let h = hsl.hue / 360; + let s = hsl.sat / 100; + let l = hsl.l / 100; + + let r, g, b; + + if (s == 0) { + r = g = b = l; // achromatic + } else { + let q = l < 0.5 ? l * (1 + s) : l + s - l * s; + let p = 2 * l - q; + + r = hue2rgb(p, q, h + 1/3); + g = hue2rgb(p, q, h); + b = hue2rgb(p, q, h - 1/3); + } + + return { + red: Math.round(r * 255), + green: Math.round(g * 255), + blue: Math.round(b * 255) + }; +} + +function RGB_to_HSL(rgb) { + let r = rgb.red / 255; + let g = rgb.green / 255; + let b = rgb.blue / 255; + + let max = Math.max(r, g, b), min = Math.min(r, g, b); + + if (max == min || max - min < 0.01) { + h = s = 0; // achromatic + } else { + var d = max - min; + s = d / (2 - max - min); + + switch (max) { + case r: h = (g - b) / d + (g < b ? 6 : 0); break; + case g: h = (b - r) / d + 2; break; + case b: h = (r - g) / d + 4; break; + } + + h /= 6; + } + + let l = 1 - 0.5 * s; + + return { + hue: Math.round(h * 360), + sat: Math.round(s * 100), + l: Math.round(l * 100) + }; +} + +module.exports = { + fillPartialHSL, + clamp, + HSL_to_RGB, + RGB_to_HSL, +}; \ No newline at end of file