view color.py @ 23:7d9a056e29fe

esp rgbw output; cleanup
author drewp@bigasterisk.com
date Mon, 29 Jan 2024 23:41:27 -0800
parents ab80e8826441
children
line wrap: on
line source

import logging
from dataclasses import dataclass

from dataclasses_json import DataClassJsonMixin

log = logging.getLogger('colr')


def lerp(a, b, t):
    return (1 - t) * a + (t) * b


@dataclass(frozen=True)
class Color(DataClassJsonMixin):
    """This is a target color that should look "the same" on all lights you send
    it to. We convert it somehow to a DeviceColor which has the color
    coordinates (maybe not RGB) that get sent to a light."""
    r: float
    g: float
    b: float

    def __post_init__(self):
        super().__setattr__('r', max(0, min(1, self.r)))
        super().__setattr__('g', max(0, min(1, self.g)))
        super().__setattr__('b', max(0, min(1, self.b)))

    def __repr__(self):
        return f'(Color(r={self.r:.3f}, g={self.g:.3f}, b={self.b:.3f}))'

    def avg(self):
        return (self.r + self.g + self.b) / 3

    def mix(self, other, x):
        return Color(
            lerp(self.r, other.r, x),
            lerp(self.g, other.g, x),
            lerp(self.b, other.b, x),
        )

    def hex(self):
        r, g, b = int(self.r * 255), int(self.g * 255), int(self.b * 255)
        return '#%02x%02x%02x' % (r, g, b)

    @classmethod
    def fromHex(cls, h: str):
        return cls(
            r=int(h[1:3], 16) / 255,
            g=int(h[3:5], 16) / 255,
            b=int(h[5:7], 16) / 255,
        )