mirror of
https://github.com/fmtr/haco.git
synced 2026-12-02 12:57:10 -05:00
Compare commits
No commits in common. "main" and "v0.1.2" have entirely different histories.
47 changed files with 396 additions and 1407 deletions
67
.github/workflows/main.yml
vendored
Normal file
67
.github/workflows/main.yml
vendored
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
name: Version and Deploy
|
||||
|
||||
on:
|
||||
push:
|
||||
paths:
|
||||
- 'haco/version'
|
||||
workflow_dispatch:
|
||||
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
env:
|
||||
VERSION: ${{ github.event.inputs.version }}
|
||||
NAME: ${{ github.event.repository.name }}
|
||||
NAME_SHORT: ${{ github.event.repository.name }}
|
||||
ORG: ${{ github.repository_owner }}
|
||||
PATH_VERSION: haco/version
|
||||
#SHLINK_API_KEY: ${{ secrets.SHLINK_API_KEY }}
|
||||
#LINK_ID: haco/tapp
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Set Version Environment Variable
|
||||
run: |
|
||||
VERSION=$(cat ${PATH_VERSION})
|
||||
echo "VERSION=$VERSION" >> $GITHUB_ENV
|
||||
|
||||
- name: Install Tools
|
||||
run: |
|
||||
pip install twine
|
||||
pip install -U packaging setuptools twine pip build #https://github.com/pypa/twine/issues/1216
|
||||
|
||||
|
||||
- name: Increment Version
|
||||
env:
|
||||
GIT_EMAIL: ${{ secrets.GIT_EMAIL }}
|
||||
run: |
|
||||
git config --global user.name 'Frontmatter Actions'
|
||||
git config --global user.email "$GIT_EMAIL"
|
||||
VERSION=${{ env.VERSION }}
|
||||
git tag -a v${VERSION} -m "Release version ${VERSION}"
|
||||
git checkout --track origin/release
|
||||
git rebase main
|
||||
git push --follow-tags
|
||||
|
||||
- name: Release
|
||||
uses: softprops/action-gh-release@v1
|
||||
with:
|
||||
tag_name: v${{ env.VERSION }}
|
||||
generate_release_notes: true
|
||||
#prerelease: true
|
||||
|
||||
- name: Build Wheel
|
||||
run: |
|
||||
python -m build
|
||||
|
||||
- name: Push Wheel
|
||||
env:
|
||||
TWINE_PASSWORD: ${{ secrets.PYPI_TOKEN }}
|
||||
TWINE_USERNAME: __token__
|
||||
run: |
|
||||
twine upload dist/*
|
||||
|
|
@ -1 +0,0 @@
|
|||
docs/changelog/0.4.7.md
|
||||
29
README.md
29
README.md
|
|
@ -1,27 +1,8 @@
|
|||
# `haco` Home Assistant Control Objects
|
||||
|
||||
`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.
|
||||
`haco` is a Python/Berry library 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.
|
||||
|
||||
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.
|
||||
|
||||
### Why MQTT?
|
||||
|
||||
You might wonder why we use MQTT instead of directly using Home Assistant's APIs. The reason is flexibility: using MQTT allows
|
||||
`haco` to target any device or environment that has an MQTT client, not just those that can easily make HTTP requests or run a full HA integration. This makes it ideal for lightweight embedded systems and cross-platform utility.
|
||||
|
||||
### Why Would I Want Such a Thing?
|
||||
|
||||
Integrating custom hardware or scripts with Home Assistant often involves a lot of boilerplate: defining MQTT topics, crafting JSON payloads for discovery, and managing state updates.
|
||||
`haco` handles the heavy lifting, letting you define your device and its controls in clean, declarative Python.
|
||||
|
||||
If you're building a custom IoT device, a script to monitor your system, or just want a simpler way to bridge your code to Home Assistant, then you might find
|
||||
`haco` useful.
|
||||
|
||||
### How it Works
|
||||
|
||||
`haco` uses MQTT to communicate with Home Assistant. It automatically generates the discovery configurations required for Home Assistant to "see" your device and its entities. All you need to do is define a
|
||||
`Device` with some `Controls` and start the `ClientHaco`.
|
||||
|
||||
## Documentation
|
||||
|
||||
[See Documentation](https://fmtr.link/haco/doc)
|
||||
It is in very early release. Documentation is (may) be forthcoming.
|
||||
|
|
|
|||
9
build.env
Normal file
9
build.env
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
CHANNEL="dev"
|
||||
#ORG="fmtr"
|
||||
PACKAGE="haco"
|
||||
PORT="06"
|
||||
BASE="python"
|
||||
HOST="ws.lan"
|
||||
COMPUTE="cpu"
|
||||
EXTRAS="all"
|
||||
#ENTRYPOINT="fmtr-dns-launch"
|
||||
|
|
@ -1,6 +0,0 @@
|
|||
- 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.
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
- 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.
|
||||
|
||||
|
|
@ -1 +0,0 @@
|
|||
- Updated the Corio dependency to the current compatible release.
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
- Updated Corio integration for the current package paths API.
|
||||
- Added an automated test environment for the package test suite.
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
- Restored the runtime dependency metadata for installations.
|
||||
- Added the automated Haco test environment to release validation.
|
||||
|
|
@ -1 +0,0 @@
|
|||
- Update the Corio dependency to its latest stable release.
|
||||
|
|
@ -1 +0,0 @@
|
|||
- Logs now use the package name and version and respect the configured development or production environment.
|
||||
|
|
@ -1,99 +0,0 @@
|
|||
`haco` provides several control types that correspond to Home Assistant platforms. Each control typically has a
|
||||
`state` and a `command` method that you can override to handle communication.
|
||||
|
||||
# Supported Controls
|
||||
|
||||
## Button
|
||||
|
||||
A button in Home Assistant that can be pressed to trigger an action in your script.
|
||||
|
||||
- **Platform**: `button`
|
||||
- **Overridable Methods**:
|
||||
- `command(self, value)`: Called when the button is pressed in Home Assistant.
|
||||
|
||||
```python
|
||||
from haco import Button
|
||||
|
||||
class MyButton(Button):
|
||||
def command(self, value):
|
||||
print("Button was pressed!")
|
||||
```
|
||||
|
||||
## Switch
|
||||
|
||||
A toggle switch that can be turned on or off.
|
||||
|
||||
- **Platform**: `switch`
|
||||
- **Overridable Methods**:
|
||||
- `state(self, value)`: Should return the current state of the switch (`True` for on, `False` for off).
|
||||
- `command(self, value)`: Called when the switch is toggled in Home Assistant.
|
||||
|
||||
```python
|
||||
from haco import Switch
|
||||
|
||||
class MySwitch(Switch):
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
self._on = False
|
||||
|
||||
def state(self, value):
|
||||
return self._on
|
||||
|
||||
def command(self, value):
|
||||
self._on = value
|
||||
print(f"Switch is now {'ON' if self._on else 'OFF'}")
|
||||
```
|
||||
|
||||
## Sensor
|
||||
|
||||
A read-only sensor that displays a value in Home Assistant.
|
||||
|
||||
- **Platform**: `sensor`
|
||||
- **Overridable Methods**:
|
||||
- `state(self, value)`: Should return the current value of the sensor.
|
||||
|
||||
```python
|
||||
from haco import Sensor
|
||||
|
||||
class MySensor(Sensor):
|
||||
def state(self, value):
|
||||
return 42 # Or some dynamic value
|
||||
```
|
||||
|
||||
## Number
|
||||
|
||||
A slider or input box for numeric values.
|
||||
|
||||
- **Platform**: `number`
|
||||
- **Overridable Methods**:
|
||||
- `state(self, value)`: Should return the current numeric value.
|
||||
- `command(self, value)`: Called when the value is changed in Home Assistant.
|
||||
|
||||
## Select
|
||||
|
||||
A dropdown list of options.
|
||||
|
||||
- **Platform**: `select`
|
||||
- **Parameters**: `options` (list of strings)
|
||||
- **Overridable Methods**:
|
||||
- `state(self, value)`: Should return the currently selected option.
|
||||
- `command(self, value)`: Called when a new option is selected in Home Assistant.
|
||||
|
||||
# Customizing Controls
|
||||
|
||||
Most controls accept common parameters in their constructor:
|
||||
|
||||
- `name`: The display name in Home Assistant.
|
||||
- `icon`: An optional MDI icon (e.g., `mdi:lightbulb` or just `lightbulb`).
|
||||
|
||||
Example:
|
||||
|
||||
```python
|
||||
btn = Button(name="Panic Button", icon="alert")
|
||||
```
|
||||
|
||||
# Advanced: Custom Capabilities
|
||||
|
||||
For more complex platforms like `climate`,
|
||||
`haco` uses "Capabilities". A capability groups a state and a command topic. You can see how these are implemented in
|
||||
`haco/climate.py`.
|
||||
|
|
@ -1,7 +0,0 @@
|
|||
!!! tip "How Do I Get Started?"
|
||||
|
||||
See the [Quick Start](quick-start.md) section.
|
||||
|
||||
--8<--
|
||||
README.md
|
||||
--8<--
|
||||
|
|
@ -1,48 +0,0 @@
|
|||
The easiest way to get started with `haco` is to define a simple device and run the client.
|
||||
|
||||
# Installation
|
||||
|
||||
`haco` can be installed via pip:
|
||||
|
||||
```bash
|
||||
pip install haco
|
||||
```
|
||||
|
||||
!!! tip "MQTT Broker Required"
|
||||
|
||||
`haco` communicates with Home Assistant via MQTT. Ensure you have an MQTT broker (like Mosquitto) running and accessible.
|
||||
|
||||
# Basic Usage
|
||||
|
||||
Here is a minimal example that creates a device with a single button:
|
||||
|
||||
```python
|
||||
import asyncio
|
||||
from haco import Button, Device, ClientHaco
|
||||
|
||||
async def main():
|
||||
# 1. Define your controls
|
||||
btn = Button(name="My Awesome Button")
|
||||
|
||||
# 2. Group them into a device
|
||||
device = Device(name="My Cool Device", controls=[btn])
|
||||
|
||||
# 3. Create and start the client
|
||||
# Replace 'mqtt.service' with your MQTT broker's address
|
||||
client = ClientHaco(hostname='mqtt.service', device=device)
|
||||
|
||||
print("Starting haco client...")
|
||||
await client.start()
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
```
|
||||
|
||||
# What Happens Next?
|
||||
|
||||
1. **Discovery**: When the script runs, it sends discovery messages to Home Assistant.
|
||||
2. **Entity Created
|
||||
**: A new device named "My Cool Device" will appear in Home Assistant with a button entity named "My Awesome Button".
|
||||
3. **Control**: When you press the button in the Home Assistant UI,
|
||||
`haco` will receive the command. You can then handle this command in your Python script by overriding the
|
||||
`command` method or providing a callback (see [Control Types](controls.md) for more details).
|
||||
50
haco/base.py
50
haco/base.py
|
|
@ -1,39 +1,27 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from typing import Any, ClassVar
|
||||
|
||||
from pydantic import ConfigDict
|
||||
|
||||
from corio import dm
|
||||
from dataclasses import dataclass, fields
|
||||
from typing import Any
|
||||
|
||||
|
||||
class Base(dm.Base):
|
||||
"""
|
||||
@dataclass(kw_only=True)
|
||||
class Base:
|
||||
DATA = dict()
|
||||
|
||||
Base class for haco objects. Provides model dumping functionality.
|
||||
def model_dump(self) -> dict[str, Any]:
|
||||
data = {} | self.DATA
|
||||
for fld in fields(self):
|
||||
meta = fld.metadata
|
||||
if meta.get('exclude', False):
|
||||
continue
|
||||
|
||||
"""
|
||||
model_config = ConfigDict(arbitrary_types_allowed=True, extra='allow')
|
||||
DATA: ClassVar[dict[str, Any]] = {}
|
||||
value = getattr(self, fld.name)
|
||||
|
||||
def model_dump(self, *args, **kwargs) -> dict[str, Any]:
|
||||
"""
|
||||
Dump this model for Home Assistant discovery payloads.
|
||||
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]
|
||||
|
||||
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.
|
||||
"""
|
||||
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)
|
||||
if value is not None:
|
||||
data[fld.name] = value
|
||||
return data
|
||||
|
|
|
|||
|
|
@ -1,83 +0,0 @@
|
|||
from enum import StrEnum
|
||||
from typing import ClassVar
|
||||
|
||||
from haco.capabilities import Capability
|
||||
from haco.control import Control
|
||||
|
||||
|
||||
class DeviceClass(StrEnum):
|
||||
"""
|
||||
|
||||
Sourced from:
|
||||
https://www.home-assistant.io/integrations/binary_sensor/#device-class
|
||||
|
||||
"""
|
||||
|
||||
BATTERY = "battery" # on means low, off means normal
|
||||
BATTERY_CHARGING = "battery_charging" # on means charging, off means not charging
|
||||
CARBON_MONOXIDE = "carbon_monoxide" # on means carbon monoxide detected, off no carbon monoxide (clear)
|
||||
COLD = "cold" # on means cold, off means normal
|
||||
CONNECTIVITY = "connectivity" # on means connected, off means disconnected
|
||||
DOOR = "door" # on means open, off means closed
|
||||
GARAGE_DOOR = "garage_door" # on means open, off means closed
|
||||
GAS = "gas" # on means gas detected, off means no gas (clear)
|
||||
HEAT = "heat" # on means hot, off means normal
|
||||
LIGHT = "light" # on means light detected, off means no light
|
||||
LOCK = "lock" # on means open (unlocked), off means closed (locked)
|
||||
MOISTURE = "moisture" # on means moisture detected (wet), off means no moisture (dry)
|
||||
MOTION = "motion" # on means motion detected, off means no motion (clear)
|
||||
MOVING = "moving" # on means moving, off means not moving (stopped)
|
||||
OCCUPANCY = "occupancy" # on means occupied (detected), off means not occupied (clear)
|
||||
OPENING = "opening" # on means open, off means closed
|
||||
PLUG = "plug" # on means device is plugged in, off means device is unplugged
|
||||
POWER = "power" # on means power detected, off means no power
|
||||
PRESENCE = "presence" # on means home, off means away
|
||||
PROBLEM = "problem" # on means problem detected, off means no problem (OK)
|
||||
RUNNING = "running" # on means running, off means not running
|
||||
SAFETY = "safety" # on means unsafe, off means safe
|
||||
SMOKE = "smoke" # on means smoke detected, off means no smoke (clear)
|
||||
SOUND = "sound" # on means sound detected, off means no sound (clear)
|
||||
TAMPER = "tamper" # on means tampering detected, off means no tampering (clear)
|
||||
UPDATE = "update" # on means update available, off means up-to-date
|
||||
VIBRATION = "vibration" # on means vibration detected, off means no vibration (clear)
|
||||
WINDOW = "window" # on means open, off means closed
|
||||
|
||||
|
||||
class BinarySensor(Control):
|
||||
"""
|
||||
|
||||
A binary sensor for reporting on/off states to Home Assistant.
|
||||
|
||||
"""
|
||||
DATA: ClassVar[dict] = dict(
|
||||
platform='binary_sensor'
|
||||
)
|
||||
|
||||
device_class: DeviceClass | None = None
|
||||
|
||||
def command(self, value: bool):
|
||||
"""
|
||||
|
||||
Binary sensors do not support commands.
|
||||
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def state(self, value: bool | None) -> bool:
|
||||
"""
|
||||
|
||||
Return the current state of the binary sensor.
|
||||
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
@classmethod
|
||||
def get_capabilities(cls) -> list[Capability]:
|
||||
"""
|
||||
|
||||
Get the capabilities for the binary sensor (state only).
|
||||
|
||||
"""
|
||||
return [
|
||||
Capability(name=None, command=None)
|
||||
]
|
||||
|
|
@ -1,34 +1,20 @@
|
|||
from typing import ClassVar
|
||||
from dataclasses import dataclass
|
||||
|
||||
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: ClassVar[dict] = dict(
|
||||
DATA = dict(
|
||||
platform='button'
|
||||
)
|
||||
|
||||
def command(self, value: None):
|
||||
"""
|
||||
|
||||
Handle button press commands from Home Assistant.
|
||||
|
||||
"""
|
||||
def command(self, value):
|
||||
raise NotImplementedError()
|
||||
|
||||
@classmethod
|
||||
def get_capabilities(cls) -> list[Capability]:
|
||||
"""
|
||||
|
||||
Get the capabilities for the button (command only).
|
||||
|
||||
"""
|
||||
def get_capabilities(cls):
|
||||
return [
|
||||
Capability(name=None, state=None)
|
||||
]
|
||||
|
|
|
|||
|
|
@ -1,11 +1,9 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Type, ClassVar
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from corio.iterator import strip_none
|
||||
from dataclasses import dataclass, field
|
||||
from typing import TYPE_CHECKING, Type
|
||||
|
||||
from fmtr.tools.iterator_tools import strip_none
|
||||
from haco.base import Base
|
||||
from haco.topics import AnnounceTopicState, AnnounceTopicCommand
|
||||
from haco.utils import Converters
|
||||
|
|
@ -14,34 +12,20 @@ if TYPE_CHECKING:
|
|||
from haco.control import Control
|
||||
|
||||
|
||||
@dataclass(kw_only=True)
|
||||
class Capability(Base):
|
||||
"""
|
||||
|
||||
A capability groups a state and a command topic.
|
||||
|
||||
"""
|
||||
name: str | None = None
|
||||
|
||||
converters: Type[Converters] | None = Field(default=None, exclude=True, repr=False)
|
||||
converters: Type[Converters] | None = field(default=None, metadata=dict(exclude=True))
|
||||
|
||||
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 = Field(default=None, exclude=True, repr=False)
|
||||
announce: ClassVar[None] = None
|
||||
parent: Control | None = None
|
||||
announce = None
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
from haco.control import Control
|
||||
Control == Control
|
||||
super().__init__(**kwargs)
|
||||
|
||||
def set_parent(self, control: Control):
|
||||
"""
|
||||
|
||||
Set the parent control for the capability and its topics.
|
||||
|
||||
"""
|
||||
def set_parent(self, control):
|
||||
self.parent = control
|
||||
for topic in self.topics:
|
||||
topic.set_parent(self)
|
||||
|
|
@ -49,41 +33,21 @@ class Capability(Base):
|
|||
self.converters = self.converters or self.control.converters
|
||||
|
||||
def get_announce(self) -> dict:
|
||||
"""
|
||||
|
||||
Get the discovery announcement data for the capability's topics.
|
||||
|
||||
"""
|
||||
data = {}
|
||||
for topic in self.topics:
|
||||
data |= topic.get_announce()
|
||||
return data
|
||||
|
||||
def get_subscriptions(self) -> dict:
|
||||
"""
|
||||
|
||||
Get the MQTT topic subscriptions for the capability's command topics.
|
||||
|
||||
"""
|
||||
data = {}
|
||||
for topic in self.topics:
|
||||
data |= topic.get_subscriptions()
|
||||
return data
|
||||
|
||||
@property
|
||||
def topics(self) -> list:
|
||||
"""
|
||||
|
||||
The state and command topics for the capability.
|
||||
|
||||
"""
|
||||
def topics(self):
|
||||
return strip_none(self.state, self.command)
|
||||
|
||||
@property
|
||||
def control(self) -> Control:
|
||||
"""
|
||||
|
||||
The parent control of the capability.
|
||||
|
||||
"""
|
||||
def control(self):
|
||||
return self.parent
|
||||
|
|
|
|||
|
|
@ -1,24 +1,17 @@
|
|||
import asyncio
|
||||
from pathlib import Path
|
||||
|
||||
import aiomqtt
|
||||
from corio import mqtt
|
||||
import asyncio
|
||||
|
||||
from fmtr.tools import mqtt, Constants
|
||||
from haco import constants
|
||||
from haco.constants import SUBSCRIBE
|
||||
from haco.obs import logger
|
||||
from haco.utils import get_prefix
|
||||
|
||||
|
||||
class ClientHaco(mqtt.Client):
|
||||
"""
|
||||
|
||||
MQTT Client for haco, handling communication between Home Assistant and a device.
|
||||
|
||||
"""
|
||||
ONLINE = 'online'
|
||||
OFFLINE = 'offline'
|
||||
|
||||
aiomqtt.Client
|
||||
|
||||
def __init__(self, *args, device=None, will=None, identifier=None, **kwargs):
|
||||
self.will = will or mqtt.Will(topic=str(constants.TOPIC_AVAIL), payload=self.OFFLINE, retain=True, qos=1, )
|
||||
identifier = identifier or constants.CLIENT_ID
|
||||
|
|
@ -27,44 +20,37 @@ class ClientHaco(mqtt.Client):
|
|||
super().__init__(*args, will=self.will, identifier=identifier, **kwargs)
|
||||
|
||||
@property
|
||||
def topic(self) -> Path:
|
||||
"""
|
||||
|
||||
The MQTT topic prefix for the client.
|
||||
|
||||
"""
|
||||
def topic(self):
|
||||
return constants.TOPIC_CLIENT
|
||||
|
||||
async def handle(self):
|
||||
"""
|
||||
|
||||
Handle incoming MQTT messages by delegating them to the device's controls.
|
||||
|
||||
"""
|
||||
"""Listen for command messages from HA."""
|
||||
|
||||
for topic_sub in self.device.subscriptions.keys():
|
||||
logger.info(f"{get_prefix(SUBSCRIBE)}: {topic_sub}")
|
||||
logger.info(f"Subscribing to {topic_sub}")
|
||||
await self.subscribe(topic_sub)
|
||||
|
||||
async for message in self.messages:
|
||||
payload = message.payload.decode()
|
||||
logger.info(f"{message.topic.value}{Constants.ARROW}{payload}")
|
||||
topic_command = self.device.subscriptions[message.topic.value]
|
||||
await topic_command.handle(message)
|
||||
echo_val = await topic_command.handle(message)
|
||||
|
||||
|
||||
|
||||
async def start(self):
|
||||
"""
|
||||
|
||||
Start the MQTT client and handle reconnection.
|
||||
|
||||
"""
|
||||
while True:
|
||||
try:
|
||||
async with self:
|
||||
await self.device.initialise()
|
||||
|
||||
await self.device.announce()
|
||||
|
||||
await self.publish(self.will.topic, self.ONLINE, retain=True)
|
||||
|
||||
# await self.publish('haco/development/3012edb1a6d4-1ed9c3469373/dev-device/dev-climate-b/power/command', "OFF", retain=True)
|
||||
|
||||
await self.handle()
|
||||
|
||||
except aiomqtt.MqttError as e:
|
||||
logger.info(f"MQTT disconnected: {e}; retrying in 5s")
|
||||
logger.info(f"⚠️ MQTT disconnected: {e}; retrying in 5s")
|
||||
await asyncio.sleep(5)
|
||||
|
|
|
|||
|
|
@ -1,16 +1,13 @@
|
|||
from typing import Literal, ClassVar
|
||||
from dataclasses import dataclass
|
||||
from typing import Literal
|
||||
|
||||
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: ClassVar[dict] = dict(
|
||||
DATA = dict(
|
||||
platform='climate'
|
||||
)
|
||||
|
||||
|
|
@ -26,61 +23,27 @@ class Climate(Control):
|
|||
fan_modes: list[str] | None = None
|
||||
swing_modes: list[str] | None = None
|
||||
|
||||
def temperature_command(self, value: float) -> float:
|
||||
"""
|
||||
|
||||
Handle target temperature commands.
|
||||
|
||||
"""
|
||||
def temperature_command(self, value):
|
||||
raise NotImplementedError()
|
||||
|
||||
def mode_command(self, value: str) -> str:
|
||||
"""
|
||||
|
||||
Handle HVAC mode commands.
|
||||
|
||||
"""
|
||||
def mode_command(self, value):
|
||||
raise NotImplementedError()
|
||||
|
||||
def fan_mode_command(self, value: str) -> str:
|
||||
"""
|
||||
|
||||
Handle fan mode commands.
|
||||
|
||||
"""
|
||||
def fan_mode_command(self, value):
|
||||
raise NotImplementedError()
|
||||
|
||||
def fan_mode_state(self, value: str | None) -> str:
|
||||
"""
|
||||
|
||||
Return the current fan mode.
|
||||
|
||||
"""
|
||||
def fan_mode_state(self, value):
|
||||
raise NotImplementedError()
|
||||
|
||||
def power_command(self, value: bool) -> bool:
|
||||
"""
|
||||
|
||||
Handle power toggle commands.
|
||||
|
||||
"""
|
||||
def power_command(self, value):
|
||||
raise NotImplementedError()
|
||||
|
||||
def power_state(self, value: bool | None) -> bool:
|
||||
"""
|
||||
|
||||
Return the current power state.
|
||||
|
||||
"""
|
||||
def power_state(self, value):
|
||||
raise NotImplementedError()
|
||||
|
||||
@classmethod
|
||||
def get_capabilities(cls) -> list[Capability]:
|
||||
"""
|
||||
|
||||
Get the capabilities for the climate control.
|
||||
|
||||
"""
|
||||
def get_capabilities(cls):
|
||||
return [
|
||||
Capability(name="current_temperature", command=None),
|
||||
Capability(name="temperature"),
|
||||
|
|
|
|||
|
|
@ -1,12 +1,6 @@
|
|||
"""
|
||||
|
||||
Global constants for the haco library.
|
||||
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from corio import env, Path, net
|
||||
|
||||
from fmtr.tools import env, Path, net
|
||||
from haco.paths import paths
|
||||
|
||||
STATUS = 'status'
|
||||
|
|
@ -19,6 +13,3 @@ TOPIC_ROOT = Path(paths.name) / env.CHANNEL
|
|||
TOPIC_CLIENT = TOPIC_ROOT / CLIENT_ID
|
||||
TOPIC_AVAIL = TOPIC_CLIENT / STATUS
|
||||
PREFIX_MDI = "mdi:"
|
||||
|
||||
ANNOUNCE = 'announce'
|
||||
SUBSCRIBE = 'subscribe'
|
||||
|
|
|
|||
117
haco/control.py
117
haco/control.py
|
|
@ -1,43 +1,36 @@
|
|||
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.jsn import to_json
|
||||
|
||||
from fmtr.tools.json_tools import to_json
|
||||
from haco.base import Base
|
||||
from haco.capabilities import Capability
|
||||
from haco.constants import PREFIX_MDI, ANNOUNCE
|
||||
from haco.constants import PREFIX_MDI
|
||||
from haco.obs import logger
|
||||
from haco.utils import sanitize_name, Converters, ConvertersBool, get_prefix
|
||||
from haco.utils import sanitize_name, Converters, ConvertersBool
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from haco.device import Device
|
||||
|
||||
DeviceT = TypeVar("DeviceT")
|
||||
DeviceT = TypeVar("DeviceT", bound="Device")
|
||||
|
||||
|
||||
@dataclass(kw_only=True)
|
||||
class Control(Base, Generic[DeviceT]):
|
||||
"""
|
||||
|
||||
Base class for Home Assistant controls.
|
||||
|
||||
"""
|
||||
converters: ClassVar[Type[Converters]] = ConvertersBool
|
||||
|
||||
name: str
|
||||
icon: str | None = None
|
||||
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
|
||||
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)
|
||||
|
||||
subscriptions: dict | None = Field(default=None, exclude=True, repr=False)
|
||||
# announce: dict | None = field(default=None, metadata=dict(exclude=True))
|
||||
subscriptions: dict | None = field(default=None, metadata=dict(exclude=True), init=False)
|
||||
|
||||
def model_post_init(self, __context):
|
||||
def __post_init__(self):
|
||||
self.capabilities = self.get_capabilities()
|
||||
|
||||
if not self.icon:
|
||||
|
|
@ -46,12 +39,8 @@ class Control(Base, Generic[DeviceT]):
|
|||
if not self.icon.startswith(PREFIX_MDI):
|
||||
self.icon = f"{PREFIX_MDI}{self.icon}"
|
||||
|
||||
def set_parent(self, device: DeviceT):
|
||||
"""
|
||||
|
||||
Set the parent device for the control and its capabilities.
|
||||
|
||||
"""
|
||||
def set_parent(self, device):
|
||||
self.device = device
|
||||
|
||||
for cap in self.capabilities:
|
||||
|
|
@ -60,22 +49,15 @@ class Control(Base, Generic[DeviceT]):
|
|||
self.unique_id = self.get_unique_id()
|
||||
self.availability_topic = self.get_availability_topic()
|
||||
self.subscriptions = self.get_subscriptions()
|
||||
#self.announce = self.get_announce()
|
||||
|
||||
|
||||
|
||||
@property
|
||||
def parent(self) -> DeviceT:
|
||||
"""
|
||||
|
||||
The parent device of the control.
|
||||
|
||||
"""
|
||||
def parent(self):
|
||||
return self.device
|
||||
|
||||
def get_announce(self) -> dict:
|
||||
"""
|
||||
|
||||
Get the discovery announcement data for the control.
|
||||
|
||||
"""
|
||||
def get_announce(self):
|
||||
data = self.model_dump()
|
||||
for cap in self.capabilities:
|
||||
data |= cap.get_announce()
|
||||
|
|
@ -83,12 +65,7 @@ class Control(Base, Generic[DeviceT]):
|
|||
return data
|
||||
|
||||
@classmethod
|
||||
def get_capabilities(cls) -> list[Capability]:
|
||||
"""
|
||||
|
||||
Get the capabilities of the control.
|
||||
|
||||
"""
|
||||
def get_capabilities(cls):
|
||||
return [
|
||||
Capability(name=None)
|
||||
]
|
||||
|
|
@ -98,45 +75,20 @@ class Control(Base, Generic[DeviceT]):
|
|||
|
||||
@property
|
||||
def name_san(self) -> str:
|
||||
"""
|
||||
|
||||
Sanitized name of the control.
|
||||
|
||||
"""
|
||||
return sanitize_name(self.name)
|
||||
|
||||
@property
|
||||
def topic(self) -> Path:
|
||||
"""
|
||||
|
||||
The MQTT topic prefix for the control.
|
||||
|
||||
"""
|
||||
def topic(self):
|
||||
return self.device.topic / self.name_san
|
||||
|
||||
@property
|
||||
def announce_topic(self) -> str:
|
||||
"""
|
||||
|
||||
The MQTT topic for discovery announcement.
|
||||
|
||||
"""
|
||||
def announce_topic(self):
|
||||
return f"homeassistant/{self.DATA['platform']}/{self.unique_id}/config"
|
||||
|
||||
def get_availability_topic(self) -> str:
|
||||
"""
|
||||
|
||||
Get the availability topic for the control (uses the client's will topic).
|
||||
|
||||
"""
|
||||
return self.device.client.will.topic
|
||||
|
||||
def get_subscriptions(self) -> dict:
|
||||
"""
|
||||
|
||||
Get the MQTT topic subscriptions for the control's capabilities.
|
||||
|
||||
"""
|
||||
|
||||
data = {}
|
||||
|
||||
|
|
@ -146,31 +98,24 @@ class Control(Base, Generic[DeviceT]):
|
|||
return data
|
||||
|
||||
async def initialise(self):
|
||||
"""
|
||||
|
||||
Initialise the control by announcing it and setting its initial state.
|
||||
|
||||
"""
|
||||
await self.announce()
|
||||
for capability in self.capabilities:
|
||||
if not capability.state:
|
||||
continue
|
||||
await capability.state.handle(value=None)
|
||||
...
|
||||
|
||||
async def announce(self):
|
||||
"""
|
||||
|
||||
Announce the control to Home Assistant via MQTT discovery.
|
||||
Entities must be able to announce themselves to Home Assistant, e.g. when a pulldown changes its options, etc.
|
||||
|
||||
"""
|
||||
topic = self.announce_topic
|
||||
data = self.get_announce()
|
||||
data_json = to_json(data)
|
||||
|
||||
logger.info(f'{get_prefix(ANNOUNCE)}: {data} {Constants.ARROW_RIGHT} {topic}')
|
||||
|
||||
data_json = to_json(self.get_announce())
|
||||
logger.info(f'Announcing {topic} with {data_json}')
|
||||
await self.device.client.publish(topic, data_json, retain=True)
|
||||
|
||||
for capability in self.capabilities:
|
||||
if not capability.state:
|
||||
continue
|
||||
await capability.state.handle(value=None)
|
||||
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
|
|
|||
|
|
@ -1,11 +1,9 @@
|
|||
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
|
||||
|
|
@ -14,95 +12,52 @@ if TYPE_CHECKING:
|
|||
from haco.client import ClientHaco
|
||||
|
||||
|
||||
@dataclass(kw_only=True)
|
||||
class Device(Base):
|
||||
"""
|
||||
|
||||
A Home Assistant device, containing one or more controls.
|
||||
|
||||
"""
|
||||
name: str
|
||||
manufacturer: str | None = None
|
||||
model: str | None = None
|
||||
sw_version: str | None = None
|
||||
|
||||
identifiers: list[str] | None = None
|
||||
identifiers: list[str] | None = field(default=None, init=False)
|
||||
|
||||
controls: List[Control] = Field(default_factory=list, exclude=True, repr=False)
|
||||
controls: List[Control] = field(default_factory=list, metadata=dict(exclude=True))
|
||||
|
||||
parent: ClientHaco | None = Field(default=None, exclude=True, repr=False)
|
||||
subscriptions: dict | None = Field(default=None, exclude=True, repr=False)
|
||||
parent: ClientHaco | None = field(metadata=dict(exclude=True), init=False)
|
||||
# announce: dict | None = field(default=None, metadata=dict(exclude=True), init=False)
|
||||
subscriptions: dict | None = field(default=None, metadata=dict(exclude=True), init=False)
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
from haco.client import ClientHaco
|
||||
ClientHaco == ClientHaco
|
||||
super().__init__(**kwargs)
|
||||
|
||||
def set_parent(self, client: ClientHaco):
|
||||
"""
|
||||
|
||||
Set the parent client for the device and its controls.
|
||||
|
||||
"""
|
||||
def set_parent(self, client):
|
||||
self.parent = client
|
||||
|
||||
self.identifiers = [self.name_san]
|
||||
|
||||
for control in self.controls:
|
||||
control.set_parent(self)
|
||||
#self.announce = self.get_announce()
|
||||
self.subscriptions = self.get_subscriptions()
|
||||
|
||||
self
|
||||
|
||||
@cached_property
|
||||
def topic(self) -> Path:
|
||||
"""
|
||||
|
||||
The MQTT topic prefix for the device.
|
||||
|
||||
"""
|
||||
def topic(self):
|
||||
return self.client.topic / self.name_san
|
||||
|
||||
@property
|
||||
def name_san(self) -> str:
|
||||
"""
|
||||
|
||||
Sanitized name of the device.
|
||||
|
||||
"""
|
||||
return sanitize_name(self.name)
|
||||
|
||||
async def announce(self):
|
||||
"""
|
||||
|
||||
Announce all controls of the device to Home Assistant.
|
||||
|
||||
"""
|
||||
for control in self.controls:
|
||||
await control.announce()
|
||||
|
||||
async def initialise(self):
|
||||
"""
|
||||
|
||||
Initialise all controls of the device.
|
||||
|
||||
"""
|
||||
for control in self.controls:
|
||||
await control.initialise()
|
||||
|
||||
|
||||
@property
|
||||
def client(self) -> ClientHaco:
|
||||
"""
|
||||
|
||||
The parent client of the device.
|
||||
|
||||
"""
|
||||
def client(self):
|
||||
return self.parent
|
||||
|
||||
def get_subscriptions(self) -> dict:
|
||||
"""
|
||||
|
||||
Get all MQTT topic subscriptions for the device's controls.
|
||||
|
||||
"""
|
||||
data = {}
|
||||
for control in self.controls:
|
||||
data |= control.subscriptions
|
||||
|
|
|
|||
100
haco/fan.py
100
haco/fan.py
|
|
@ -1,100 +0,0 @@
|
|||
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"),
|
||||
]
|
||||
|
|
@ -1,3 +1,4 @@
|
|||
from dataclasses import dataclass
|
||||
from enum import StrEnum
|
||||
from typing import ClassVar, Type
|
||||
|
||||
|
|
@ -11,13 +12,9 @@ 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: ClassVar[dict] = dict(
|
||||
DATA = dict(
|
||||
platform='number'
|
||||
)
|
||||
converters: ClassVar[Type[Converters]] = ConvertersNumeric
|
||||
|
|
@ -28,18 +25,8 @@ class Number(Control):
|
|||
step: float = 1.
|
||||
uom: Uom | None = None
|
||||
|
||||
def command(self, value: float) -> float:
|
||||
"""
|
||||
|
||||
Handle numeric value commands from Home Assistant.
|
||||
|
||||
"""
|
||||
def command(self, value):
|
||||
raise NotImplementedError()
|
||||
|
||||
def state(self, value: float | None) -> float:
|
||||
"""
|
||||
|
||||
Return the current numeric state.
|
||||
|
||||
"""
|
||||
def state(self, value):
|
||||
raise NotImplementedError()
|
||||
|
|
|
|||
15
haco/obs.py
15
haco/obs.py
|
|
@ -1,12 +1,11 @@
|
|||
"""
|
||||
|
||||
Observability and logging setup for the haco library.
|
||||
|
||||
"""
|
||||
from corio import debug, logs
|
||||
|
||||
from fmtr.tools import logging, debug, Constants
|
||||
from haco.paths import paths
|
||||
from haco.version import __version__
|
||||
|
||||
debug.trace()
|
||||
|
||||
logger = logs.from_paths(paths)
|
||||
logger = logging.get_logger(
|
||||
name=paths.name_ns,
|
||||
stream=Constants.INFRA,
|
||||
version=__version__,
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,8 +1,3 @@
|
|||
"""
|
||||
from fmtr.tools import sets
|
||||
|
||||
Path definitions for the haco library.
|
||||
|
||||
"""
|
||||
from corio import paths
|
||||
|
||||
paths = paths.PackagePaths()
|
||||
paths = sets.PackagePaths()
|
||||
|
|
|
|||
|
|
@ -1 +0,0 @@
|
|||
../pyproject.toml
|
||||
|
|
@ -1,17 +1,16 @@
|
|||
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 = LogfireLoggingHandler(logfire_instance=logger)
|
||||
handler = logger.LogfireLoggingHandler()
|
||||
logging.basicConfig(handlers=[handler], level=logging.DEBUG)
|
||||
|
||||
async def main():
|
||||
|
|
@ -24,7 +23,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.service', device=device, logger=logging.getLogger(__name__))
|
||||
client = ClientHaco(hostname=MQTT_HOST, device=device, logger=logging.getLogger(__name__))
|
||||
|
||||
await client.start()
|
||||
|
||||
|
|
|
|||
|
|
@ -1,34 +1,20 @@
|
|||
from typing import ClassVar
|
||||
from dataclasses import dataclass
|
||||
|
||||
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: ClassVar[dict] = dict(
|
||||
DATA = dict(
|
||||
platform='select'
|
||||
)
|
||||
converters = ConvertersString
|
||||
|
||||
options: list[str]
|
||||
|
||||
def command(self, value: str) -> str:
|
||||
"""
|
||||
|
||||
Handle option selection commands from Home Assistant.
|
||||
|
||||
"""
|
||||
def command(self, value):
|
||||
raise NotImplementedError()
|
||||
|
||||
def state(self, value: str | None) -> str:
|
||||
"""
|
||||
|
||||
Return the currently selected option.
|
||||
|
||||
"""
|
||||
def state(self, value):
|
||||
raise NotImplementedError()
|
||||
|
|
|
|||
108
haco/sensor.py
108
haco/sensor.py
|
|
@ -1,108 +0,0 @@
|
|||
from enum import StrEnum
|
||||
from typing import Any, ClassVar
|
||||
|
||||
from haco.capabilities import Capability
|
||||
from haco.control import Control
|
||||
from haco.uom import Uom
|
||||
from haco.utils import ConvertersString
|
||||
|
||||
|
||||
class DeviceClass(StrEnum):
|
||||
"""
|
||||
|
||||
Sourced from: https://www.home-assistant.io/integrations/sensor/#device-class
|
||||
|
||||
"""
|
||||
|
||||
APPARENT_POWER = "apparent_power" # Apparent power in VA.
|
||||
AQI = "aqi" # Air Quality Index (unitless).
|
||||
ATMOSPHERIC_PRESSURE = "atmospheric_pressure" # Atmospheric pressure in cbar, bar, hPa, inHg, kPa, mbar, Pa, or psi.
|
||||
BATTERY = "battery" # Battery percentage in %.
|
||||
CARBON_DIOXIDE = "carbon_dioxide" # CO₂ in ppm.
|
||||
CARBON_MONOXIDE = "carbon_monoxide" # CO in ppm.
|
||||
CURRENT = "current" # Current in A or mA.
|
||||
DATA_RATE = "data_rate" # Data rate in bit/s, kbit/s, Mbit/s, Gbit/s, B/s, kB/s, MB/s, GB/s, KiB/s, MiB/s, or GiB/s.
|
||||
DATA_SIZE = "data_size" # Data size in bit, kbit, Mbit, Gbit, B, kB, MB, GB, TB, PB, EB, ZB, YB, KiB, MiB, GiB, TiB, PiB, EiB, ZiB, or YiB.
|
||||
DATE = "date" # ISO 8601 date string.
|
||||
DISTANCE = "distance" # Distance in km, m, cm, mm, mi, yd, or in.
|
||||
DURATION = "duration" # Duration in d, h, min, or s.
|
||||
ENERGY = "energy" # Energy in Wh, kWh, MWh, MJ, or GJ.
|
||||
ENERGY_STORAGE = "energy_storage" # Stored energy in Wh, kWh, MWh, MJ, or GJ.
|
||||
ENUM = "enum" # Limited set of non-numeric states.
|
||||
FREQUENCY = "frequency" # Frequency in Hz, kHz, MHz, or GHz.
|
||||
GAS = "gas" # Gas volume in m³, ft³, or CCF.
|
||||
HUMIDITY = "humidity" # Humidity in %.
|
||||
ILLUMINANCE = "illuminance" # Light level in lx.
|
||||
IRRADIANCE = "irradiance" # Irradiance in W/m² or BTU/(h⋅ft²).
|
||||
MOISTURE = "moisture" # Water content in %.
|
||||
MONETARY = "monetary" # Monetary value (ISO 4217).
|
||||
NITROGEN_DIOXIDE = "nitrogen_dioxide" # NO₂ in µg/m³.
|
||||
NITROGEN_MONOXIDE = "nitrogen_monoxide" # NO in µg/m³.
|
||||
NITROUS_OXIDE = "nitrous_oxide" # N₂O in µg/m³.
|
||||
OZONE = "ozone" # O₃ in µg/m³.
|
||||
PH = "ph" # pH value.
|
||||
PM1 = "pm1" # Particulate matter <1µm in µg/m³.
|
||||
PM25 = "pm25" # Particulate matter <2.5µm in µg/m³.
|
||||
PM10 = "pm10" # Particulate matter <10µm in µg/m³.
|
||||
POWER_FACTOR = "power_factor" # Power factor (unitless or %).
|
||||
POWER = "power" # Power in W or kW.
|
||||
PRECIPITATION = "precipitation" # Accumulated precipitation.
|
||||
PRECIPITATION_INTENSITY = "precipitation_intensity" # Precipitation rate.
|
||||
PRESSURE = "pressure" # Pressure in Pa, kPa, hPa, bar, cbar, mbar, mmHg, inHg, or psi.
|
||||
REACTIVE_POWER = "reactive_power" # Reactive power in var.
|
||||
SIGNAL_STRENGTH = "signal_strength" # Signal strength in dB or dBm.
|
||||
SOUND_PRESSURE = "sound_pressure" # Sound pressure in dB or dBA.
|
||||
SPEED = "speed" # Speed in ft/s, in/d, in/h, km/h, kn, m/s, mph, or mm/d.
|
||||
SULPHUR_DIOXIDE = "sulphur_dioxide" # SO₂ in µg/m³.
|
||||
TEMPERATURE = "temperature" # Temperature in °C, °F, or K.
|
||||
TIMESTAMP = "timestamp" # Datetime object or ISO 8601 string.
|
||||
VOLATILE_ORGANIC_COMPOUNDS = "volatile_organic_compounds" # VOC in µg/m³.
|
||||
VOLATILE_ORGANIC_COMPOUNDS_PARTS = "volatile_organic_compounds_parts" # VOC in ppm or ppb.
|
||||
VOLTAGE = "voltage" # Voltage in V or mV.
|
||||
VOLUME = "volume" # Volume in L, mL, gal, fl. oz., m³, ft³, or CCF.
|
||||
VOLUME_STORAGE = "volume_storage" # Stored volume.
|
||||
WATER = "water" # Water consumption in L, gal, m³, ft³, or CCF.
|
||||
WEIGHT = "weight" # Mass in kg, g, mg, µg, oz, lb, or st.
|
||||
WIND_SPEED = "wind_speed" # Wind speed in ft/s, km/h, kn, m/s, or mph.
|
||||
|
||||
|
||||
class Sensor(Control):
|
||||
"""
|
||||
|
||||
A sensor control for reporting numeric or string values to Home Assistant.
|
||||
|
||||
"""
|
||||
DATA: ClassVar[dict] = dict(
|
||||
platform='sensor'
|
||||
)
|
||||
converters = ConvertersString
|
||||
|
||||
unit_of_measurement: Uom | None = None
|
||||
device_class: DeviceClass | None = None
|
||||
|
||||
def command(self, value: Any):
|
||||
"""
|
||||
|
||||
Sensors do not support commands.
|
||||
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def state(self, value: Any) -> Any:
|
||||
"""
|
||||
|
||||
Return the current state of the sensor.
|
||||
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
@classmethod
|
||||
def get_capabilities(cls) -> list[Capability]:
|
||||
"""
|
||||
|
||||
Get the capabilities for the sensor (state only).
|
||||
|
||||
"""
|
||||
return [
|
||||
Capability(name=None, command=None)
|
||||
]
|
||||
|
|
@ -1,30 +1,17 @@
|
|||
from typing import ClassVar
|
||||
from dataclasses import dataclass
|
||||
|
||||
from haco.control import Control
|
||||
|
||||
|
||||
@dataclass(kw_only=True)
|
||||
class Switch(Control):
|
||||
"""
|
||||
|
||||
A switch control that can be toggled on or off.
|
||||
|
||||
"""
|
||||
DATA: ClassVar[dict] = dict(
|
||||
DATA = dict(
|
||||
platform='switch'
|
||||
)
|
||||
|
||||
def command(self, value: bool) -> bool:
|
||||
"""
|
||||
|
||||
Handle toggle commands from Home Assistant.
|
||||
|
||||
"""
|
||||
def command(self, value):
|
||||
raise NotImplementedError()
|
||||
|
||||
def state(self, value: bool | None) -> bool:
|
||||
"""
|
||||
|
||||
Return the current state of the switch.
|
||||
|
||||
"""
|
||||
def state(self, value):
|
||||
raise NotImplementedError()
|
||||
|
|
|
|||
|
|
@ -1,155 +0,0 @@
|
|||
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()
|
||||
|
|
@ -1,112 +0,0 @@
|
|||
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")
|
||||
43
haco/text.py
43
haco/text.py
|
|
@ -1,43 +0,0 @@
|
|||
from enum import StrEnum
|
||||
from typing import ClassVar
|
||||
|
||||
from haco.control import Control
|
||||
from haco.utils import ConvertersString
|
||||
|
||||
|
||||
class Mode(StrEnum):
|
||||
TEXT = "text"
|
||||
PASSWORD = "password"
|
||||
|
||||
|
||||
class Text(Control):
|
||||
"""
|
||||
|
||||
A text control for text input in Home Assistant.
|
||||
|
||||
"""
|
||||
DATA: ClassVar[dict] = dict(
|
||||
platform='text'
|
||||
)
|
||||
converters = ConvertersString
|
||||
|
||||
pattern: str | None = None
|
||||
min: int | None = None
|
||||
max: int | None = None
|
||||
mode: Mode = Mode.TEXT
|
||||
|
||||
def command(self, value: str) -> str:
|
||||
"""
|
||||
|
||||
Handle text input commands from Home Assistant.
|
||||
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def state(self, value: str | None) -> str:
|
||||
"""
|
||||
|
||||
Return the current text state.
|
||||
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
100
haco/topics.py
100
haco/topics.py
|
|
@ -1,26 +1,18 @@
|
|||
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 fmtr.tools import aio
|
||||
from haco.obs import logger
|
||||
from haco.utils import get_prefix
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from haco.capabilities import Capability
|
||||
from capabilities import Capability
|
||||
|
||||
|
||||
class AnnounceTopic(Base):
|
||||
"""
|
||||
|
||||
Base class for MQTT topics used for discovery and communication.
|
||||
|
||||
"""
|
||||
@dataclass(kw_only=True)
|
||||
class AnnounceTopic:
|
||||
IO: ClassVar[str | None] = None
|
||||
|
||||
KEY_DEFAULTS: ClassVar[dict] = {True: '{capability}_{io}_topic', False: '{io}_topic'}
|
||||
|
|
@ -28,23 +20,13 @@ class AnnounceTopic(Base):
|
|||
key: str | None = None
|
||||
value: str = '{path}/{capability}/{io}'
|
||||
|
||||
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)
|
||||
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)
|
||||
|
||||
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)
|
||||
control_method: Callable | None = field(default=None, metadata=dict(exclude=True))
|
||||
|
||||
def set_parent(self, capability: Capability):
|
||||
"""
|
||||
|
||||
Set the parent capability for the topic and link it to the control's method.
|
||||
|
||||
"""
|
||||
self.parent = capability
|
||||
if self.key is None:
|
||||
self.key = self.KEY_DEFAULTS[bool(self.capability.name)]
|
||||
|
|
@ -73,12 +55,7 @@ class AnnounceTopic(Base):
|
|||
def topic(self):
|
||||
return self.fill(self.value)
|
||||
|
||||
def get_announce(self) -> dict:
|
||||
"""
|
||||
|
||||
Get the discovery announcement data for the topic.
|
||||
|
||||
"""
|
||||
def get_announce(self):
|
||||
return {self.topic_key: self.topic}
|
||||
|
||||
@property
|
||||
|
|
@ -92,12 +69,7 @@ class AnnounceTopic(Base):
|
|||
def callback_class_method_name(self):
|
||||
return f'{self.capability.control.__class__.__name__}.{self.callback_name}'
|
||||
|
||||
def get_subscriptions(self) -> dict:
|
||||
"""
|
||||
|
||||
Get the MQTT topic subscriptions for this topic (empty for base class).
|
||||
|
||||
"""
|
||||
def get_subscriptions(self):
|
||||
return {}
|
||||
|
||||
@cached_property
|
||||
|
|
@ -108,28 +80,14 @@ class AnnounceTopic(Base):
|
|||
raise NotImplementedError()
|
||||
|
||||
|
||||
@dataclass(kw_only=True)
|
||||
class AnnounceTopicState(AnnounceTopic):
|
||||
"""
|
||||
|
||||
MQTT topic for reporting state to Home Assistant.
|
||||
|
||||
"""
|
||||
IO: ClassVar[str] = 'state'
|
||||
|
||||
def get_subscriptions(self) -> dict:
|
||||
"""
|
||||
|
||||
Get the MQTT topic subscriptions for this state topic (empty as it is output only).
|
||||
|
||||
"""
|
||||
def get_subscriptions(self):
|
||||
return {}
|
||||
|
||||
async def handle(self, value=None):
|
||||
"""
|
||||
|
||||
Handle state reporting. Calls the linked control method and publishes the result.
|
||||
|
||||
"""
|
||||
|
||||
if not self.control_method:
|
||||
logger.error(f'Incomplete base class: {self.callback_class_method_name}')
|
||||
|
|
@ -148,18 +106,11 @@ class AnnounceTopicState(AnnounceTopic):
|
|||
return
|
||||
|
||||
value_raw = self.capability.converters.state(value)
|
||||
await self.capability.control.device.client.publish(self.topic, value_raw, retain=True)
|
||||
|
||||
logger.info(f'{get_prefix(self.IO)}: {self.topic} {Constants.ARROW_RIGHT} {value_raw}')
|
||||
|
||||
await self.capability.control.device.client.publish(self.topic, value_raw)
|
||||
return value_raw
|
||||
|
||||
@dataclass(kw_only=True)
|
||||
class AnnounceTopicCommand(AnnounceTopic):
|
||||
"""
|
||||
|
||||
MQTT topic for receiving commands from Home Assistant.
|
||||
|
||||
"""
|
||||
IO: ClassVar[str] = 'command'
|
||||
|
||||
@property
|
||||
|
|
@ -167,23 +118,15 @@ class AnnounceTopicCommand(AnnounceTopic):
|
|||
return self.capability.state
|
||||
|
||||
async def handle(self, message):
|
||||
"""
|
||||
|
||||
Handle incoming command messages. Decodes, converts, calls the linked control method, and updates state.
|
||||
|
||||
"""
|
||||
|
||||
value = message.payload.decode('utf-8')
|
||||
value = self.capability.converters.command(value)
|
||||
|
||||
logger.info(f'{get_prefix(self.IO)}: {value} {Constants.ARROW_LEFT} {self.topic}')
|
||||
|
||||
|
||||
if not self.control_method:
|
||||
logger.error(f'Incomplete base class: {self.callback_class_method_name}')
|
||||
return
|
||||
|
||||
is_async = aio.is_async(self.control_method)
|
||||
value = message.payload.decode('utf-8')
|
||||
value = self.capability.converters.command(value)
|
||||
|
||||
try:
|
||||
|
||||
if is_async:
|
||||
|
|
@ -195,14 +138,11 @@ class AnnounceTopicCommand(AnnounceTopic):
|
|||
logger.warning(f'Subclass has not implemented method: {self.callback_class_method_name} {self.topic} {value}')
|
||||
return
|
||||
|
||||
# Echo back as new state
|
||||
topic_state = self.state
|
||||
if topic_state:
|
||||
await topic_state.handle(value_raw)
|
||||
|
||||
def get_subscriptions(self) -> dict:
|
||||
"""
|
||||
|
||||
Get the MQTT topic subscriptions for this command topic.
|
||||
|
||||
"""
|
||||
def get_subscriptions(self):
|
||||
return {self.topic: self}
|
||||
|
|
|
|||
|
|
@ -4,8 +4,6 @@ from enum import StrEnum
|
|||
class Uom(StrEnum):
|
||||
"""
|
||||
|
||||
Units of measurement for sensors.
|
||||
|
||||
Sourced from: https://github.com/home-assistant/core/blob/03b1c7ad1deb4b9494df01b27ef8e1d7dfe179ba/homeassistant/const.py#L489
|
||||
|
||||
"""
|
||||
|
|
|
|||
|
|
@ -1,8 +1,9 @@
|
|||
import string
|
||||
from dataclasses import dataclass
|
||||
from typing import Callable
|
||||
|
||||
from corio import jsn
|
||||
from corio.datatype import to_bool
|
||||
from fmtr.tools import json
|
||||
from fmtr.tools.datatype_tools import to_bool
|
||||
|
||||
CHARS_ALLOWED = string.ascii_lowercase + string.digits
|
||||
SEPS = '_- /'
|
||||
|
|
@ -17,13 +18,7 @@ BOOL_MAP = {True: ON, False: OFF}
|
|||
|
||||
from_bool = BOOL_MAP.get
|
||||
|
||||
|
||||
def sanitize_name(s: str, sep: str = '-') -> str:
|
||||
"""
|
||||
|
||||
Sanitize a string for use in MQTT topics and Home Assistant identifiers.
|
||||
|
||||
"""
|
||||
def sanitize_name(s, sep='-'):
|
||||
chars = []
|
||||
|
||||
for c in s.lower():
|
||||
|
|
@ -41,48 +36,24 @@ def sanitize_name(s: str, sep: str = '-') -> str:
|
|||
|
||||
|
||||
class Converters:
|
||||
"""
|
||||
|
||||
Base class for message converters.
|
||||
|
||||
"""
|
||||
command: Callable = None
|
||||
state: Callable = None
|
||||
|
||||
|
||||
class ConvertersBool(Converters):
|
||||
"""
|
||||
|
||||
Converters for boolean values.
|
||||
|
||||
"""
|
||||
command: Callable = to_bool
|
||||
state: Callable = from_bool
|
||||
|
||||
|
||||
class ConvertersString(Converters):
|
||||
"""
|
||||
|
||||
Converters for string values.
|
||||
|
||||
"""
|
||||
command: Callable = str
|
||||
state: Callable = str
|
||||
|
||||
|
||||
class ConvertersNumeric(Converters):
|
||||
"""
|
||||
command: Callable = json.from_json
|
||||
state: Callable = json.to_json
|
||||
|
||||
Converters for numeric values.
|
||||
|
||||
"""
|
||||
command: Callable = jsn.from_json
|
||||
state: Callable = jsn.to_json
|
||||
|
||||
def get_prefix(io: str) -> str:
|
||||
"""
|
||||
|
||||
Get a short prefix for IO operations (e.g. 'ST' for state, 'CO' for command).
|
||||
|
||||
"""
|
||||
return io[:2].upper()
|
||||
@dataclass
|
||||
class Metadata:
|
||||
exclude: bool = False
|
||||
|
|
|
|||
3
haco/v0/haco/binary_sensor.py
Normal file
3
haco/v0/haco/binary_sensor.py
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
|
||||
|
||||
|
||||
57
haco/v0/haco/fan.py
Normal file
57
haco/v0/haco/fan.py
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
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
|
||||
44
haco/v0/haco/sensor.py
Normal file
44
haco/v0/haco/sensor.py
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
from haco.data.type_sensor import DeviceClassSensor
|
||||
from haco.data.uom import Uom
|
||||
|
||||
import haco.capabilities
|
||||
import haco.topics
|
||||
from haco import schema
|
||||
from haco.control import Control
|
||||
|
||||
|
||||
class Sensor(Control):
|
||||
NAME = 'sensor'
|
||||
|
||||
UOM_TYPE = DeviceClassSensor
|
||||
UOM = Uom
|
||||
|
||||
@classmethod
|
||||
def get_schema(cls):
|
||||
return schema.Schema(
|
||||
capabilities=[
|
||||
haco.capabilities.Capability(
|
||||
ha=None,
|
||||
tasmota=schema.Tasmota(announce_data=haco.topics.AnnounceTopic(key='{io_ha}_topic'))
|
||||
)
|
||||
]
|
||||
)
|
||||
|
||||
def __init__(self, name, data_type=None, uom=None, icon=None, uom_type=None):
|
||||
self.data_type = data_type
|
||||
self.device_class = uom_type
|
||||
self.uom = uom
|
||||
|
||||
super().__init__(name, icon=icon)
|
||||
|
||||
@property
|
||||
def control_type(self):
|
||||
return self.data_type or (lambda v: v)
|
||||
|
||||
def get_config_ha_ex(self):
|
||||
data = {
|
||||
'unit_of_measurement': self.uom,
|
||||
'device_class': self.device_class
|
||||
}
|
||||
|
||||
return data
|
||||
27
haco/v0/haco/text.py
Normal file
27
haco/v0/haco/text.py
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
from haco.control import Control
|
||||
|
||||
from haco.tools import get_range_pair
|
||||
|
||||
|
||||
class Text(Control):
|
||||
NAME = 'text'
|
||||
|
||||
def __init__(self, name, icon=None, size_range: range = None, pattern: str = None):
|
||||
self.min, self.max = get_range_pair(size_range)
|
||||
self.pattern = pattern
|
||||
|
||||
super().__init__(name, icon=icon)
|
||||
|
||||
def get_config_ha_ex(self):
|
||||
data = {
|
||||
'min': self.min,
|
||||
'max': self.max,
|
||||
'pattern': self.pattern,
|
||||
'mode': self.__class__.__name__.lower()
|
||||
}
|
||||
|
||||
return data
|
||||
|
||||
|
||||
class Password(Text):
|
||||
...
|
||||
1
haco/version
Normal file
1
haco/version
Normal file
|
|
@ -0,0 +1 @@
|
|||
0.1.2
|
||||
3
haco/version.py
Normal file
3
haco/version.py
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
from fmtr.tools import version
|
||||
|
||||
__version__ = version.read()
|
||||
|
|
@ -1,86 +1,3 @@
|
|||
[build-system]
|
||||
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"]
|
||||
requires = ["fmtr.tools[setup,debug]"]
|
||||
build-backend = "setuptools.build_meta" #
|
||||
13
setup.py
Normal file
13
setup.py
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
from fmtr.tools import Setup
|
||||
|
||||
setup = Setup(
|
||||
org=None,
|
||||
dependencies=dict(
|
||||
install=[
|
||||
'fmtr.tools[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}',
|
||||
)
|
||||
Loading…
Add table
Add a link
Reference in a new issue