Skip to content

Instantly share code, notes, and snippets.

@Frontesque
Created May 17, 2023 21:58
Show Gist options
  • Save Frontesque/4ec09ce0f860b5559e7930fa6e37cdf8 to your computer and use it in GitHub Desktop.
Save Frontesque/4ec09ce0f860b5559e7930fa6e37cdf8 to your computer and use it in GitHub Desktop.
rgb2tuya - Convert RGB to the Tuya-compatible color string
function rgb2hsv(r, g, b) {
r /= 255, g /= 255, b /= 255;
var max = Math.max(r, g, b), min = Math.min(r, g, b);
var h, s, v = max;
var d = max - min;
s = max == 0 ? 0 : d / max;
if (max == min) {
h = 0; // achromatic
} else {
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;
}
return [ h, s, v ];
}
function rgb2tuya(r,g,b) {
//--- Set Up Initial Values ---//
const rgb = [r,g,b];
const hsv = rgb2hsv(rgb[0] / 255, rgb[1] / 255, rgb[2] / 255);
//--- Set Final Values ---//
let hexValue = new String();
let hexValue_hsv = new String();
//--- Generate HEX ---//
for (const i in rgb) {
let hex = rgb[i].toString(16)
if (hex.length == 1) hex = '0'+hex;
hexValue += hex;
}
//--- Generate HSV ---//
let hsvarray = [parseInt(hsv[0] * 360), parseInt(hsv[1] * 255), parseInt(hsv[2] * 255)]
for (const i in hsvarray) {
let hex = hsvarray[i].toString(16)
if (hex.length == 1) hex = '0'+hex;
hexValue_hsv += hex;
}
//--- Ensure that HSV is correct length ---//
if (hexValue_hsv.length == 7) hexValue_hsv = "0"+hexValue_hsv;
if (hexValue_hsv.length == 6) hexValue_hsv = "00"+hexValue_hsv;
//--- Return data to function call ---//
return hexValue+hexValue_hsv.slice(0,-2)+"ff"; // replacing last 2 digits to force the bulb to use full brightness
}
module.exports = rgb2tuya;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment