view color_convert.py @ 29:35affd4d37d4 default tip

add 1st ikea color light
author drewp@bigasterisk.com
date Sat, 14 Dec 2024 22:36:29 -0800
parents ecbbf76318bb
children
line wrap: on
line source

import colorsys
import logging
from dataclasses import dataclass

from color import Color

log = logging.getLogger('conv')


def inverseLerp(a, b, val) -> float:
    return (val - a) / (b - a)


def clamped(x) -> float:
    return min(1, max(0, x))


def simpleWhiteVal(r, g, b) -> float:
    h, s, v = colorsys.rgb_to_hsv(r, g, b)
    return (1 - s)**2 * clamped(inverseLerp(.5, 1, v))**2


@dataclass(frozen=True)
class DeviceColor:
    """neutral representation of the adjusted color that we send to a device"""
    r: float = 0
    g: float = 0
    b: float = 0
    w: float = 0
    x: float = 0
    y: float = 0
    cw: float = 0
    ww: float = 0
    brightness: float = 0
    temp: float = 0

    def summary(self) -> dict:
        return dict([(k, round(v, 3)) for k, v in self.__dict__.items() if v > 0])


# fix this to send what z2m likes
def zbConv(c: Color) -> DeviceColor:
    return DeviceColor(r=c.r, g=c.g, b=c.b, brightness=max(c.r, c.g, c.b))


def ikeaWhiteConv(c: Color) -> DeviceColor:
    return DeviceColor(brightness=max(c.r, c.g, c.b), temp=454)


def oneWhiteConv(c: Color) -> DeviceColor:
    return DeviceColor(r=c.r, g=c.g, b=c.b, w=simpleWhiteVal(c.r, c.g, c.b))


def brightnessConv(c: Color) -> DeviceColor:
    return DeviceColor(brightness=max(c.r, c.g, c.b))


def twoWhitesConv(c: Color) -> DeviceColor:
    return DeviceColor(r=c.r, g=c.g, b=c.b, cw=simpleWhiteVal(c.r, c.g, c.b), ww=simpleWhiteVal(c.r, c.g, c.b))


def relayConv(c: Color) -> DeviceColor:
    return DeviceColor(brightness=1 if (max(c.r, c.g, c.b) > 0) else 0)