IKEA Tradfri Color Changing bulb on Hue Bridge no control of colors

Hello,
based on the workaround from ei_Gelb_Geek I created a script where it is possible to use the colorpicker. It’s not perfect, but in many cases the bulb takes on the color I picked in OH.
The script takes the HSB value as input, translates it into RGB, then XYZ and finally into xy.

#!/bin/bash

# -- $1 = Bulb ID -- $2 = HSB Value           

openhab_ip="192.168.xxx.xxx:80"
rest_api="yyy"     --api key 

#Functions
function round_down {
    echo $(printf %.$2f $(echo "scale=$2;(((10^$2)*$1))/(10^$2)" | bc))
};

function inverse_rgb {
    if (( $(echo "$1 < 0.04045" | bc -l) ));
    then
        echo $(bc <<< "scale=9; $1/12.92")
    else
        echo $(bc -l <<< "scale=9; e(2.4*l(($1+0.055)/1.055))")
    fi
};


#1 convert HSB to RGB
IFS=',' read -r -a HSBarray <<< "$2"

H=${HSBarray[0]}
S=${HSBarray[1]}
B=${HSBarray[2]}
    #echo "HSB:"$H, $S, $B

H=$(bc <<< "scale=9; $H/360")
B=$(bc <<< "scale=9; $B/100")
S=$(bc <<< "scale=9; $S/100")
    #echo "HSB:"$H, $S, $B

i=$(bc <<< "scale=9; $H*6")
i=$(round_down $i 0);
    #echo $i
f=$(bc <<< "scale=9; $H*6-$i")
    #echo $f
p=$(bc <<< "scale=9; $B*(1-$S)")
    #echo $p
q=$(bc <<< "scale=9; $B*(1-$f*$S)")
    #echo $q
t=$(bc <<< "scale=9; $B*(1-(1-$f)*$S)")
    #echo $t
icase=$(bc <<< "scale=0; $i%6")
    #echo $icase
case "$icase" in
"0")
    r=$B
    g=$t
    b=$p
    ;;
"1")
    r=$q
    g=$B
    b=$p
    ;;
"2")
    r=$p
    g=$B
    b=$t
    ;;
"3")
    r=$p
    g=$q
    b=$B
    ;;
"4")
    r=$t
    g=$p
    b=$B
    ;;
"5")
    r=$B
    g=$p
    b=$q
    ;;
esac
    #echo $r, $g, $b
R=$(bc <<< "scale=9; $r*255")
G=$(bc <<< "scale=9; $g*255")
B=$(bc <<< "scale=9; $b*255")
    #echo $R, $G, $B

#2 convert RGB to XYZ
    #2a Inverse sRGB Companding
r=`inverse_rgb $r`
g=`inverse_rgb $g`
b=`inverse_rgb $b`
#echo $r, $g, $b

    #2b RGB Matrix Calculation
m1[0]=0.4124564
m1[1]=0.3575761
m1[2]=0.1804375
m2[0]=0.2126729
m2[1]=0.7151522
m2[2]=0.072175
m3[0]=0.0193339
m3[1]=0.119192
m3[2]=0.9503041
rgb[0]=$r
rgb[1]=$g
rgb[2]=$b

X=0
for (( c=0; c<3; c++ ));
do
   X=$(bc <<< "scale=9; $X+${m1[$c]}*${rgb[$c]}")
done
Y=0
for (( c=0; c<3; c++ ));
do
   Y=$(bc <<< "scale=9; $Y+${m2[$c]}*${rgb[$c]}")
done
Z=0
for (( c=0; c<3; c++ ));
do
   Z=$(bc <<< "scale=9; $Z+${m3[$c]}*${rgb[$c]}")
done
    #echo $X, $Y, $Z

#3 convert XYZ to xy
x=$(bc <<< "scale=9; $X/($X+$Y+$Z)")
y=$(bc <<< "scale=9; $Y/($X+$Y+$Z)")
    #echo $x, $y
x="0"$x
y="0"$y

#4 Send via RestAPI
curl -s -H  "Accept: application/json" -X PUT --data '{ "on": true, "xy": ['"$x"','"$y"']}' http://$openhab_ip/api/$rest_api/lights/$1/state

2 Likes