mirror of
https://github.com/fmtr/haco.git
synced 2026-10-26 19:01:51 -04:00
Refactor data models: Replace dataclass with pydantic and simplify imports
This commit is contained in:
parent
f1b1cac91a
commit
4d65bf6a59
20 changed files with 107 additions and 103 deletions
51
haco/base.py
51
haco/base.py
|
|
@ -1,38 +1,39 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, fields
|
||||
from typing import Any
|
||||
from typing import Any, ClassVar
|
||||
|
||||
from pydantic import ConfigDict
|
||||
|
||||
from corio import dm
|
||||
|
||||
|
||||
@dataclass(kw_only=True)
|
||||
class Base:
|
||||
class Base(dm.Base):
|
||||
"""
|
||||
|
||||
Base class for haco objects. Provides model dumping functionality.
|
||||
|
||||
"""
|
||||
model_config = ConfigDict(arbitrary_types_allowed=True, extra='allow')
|
||||
DATA: ClassVar[dict[str, Any]] = {}
|
||||
|
||||
DATA = dict()
|
||||
|
||||
def model_dump(self) -> dict[str, Any]:
|
||||
def model_dump(self, *args, **kwargs) -> dict[str, Any]:
|
||||
"""
|
||||
Dump this model for Home Assistant discovery payloads.
|
||||
|
||||
Dump the object to a dictionary, excluding fields marked with `exclude=True` in metadata.
|
||||
|
||||
Behavior differences from vanilla Pydantic:
|
||||
- Defaults to `exclude_none=True`.
|
||||
- Merges class-level `DATA` into the dumped mapping.
|
||||
- Excludes runtime extra attributes (used for dynamic callbacks) so they
|
||||
do not leak into announce payloads.
|
||||
"""
|
||||
data = {} | self.DATA
|
||||
for fld in fields(self):
|
||||
meta = fld.metadata
|
||||
if meta.get('exclude', False):
|
||||
continue
|
||||
|
||||
value = getattr(self, fld.name)
|
||||
|
||||
if hasattr(value, self.model_dump.__name__):
|
||||
value = value.model_dump()
|
||||
elif isinstance(value, list):
|
||||
value = [v.model_dump() if hasattr(v, self.model_dump.__name__) else v for v in value]
|
||||
|
||||
if value is not None:
|
||||
data[fld.name] = value
|
||||
return data
|
||||
kwargs.setdefault("exclude_none", True)
|
||||
exclude = kwargs.pop("exclude", None)
|
||||
extra = getattr(self, "__pydantic_extra__", None) or {}
|
||||
extra_keys = set(extra.keys())
|
||||
if exclude is None:
|
||||
exclude = extra_keys
|
||||
elif isinstance(exclude, set):
|
||||
exclude |= extra_keys
|
||||
else:
|
||||
exclude = set(exclude) | extra_keys
|
||||
return self.DATA | super().model_dump(*args, exclude=exclude, **kwargs)
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
from dataclasses import dataclass
|
||||
from enum import StrEnum
|
||||
from typing import ClassVar
|
||||
|
||||
from haco.capabilities import Capability
|
||||
from haco.control import Control
|
||||
|
|
@ -43,14 +43,13 @@ class DeviceClass(StrEnum):
|
|||
WINDOW = "window" # on means open, off means closed
|
||||
|
||||
|
||||
@dataclass(kw_only=True)
|
||||
class BinarySensor(Control):
|
||||
"""
|
||||
|
||||
A binary sensor for reporting on/off states to Home Assistant.
|
||||
|
||||
"""
|
||||
DATA = dict(
|
||||
DATA: ClassVar[dict] = dict(
|
||||
platform='binary_sensor'
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -1,17 +1,16 @@
|
|||
from dataclasses import dataclass
|
||||
from typing import ClassVar
|
||||
|
||||
from haco.capabilities import Capability
|
||||
from haco.control import Control
|
||||
|
||||
|
||||
@dataclass(kw_only=True)
|
||||
class Button(Control):
|
||||
"""
|
||||
|
||||
A button control that can be pressed in Home Assistant.
|
||||
|
||||
"""
|
||||
DATA = dict(
|
||||
DATA: ClassVar[dict] = dict(
|
||||
platform='button'
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,8 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import TYPE_CHECKING, Type
|
||||
from typing import TYPE_CHECKING, Type, ClassVar
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from corio.iterator_tools import strip_none
|
||||
|
||||
|
|
@ -13,7 +14,6 @@ if TYPE_CHECKING:
|
|||
from haco.control import Control
|
||||
|
||||
|
||||
@dataclass(kw_only=True)
|
||||
class Capability(Base):
|
||||
"""
|
||||
|
||||
|
|
@ -22,14 +22,19 @@ class Capability(Base):
|
|||
"""
|
||||
name: str | None = None
|
||||
|
||||
converters: Type[Converters] | None = field(default=None, metadata=dict(exclude=True))
|
||||
converters: Type[Converters] | None = Field(default=None, exclude=True, repr=False)
|
||||
|
||||
state: AnnounceTopicState | None = field(default_factory=AnnounceTopicState)
|
||||
command: AnnounceTopicCommand | None = field(default_factory=AnnounceTopicCommand)
|
||||
state: AnnounceTopicState | None = Field(default_factory=AnnounceTopicState)
|
||||
command: AnnounceTopicCommand | None = Field(default_factory=AnnounceTopicCommand)
|
||||
|
||||
|
||||
parent: Control | None = None
|
||||
announce = None
|
||||
parent: Control | None = Field(default=None, exclude=True, repr=False)
|
||||
announce: ClassVar[None] = None
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
from haco.control import Control
|
||||
Control == Control
|
||||
super().__init__(**kwargs)
|
||||
|
||||
def set_parent(self, control: Control):
|
||||
"""
|
||||
|
|
|
|||
|
|
@ -1,18 +1,16 @@
|
|||
from dataclasses import dataclass
|
||||
from typing import Literal
|
||||
from typing import Literal, ClassVar
|
||||
|
||||
from haco.capabilities import Capability
|
||||
from haco.control import Control
|
||||
|
||||
|
||||
@dataclass(kw_only=True)
|
||||
class Climate(Control):
|
||||
"""
|
||||
|
||||
A climate control for managing HVAC systems.
|
||||
|
||||
"""
|
||||
DATA = dict(
|
||||
DATA: ClassVar[dict] = dict(
|
||||
platform='climate'
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -1,8 +1,9 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import TYPE_CHECKING, TypeVar, Generic, Type, ClassVar
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from corio import Constants
|
||||
from corio import Path
|
||||
from corio.json_tools import to_json
|
||||
|
|
@ -16,10 +17,9 @@ from haco.utils import sanitize_name, Converters, ConvertersBool, get_prefix
|
|||
if TYPE_CHECKING:
|
||||
from haco.device import Device
|
||||
|
||||
DeviceT = TypeVar("DeviceT", bound="Device")
|
||||
DeviceT = TypeVar("DeviceT")
|
||||
|
||||
|
||||
@dataclass(kw_only=True)
|
||||
class Control(Base, Generic[DeviceT]):
|
||||
"""
|
||||
|
||||
|
|
@ -30,14 +30,14 @@ class Control(Base, Generic[DeviceT]):
|
|||
|
||||
name: str
|
||||
icon: str | None = None
|
||||
device: DeviceT = field(default=None, init=False)
|
||||
capabilities: None | list[Capability] = field(default=None, metadata=dict(exclude=True))
|
||||
unique_id: str | None = field(default=None, init=False)
|
||||
availability_topic: str | None = field(default=None, init=False)
|
||||
device: DeviceT | None = Field(default=None, exclude=True, repr=False)
|
||||
capabilities: list = Field(default_factory=list, exclude=True, repr=False)
|
||||
unique_id: str | None = None
|
||||
availability_topic: str | None = None
|
||||
|
||||
subscriptions: dict | None = field(default=None, metadata=dict(exclude=True), init=False)
|
||||
subscriptions: dict | None = Field(default=None, exclude=True, repr=False)
|
||||
|
||||
def __post_init__(self):
|
||||
def model_post_init(self, __context):
|
||||
self.capabilities = self.get_capabilities()
|
||||
|
||||
if not self.icon:
|
||||
|
|
|
|||
|
|
@ -1,10 +1,11 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from functools import cached_property
|
||||
from pathlib import Path
|
||||
from typing import List, TYPE_CHECKING
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from haco.base import Base
|
||||
from haco.control import Control
|
||||
from haco.utils import sanitize_name
|
||||
|
|
@ -13,7 +14,6 @@ if TYPE_CHECKING:
|
|||
from haco.client import ClientHaco
|
||||
|
||||
|
||||
@dataclass(kw_only=True)
|
||||
class Device(Base):
|
||||
"""
|
||||
|
||||
|
|
@ -25,12 +25,17 @@ class Device(Base):
|
|||
model: str | None = None
|
||||
sw_version: str | None = None
|
||||
|
||||
identifiers: list[str] | None = field(default=None, init=False)
|
||||
identifiers: list[str] | None = None
|
||||
|
||||
controls: List[Control] = field(default_factory=list, metadata=dict(exclude=True))
|
||||
controls: List[Control] = Field(default_factory=list, exclude=True, repr=False)
|
||||
|
||||
parent: ClientHaco | None = field(metadata=dict(exclude=True), init=False)
|
||||
subscriptions: dict | None = field(default=None, metadata=dict(exclude=True), init=False)
|
||||
parent: ClientHaco | None = Field(default=None, exclude=True, repr=False)
|
||||
subscriptions: dict | None = Field(default=None, exclude=True, repr=False)
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
from haco.client import ClientHaco
|
||||
ClientHaco == ClientHaco
|
||||
super().__init__(**kwargs)
|
||||
|
||||
def set_parent(self, client: ClientHaco):
|
||||
"""
|
||||
|
|
|
|||
|
|
@ -1,18 +1,17 @@
|
|||
from dataclasses import dataclass
|
||||
from typing import ClassVar
|
||||
|
||||
from haco.capabilities import Capability
|
||||
from haco.control import Control
|
||||
from haco.utils import ON, OFF, ConvertersNumeric, ConvertersString
|
||||
|
||||
|
||||
@dataclass(kw_only=True)
|
||||
class Fan(Control):
|
||||
"""
|
||||
|
||||
A fan control with support for speed percentage, preset modes, and oscillation.
|
||||
|
||||
"""
|
||||
DATA = dict(
|
||||
DATA: ClassVar[dict] = dict(
|
||||
platform="fan"
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
from dataclasses import dataclass
|
||||
from enum import StrEnum
|
||||
from typing import ClassVar, Type
|
||||
|
||||
|
|
@ -12,14 +11,13 @@ class Mode(StrEnum):
|
|||
SLIDER = "slider"
|
||||
|
||||
|
||||
@dataclass(kw_only=True)
|
||||
class Number(Control):
|
||||
"""
|
||||
|
||||
A number control (slider or box) for numeric input in Home Assistant.
|
||||
|
||||
"""
|
||||
DATA = dict(
|
||||
DATA: ClassVar[dict] = dict(
|
||||
platform='number'
|
||||
)
|
||||
converters: ClassVar[Type[Converters]] = ConvertersNumeric
|
||||
|
|
|
|||
|
|
@ -11,6 +11,6 @@ debug.trace()
|
|||
|
||||
logger = logging.get_logger(
|
||||
name=paths.name_ns,
|
||||
stream=Constants.INFRA,
|
||||
stream=Constants.DEVELOPMENT,
|
||||
version=paths.metadata.version,
|
||||
)
|
||||
|
|
|
|||
|
|
@ -4,7 +4,6 @@ import logging
|
|||
from haco.button import Button
|
||||
from haco.client import ClientHaco
|
||||
from haco.climate import Climate
|
||||
from haco.constants import MQTT_HOST
|
||||
from haco.device import Device
|
||||
from haco.obs import logger
|
||||
from haco.select import Select
|
||||
|
|
@ -23,7 +22,7 @@ async def main():
|
|||
sel1 = Select(name="Dev Select 1", options=['a', 'b', 'c'])
|
||||
device = Device(name="Dev Device", controls=[climate_a, climate_b, b1, s1, sel1])
|
||||
|
||||
client = ClientHaco(hostname=MQTT_HOST, device=device, logger=logging.getLogger(__name__))
|
||||
client = ClientHaco(hostname='mqtt.service', device=device, logger=logging.getLogger(__name__))
|
||||
|
||||
await client.start()
|
||||
|
||||
|
|
|
|||
|
|
@ -1,17 +1,16 @@
|
|||
from dataclasses import dataclass
|
||||
from typing import ClassVar
|
||||
|
||||
from haco.control import Control
|
||||
from haco.utils import ConvertersString
|
||||
|
||||
|
||||
@dataclass(kw_only=True)
|
||||
class Select(Control):
|
||||
"""
|
||||
|
||||
A select control (dropdown) for choosing from a list of options in Home Assistant.
|
||||
|
||||
"""
|
||||
DATA = dict(
|
||||
DATA: ClassVar[dict] = dict(
|
||||
platform='select'
|
||||
)
|
||||
converters = ConvertersString
|
||||
|
|
|
|||
|
|
@ -1,6 +1,5 @@
|
|||
from dataclasses import dataclass
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
from typing import Any, ClassVar
|
||||
|
||||
from haco.capabilities import Capability
|
||||
from haco.control import Control
|
||||
|
|
@ -67,14 +66,13 @@ class DeviceClass(StrEnum):
|
|||
WIND_SPEED = "wind_speed" # Wind speed in ft/s, km/h, kn, m/s, or mph.
|
||||
|
||||
|
||||
@dataclass(kw_only=True)
|
||||
class Sensor(Control):
|
||||
"""
|
||||
|
||||
A sensor control for reporting numeric or string values to Home Assistant.
|
||||
|
||||
"""
|
||||
DATA = dict(
|
||||
DATA: ClassVar[dict] = dict(
|
||||
platform='sensor'
|
||||
)
|
||||
converters = ConvertersString
|
||||
|
|
|
|||
|
|
@ -1,16 +1,15 @@
|
|||
from dataclasses import dataclass
|
||||
from typing import ClassVar
|
||||
|
||||
from haco.control import Control
|
||||
|
||||
|
||||
@dataclass(kw_only=True)
|
||||
class Switch(Control):
|
||||
"""
|
||||
|
||||
A switch control that can be toggled on or off.
|
||||
|
||||
"""
|
||||
DATA = dict(
|
||||
DATA: ClassVar[dict] = dict(
|
||||
platform='switch'
|
||||
)
|
||||
|
||||
|
|
|
|||
0
haco/tests/__init__.py
Normal file
0
haco/tests/__init__.py
Normal file
|
|
@ -1,5 +1,5 @@
|
|||
from dataclasses import dataclass
|
||||
from enum import StrEnum
|
||||
from typing import ClassVar
|
||||
|
||||
from haco.control import Control
|
||||
from haco.utils import ConvertersString
|
||||
|
|
@ -10,14 +10,13 @@ class Mode(StrEnum):
|
|||
PASSWORD = "password"
|
||||
|
||||
|
||||
@dataclass(kw_only=True)
|
||||
class Text(Control):
|
||||
"""
|
||||
|
||||
A text control for text input in Home Assistant.
|
||||
|
||||
"""
|
||||
DATA = dict(
|
||||
DATA: ClassVar[dict] = dict(
|
||||
platform='text'
|
||||
)
|
||||
converters = ConvertersString
|
||||
|
|
|
|||
|
|
@ -1,20 +1,21 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from functools import cached_property
|
||||
from typing import ClassVar, TYPE_CHECKING, Callable
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from corio import aio, Constants
|
||||
|
||||
from haco.base import Base
|
||||
from haco.obs import logger
|
||||
from haco.utils import get_prefix
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from capabilities import Capability
|
||||
from haco.capabilities import Capability
|
||||
|
||||
|
||||
@dataclass(kw_only=True)
|
||||
class AnnounceTopic:
|
||||
class AnnounceTopic(Base):
|
||||
"""
|
||||
|
||||
Base class for MQTT topics used for discovery and communication.
|
||||
|
|
@ -27,11 +28,16 @@ class AnnounceTopic:
|
|||
key: str | None = None
|
||||
value: str = '{path}/{capability}/{io}'
|
||||
|
||||
parent: Capability | None = None
|
||||
announce: dict | None = field(default=None, metadata=dict(exclude=True))
|
||||
subscriptions: dict | None = field(default=None, metadata=dict(exclude=True), init=False)
|
||||
parent: Capability | None = Field(default=None, exclude=True, repr=False)
|
||||
announce: dict | None = Field(default=None, exclude=True, repr=False)
|
||||
subscriptions: dict | None = Field(default=None, exclude=True, repr=False)
|
||||
|
||||
control_method: Callable | None = field(default=None, metadata=dict(exclude=True))
|
||||
control_method: Callable | None = Field(default=None, exclude=True, repr=False)
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
from haco.capabilities import Capability
|
||||
Capability == Capability
|
||||
super().__init__(**kwargs)
|
||||
|
||||
def set_parent(self, capability: Capability):
|
||||
"""
|
||||
|
|
@ -102,7 +108,6 @@ class AnnounceTopic:
|
|||
raise NotImplementedError()
|
||||
|
||||
|
||||
@dataclass(kw_only=True)
|
||||
class AnnounceTopicState(AnnounceTopic):
|
||||
"""
|
||||
|
||||
|
|
@ -149,7 +154,6 @@ class AnnounceTopicState(AnnounceTopic):
|
|||
|
||||
return value_raw
|
||||
|
||||
@dataclass(kw_only=True)
|
||||
class AnnounceTopicCommand(AnnounceTopic):
|
||||
"""
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
import string
|
||||
from dataclasses import dataclass
|
||||
from typing import Callable
|
||||
|
||||
from corio import json
|
||||
|
|
@ -80,16 +79,6 @@ class ConvertersNumeric(Converters):
|
|||
command: Callable = json.from_json
|
||||
state: Callable = json.to_json
|
||||
|
||||
@dataclass
|
||||
class Metadata:
|
||||
"""
|
||||
|
||||
Metadata for dataclass fields.
|
||||
|
||||
"""
|
||||
exclude: bool = False
|
||||
|
||||
|
||||
def get_prefix(io: str) -> str:
|
||||
"""
|
||||
|
||||
|
|
|
|||
|
|
@ -1,3 +1,11 @@
|
|||
[build-system]
|
||||
requires = ["corio[setup,debug]"]
|
||||
build-backend = "setuptools.build_meta" #
|
||||
build-backend = "setuptools.build_meta" #
|
||||
|
||||
[project]
|
||||
name= "haco"
|
||||
dynamic = ["description", "readme", "version", "dependencies", "optional-dependencies"]
|
||||
|
||||
[tool.uv.sources]
|
||||
corio = { path = "../corio", editable = true }
|
||||
|
||||
|
|
|
|||
7
setup.py
7
setup.py
|
|
@ -5,7 +5,12 @@ setup = Setup(
|
|||
dependencies=dict(
|
||||
install=[
|
||||
'corio[version.dev,logging,sets,yaml,debug,caching,api,mqtt]',
|
||||
]
|
||||
'psutil'
|
||||
],
|
||||
test=[
|
||||
'pytest>=8.0',
|
||||
'pytest-cov>=5.0',
|
||||
],
|
||||
),
|
||||
description='Home Assistant Control Objects',
|
||||
keywords='homeassistant controls python tasmota',
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue