Mapping % sensor to RGB value for light

Still a newbie and even if I’ve succeeded in adding a bunch of integrations from lights and switches, to the alarm system and car position to trigger events, I have no idea how to add more logic.

What I want to do is set the light color after the charge % in my car battery.

Setting it with the service light.turn_on and static RGB values is no problem, what I want to do is whenever the sensor.car_state_of_charge changes, change the RGB values according to the formula:

if(charge <= 0.5)
{
    red = (charge * 2) * 255.0;
    green = 255.0;
    blue = 0;
}else
{
    red = 255.0;
    green = 255.0 + 255.0 - ((charge  * 2)* 255);
    blue = 0;
}

and then call light.turn_on with these variables.

Appreciate help and pointers.