File: dpt_232.py

package info (click to toggle)
python-xknx 3.10.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 4,044 kB
  • sloc: python: 40,087; javascript: 8,556; makefile: 32; sh: 12
file content (77 lines) | stat: -rw-r--r-- 2,146 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
"""Implementation of KNX RGB color data point type."""

from __future__ import annotations

from collections.abc import Mapping
from dataclasses import dataclass
from typing import Any

from .dpt import DPTComplex, DPTComplexData
from .payload import DPTArray, DPTBinary


@dataclass(slots=True)
class RGBColor(DPTComplexData):
    """
    Representation of RGB color.

    `red`: int 0..255
    `green`: int 0..255
    `blue`: int 0..255
    """

    red: int
    green: int
    blue: int

    @classmethod
    def from_dict(cls, data: Mapping[str, Any]) -> RGBColor:
        """Init from a dictionary."""
        try:
            red = int(data["red"])
            green = int(data["green"])
            blue = int(data["blue"])
        except KeyError as err:
            raise ValueError(f"Missing required key: {err}") from err
        except (ValueError, TypeError) as err:
            raise ValueError(f"Invalid value for RGB color: {err}") from err

        return cls(red=red, green=green, blue=blue)

    def as_dict(self) -> dict[str, int]:
        """Create a JSON serializable dictionary."""
        return {
            "red": self.red,
            "green": self.green,
            "blue": self.blue,
        }


class DPTColorRGB(DPTComplex[RGBColor]):
    """Abstraction for KNX 3 octet color RGB (DPT 232.600)."""

    data_type = RGBColor
    payload_type = DPTArray
    payload_length = 3
    dpt_main_number = 232
    dpt_sub_number = 600
    value_type = "color_rgb"

    @classmethod
    def from_knx(cls, payload: DPTArray | DPTBinary) -> RGBColor:
        """Parse/deserialize from KNX/IP raw data."""
        raw = cls.validate_payload(payload)
        return RGBColor(
            red=raw[0],
            green=raw[1],
            blue=raw[2],
        )

    @classmethod
    def _to_knx(cls, value: RGBColor) -> DPTArray:
        """Serialize to KNX/IP raw data."""
        colors: tuple[int, int, int] = (value.red, value.green, value.blue)
        for color in colors:
            if not 0 <= color <= 255:
                raise ValueError(f"Color value out of range 0..255: {value}")
        return DPTArray(colors)