diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 120000 index 0000000..612588c --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1 @@ +docs/changelog/0.4.7.md \ No newline at end of file diff --git a/README.md b/README.md index 408d50d..e7c780a 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # `haco` Home Assistant Control Objects -`haco` is a to greatly simplify the process of exposing Home Assistant controls (e.g. Pull-down Lists, Number Sliders, Sensors, etc.) from a device - and handling the communication between both sides. +`haco` greatly simplifies the process of exposing Home Assistant controls (e.g. Pull-down Lists, Number Sliders, Sensors, etc.) from a device - and handling the communication between both sides. While the current implementation is in Python, the capability definitions for controls are designed to be shared across different languages. Support for additional languages (namely native support for Tasmota Berry) is planned. @@ -24,7 +24,4 @@ If you're building a custom IoT device, a script to monitor your system, or just ## Documentation -[See Documentation](docs/index.md) - -- [Quick Start](docs/quick-start.md) -- [Control Types](docs/controls.md) +[See Documentation](https://fmtr.link/haco/doc) diff --git a/docs/changelog/0.3.0.md b/docs/changelog/0.3.0.md new file mode 100644 index 0000000..1502b84 --- /dev/null +++ b/docs/changelog/0.3.0.md @@ -0,0 +1,6 @@ +- Refactored core models from `dataclass` to Pydantic across active entities (`Base`, `Device`, `Control`, `Capability`, topic models, and concrete control types like `Switch`, `Climate`, `Sensor`, etc.). +- Replaced dataclass-specific field metadata (`metadata=dict(exclude=True)`, `field(...)`, `__post_init__`) with native Pydantic patterns (`Field(...)`, `model_post_init`, class inheritance from `corio.dm.Base`). +- Updated parent/back-reference handling to follow the parent-typing pattern, including explicit in-`__init__` imports for forward references (e.g. `Device.parent: ClientHaco | None`). +- Reworked `Base.model_dump()` to preserve discovery behavior by merging class `DATA`, defaulting to `exclude_none=True`, and excluding runtime extra attributes so dynamic callbacks do not leak into HA announce payloads. +- Cleaned up dataclass leftovers by removing the unused `Metadata` helper from `haco/utils.py` and simplifying related imports. +- Added packaging metadata and testing support updates: `pyproject.toml` project metadata/uv source config, `setup.py` test extras (`pytest`, `pytest-cov`), and initial `haco/tests` package scaffolding. diff --git a/docs/changelog/0.3.4.md b/docs/changelog/0.3.4.md new file mode 100644 index 0000000..58b84ad --- /dev/null +++ b/docs/changelog/0.3.4.md @@ -0,0 +1,3 @@ +- Updated for `corio` module refactors by switching imports to current paths (`corio.iterator`, `corio.jsn`, `corio.datatype`, and `corio.logs`) across capabilities, control serialization, converters, and logging setup. +- Added `haco/tests/test_pydantic_models.py` coverage to verify Home Assistant announce payload shape for `Switch` and `Climate`, runtime-attribute exclusion from `model_dump()`, and parent/subscription wiring behavior. + diff --git a/docs/changelog/0.4.3.md b/docs/changelog/0.4.3.md new file mode 100644 index 0000000..0b09f2b --- /dev/null +++ b/docs/changelog/0.4.3.md @@ -0,0 +1 @@ +- Updated the Corio dependency to the current compatible release. diff --git a/docs/changelog/0.4.4.md b/docs/changelog/0.4.4.md new file mode 100644 index 0000000..be96460 --- /dev/null +++ b/docs/changelog/0.4.4.md @@ -0,0 +1,2 @@ +- Updated Corio integration for the current package paths API. +- Added an automated test environment for the package test suite. diff --git a/docs/changelog/0.4.5.md b/docs/changelog/0.4.5.md new file mode 100644 index 0000000..cbe3fb3 --- /dev/null +++ b/docs/changelog/0.4.5.md @@ -0,0 +1,2 @@ +- Restored the runtime dependency metadata for installations. +- Added the automated Haco test environment to release validation. diff --git a/docs/changelog/0.4.6.md b/docs/changelog/0.4.6.md new file mode 100644 index 0000000..1885d7a --- /dev/null +++ b/docs/changelog/0.4.6.md @@ -0,0 +1 @@ +- Update the Corio dependency to its latest stable release. diff --git a/docs/changelog/0.4.7.md b/docs/changelog/0.4.7.md new file mode 100644 index 0000000..ef5baae --- /dev/null +++ b/docs/changelog/0.4.7.md @@ -0,0 +1 @@ +- Logs now use the package name and version and respect the configured development or production environment. \ No newline at end of file diff --git a/haco/base.py b/haco/base.py index a24c157..5a3d662 100644 --- a/haco/base.py +++ b/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) diff --git a/haco/binary_sensor.py b/haco/binary_sensor.py index 480fa20..fe3e23c 100644 --- a/haco/binary_sensor.py +++ b/haco/binary_sensor.py @@ -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' ) diff --git a/haco/button.py b/haco/button.py index 2329a64..113fbf6 100644 --- a/haco/button.py +++ b/haco/button.py @@ -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' ) diff --git a/haco/capabilities.py b/haco/capabilities.py index cf6506c..17b1d83 100644 --- a/haco/capabilities.py +++ b/haco/capabilities.py @@ -1,9 +1,10 @@ from __future__ import annotations -from dataclasses import dataclass, field -from typing import TYPE_CHECKING, Type +from typing import TYPE_CHECKING, Type, ClassVar -from corio.iterator_tools import strip_none +from pydantic import Field + +from corio.iterator import strip_none from haco.base import Base from haco.topics import AnnounceTopicState, AnnounceTopicCommand @@ -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): """ diff --git a/haco/climate.py b/haco/climate.py index 69635da..c616fff 100644 --- a/haco/climate.py +++ b/haco/climate.py @@ -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' ) diff --git a/haco/control.py b/haco/control.py index b635c3c..114d62e 100644 --- a/haco/control.py +++ b/haco/control.py @@ -1,11 +1,12 @@ 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 +from corio.jsn import to_json from haco.base import Base from haco.capabilities import Capability @@ -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, 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: diff --git a/haco/device.py b/haco/device.py index e66cffd..64f8d6b 100644 --- a/haco/device.py +++ b/haco/device.py @@ -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): """ diff --git a/haco/fan.py b/haco/fan.py new file mode 100644 index 0000000..b46d4cd --- /dev/null +++ b/haco/fan.py @@ -0,0 +1,100 @@ +from typing import ClassVar + +from haco.capabilities import Capability +from haco.control import Control +from haco.utils import ON, OFF, ConvertersNumeric, ConvertersString + + +class Fan(Control): + """ + + A fan control with support for speed percentage, preset modes, and oscillation. + + """ + DATA: ClassVar[dict] = dict( + platform="fan" + ) + + speed_range_min: int | None = None + speed_range_max: int | None = None + preset_modes: list[str] | None = None + payload_oscillation_on: str = ON + payload_oscillation_off: str = OFF + + def command(self, value: bool) -> bool: + """ + + Handle on/off commands for the fan. + + """ + raise NotImplementedError() + + def state(self, value: bool | None) -> bool: + """ + + Return the current on/off state of the fan. + + """ + raise NotImplementedError() + + def preset_mode_command(self, value: str) -> str: + """ + + Handle preset mode commands. + + """ + raise NotImplementedError() + + def preset_mode_state(self, value: str | None) -> str: + """ + + Return the current preset mode. + + """ + raise NotImplementedError() + + def percentage_command(self, value: int) -> int: + """ + + Handle percentage (speed) commands. + + """ + raise NotImplementedError() + + def percentage_state(self, value: int | None) -> int: + """ + + Return the current speed percentage. + + """ + raise NotImplementedError() + + def oscillation_command(self, value: bool) -> bool: + """ + + Handle oscillation toggle commands. + + """ + raise NotImplementedError() + + def oscillation_state(self, value: bool | None) -> bool: + """ + + Return the current oscillation state. + + """ + raise NotImplementedError() + + @classmethod + def get_capabilities(cls) -> list[Capability]: + """ + + Get the capabilities for the fan control. + + """ + return [ + Capability(name=None), + Capability(name="preset_mode", converters=ConvertersString), + Capability(name="percentage", converters=ConvertersNumeric), + Capability(name="oscillation"), + ] diff --git a/haco/meta.json b/haco/meta.json deleted file mode 100644 index 93fe239..0000000 --- a/haco/meta.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "version": "0.2.1", - "port": 6, - "entrypoint": null, - "base": "python", - "description": null, - "org_singleton": null, - "org_github": "fmtr", - "org_friendly": "Frontmatter AI", - "is_client": false, - "scripts": [], - "services": [], - "docs": { - "nav": [ - { - "Home": "index.md" - }, - { - "Quick Start": "quick-start.md" - }, - { - "Control Types": "controls.md" - } - ] - }, - "setup": {}, - "is_pypi": true, - "is_dockerhub": false -} \ No newline at end of file diff --git a/haco/number.py b/haco/number.py index 8604d9b..e7e58d4 100644 --- a/haco/number.py +++ b/haco/number.py @@ -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 diff --git a/haco/obs.py b/haco/obs.py index f8832b6..3dc4036 100644 --- a/haco/obs.py +++ b/haco/obs.py @@ -3,14 +3,10 @@ Observability and logging setup for the haco library. """ -from corio import logging, debug, Constants +from corio import debug, logs from haco.paths import paths debug.trace() -logger = logging.get_logger( - name=paths.name_ns, - stream=Constants.INFRA, - version=paths.metadata.version, -) +logger = logs.from_paths(paths) diff --git a/haco/paths.py b/haco/paths.py index aa2a0b4..25f0abf 100644 --- a/haco/paths.py +++ b/haco/paths.py @@ -3,6 +3,6 @@ Path definitions for the haco library. """ -from corio import sets +from corio import paths -paths = sets.PackagePaths() +paths = paths.PackagePaths() diff --git a/haco/pyproject.package.toml b/haco/pyproject.package.toml new file mode 120000 index 0000000..1e11d78 --- /dev/null +++ b/haco/pyproject.package.toml @@ -0,0 +1 @@ +../pyproject.toml \ No newline at end of file diff --git a/haco/sb3.py b/haco/sb3.py index 3a206c2..ba65113 100644 --- a/haco/sb3.py +++ b/haco/sb3.py @@ -1,16 +1,17 @@ import asyncio import logging +from logfire import LogfireLoggingHandler + 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 from haco.switch import Switch -handler = logger.LogfireLoggingHandler() +handler = LogfireLoggingHandler(logfire_instance=logger) logging.basicConfig(handlers=[handler], level=logging.DEBUG) async def main(): @@ -23,7 +24,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() diff --git a/haco/select.py b/haco/select.py index 1a1db28..e6c8235 100644 --- a/haco/select.py +++ b/haco/select.py @@ -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 diff --git a/haco/sensor.py b/haco/sensor.py index 91dc1df..6b5451d 100644 --- a/haco/sensor.py +++ b/haco/sensor.py @@ -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 diff --git a/haco/switch.py b/haco/switch.py index 09eb5c4..4e15d09 100644 --- a/haco/switch.py +++ b/haco/switch.py @@ -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' ) diff --git a/haco/tests/__init__.py b/haco/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/haco/tests/test_move_complete.py b/haco/tests/test_move_complete.py new file mode 100644 index 0000000..47d2bbe --- /dev/null +++ b/haco/tests/test_move_complete.py @@ -0,0 +1,155 @@ +from __future__ import annotations + +import asyncio +from types import SimpleNamespace +from unittest.mock import AsyncMock + +import pytest + +from corio import Path + +from haco.device import Device +from haco.switch import Switch + + +def run(coro): + return asyncio.run(coro) + + +def message(payload: str) -> SimpleNamespace: + return SimpleNamespace(payload=payload.encode("utf-8")) + + +@pytest.fixture +def client_stub(): + return SimpleNamespace( + topic=Path("root/client"), + will=SimpleNamespace(topic="root/status"), + publish=AsyncMock(), + ) + + +_UNSET = object() + + +def build_switch(client_stub, *, command=_UNSET, state=_UNSET): + switch = Switch(name="Main") + if command is not _UNSET: + switch.command = command + if state is not _UNSET: + switch.state = state + + device = Device(name="Dev", controls=[switch]) + device.set_parent(client_stub) + return switch + + +def test_move_complete_sync_command_updates_state_and_publishes(client_stub): + seen_command = [] + seen_state = [] + + def command(value): + seen_command.append(value) + return value + + def state(value): + seen_state.append(value) + return value + + switch = build_switch(client_stub, command=command, state=state) + command_topic = switch.capabilities[0].command + + run(command_topic.handle(message("ON"))) + + assert seen_command == [True] + assert seen_state == [True] + client_stub.publish.assert_awaited_once_with( + "root/client/dev/main/default/state", + "ON", + retain=True, + ) + + +def test_move_complete_async_command_updates_state_and_publishes(client_stub): + seen_command = [] + seen_state = [] + + async def command(value): + seen_command.append(value) + return not value + + async def state(value): + seen_state.append(value) + return value + + switch = build_switch(client_stub, command=command, state=state) + command_topic = switch.capabilities[0].command + + run(command_topic.handle(message("OFF"))) + + assert seen_command == [False] + assert seen_state == [True] + client_stub.publish.assert_awaited_once_with( + "root/client/dev/main/default/state", + "ON", + retain=True, + ) + + +def test_move_complete_state_handler_sync_publish_path(client_stub): + seen_state = [] + + def state(value): + seen_state.append(value) + return value + + switch = build_switch(client_stub, state=state) + state_topic = switch.capabilities[0].state + + value_raw = run(state_topic.handle(False)) + + assert seen_state == [False] + assert value_raw == "OFF" + client_stub.publish.assert_awaited_once_with( + "root/client/dev/main/default/state", + "OFF", + retain=True, + ) + + +def test_move_complete_command_missing_handler_stops_before_state(client_stub): + seen_state = [] + switch = build_switch( + client_stub, + command=None, + state=lambda value: seen_state.append(value) or value, + ) + command_topic = switch.capabilities[0].command + + result = run(command_topic.handle(message("ON"))) + + assert result is None + assert seen_state == [] + client_stub.publish.assert_not_awaited() + + +def test_move_complete_state_missing_handler_stops(client_stub): + switch = build_switch(client_stub, state=None) + state_topic = switch.capabilities[0].state + + result = run(state_topic.handle(True)) + + assert result is None + client_stub.publish.assert_not_awaited() + + +def test_move_complete_not_implemented_command_stops_before_state(client_stub): + seen_state = [] + switch = build_switch(client_stub, state=lambda value: seen_state.append(value) or value) + command_topic = switch.capabilities[0].command + + result = run(command_topic.handle(message("ON"))) + + assert result is None + assert seen_state == [] + client_stub.publish.assert_not_awaited() diff --git a/haco/tests/test_pydantic_models.py b/haco/tests/test_pydantic_models.py new file mode 100644 index 0000000..7893131 --- /dev/null +++ b/haco/tests/test_pydantic_models.py @@ -0,0 +1,112 @@ +from __future__ import annotations + +from types import SimpleNamespace + +import pytest + +from corio import Path + +from haco.climate import Climate +from haco.device import Device +from haco.switch import Switch + + +@pytest.fixture +def client_stub(): + return SimpleNamespace( + topic=Path("root/client"), + will=SimpleNamespace(topic="root/status"), + ) + + +def test_switch_announce_payload_matches_expected(client_stub): + switch = Switch(name="Main", icon="power") + device = Device(name="Dev", controls=[switch]) + device.set_parent(client_stub) + + data = switch.get_announce() + assert data == { + "platform": "switch", + "name": "Main", + "icon": "mdi:power", + "unique_id": "dev-main", + "availability_topic": "root/status", + "device": { + "name": "Dev", + "identifiers": ["dev"], + }, + "state_topic": "root/client/dev/main/default/state", + "command_topic": "root/client/dev/main/default/command", + } + + +def test_climate_announce_payload_has_expected_ha_keys(client_stub): + climate = Climate(name="Cl") + device = Device(name="Dev", controls=[climate]) + device.set_parent(client_stub) + + data = climate.get_announce() + + expected_subset = { + "platform", + "name", + "unique_id", + "availability_topic", + "temperature_unit", + "temperature_min", + "temperature_max", + "mode_command_topic", + "mode_state_topic", + "temperature_command_topic", + "temperature_state_topic", + "power_command_topic", + "power_state_topic", + } + assert expected_subset.issubset(set(data)) + assert not any(key in data for key in {"capabilities", "subscriptions", "parent"}) + assert not any(callable(value) for value in data.values()) + + +def test_control_announce_includes_device_announce_data(client_stub): + switch = Switch(name="Main") + device = Device( + name="Dev", + manufacturer="ACME", + model="Model X", + sw_version="1.2.3", + controls=[switch], + ) + device.set_parent(client_stub) + + data = switch.get_announce() + assert data["device"] == { + "name": "Dev", + "manufacturer": "ACME", + "model": "Model X", + "sw_version": "1.2.3", + "identifiers": ["dev"], + } + assert "controls" not in data["device"] + assert "parent" not in data["device"] + assert "subscriptions" not in data["device"] + + +def test_model_dump_excludes_runtime_extra_attributes(): + switch = Switch(name="Main") + switch.dynamic_callback = lambda value: value + + dumped = switch.model_dump() + assert "dynamic_callback" not in dumped + + +def test_parent_wiring_sets_control_subscriptions(client_stub): + switch = Switch(name="Main") + device = Device(name="Dev", controls=[switch]) + device.set_parent(client_stub) + + assert switch.unique_id == "dev-main" + assert switch.availability_topic == "root/status" + assert device.subscriptions is not None + assert "root/client/dev/main/default/command" in device.subscriptions + handler = device.subscriptions["root/client/dev/main/default/command"] + assert hasattr(handler, "handle") diff --git a/haco/text.py b/haco/text.py index d511a74..237fffd 100644 --- a/haco/text.py +++ b/haco/text.py @@ -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 diff --git a/haco/topics.py b/haco/topics.py index eaed85b..72894fb 100644 --- a/haco/topics.py +++ b/haco/topics.py @@ -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): """ diff --git a/haco/utils.py b/haco/utils.py index 5c99117..67dc687 100644 --- a/haco/utils.py +++ b/haco/utils.py @@ -1,9 +1,8 @@ import string -from dataclasses import dataclass from typing import Callable -from corio import json -from corio.datatype_tools import to_bool +from corio import jsn +from corio.datatype import to_bool CHARS_ALLOWED = string.ascii_lowercase + string.digits SEPS = '_- /' @@ -77,18 +76,8 @@ class ConvertersNumeric(Converters): Converters for numeric values. """ - command: Callable = json.from_json - state: Callable = json.to_json - -@dataclass -class Metadata: - """ - - Metadata for dataclass fields. - - """ - exclude: bool = False - + command: Callable = jsn.from_json + state: Callable = jsn.to_json def get_prefix(io: str) -> str: """ diff --git a/haco/v0/haco/fan.py b/haco/v0/haco/fan.py deleted file mode 100644 index c6472d7..0000000 --- a/haco/v0/haco/fan.py +++ /dev/null @@ -1,57 +0,0 @@ -from haco.control import Control -from haco.schema import Schema, Capability, AnnounceTopic, Tasmota, ControlType, HomeAssistant -from haco.tools import get_range_pair, invert_bool - -from haco import constants - - -class Fan(Control): - NAME = 'fan' - - @classmethod - def get_schema(cls): - schema = Schema( - capabilities=[ - Capability( - ha=HomeAssistant(announce_data=AnnounceTopic(key='{io_ha}_topic')), - tasmota=Tasmota(announce_data=AnnounceTopic(key='{io_ha}_topic')) - ), - Capability( - name='preset_mode', - type=str - ), - Capability( - name='percentage', - type=int - ), - Capability( - name='oscillation', - type=ControlType - ) - - ] - ) - return schema - - def __init__(self, name=None, preset_modes=None, icon=None, speed_range=None): - self.temperature_unit = speed_range - self.speed_min, self.speed_max = get_range_pair(speed_range) - self.preset_modes = preset_modes - - super().__init__(name, icon=icon) - - def get_config_ha_ex(self): - data = { - 'speed_range_min': self.speed_min, - 'speed_range_max': self.speed_max, - 'preset_modes': self.preset_modes, - 'payload_oscillation_on': constants.ON, - 'payload_oscillation_off': constants.OFF, - - } - - return data - - @property - def control_type(self): - return invert_bool diff --git a/pyproject.toml b/pyproject.toml index 96c0041..8e8059d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,3 +1,86 @@ [build-system] -requires = ["corio[setup,debug]"] -build-backend = "setuptools.build_meta" # \ No newline at end of file +requires = ["setuptools>=82", "wheel"] +build-backend = "setuptools.build_meta" + +[tool.corio.metadata] +version = "0.4.7" +port = 6 +base = "python" +description = "Home Assistant Control Objects" +org_github = "fmtr" +org_friendly = "Frontmatter AI" +is_client = false +scripts = [] +services = [] +keywords = ["homeassistant", "controls", "python", "tasmota"] +is_pypi = true +is_dockerhub = false +editables = ["corio"] + +[tool.corio.metadata.setup] + +[tool.corio.test-envs] +dev = ["dev"] + +[tool.setuptools] +include-package-data = false + +[tool.setuptools.packages.find] +where = ["."] +include = ["haco*"] +namespaces = false + +[tool.setuptools.package-data] +haco = ["pyproject.package.toml", "**/assets/**"] + +[tool.uv.sources.corio] +path = "../corio" +editable = true + +[tool.uv.config-settings-package.corio] +editable_mode = "compat" + +[tool.tox] +requires = ["tox>=4.22", "tox-uv>=1"] +env_list = ["prod"] + +[tool.tox.env.dev] +description = "Run haco tests." +deps = ["-e ../corio[api,caching,debug,mqtt,sets,test,yaml]", "psutil"] +commands = [["python", "-m", "pytest", "-q", "{posargs:haco/tests}"]] +install_command = ["uv", "pip", "install", "--refresh-package", "corio", "{opts}", "{packages}"] +skip_install = true + +[tool.tox.env.prod] +description = "Run haco tests." +deps = ["corio[test]~=2.21.6"] +commands = [["python", "-m", "pytest", "-q", "{posargs:haco/tests}"]] +install_command = ["uv", "pip", "install", "--refresh-package", "corio", "{opts}", "{packages}"] + +[tool.pytest.ini_options] +asyncio_default_fixture_loop_scope = "function" + +[project] +name = "haco" +version = "0.4.7" +description = "Home Assistant Control Objects" +readme = "README.md" +license = "Apache-2.0" +keywords = ["homeassistant", "controls", "python", "tasmota"] +dependencies = ["corio[api,caching,debug,mqtt,sets,yaml]~=2.21.6", "psutil"] + +[[project.authors]] +name = "Frontmatter AI" +email = "innovative.fowler@mask.pro.fmtr.dev" + +[project.optional-dependencies] +dev = ["corio[infra]~=2.21.6"] +test = ["corio[test]~=2.21.6"] + +[project.urls] +Homepage = "https://github.com/fmtr/haco" + +[project.scripts] + +[dependency-groups] +dev = ["corio[infra]~=2.21.6"] diff --git a/setup.py b/setup.py deleted file mode 100644 index 724e820..0000000 --- a/setup.py +++ /dev/null @@ -1,13 +0,0 @@ -from corio import Setup - -setup = Setup( - org=None, - dependencies=dict( - install=[ - 'corio[version.dev,logging,sets,yaml,debug,caching,api,mqtt]', - ] - ), - description='Home Assistant Control Objects', - keywords='homeassistant controls python tasmota', - # url=f'https://fmtr.link/{name}', -)