>Daniel's Homepage

Posts

My posts about programming and things.
Date format is day/month/year because I'm sane.

Setting my rooms lighting to match my background

5/3/2025

I use Home Assistant for various things, one is controlling the two RGB lightbulbs in my room.

I have recently put a TV up on my wall, when I am not watching something on it, I generally leave it with the background showing. I've found at night when I turn my lights down it creates a nice warm glow of color. So I decided to automatically change my lights color to match that of the background.

The script is pretty simple, it sets the background (swww daemon) to a random image every 5 minutes. I take the average color of that image and send it to Home Assistant which sets my rooms lights to match this color. The brightness is controlled by me.

I also added a toggle inside Home Assistant that can disable the scripts ability to change the lights, this is so during the day when I just want normal lighting I can turn it off easily.




This is the script:

#!/bin/bash

sleep 2

if [[ $# -lt 1 ]] || [[ ! -d $1   ]]; then
    echo "Usage:
    $0 "
    exit 1
fi

# Edit below to control the images transition
export SWWW_TRANSITION_FPS=60
export SWWW_TRANSITION_STEP=2

INTERVAL=300

HA_URL="http://URL:8123"
BEARER_TOKEN="TOKEN"
hex_to_rgb() {
    hex=$1
    r=$(echo $((16#${hex:1:2})))
    g=$(echo $((16#${hex:3:2})))
    b=$(echo $((16#${hex:5:2})))
    echo "$r,$g,$b"
}


while true; do
    find "$1" -type f \
    | while read -r img; do
        echo "$((RANDOM % 1000)):$img"
    done \
    | sort -n | cut -d':' -f2- \
    | while read -r img; do
        swww img "$img"
        color=$(convert ${img} -resize 1x1 txt:- | grep -Po "#[[:xdigit:]]{6}")
        rgb=$(hex_to_rgb $color)
        # Check if light control is enabled by checking the input_boolean state
        light_control_enabled=$(curl -s -X GET -H "Authorization: Bearer $BEARER_TOKEN" \
        "$HA_URL/api/states/input_boolean.light_control_enabled" | jq -r '.state')
        
        if [ "$light_control_enabled" != "on" ]; then
            echo "Light control is disabled."
        else
            curl -X POST -H "Authorization: Bearer $BEARER_TOKEN" \
            -H "Content-Type: application/json" \
            -d "{\"entity_id\": \"light.bedroom_lights\", \"rgb_color\": [$rgb]}" \
            $HA_URL/api/services/light/turn_on
        fi
        curl -X POST http://192.168.1.216/pump -H "Content-Type: application/json" -d "{\"avgcol\": \"${color}\"}"
        sleep $INTERVAL
    done
done




FSF member


RSS feed

page generated 5/3/2025 using websitegenerator in C