diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml deleted file mode 100644 index 6556dfc..0000000 --- a/.github/workflows/main.yml +++ /dev/null @@ -1,76 +0,0 @@ -name: Version and Deploy - -on: - workflow_dispatch: - inputs: - version: - description: 'Version' - required: true - - -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 }} - REBRANDLY_API_KEY: ${{ secrets.REBRANDLY_API_KEY }} - LINK_ID: ca4942821f5740fbaa46d1066b5cd7e4 - - steps: - - uses: actions/checkout@v3 - with: - fetch-depth: 0 - - - - name: Install Tools - run: | - pip install twine tappack - - - name: Increment Version - run: | - - git config --global user.name 'Frontmatter Actions' - git config --global user.email 'actions@frontmatter.ai' - echo -n ${VERSION} > ${NAME}/version - python3 update_version.py ${VERSION} - tappack --module-path berry/ --output ./${NAME_SHORT}.tapp - - git add ${NAME}/version - git add berry/${NAME_SHORT}_version.be - git add ha/addon/config.yaml - - git commit -am "Increment version number to ${VERSION} for release" - git push - 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: - files: haco.tapp - tag_name: v${{ github.event.inputs.version }} - generate_release_notes: true - - - name: Build Wheel - run: | - python setup.py sdist bdist_wheel - - - name: Push Wheel - env: - TWINE_PASSWORD: ${{ secrets.PYPI_TOKEN }} - TWINE_USERNAME: __token__ - run: | - twine upload dist/* - - - name: Update Link - run: | - URL=https://github.com/${ORG}/${NAME}/releases/download/v${VERSION}/${NAME_SHORT}.tapp - DATA="{\"destination\": \"${URL}\"}" - curl --request POST --url https://api.rebrandly.com/v1/links/${LINK_ID} --header 'accept: application/json' --header "apikey: ${REBRANDLY_API_KEY}" --header 'content-type: application/json' --data "$DATA" &> /dev/null - 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 e69de29..e7c780a 100644 --- a/README.md +++ b/README.md @@ -0,0 +1,27 @@ +# `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. + +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) diff --git a/berry/haco_version.be b/berry/haco_version.be deleted file mode 100644 index 85fad4a..0000000 --- a/berry/haco_version.be +++ /dev/null @@ -1,5 +0,0 @@ -var VERSION='0.0.2' - -var mod = module("haco_version") -mod.VERSION=VERSION -return mod \ No newline at end of file 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/docs/controls.md b/docs/controls.md new file mode 100644 index 0000000..07beb5c --- /dev/null +++ b/docs/controls.md @@ -0,0 +1,99 @@ +`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`. diff --git a/docs/index.md b/docs/index.md new file mode 100644 index 0000000..2ffdb68 --- /dev/null +++ b/docs/index.md @@ -0,0 +1,7 @@ +!!! tip "How Do I Get Started?" + + See the [Quick Start](quick-start.md) section. + +--8<-- +README.md +--8<-- diff --git a/docs/quick-start.md b/docs/quick-start.md new file mode 100644 index 0000000..28be7b8 --- /dev/null +++ b/docs/quick-start.md @@ -0,0 +1,48 @@ +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). diff --git a/ha/addon/DOCS.md b/ha/addon/DOCS.md deleted file mode 100644 index 67c5929..0000000 --- a/ha/addon/DOCS.md +++ /dev/null @@ -1 +0,0 @@ -For general documentation, see **[the project wiki](https://link.frontmatter.ai/haco/doc)**. \ No newline at end of file diff --git a/ha/addon/Dockerfile b/ha/addon/Dockerfile deleted file mode 100644 index 4d743a4..0000000 --- a/ha/addon/Dockerfile +++ /dev/null @@ -1,10 +0,0 @@ -ARG BUILD_FROM -FROM $BUILD_FROM - -ARG BUILD_VERSION -RUN pip install haco==${BUILD_VERSION} - -COPY run.sh / -RUN chmod a+x /run.sh - -CMD [ "/run.sh" ] \ No newline at end of file diff --git a/ha/addon/README.md b/ha/addon/README.md deleted file mode 100644 index fe84005..0000000 --- a/ha/addon/README.md +++ /dev/null @@ -1 +0,0 @@ -../../README.md \ No newline at end of file diff --git a/ha/addon/config.yaml b/ha/addon/config.yaml deleted file mode 100644 index e22a05a..0000000 --- a/ha/addon/config.yaml +++ /dev/null @@ -1,19 +0,0 @@ -arch: - - aarch64 - - amd64 - - armhf - - armv7 - - i386 -description: Python-based controls for Tasmota devices. -init: false -map: - - config:rw -name: haco -options: -#panel_icon: mdi:nature-people -schema: -services: - - mqtt:need -slug: haco -url: https://link.frontmatter.ai/haco -version: 0.0.2 diff --git a/ha/addon/translations/en.yaml b/ha/addon/translations/en.yaml deleted file mode 100644 index d7356f1..0000000 --- a/ha/addon/translations/en.yaml +++ /dev/null @@ -1,2 +0,0 @@ ---- -configuration: diff --git a/haco/base.py b/haco/base.py new file mode 100644 index 0000000..5a3d662 --- /dev/null +++ b/haco/base.py @@ -0,0 +1,39 @@ +from __future__ import annotations + +from typing import Any, ClassVar + +from pydantic import ConfigDict + +from corio import dm + + +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]] = {} + + def model_dump(self, *args, **kwargs) -> dict[str, Any]: + """ + Dump this model for Home Assistant discovery payloads. + + 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) diff --git a/haco/binary_sensor.py b/haco/binary_sensor.py new file mode 100644 index 0000000..fe3e23c --- /dev/null +++ b/haco/binary_sensor.py @@ -0,0 +1,83 @@ +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) + ] diff --git a/haco/button.py b/haco/button.py new file mode 100644 index 0000000..113fbf6 --- /dev/null +++ b/haco/button.py @@ -0,0 +1,34 @@ +from typing import ClassVar + +from haco.capabilities import Capability +from haco.control import Control + + +class Button(Control): + """ + + A button control that can be pressed in Home Assistant. + + """ + DATA: ClassVar[dict] = dict( + platform='button' + ) + + def command(self, value: None): + """ + + Handle button press commands from Home Assistant. + + """ + raise NotImplementedError() + + @classmethod + def get_capabilities(cls) -> list[Capability]: + """ + + Get the capabilities for the button (command only). + + """ + return [ + Capability(name=None, state=None) + ] diff --git a/haco/capabilities.py b/haco/capabilities.py new file mode 100644 index 0000000..17b1d83 --- /dev/null +++ b/haco/capabilities.py @@ -0,0 +1,89 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Type, ClassVar + +from pydantic import Field + +from corio.iterator import strip_none + +from haco.base import Base +from haco.topics import AnnounceTopicState, AnnounceTopicCommand +from haco.utils import Converters + +if TYPE_CHECKING: + from haco.control import Control + + +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) + + 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 + + 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. + + """ + self.parent = control + for topic in self.topics: + topic.set_parent(self) + + 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. + + """ + return strip_none(self.state, self.command) + + @property + def control(self) -> Control: + """ + + The parent control of the capability. + + """ + return self.parent diff --git a/haco/client.py b/haco/client.py new file mode 100644 index 0000000..02d1654 --- /dev/null +++ b/haco/client.py @@ -0,0 +1,70 @@ +import asyncio +from pathlib import Path + +import aiomqtt +from corio import mqtt + +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' + + 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 + self.device = device + self.device.set_parent(self) + super().__init__(*args, will=self.will, identifier=identifier, **kwargs) + + @property + def topic(self) -> Path: + """ + + The MQTT topic prefix for the client. + + """ + return constants.TOPIC_CLIENT + + async def handle(self): + """ + + Handle incoming MQTT messages by delegating them to the device's controls. + + """ + + for topic_sub in self.device.subscriptions.keys(): + logger.info(f"{get_prefix(SUBSCRIBE)}: {topic_sub}") + await self.subscribe(topic_sub) + + async for message in self.messages: + topic_command = self.device.subscriptions[message.topic.value] + 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.publish(self.will.topic, self.ONLINE, retain=True) + await self.handle() + + except aiomqtt.MqttError as e: + logger.info(f"MQTT disconnected: {e}; retrying in 5s") + await asyncio.sleep(5) diff --git a/haco/climate.py b/haco/climate.py index 0387355..c616fff 100644 --- a/haco/climate.py +++ b/haco/climate.py @@ -1,112 +1,92 @@ -from haco.control import Control -from haco.schema import Schema, Capability, AnnounceTopic, Tasmota -from haco.tools import get_range_pair +from typing import Literal, ClassVar -CELSIUS_C = 'C' -FAHRENHEIT_F = 'F' +from haco.capabilities import Capability +from haco.control import Control class Climate(Control): - NAME = 'climate' + """ + + A climate control for managing HVAC systems. + + """ + DATA: ClassVar[dict] = dict( + platform='climate' + ) + + + temperature_unit: Literal["C", "F"] = "C" + temperature_min: float = 0 + temperature_max: float = 40 + humidity_min: float = 0 + humidity_max: float = 100 + precision: int = 1 + modes: list[str] | None = None + preset_modes: list[str] | None = None + fan_modes: list[str] | None = None + swing_modes: list[str] | None = None + + def temperature_command(self, value: float) -> float: + """ + + Handle target temperature commands. + + """ + raise NotImplementedError() + + def mode_command(self, value: str) -> str: + """ + + Handle HVAC mode commands. + + """ + raise NotImplementedError() + + def fan_mode_command(self, value: str) -> str: + """ + + Handle fan mode commands. + + """ + raise NotImplementedError() + + def fan_mode_state(self, value: str | None) -> str: + """ + + Return the current fan mode. + + """ + raise NotImplementedError() + + def power_command(self, value: bool) -> bool: + """ + + Handle power toggle commands. + + """ + raise NotImplementedError() + + def power_state(self, value: bool | None) -> bool: + """ + + Return the current power state. + + """ + raise NotImplementedError() @classmethod - def get_schema(cls): - schema = Schema( - capabilities=[ - Capability( - name='mode', - type=str - ), - Capability( - name='target_humidity' - ), - Capability( - name='temperature', - alias='target_temperature' - ), - Capability( - name='temperature_high' - ), - Capability( - name='temperature_low' - ), - Capability( - name='swing_mode', - type=str - ), - Capability( - name='preset_mode', - type=str - ), - Capability( - name='current_humidity', - ha=None, - tamota=Tasmota(announce_data=AnnounceTopic(key='{capability}_topic')) - ), - Capability( - name='current_temperature', - ha=None, - tamota=Tasmota(announce_data=AnnounceTopic(key='{capability}_topic')) - ), - Capability( - name='action', - type=str, - ha=None, - tamota=Tasmota(announce_data=AnnounceTopic(key='{capability}_topic')) - ) - ] - ) - return schema + def get_capabilities(cls) -> list[Capability]: + """ - # def init(name, entity_id, icon, temperature_unit, temperature_range, humidity_range, modes, preset_modes, fan_modes, swing_modes, precision, callbacks) + Get the capabilities for the climate control. - def __init__(self, name=None, icon=None, temperature_unit=None, temperature_range=None, humidity_range=None, - modes=None, preset_modes=None, fan_modes=None, swing_modes=None, precision=None): - self.temperature_unit = temperature_unit - - self.temperature_min, self.temperature_max = get_range_pair(temperature_range) - self.humidity_min, self.humidity_max = get_range_pair(humidity_range) - - self.precision = precision - # self.type = float if self.precision is None else int if self.precision == 1 else float if self.temperature_unit == 'C' else int - - self.fan_modes = fan_modes - self.modes = modes - self.preset_modes = preset_modes - self.swing_modes = swing_modes - - super().__init__(name, icon=icon) - - @property - def control_type(self): - - if self.precision == 1: - return int - - if self.precision: - return float - - unit = self.temperature_unit or CELSIUS_C - - if unit == CELSIUS_C: - return float - else: - return int - - def get_config_ha_ex(self): - data = { - - 'fan_modes': self.fan_modes, - 'preset_modes': self.preset_modes, - 'swing_modes': self.swing_modes, - 'modes': self.modes, - 'min_temp': self.temperature_min, - 'max_temp': self.temperature_max, - 'min_humidity': self.humidity_min, - 'max_humidity': self.humidity_max, - 'precision': self.precision, - 'temperature_unit': self.temperature_unit - - } - - return data + """ + return [ + Capability(name="current_temperature", command=None), + Capability(name="temperature"), + Capability(name="current_humidity"), + Capability(name="target_humidity"), + Capability(name="mode"), + Capability(name="fan_mode"), + Capability(name="power"), + ] diff --git a/haco/constants.py b/haco/constants.py index bac17ee..989496f 100644 --- a/haco/constants.py +++ b/haco/constants.py @@ -1,5 +1,24 @@ -import string +""" -CHARS_ALLOWED = string.ascii_lowercase + string.digits -SEPS_ALLOWED = '_- ' -BRANCH = 'release' +Global constants for the haco library. + +""" +from __future__ import annotations + +from corio import env, Path, net + +from haco.paths import paths + +STATUS = 'status' +HOSTNAME = net.get_hostname().lower() +MAC = net.MAC() + +CLIENT_ID = f'{HOSTNAME}-{MAC.hex}' + +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' diff --git a/haco/control.py b/haco/control.py index c09743d..114d62e 100644 --- a/haco/control.py +++ b/haco/control.py @@ -1,107 +1,178 @@ -import logging -from functools import partial +from __future__ import annotations -from haco import schema, tools -from haco.callback import Callback -from haco.schema import Schema, Platform, Tasmota, HomeAssistant, AnnounceTopic, Capability -from haco.tools import log_publish +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 haco.base import Base +from haco.capabilities import Capability +from haco.constants import PREFIX_MDI, ANNOUNCE +from haco.obs import logger +from haco.utils import sanitize_name, Converters, ConvertersBool, get_prefix + +if TYPE_CHECKING: + from haco.device import Device + +DeviceT = TypeVar("DeviceT") -class Control: - NAME = None +class Control(Base, Generic[DeviceT]): + """ - control_type = str + Base class for Home Assistant controls. - @classmethod - def get_schema(cls): - schema = Schema( - capabilities=[ - Capability( - name='state', - ha=HomeAssistant(announce_data=AnnounceTopic(key='{io_ha}_topic')), - tamota=Tasmota(announce_data=AnnounceTopic(key='{io_ha}_topic')) - ) - ] - ) - return schema + """ + converters: ClassVar[Type[Converters]] = ConvertersBool - def __init__(self, name, icon=None): + 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 - from device import Device + subscriptions: dict | None = Field(default=None, exclude=True, repr=False) - self.name = name + def model_post_init(self, __context): + self.capabilities = self.get_capabilities() - self.device: Device = None - self.schema = self.get_schema() - self.get = self.schema.get - self.schema.control = self - - self.icon = icon - - @property - def name_sanitized(self): - return tools.sanitize_name(self.name) - - def callback(self, trigger=None): - return partial(self.add_callback, trigger) - - def add_callback(self, trigger, function): - - if (function_name := function.__name__) in {Tasmota.PLATFORM, HomeAssistant.PLATFORM}: - function_name = f'state_{function_name}' - - callback_names = self.schema.get_callback_function_names() - - if function_name not in callback_names: - msg = f'Callback function "{function_name}" name is not valid. Must be one of: {sorted(callback_names)}' - raise ValueError(msg) - - capability_id, platform_id = function_name.rsplit('_', 1) - callback = Callback(capability=capability_id, platform=platform_id, trigger=trigger, function=function) - platform: Platform = self.schema.get_alias(capability_id).get(platform_id) - platform.callback = callback - - def get_subscriptions(self): - return self.schema.get_subscriptions() - - def get_config_tasmota(self): - return self.schema.get_config_tasmota() - - def get_config_ha_base(self): - data = { - "unique_id": f"{self.device.name_sanitized}-{self.device.mac_short}-{self.name_sanitized}", - "name": self.name, - "availability_topic": f"tele/{self.device.topic}/LWT", - "payload_off": schema.OFF, - "payload_available": "Online", - "payload_on": schema.ON, - "payload_not_available": "Offline", - "force_update": True, - "icon": self.icon, - # "entity_id": self.entity_id - } - data.update(self.schema.get_config_ha()) - - return data - - def get_config_ha(self): - data = self.get_config_ha_base() | self.get_config_ha_ex() - data = {k: v for k, v in data.items() if v is not None} - return data - - def get_config_ha_ex(self): - return {} - - async def process_message(self, client, capability_id, platform_id, message): - - if not message.payload: - logging.warning(f'Topic {message.topic.value} got empty payload. It may have been deleted.') + if not self.icon: return - platform = self.schema.get(capability_id).get(platform_id) - output = platform.handle(message) - topic = str(platform.get_topic_publish()) - await log_publish(client, topic, output) + if not self.icon.startswith(PREFIX_MDI): + self.icon = f"{PREFIX_MDI}{self.icon}" - def get_announce_topic(self): - return f"homeassistant/{self.NAME}/{self.device.name_sanitized}/{self.name_sanitized}/config" + def set_parent(self, device: DeviceT): + """ + + Set the parent device for the control and its capabilities. + + """ + self.device = device + + for cap in self.capabilities: + cap.set_parent(self) + + self.unique_id = self.get_unique_id() + self.availability_topic = self.get_availability_topic() + self.subscriptions = self.get_subscriptions() + + @property + def parent(self) -> DeviceT: + """ + + The parent device of the control. + + """ + return self.device + + def get_announce(self) -> dict: + """ + + Get the discovery announcement data for the control. + + """ + data = self.model_dump() + for cap in self.capabilities: + data |= cap.get_announce() + + return data + + @classmethod + def get_capabilities(cls) -> list[Capability]: + """ + + Get the capabilities of the control. + + """ + return [ + Capability(name=None) + ] + + def get_unique_id(self) -> str: + return f"{self.device.name_san}-{self.name_san}" + + @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. + + """ + return self.device.topic / self.name_san + + @property + def announce_topic(self) -> str: + """ + + The MQTT topic for discovery announcement. + + """ + 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 = {} + + for capability in self.capabilities: + data |= capability.get_subscriptions() + + 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. + + """ + topic = self.announce_topic + data = self.get_announce() + data_json = to_json(data) + + logger.info(f'{get_prefix(ANNOUNCE)}: {data} {Constants.ARROW_RIGHT} {topic}') + + await self.device.client.publish(topic, data_json, retain=True) + + + +if __name__ == "__main__": + control = Control(name="test", platform="test") + control diff --git a/haco/debugging.py b/haco/debugging.py deleted file mode 100644 index 9db48ea..0000000 --- a/haco/debugging.py +++ /dev/null @@ -1,15 +0,0 @@ -from typing import Any - -from haco import trigger -from haco.sensor import Sensor -from haco.tasmota import Tasmota - - -def get_memory_sensor(): - memory_sensor = Sensor('Memory Free', uom='kB', device_class='DATA_SIZE', data_type=int) - - @memory_sensor.callback(trigger.Cron('*/30 * * * * *')) - def tasmota(value: Tasmota[Any, 'tasmota.memory()']): - return value.get('heap_free', 'unknown') - - return memory_sensor diff --git a/haco/device.py b/haco/device.py index 0d2d161..64f8d6b 100644 --- a/haco/device.py +++ b/haco/device.py @@ -1,114 +1,117 @@ -import json +from __future__ import annotations + +from functools import cached_property from pathlib import Path -from typing import List +from typing import List, TYPE_CHECKING -from haco import tools, constants +from pydantic import Field + +from haco.base import Base from haco.control import Control -from haco.tools import log_publish, split_into_chunks, log_subscribe +from haco.utils import sanitize_name + +if TYPE_CHECKING: + from haco.client import ClientHaco -class Device: +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 + + controls: List[Control] = Field(default_factory=list, exclude=True, repr=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): + """ + + Set the parent client for the device and its controls. + + """ + self.parent = client + + self.identifiers = [self.name_san] - def __init__(self, mac, controls: List[Control], run_config_post=None): - self.name = None - self.topic = None - self.hostname = None - self.mac = mac - self.run_config_post = run_config_post - self.controls = controls - self.config_id = None for control in self.controls: - control.device = self + control.set_parent(self) + self.subscriptions = self.get_subscriptions() - self.contols_dict = {control.name_sanitized: control for control in self.controls} - self.get = self.contols_dict.get + @cached_property + def topic(self) -> Path: + """ + + The MQTT topic prefix for the device. + + """ + return self.client.topic / self.name_san @property - def name_sanitized(self): - return tools.sanitize_name(self.name) + 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 mac_short(self): - return self.mac.replace(':', '').lower() + def client(self) -> ClientHaco: + """ - def get_config_ha(self): + The parent client of the device. - data_device = { - "connections": [["mac", self.mac]], - "identifiers": self.mac - } + """ + 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 = control.get_config_ha() - data_control['device'] = data_device - data[control.get_announce_topic()] = data_control + data |= control.subscriptions return data - def get_config_tasmota(self): - config = [] - for control in self.controls: - config += control.get_config_tasmota() - return config - def get_subscriptions(self): - data = {} - for control in self.controls: - data.update(control.get_subscriptions()) - - return data - - async def publish_config_ha(self, client): - data = self.get_config_ha() - for topic, data in data.items(): - await log_publish(client, topic, payload=json.dumps(data), retain=True) - - async def publish_config_tasmota(self, client): - data = self.get_config_tasmota() - - data_mqtt = {datum['trigger']: datum for datum in data if datum['type'] == 'MqttSubscription'} - data_callbacks = [datum for datum in data if datum['type'] != 'MqttSubscription'] - - tasmota_config = { - # 'id': self.config_id, - 'callbacks': data_callbacks, - 'mqtt': data_mqtt, - 'run_config_post': self.run_config_post, - - } - - self.config_id = tools.hash_string(json.dumps(tasmota_config)) - - tasmota_config['id'] = self.config_id - - tasmota_config_str = json.dumps(tasmota_config) - tasmota_config_topic = Path(f"haco/{constants.BRANCH}/{self.hostname}/config") - parts = split_into_chunks(tasmota_config_str, 750) - for i, part in enumerate(parts): - part = json.dumps({"id": self.config_id, "data": part}) - if len(part) > 1200: - raise ValueError(f'Config part too large.') - await log_publish(client, str(tasmota_config_topic / str(i)), payload=part, retain=True) - - payload_header = json.dumps({"size": len(parts), "id": self.config_id, 'force_update': True}) - await log_publish(client, str(tasmota_config_topic), payload=payload_header, retain=True) - - payload_full = json.dumps({"size": len(parts), "id": self.config_id, "data": tasmota_config}) - await log_publish(client, str(tasmota_config_topic / 'full'), payload=payload_full, retain=True) - - async def do_subscriptions(self, client): - data = self.get_subscriptions() - for topic in data.keys(): - await log_subscribe(client, str(topic)) - - async def bind(self, client, data_announce): - print(f'Found match for self: {self}') - self.name = data_announce['device_name'] - self.topic = data_announce['topic'] - self.hostname = data_announce['hostname'] - - await self.do_subscriptions(client) - - await self.publish_config_ha(client) - await self.publish_config_tasmota(client) +if __name__ == "__main__": + control = Control(name="test", platform="test") + device = Device(name="test", parent=None, controls=[control]) + data = device.model_dump() + print(device.topic) 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/load_configs.py b/haco/load_configs.py deleted file mode 100644 index 90fd275..0000000 --- a/haco/load_configs.py +++ /dev/null @@ -1,62 +0,0 @@ -from importlib import reload - -import importlib.util -import os -import yaml -from pathlib import Path - -from haco.control import Control -from haco.device import Device - -CONFIGS_PATH = Path(os.environ['HACO_CONFIGS_PATH']) - - -def load_yaml_file(file_path): - with open(file_path, 'r') as yaml_file: - data = yaml.safe_load(yaml_file) - return data - - -def load_controls_from_directory(directory_path): - assn = load_yaml_file(directory_path / 'assignments.yaml') - - controls = [] - for name, macs in assn.items(): - - if type(macs) is not list: - macs = [macs] - - macs - - for mac in macs: - - args = {'mac': mac} - - py_file = directory_path / Path(name).with_suffix('.py') - module_name = py_file.stem - - try: - module = importlib.import_module(f'haco.configs.{module_name}') - reload(module) - except ImportError: - spec = importlib.util.spec_from_file_location(module_name, str(py_file)) - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - - for obj_name in dir(module): - obj = getattr(module, obj_name) - if obj_name == 'DEVICE_CONFIG': - args.update(obj) - if isinstance(obj, Control): - args.setdefault('controls', []) - args['controls'].append(obj) - - controls.append(args) - - return controls - - -def load_devices(): - devices_args = load_controls_from_directory(CONFIGS_PATH) - devices = [Device(**args) for args in devices_args] - return devices diff --git a/haco/mqtt.py b/haco/mqtt.py deleted file mode 100644 index ecb2110..0000000 --- a/haco/mqtt.py +++ /dev/null @@ -1,62 +0,0 @@ -import aiomqtt -import asyncio -import json -import logging -import os -from pathlib import Path - -from haco import constants -from haco.device import Device -from haco.load_configs import load_devices -from haco.tools import log_received - -MQTT_PASSWORD = os.environ['MQTT_PASSWORD'] -MQTT_HOST = os.environ['MQTT_HOST'] -MQTT_PORT = int(os.environ['MQTT_PORT']) -MQTT_USERNAME = os.environ['MQTT_USERNAME'] - - -async def listen(client, devices): - TOPIC_ANNOUNCE = f"haco/{constants.BRANCH}/+/announce" - await client.subscribe(TOPIC_ANNOUNCE) - - async with client.messages() as messages: - - async for message in messages: - await log_received(message) - if message.topic.matches(TOPIC_ANNOUNCE): - - if not message.payload: - logging.warning(f'Topic {message.topic.value} got empty payload. It may have been deleted.') - continue - - data_announce = json.loads(message.payload) - mac = data_announce['wifi']['mac'] - if mac not in devices: - print(f'Got announce from device with no config: {data_announce}') - continue - - device: Device = devices[mac] - - if device.config_id and data_announce['config_id'] == device.config_id: - print(f'Device {device.name} ({device.hostname}:{device.mac}) successfully configured.') - continue - - await device.bind(client, data_announce) - devices[device.hostname] = device - - device - - else: - _, _, device_name, _, control, capability_id, platform, io = Path(message.topic.value).parts - device = devices[device_name] - await device.get(control).process_message(client, capability_id, platform, message) - - -async def start_mqtt(): - devices = load_devices() - devices = {device.mac: device for device in devices} - - async with aiomqtt.Client(hostname=MQTT_HOST, port=MQTT_PORT, username=MQTT_USERNAME, - password=MQTT_PASSWORD) as client: - await asyncio.gather(listen(client, devices)) diff --git a/haco/number.py b/haco/number.py index c87057b..e7e58d4 100644 --- a/haco/number.py +++ b/haco/number.py @@ -1,36 +1,45 @@ -from haco.control import Control +from enum import StrEnum +from typing import ClassVar, Type -from haco.tools import get_range_pair +from haco.control import Control +from haco.uom import Uom +from haco.utils import Converters, ConvertersNumeric + + +class Mode(StrEnum): + BOX = "box" + SLIDER = "slider" class Number(Control): - NAME = 'number' + """ - # def init(name, number_range, mode, step, uom, entity_id, icon, callbacks) - def __init__(self, name, number_range: range, icon=None, mode=None, step=None, uom=None): + A number control (slider or box) for numeric input in Home Assistant. - self.min, self.max = get_range_pair(number_range) - self.mode = mode - self.step = step - self.uom = uom + """ + DATA: ClassVar[dict] = dict( + platform='number' + ) + converters: ClassVar[Type[Converters]] = ConvertersNumeric - super().__init__(name, icon=icon) + min: float = 0. + max: float = 100. + mode: Mode = Mode.SLIDER + step: float = 1. + uom: Uom | None = None - @property - def control_type(self): + def command(self, value: float) -> float: + """ - if self.step is None or self.step == 1: - return int - else: - return float + Handle numeric value commands from Home Assistant. - def get_config_ha_ex(self): - data = { - 'min': self.min, - 'max': self.max, - 'mode': self.mode, - 'unit_of_measurement': self.uom, - 'step': self.step - } + """ + raise NotImplementedError() - return data + def state(self, value: float | None) -> float: + """ + + Return the current numeric state. + + """ + raise NotImplementedError() diff --git a/haco/obs.py b/haco/obs.py new file mode 100644 index 0000000..3dc4036 --- /dev/null +++ b/haco/obs.py @@ -0,0 +1,12 @@ +""" + +Observability and logging setup for the haco library. + +""" +from corio import debug, logs + +from haco.paths import paths + +debug.trace() + +logger = logs.from_paths(paths) diff --git a/haco/paths.py b/haco/paths.py new file mode 100644 index 0000000..25f0abf --- /dev/null +++ b/haco/paths.py @@ -0,0 +1,8 @@ +""" + +Path definitions for the haco library. + +""" +from corio import paths + +paths = paths.PackagePaths() diff --git a/haco/pulldown.py b/haco/pulldown.py deleted file mode 100644 index b5276ee..0000000 --- a/haco/pulldown.py +++ /dev/null @@ -1,18 +0,0 @@ -from typing import List - -from haco.control import Control - - -class Pulldown(Control): - NAME = 'select' - - def __init__(self, name, options: List[str], icon=None): - self.options = options - super().__init__(name, icon=icon) - - def get_config_ha_ex(self): - data = { - 'options': self.options, - } - - return data 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 new file mode 100644 index 0000000..ba65113 --- /dev/null +++ b/haco/sb3.py @@ -0,0 +1,35 @@ +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.device import Device +from haco.obs import logger +from haco.select import Select +from haco.switch import Switch + +handler = LogfireLoggingHandler(logfire_instance=logger) +logging.basicConfig(handlers=[handler], level=logging.DEBUG) + +async def main(): + climate_a = Climate(name="Dev Climate A", fan_modes=['a', 'b', 'c']) + climate_b = Climate(name="Dev Climate B", fan_modes=['a', 'b', 'c']) + + b1 = Button(name="Dev Button 1") + + s1 = Switch(name="Dev Switch 1") + 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__)) + + await client.start() + + + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/haco/select.py b/haco/select.py new file mode 100644 index 0000000..e6c8235 --- /dev/null +++ b/haco/select.py @@ -0,0 +1,34 @@ +from typing import ClassVar + +from haco.control import Control +from haco.utils import ConvertersString + + +class Select(Control): + """ + + A select control (dropdown) for choosing from a list of options in Home Assistant. + + """ + DATA: ClassVar[dict] = dict( + platform='select' + ) + converters = ConvertersString + + options: list[str] + + def command(self, value: str) -> str: + """ + + Handle option selection commands from Home Assistant. + + """ + raise NotImplementedError() + + def state(self, value: str | None) -> str: + """ + + Return the currently selected option. + + """ + raise NotImplementedError() diff --git a/haco/sensor.py b/haco/sensor.py index 2fd5c33..6b5451d 100644 --- a/haco/sensor.py +++ b/haco/sensor.py @@ -1,37 +1,108 @@ -import schema +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): - NAME = 'sensor' + """ + + 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_schema(cls): - return schema.Schema( - capabilities=[ - schema.Capability( - name='state', - ha=None, - tamota=schema.Tasmota(announce_data=schema.AnnounceTopic(key='{io_ha}_topic')) - ) - ] - ) + def get_capabilities(cls) -> list[Capability]: + """ - def __init__(self, name, data_type=None, uom=None, icon=None, device_class=None): - self.data_type = data_type - self.device_class = device_class - self.uom = uom + Get the capabilities for the sensor (state only). - 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 + """ + return [ + Capability(name=None, command=None) + ] diff --git a/haco/switch.py b/haco/switch.py index 2cb2320..4e15d09 100644 --- a/haco/switch.py +++ b/haco/switch.py @@ -1,14 +1,30 @@ -from haco.control import Control +from typing import ClassVar -from haco.tools import invert_bool +from haco.control import Control class Switch(Control): - NAME = 'switch' + """ - def __init__(self, name, icon=None): - super().__init__(name, icon=icon) + A switch control that can be toggled on or off. - @property - def control_type(self): - return invert_bool + """ + DATA: ClassVar[dict] = dict( + platform='switch' + ) + + def command(self, value: bool) -> bool: + """ + + Handle toggle commands from Home Assistant. + + """ + raise NotImplementedError() + + def state(self, value: bool | None) -> bool: + """ + + Return the current state of the switch. + + """ + raise NotImplementedError() diff --git a/haco/configs/__init__.py b/haco/tests/__init__.py similarity index 100% rename from haco/configs/__init__.py rename to haco/tests/__init__.py 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 8a21b55..237fffd 100644 --- a/haco/text.py +++ b/haco/text.py @@ -1,27 +1,43 @@ -from haco.control import Control +from enum import StrEnum +from typing import ClassVar -from haco.tools import get_range_pair +from haco.control import Control +from haco.utils import ConvertersString + + +class Mode(StrEnum): + TEXT = "text" + PASSWORD = "password" 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 + A text control for text input in Home Assistant. - super().__init__(name, icon=icon) + """ + DATA: ClassVar[dict] = dict( + platform='text' + ) + converters = ConvertersString - def get_config_ha_ex(self): - data = { - 'min': self.min, - 'max': self.max, - 'pattern': self.pattern, - 'mode': self.__class__.__name__.lower() - } + pattern: str | None = None + min: int | None = None + max: int | None = None + mode: Mode = Mode.TEXT - return data + def command(self, value: str) -> str: + """ + Handle text input commands from Home Assistant. -class Password(Text): - ... + """ + raise NotImplementedError() + + def state(self, value: str | None) -> str: + """ + + Return the current text state. + + """ + raise NotImplementedError() diff --git a/haco/topics.py b/haco/topics.py new file mode 100644 index 0000000..72894fb --- /dev/null +++ b/haco/topics.py @@ -0,0 +1,208 @@ +from __future__ import annotations + +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 haco.capabilities import Capability + + +class AnnounceTopic(Base): + """ + + Base class for MQTT topics used for discovery and communication. + + """ + IO: ClassVar[str | None] = None + + KEY_DEFAULTS: ClassVar[dict] = {True: '{capability}_{io}_topic', False: '{io}_topic'} + + 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) + + 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): + """ + + 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)] + + method_name = self.callback_name + method = getattr(self.capability.control, method_name, None) + self.control_method = method + setattr(self.capability.control, method_name, self.handle) + + def fill(self, mask): + return mask.format(**self.fills) + + @property + def fills(self): + return dict( + path=str(self.capability.control.topic), + capability=self.capability.name or 'default', + io=self.IO + ) + + @cached_property + def topic_key(self): + return self.fill(self.key) + + @cached_property + def topic(self): + return self.fill(self.value) + + def get_announce(self) -> dict: + """ + + Get the discovery announcement data for the topic. + + """ + return {self.topic_key: self.topic} + + @property + def callback_name(self): + if not self.capability.name: + return self.IO + + return f'{self.capability.name}_{self.IO}' + + @property + 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). + + """ + return {} + + @cached_property + def capability(self): + return self.parent + + async def handle(self, value): + raise NotImplementedError() + + +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). + + """ + 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}') + return + + is_async = aio.is_async(self.control_method) + try: + + if is_async: + value = await self.control_method(value) + else: + value = self.control_method(value) + + except NotImplementedError: + logger.warning(f'Subclass has not implemented method: {self.callback_class_method_name} {self.topic} {value}') + 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}') + + return value_raw + +class AnnounceTopicCommand(AnnounceTopic): + """ + + MQTT topic for receiving commands from Home Assistant. + + """ + IO: ClassVar[str] = 'command' + + @property + def state(self): + 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) + try: + + if is_async: + value_raw = await self.control_method(value) + else: + value_raw = self.control_method(value) + + except NotImplementedError: + logger.warning(f'Subclass has not implemented method: {self.callback_class_method_name} {self.topic} {value}') + return + + 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. + + """ + return {self.topic: self} diff --git a/haco/uom.py b/haco/uom.py new file mode 100644 index 0000000..dc579ac --- /dev/null +++ b/haco/uom.py @@ -0,0 +1,144 @@ +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 + + """ + POWER_WATT = "W" + POWER_KILO_WATT = "kW" + + VOLT = "V" + + ENERGY_WATT_HOUR = "Wh" + ENERGY_KILO_WATT_HOUR = "kWh" + + ELECTRICAL_CURRENT_AMPERE = "A" + ELECTRICAL_VOLT_AMPERE = "VA" + + DEGREE = "°" + + CURRENCY_EURO = "€" + CURRENCY_DOLLAR = "$" + CURRENCY_CENT = "¢" + + TEMP_CELSIUS = "°C" + TEMP_FAHRENHEIT = "°F" + TEMP_KELVIN = "K" + + TIME_MICROSECONDS = "μs" + TIME_MILLISECONDS = "ms" + TIME_SECONDS = "s" + TIME_MINUTES = "min" + TIME_HOURS = "h" + TIME_DAYS = "d" + TIME_WEEKS = "w" + TIME_MONTHS = "m" + TIME_YEARS = "y" + + LENGTH_MILLIMETERS = "mm" + LENGTH_CENTIMETERS = "cm" + LENGTH_METERS = "m" + LENGTH_KILOMETERS = "km" + + LENGTH_INCHES = "in" + LENGTH_FEET = "ft" + LENGTH_YARD = "yd" + LENGTH_MILES = "mi" + + FREQUENCY_HERTZ = "Hz" + FREQUENCY_GIGAHERTZ = "GHz" + + PRESSURE_PA = "Pa" + PRESSURE_HPA = "hPa" + PRESSURE_BAR = "bar" + PRESSURE_MBAR = "mbar" + PRESSURE_INHG = "inHg" + PRESSURE_PSI = "psi" + + VOLUME_LITERS = "L" + VOLUME_MILLILITERS = "mL" + VOLUME_CUBIC_METERS = "m³" + VOLUME_CUBIC_FEET = "ft³" + + VOLUME_GALLONS = "gal" + VOLUME_FLUID_OUNCE = "fl. oz." + + VOLUME_FLOW_RATE_CUBIC_METERS_PER_HOUR = "m³/h" + VOLUME_FLOW_RATE_CUBIC_FEET_PER_MINUTE = "ft³/m" + + AREA_SQUARE_METERS = "m²" + + MASS_GRAMS = "g" + MASS_KILOGRAMS = "kg" + MASS_MILLIGRAMS = "mg" + MASS_MICROGRAMS = "µg" + + MASS_OUNCES = "oz" + MASS_POUNDS = "lb" + + CONDUCTIVITY = "µS/cm" + + LIGHT_LUX = "lx" + + UV_INDEX = "UV index" + + PERCENTAGE = "%" + + IRRADIATION_WATTS_PER_SQUARE_METER = "W/m²" + + PRECIPITATION_MILLIMETERS_PER_HOUR = "mm/h" + + CONCENTRATION_MICROGRAMS_PER_CUBIC_METER = "µg/m³" + CONCENTRATION_MILLIGRAMS_PER_CUBIC_METER = "mg/m³" + CONCENTRATION_PARTS_PER_CUBIC_METER = "p/m³" + CONCENTRATION_PARTS_PER_MILLION = "ppm" + CONCENTRATION_PARTS_PER_BILLION = "ppb" + + SPEED_MILLIMETERS_PER_DAY = "mm/d" + SPEED_INCHES_PER_DAY = "in/d" + SPEED_METERS_PER_SECOND = "m/s" + SPEED_INCHES_PER_HOUR = "in/h" + SPEED_KILOMETERS_PER_HOUR = "km/h" + SPEED_MILES_PER_HOUR = "mph" + + SIGNAL_STRENGTH_DECIBELS = "dB" + SIGNAL_STRENGTH_DECIBELS_MILLIWATT = "dBm" + + DATA_BITS = "bit" + DATA_KILOBITS = "kbit" + DATA_MEGABITS = "Mbit" + DATA_GIGABITS = "Gbit" + DATA_BYTES = "B" + DATA_KILOBYTES = "kB" + DATA_MEGABYTES = "MB" + DATA_GIGABYTES = "GB" + DATA_TERABYTES = "TB" + DATA_PETABYTES = "PB" + DATA_EXABYTES = "EB" + DATA_ZETTABYTES = "ZB" + DATA_YOTTABYTES = "YB" + DATA_KIBIBYTES = "KiB" + DATA_MEBIBYTES = "MiB" + DATA_GIBIBYTES = "GiB" + DATA_TEBIBYTES = "TiB" + DATA_PEBIBYTES = "PiB" + DATA_EXBIBYTES = "EiB" + DATA_ZEBIBYTES = "ZiB" + DATA_YOBIBYTES = "YiB" + + DATA_RATE_BITS_PER_SECOND = "bit/s" + DATA_RATE_KILOBITS_PER_SECOND = "kbit/s" + DATA_RATE_MEGABITS_PER_SECOND = "Mbit/s" + DATA_RATE_GIGABITS_PER_SECOND = "Gbit/s" + DATA_RATE_BYTES_PER_SECOND = "B/s" + DATA_RATE_KILOBYTES_PER_SECOND = "kB/s" + DATA_RATE_MEGABYTES_PER_SECOND = "MB/s" + DATA_RATE_GIGABYTES_PER_SECOND = "GB/s" + DATA_RATE_KIBIBYTES_PER_SECOND = "KiB/s" + DATA_RATE_MEBIBYTES_PER_SECOND = "MiB/s" + DATA_RATE_GIBIBYTES_PER_SECOND = "GiB/s" diff --git a/haco/utils.py b/haco/utils.py new file mode 100644 index 0000000..67dc687 --- /dev/null +++ b/haco/utils.py @@ -0,0 +1,88 @@ +import string +from typing import Callable + +from corio import jsn +from corio.datatype import to_bool + +CHARS_ALLOWED = string.ascii_lowercase + string.digits +SEPS = '_- /' +BRANCH = 'release' + +CAPABILITY_DEFAULT = 'default' +RECONNECT_DELAY_SEC = 5 +ON = 'ON' +OFF = 'OFF' + +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. + + """ + chars = [] + + for c in s.lower(): + if c in SEPS: + chars.append(sep) + elif c in CHARS_ALLOWED: + chars.append(c) + + sanitized = ''.join(chars) + + if not sanitized: + raise ValueError("Sanitized string is empty") + + return sanitized + + +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): + """ + + 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() diff --git a/Dockerfile b/haco/v0/Dockerfile similarity index 88% rename from Dockerfile rename to haco/v0/Dockerfile index ad53ec5..37602f6 100644 --- a/Dockerfile +++ b/haco/v0/Dockerfile @@ -1,7 +1,7 @@ ARG VERSION ARG TYPE=development -FROM edwardbrown/python as base +FROM fmtr/python as base ENV DEBIAN_FRONTEND=noninteractive RUN apt -qq update -y @@ -16,6 +16,6 @@ RUN if [ -z "$VERSION" ] ; then pip3 install haco ; else pip3 install haco==${VE FROM ${TYPE} as image -CMD haco +CMD haco-daemon diff --git a/haco/v0/assets/air_fryer_cookbook.png b/haco/v0/assets/air_fryer_cookbook.png new file mode 100644 index 0000000..fb2bfbe Binary files /dev/null and b/haco/v0/assets/air_fryer_cookbook.png differ diff --git a/haco/v0/assets/greeter_select.png b/haco/v0/assets/greeter_select.png new file mode 100644 index 0000000..ff3546f Binary files /dev/null and b/haco/v0/assets/greeter_select.png differ diff --git a/haco/v0/assets/memory_sensor.png b/haco/v0/assets/memory_sensor.png new file mode 100644 index 0000000..6297a7e Binary files /dev/null and b/haco/v0/assets/memory_sensor.png differ diff --git a/haco/v0/assets/restart_button.png b/haco/v0/assets/restart_button.png new file mode 100644 index 0000000..0a447fd Binary files /dev/null and b/haco/v0/assets/restart_button.png differ diff --git a/haco/v0/assets/weblog_select.png b/haco/v0/assets/weblog_select.png new file mode 100644 index 0000000..a407421 Binary files /dev/null and b/haco/v0/assets/weblog_select.png differ diff --git a/berry/haco.be b/haco/v0/berry/haco.be similarity index 84% rename from berry/haco.be rename to haco/v0/berry/haco.be index 2c2b793..21951b1 100644 --- a/berry/haco.be +++ b/haco/v0/berry/haco.be @@ -2,8 +2,17 @@ import tools, string, json, mqtt var mod = module("haco") -var logger=tools.logger.logger +import haco_version +var IS_DEVELOPMENT=haco_version.CHANNEL_ID=='development' + +var logger=tools.logging.Logger( + 'haco', + IS_DEVELOPMENT?tools.logging.Logger.DEBUG_MORE:tools.logging.Logger.INFO, + IS_DEVELOPMENT +) + +tools.logger.logger=logger var CALLBACK_MAP={} var BRANCH='release' @@ -38,16 +47,18 @@ class ConfigDownloader if self.id_downloading && self.id_downloading==id - logger.error(string.format("Got duplicate new config (same as currently being download) ID: %s. Will be ignored.",id)) + logger.debug(string.format("Got duplicate new config (same as currently being downloaded) ID: %s. Will be ignored.",id)) return end - logger.debug(string.format("Received new config. ID: %s. Parts: %s",id,num_parts)) + if self.id_downloading logger.error(string.format("Got new config ID: %s while existing download ID: %s incomplete.",id,self.id_downloading)) end + logger.info(string.format("Downloading new config. ID: %s. Parts: %s",id,num_parts)) + self.id_downloading=id logger.debug(['Cancelling any existing downloads...']) @@ -162,7 +173,7 @@ class Daemon def init() - logger.info(['Starting haco daemon...']) + logger.info(string.format('Starting haco daemon (v%s) in %s seconds...',haco_version.VERSION, self.DELAY_SUBSCRIBE)) self.registry_daemon=tools.callbacks.Registry() self.registry_config=tools.callbacks.Registry() @@ -176,7 +187,7 @@ class Daemon def subscribe_daemon() - var rule_announce=tools.callbacks.Rule('mqtt#connected',/->print('announced called by mqtt#connected',self.publish_announce())) + var rule_announce=tools.callbacks.Rule('mqtt#connected',/->self.publish_announce()) self.registry_daemon.add(rule_announce) var rule_config=tools.callbacks.MqttSubscription( @@ -187,6 +198,8 @@ class Daemon if mqtt.connected() self.publish_announce() end + logger.info(string.format('The haco daemon has started. Hostname: %s, MAC: %s. Listening for configuration...', tasmota.hostname(), tools.network.get_mac())) + end def handle_config_message(data) @@ -209,12 +222,16 @@ class Daemon def get_data_announce() return { + 'version': haco_version.VERSION, 'hostname': tasmota.hostname(), 'eth': tasmota.eth(), 'wifi': tasmota.wifi(), + 'mac': tools.network.get_mac(), 'timestamp': tasmota.rtc(), 'config_id': self.config_id, 'topic': tools.mqtt.get_topic(), + 'prefix': tasmota.cmd('Prefix'), + 'fulltopic': tasmota.cmd('FullTopic')['FullTopic'], 'device_name': tools.platform.get_device_name(), } end @@ -248,7 +265,7 @@ class Daemon if self.config_id==nil var rule_control=tools.callbacks.MqttSubscription( self.TOPIC_CONTROL, - /value,data->self.handle_control_message(value,data) + /value,data->tasmota.set_timer(0,/->self.handle_control_message(value,data)) ) self.registry_daemon.add(rule_control) end @@ -256,7 +273,7 @@ class Daemon self.config_id=id self.publish_announce() - logger.info(string.format('New config ID %s applied.',id)) + logger.info(string.format('New config ID %s applied successfully.',id)) end @@ -289,6 +306,7 @@ class Daemon var callback_type=CALLBACK_MAP[data.find('type', classname(tools.callbacks.Rule))] var topic=data['topic'] var trigger=data['trigger'] + var id=data['id'] var function @@ -297,11 +315,14 @@ class Daemon function=tools.compile.evaluate(data['function']) else logger.error(string.format('Using default function for %s',trigger)) - function=/value data->{'value':value,'data':data} + function=/value,data->{'value':value,'data':data} end - - return callback_type(trigger,/value data->self.publish_output(function,value,data,topic)) + return callback_type( + trigger, + /value,data->tasmota.set_timer(0,/->self.publish_output(function,value,data,topic)), + id + ) end @@ -313,8 +334,7 @@ class Daemon end - -mod.daemon=Daemon() - +mod.Daemon=Daemon +mod.daemon=nil return mod \ No newline at end of file diff --git a/haco/v0/berry/haco_autoexec.be b/haco/v0/berry/haco_autoexec.be new file mode 100644 index 0000000..4d0f0ad --- /dev/null +++ b/haco/v0/berry/haco_autoexec.be @@ -0,0 +1,14 @@ +def autoexec(metadata) + + import haco + global.haco=haco + + haco.daemon=haco.Daemon() + + #haco.daemon.registry_daemon.remove_all() + +end + +var mod = module("haco_autoexec") +mod.autoexec=autoexec +return mod \ No newline at end of file diff --git a/haco/v0/berry/haco_version.be b/haco/v0/berry/haco_version.be new file mode 100644 index 0000000..1701bfd --- /dev/null +++ b/haco/v0/berry/haco_version.be @@ -0,0 +1,8 @@ +var VERSION='0.0.25' + +var mod = module("haco_version") +mod.VERSION=VERSION +mod.METADATA=(global.TAPP_METADATA!=nil?global.TAPP_METADATA:{}).find('haco',{}) +mod.CHANNEL_ID=mod.METADATA.find('channel_id') + +return mod \ No newline at end of file diff --git a/berry/manifest.yaml b/haco/v0/berry/manifest.yaml similarity index 79% rename from berry/manifest.yaml rename to haco/v0/berry/manifest.yaml index 3187968..ead57de 100644 --- a/berry/manifest.yaml +++ b/haco/v0/berry/manifest.yaml @@ -26,3 +26,7 @@ patches: path: haco_version.be pattern: \bvar\s+VERSION\s*=\s*'{version}' +code_mask: | + import tools + downloader=tools.web.Downloader('{url}',nil,/->print(tasmota.cmd('restart 1'))) + diff --git a/haco/v0/configs/__init__.py b/haco/v0/configs/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/haco/v0/configs/demo.py b/haco/v0/configs/demo.py new file mode 100644 index 0000000..74b85a0 --- /dev/null +++ b/haco/v0/configs/demo.py @@ -0,0 +1,45 @@ +from haco import Button, Tasmota + +restart = Button('Restart Tasmota', icon='restart') + + +@restart.callback() +def ha(value) -> Tasmota[str, 'tasmota.cmd("restart 1")']: + return value + + +from haco import Sensor + +memory = Sensor('Memory Free', icon='memory', uom=Sensor.UOM.DATA_KILOBYTES, uom_type=Sensor.UOM_TYPE.DATA_SIZE) + + +@memory.callback(trigger='Tele#Heap') +def tasmota(value: int): + return value + + +from haco import Button, Tasmota + +restart = Button('Restart Tasmota', icon='restart') + + +@restart.callback() +def ha(value) -> Tasmota[str, 'tasmota.cmd("restart 1")']: + return value + + +from haco import Select, Tasmota + +LOG_LEVELS = ["None", "Error", "Info", "Debug", "Debug More"] + +weblog = Select('WebLog Level', icon='console', options=LOG_LEVELS) + + +@weblog.callback() +def ha(value) -> Tasmota[str, 'tasmota.cmd("WebLog "+value)']: + return LOG_LEVELS.index(value) + + +@weblog.callback(trigger='WebLog') +def tasmota(value: int): + return LOG_LEVELS[value] diff --git a/haco/configs/development.py b/haco/v0/configs/development.py similarity index 87% rename from haco/configs/development.py rename to haco/v0/configs/development.py index 39468c6..2293e3f 100644 --- a/haco/configs/development.py +++ b/haco/v0/configs/development.py @@ -1,11 +1,5 @@ -from haco.climate import Climate -from haco.debugging import get_memory_sensor -from haco.device import Device -from haco.number import Number -from haco.pulldown import Pulldown -from haco.sensor import Sensor -from haco.tasmota import Tasmota -from haco.text import Text, Password +from haco import Number, Tasmota, Select, Sensor, Text, Password, Climate + number = Number( 'Dev Number Test Control', @@ -125,7 +119,7 @@ def temperature_low_tasmota(value: int): return value -pulldown = Pulldown( +pulldown = Select( 'Dev Select Test Control', options=list('ABC') ) @@ -152,9 +146,6 @@ def tasmota(value: str): text = Text('Dev Text Test Control') password = Password('Dev Password Test Control') -from haco.configs.development import text, password -from haco.tasmota import Tasmota - @text.callback() def ha(value: str) -> Tasmota[str, 'tasmota.cmd("var11 "+str(value))']: @@ -176,7 +167,6 @@ def tasmota(value: str): return value -dev_dehum = Device( - mac='8C:4B:14:85:8D:98', - controls=[number, climate, text, password, sensor, pulldown, get_memory_sensor()] -) +from haco.debugging import get_tasmota_updater + +update = get_tasmota_updater() diff --git a/haco/configs/air_fryer.py b/haco/v0/configs/proscenic_t21.py similarity index 68% rename from haco/configs/air_fryer.py rename to haco/v0/configs/proscenic_t21.py index 087d615..ba192bf 100644 --- a/haco/configs/air_fryer.py +++ b/haco/v0/configs/proscenic_t21.py @@ -1,14 +1,12 @@ import math - -from haco import tuya -from haco.pulldown import Pulldown -from haco.sensor import Sensor -from haco.tasmota import Tasmota +from haco.debugging import get_tasmota_updater from haco.tools import add_tuya_io +from haco import Tasmota, Number, Sensor, Select, Switch, tuya + OPTIONS = ['Default', 'Fries', 'Shrimp', 'Pizza', 'Chicken', 'Fish', 'Steak', 'Cake', 'Bacon', 'Preheat', 'Custom'] -cookbook = Pulldown('Cookbook', options=OPTIONS, icon='mdi:chef-hat') +cookbook = Select('Cookbook', options=OPTIONS, icon='chef-hat') @cookbook.callback() @@ -23,9 +21,10 @@ def tasmota(value: int): time_remaining = Sensor( name='Time Remaining', - uom='minutes', - icon='mdi:timer', - device_class='DURATION' + uom=Sensor.UOM.TIME_MINUTES, + uom_type=Sensor.UOM_TYPE.DURATION, + icon='timer', + ) @@ -34,16 +33,12 @@ def tasmota(value: int): return value -from haco.switch import Switch - -from haco.number import Number -from haco import tuya - cooking_time = Number( name='Cooking Time', number_range=range(1, 60), - uom='minutes', - icon='mdi:timer' + uom=Number.UOM.TIME_MINUTES, + mode='box', + icon='timer' ) @@ -56,31 +51,12 @@ def tasmota(value: int): def ha(value: int) -> Tasmota[int, tuya.send(2, 7)]: return value - -cooking_temp = Number( - name='Cooking Temperature (F)', - number_range=range(1, 60), - uom='minutes', - icon='mdi:timer' -) - - -@cooking_temp.callback(trigger=tuya.received(2, 7)) -def tasmota(value: int): - return value - - -@cooking_temp.callback() -def ha(value: int) -> Tasmota[int, tuya.send(2, 7)]: - return value - - cooking_temp_f = Number( 'Cooking Temperature (F)', number_range=range(170, 399), mode='slider', - uom='°F', - icon='mdi:temperature-fahrenheit' + uom=Number.UOM.TEMP_FAHRENHEIT, + icon='temperature-fahrenheit' ) @@ -98,8 +74,8 @@ cooking_temp_c = Number( 'Cooking Temperature (C)', number_range=range(77, 204), mode='slider', - uom='°C', - icon='mdi:temperature-celsius' + uom=Number.UOM.TEMP_CELSIUS, + icon='temperature-celsius' ) @@ -115,14 +91,14 @@ def tasmota(value: float): cook_pause = Switch( name='Cook/Pause', - icon='mdi:play-pause' + icon='play-pause' ) add_tuya_io(cook_pause, int, 1, 2) power = Switch( name='Power', - icon='mdi:power' + icon='power' ) add_tuya_io(power, int, 1, 1) @@ -130,31 +106,34 @@ add_tuya_io(power, int, 1, 1) delay_time = Number( name='Delay Time', number_range=range(0, 720), - uom='minutes', - icon='mdi:timer-pause' + uom=Sensor.UOM.TIME_MINUTES, + mode='box', + icon='timer-pause' ) add_tuya_io(delay_time, int, 2, 6) status = Sensor( name='Status', - icon='mdi:playlist-play', - device_class='ENUM' + icon='playlist-play', + uom_type=Sensor.UOM_TYPE.ENUM ) -keep_warm_time = Number( - name='Keep Warm Time', - number_range=range(0, 120), - uom='minutes', - icon='mdi:timer-sync' -) - -add_tuya_io(keep_warm_time, int, 2, 105) - @status.callback(trigger=tuya.received(4, 5)) def tasmota(value: int): return ['Ready', 'Delayed Cook', 'Cooking', 'Keep Warm', 'Off', 'Cooking Complete'][value] +keep_warm_time = Number( + name='Keep Warm Time', + number_range=range(0, 120), + uom=Sensor.UOM.TIME_MINUTES, + icon='timer-sync', + mode='box', +) + +add_tuya_io(keep_warm_time, int, 2, 105) + +update = get_tasmota_updater() DEVICE_CONFIG = {'run_config_post': f'def () return tasmota.cmd("TuyaSend0") end'} diff --git a/haco/v0/configs/test.py b/haco/v0/configs/test.py new file mode 100644 index 0000000..a1eccc7 --- /dev/null +++ b/haco/v0/configs/test.py @@ -0,0 +1,25 @@ +from haco import Select, Tasmota + +greeter = Select('Greeter', icon='hand-wave', options=['Hi', 'Hello Word', 'Bienvenue']) + +set_greeting = """ +def (value,data) + + import string + var cmd=string.format('var16 %s',value) + tasmota.cmd(cmd) + + print(string.format('haco says: %s!',value)) + +end +""" + + +@greeter.callback() +def ha(value) -> Tasmota[str, set_greeting]: + return value + + +@greeter.callback(trigger='WebLog') +def tasmota(value: int): + return value diff --git a/haco/v0/data/__init__.py b/haco/v0/data/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/haco/v0/data/type_binary_sensor.py b/haco/v0/data/type_binary_sensor.py new file mode 100644 index 0000000..dc4b1b0 --- /dev/null +++ b/haco/v0/data/type_binary_sensor.py @@ -0,0 +1,36 @@ +class DeviceClassBinarySensor: + """ + + Sourced from: + https://www.home-assistant.io/integrations/binary_sensor/#device-class + + """ + NONE: type(None) = None # Generic on/off. This is the default and doesn’t need to be set. + BATTERY: str = "battery" # on means low, off means normal + BATTERY_CHARGING: str = "battery_charging" # on means charging, off means not charging + CARBON_MONOXIDE: str = "carbon_monoxide" # on means carbon monoxide detected, off no carbon monoxide (clear) + COLD: str = "cold" # on means cold, off means normal + CONNECTIVITY: str = "connectivity" # on means connected, off means disconnected + DOOR: str = "door" # on means open, off means closed + GARAGE_DOOR: str = "garage_door" # on means open, off means closed + GAS: str = "gas" # on means gas detected, off means no gas (clear) + HEAT: str = "heat" # on means hot, off means normal + LIGHT: str = "light" # on means light detected, off means no light + LOCK: str = "lock" # on means open (unlocked), off means closed (locked) + MOISTURE: str = "moisture" # on means moisture detected (wet), off means no moisture (dry) + MOTION: str = "motion" # on means motion detected, off means no motion (clear) + MOVING: str = "moving" # on means moving, off means not moving (stopped) + OCCUPANCY: str = "occupancy" # on means occupied (detected), off means not occupied (clear) + OPENING: str = "opening" # on means open, off means closed + PLUG: str = "plug" # on means device is plugged in, off means device is unplugged + POWER: str = "power" # on means power detected, off means no power + PRESENCE: str = "presence" # on means home, off means away + PROBLEM: str = "problem" # on means problem detected, off means no problem (OK) + RUNNING: str = "running" # on means running, off means not running + SAFETY: str = "safety" # on means unsafe, off means safe + SMOKE: str = "smoke" # on means smoke detected, off means no smoke (clear) + SOUND: str = "sound" # on means sound detected, off means no sound (clear) + TAMPER: str = "tamper" # on means tampering detected, off means no tampering (clear) + UPDATE: str = "update" # on means update available, off means up-to-date + VIBRATION: str = "vibration" # on means vibration detected, off means no vibration (clear) + WINDOW: str = "window" # on means open, off means closed diff --git a/haco/v0/data/type_sensor.py b/haco/v0/data/type_sensor.py new file mode 100644 index 0000000..3ba873e --- /dev/null +++ b/haco/v0/data/type_sensor.py @@ -0,0 +1,58 @@ +class DeviceClassSensor: + """ + + Sourced from: + https://www.home-assistant.io/integrations/sensor/#device-class + + """ + NONE: type(None) = None # Generic sensor. This is the default and doesn’t need to be set. + APPARENT_POWER: str = "apparent_power" # Apparent power in VA. + AQI: str = "aqi" # Air Quality Index (unitless). + ATMOSPHERIC_PRESSURE: str = "atmospheric_pressure" # Atmospheric pressure in cbar, bar, hPa, inHg, kPa, mbar, Pa, or psi. + BATTERY: str = "battery" # Percentage of battery that is left in %. + CARBON_DIOXIDE: str = "carbon_dioxide" # Carbon Dioxide in CO2 (Smoke) in ppm. + CARBON_MONOXIDE: str = "carbon_monoxide" # Carbon Monoxide in CO (Gas CNG/LPG) in ppm. + CURRENT: str = "current" # Current in A or mA. + DATA_RATE: str = "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: str = "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: str = "date" # Date string (ISO 8601). + DISTANCE: str = "distance" # Generic distance in km, m, cm, mm, mi, yd, or in. + DURATION: str = "duration" # Duration in d, h, min, or s. + ENERGY: str = "energy" # Energy in Wh, kWh, MWh, MJ, or GJ. + ENERGY_STORAGE: str = "energy_storage" # Stored energy in Wh, kWh, MWh, MJ, or GJ. + ENUM: str = "enum" # Has a limited set of (non-numeric) states. + FREQUENCY: str = "frequency" # Frequency in Hz, kHz, MHz, or GHz. + GAS: str = "gas" # Gas volume in m³, ft³, or CCF. + HUMIDITY: str = "humidity" # Percentage of humidity in the air in %. + ILLUMINANCE: str = "illuminance" # The current light level in lx. + IRRADIANCE: str = "irradiance" # Irradiance in W/m² or BTU/(h⋅ft²). + MOISTURE: str = "moisture" # Percentage of water in a substance in %. + MONETARY: str = "monetary" # The monetary value (ISO 4217). + NITROGEN_DIOXIDE: str = "nitrogen_dioxide" # Concentration of Nitrogen Dioxide in µg/m³. + NITROGEN_MONOXIDE: str = "nitrogen_monoxide" # Concentration of Nitrogen Monoxide in µg/m³. + NITROUS_OXIDE: str = "nitrous_oxide" # Concentration of Nitrous Oxide in µg/m³. + OZONE: str = "ozone" # Concentration of Ozone in µg/m³. + PH: str = "ph" # Potential hydrogen (pH) value of a water solution. + PM1: str = "pm1" # Concentration of particulate matter less than 1 micrometer in µg/m³. + PM25: str = "pm25" # Concentration of particulate matter less than 2.5 micrometers in µg/m³. + PM10: str = "pm10" # Concentration of particulate matter less than 10 micrometers in µg/m³. + POWER_FACTOR: str = "power_factor" # Power factor (unitless), unit may be None or %. + POWER: str = "power" # Power in W or kW. + PRECIPITATION: str = "precipitation" # Accumulated precipitation in cm, in, or mm. + PRECIPITATION_INTENSITY: str = "precipitation_intensity" # Precipitation intensity in in/d, in/h, mm/d, or mm/h. + PRESSURE: str = "pressure" # Pressure in Pa, kPa, hPa, bar, cbar, mbar, mmHg, inHg, or psi. + REACTIVE_POWER: str = "reactive_power" # Reactive power in var. + SIGNAL_STRENGTH: str = "signal_strength" # Signal strength in dB or dBm. + SOUND_PRESSURE: str = "sound_pressure" # Sound pressure in dB or dBA. + SPEED: str = "speed" # Generic speed in ft/s, in/d, in/h, km/h, kn, m/s, mph, or mm/d. + SULPHUR_DIOXIDE: str = "sulphur_dioxide" # Concentration of sulphur dioxide in µg/m³. + TEMPERATURE: str = "temperature" # Temperature in °C, °F, or K. + TIMESTAMP: str = "timestamp" # Datetime object or timestamp string (ISO 8601). + VOLATILE_ORGANIC_COMPOUNDS: str = "volatile_organic_compounds" # Concentration of volatile organic compounds in µg/m³. + VOLATILE_ORGANIC_COMPOUNDS_PARTS: str = "volatile_organic_compounds_parts" # Ratio of volatile organic compounds in ppm or ppb. + VOLTAGE: str = "voltage" # Voltage in V or mV. + VOLUME: str = "volume" # Generic volume in L, mL, gal, fl. oz., m³, ft³, or CCF. + VOLUME_STORAGE: str = "volume_storage" # Generic stored volume in L, mL, gal, fl. oz., m³, ft³, or CCF. + WATER: str = "water" # Water consumption in L, gal, m³, ft³, or CCF. + WEIGHT: str = "weight" # Generic mass in kg, g, mg, µg, oz, lb, or st. + WIND_SPEED: str = "wind_speed" # Wind speed in ft/s, km/h, kn, m/s, or mph. diff --git a/haco/v0/docker-compose.yml b/haco/v0/docker-compose.yml new file mode 100755 index 0000000..45e6945 --- /dev/null +++ b/haco/v0/docker-compose.yml @@ -0,0 +1,13 @@ +version: '3.4' +services: + haco-dev: + build: + context: . + dockerfile: Dockerfile + target: development + image: haco:dev + container_name: haco + env_file: + - ${ENV_PATH} + volumes: + - /fm/haco/artifacts:/haco \ No newline at end of file diff --git a/ha/addon/CHANGELOG.md b/haco/v0/ha/addon/CHANGELOG.md similarity index 62% rename from ha/addon/CHANGELOG.md rename to haco/v0/ha/addon/CHANGELOG.md index 5bf094e..47f41bd 100644 --- a/ha/addon/CHANGELOG.md +++ b/haco/v0/ha/addon/CHANGELOG.md @@ -1 +1 @@ -For the latest changes, see **[the project releases page](https://link.frontmatter.ai/haco/changes)**. \ No newline at end of file +For the latest changes, see **[the project releases page](https://fmtr.link/haco/changes)**. \ No newline at end of file diff --git a/haco/v0/ha/addon/DOCS.md b/haco/v0/ha/addon/DOCS.md new file mode 100644 index 0000000..bfffc09 --- /dev/null +++ b/haco/v0/ha/addon/DOCS.md @@ -0,0 +1 @@ +For general documentation, see **[the project wiki](https://fmtr.link/haco/doc)**. \ No newline at end of file diff --git a/haco/v0/ha/addon/Dockerfile b/haco/v0/ha/addon/Dockerfile new file mode 100644 index 0000000..61e4d62 --- /dev/null +++ b/haco/v0/ha/addon/Dockerfile @@ -0,0 +1,11 @@ +ARG BUILD_FROM +FROM $BUILD_FROM + +ARG BUILD_VERSION +RUN apk add --no-cache py3-pip +RUN pip install haco==${BUILD_VERSION} --break-system-packages + +COPY run.sh / +RUN chmod a+x /run.sh + +CMD [ "/run.sh" ] \ No newline at end of file diff --git a/haco/v0/ha/addon/README.md b/haco/v0/ha/addon/README.md new file mode 120000 index 0000000..fe84005 --- /dev/null +++ b/haco/v0/ha/addon/README.md @@ -0,0 +1 @@ +../../README.md \ No newline at end of file diff --git a/haco/v0/ha/addon/config.yaml b/haco/v0/ha/addon/config.yaml new file mode 100644 index 0000000..0083fa5 --- /dev/null +++ b/haco/v0/ha/addon/config.yaml @@ -0,0 +1,25 @@ +arch: + - aarch64 + - amd64 + - armhf + - armv7 + - i386 +description: Home Assistant Control Objects +init: false +map: + - config:rw +name: haco +options: + assignments: + - config: null + identifier: null +panel_icon: mdi:network-pos +schema: + assignments: + - config: str + identifier: str +services: + - mqtt:need +slug: haco +url: https://fmtr.link/haco +version: 0.0.25 diff --git a/haco/v0/ha/addon/icon.png b/haco/v0/ha/addon/icon.png new file mode 100644 index 0000000..083550a Binary files /dev/null and b/haco/v0/ha/addon/icon.png differ diff --git a/haco/v0/ha/addon/logo.png b/haco/v0/ha/addon/logo.png new file mode 100644 index 0000000..f1cd97e Binary files /dev/null and b/haco/v0/ha/addon/logo.png differ diff --git a/ha/addon/run.sh b/haco/v0/ha/addon/run.sh similarity index 84% rename from ha/addon/run.sh rename to haco/v0/ha/addon/run.sh index 5a084cf..4419205 100644 --- a/ha/addon/run.sh +++ b/haco/v0/ha/addon/run.sh @@ -2,6 +2,7 @@ export HACO_IS_ADDON=true export HACO_CONFIGS_PATH="/config/haco" +export HACO_OPTIONS_PATH="/data/options.json" export MQTT_HOST="$(bashio::services mqtt 'host')" export MQTT_PASSWORD="$(bashio::services mqtt 'password')" export MQTT_PORT="$(bashio::services mqtt 'port')" diff --git a/haco/v0/haco/__init__.py b/haco/v0/haco/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/haco/berry.py b/haco/v0/haco/berry.py similarity index 100% rename from haco/berry.py rename to haco/v0/haco/berry.py diff --git a/haco/v0/haco/button.py b/haco/v0/haco/button.py new file mode 100644 index 0000000..b7b7216 --- /dev/null +++ b/haco/v0/haco/button.py @@ -0,0 +1,22 @@ +import haco.capabilities +import haco.topics +from haco import schema +from haco.control import Control + + +class Button(Control): + NAME = 'button' + + @classmethod + def get_schema(cls): + return schema.Schema( + capabilities=[ + haco.capabilities.Capability( + ha=schema.HomeAssistant(announce_data=haco.topics.AnnounceTopic(key='{io_ha}_topic')), + tasmota=None + ) + ] + ) + + def __init__(self, name, icon=None): + super().__init__(name, icon=icon) diff --git a/haco/callback.py b/haco/v0/haco/callback.py similarity index 86% rename from haco/callback.py rename to haco/v0/haco/callback.py index b149f16..6728c83 100644 --- a/haco/callback.py +++ b/haco/v0/haco/callback.py @@ -1,12 +1,12 @@ -from collections import namedtuple - import inspect import typing +from collections import namedtuple from typing import _AnnotatedAlias -from haco import berry from haco.trigger import Trigger, Rule +from haco import berry, schema + Signature = namedtuple('Signature', ['type', 'expression']) @@ -66,7 +66,7 @@ class Callback: known_args = {'value', 'data'} skip_args = {'control'} - if self.platform == 'tasmota': + if self.platform == schema.Tasmota.PLATFORM: berry_exp = {} for name, (type, exp) in arg_data.items(): @@ -76,7 +76,7 @@ class Callback: continue if name not in known_args: - msg = f'Callback {self.function_name} argument {name} requires a Berry expression annotation.' + msg = f'Callback "{self.function_name}" argument "{name}" requires a Berry expression annotation.' raise ValueError(msg) exp = name @@ -104,6 +104,12 @@ class Callback: self.function_tasmota - if self.platform == 'tasmota': + if self.platform == schema.Tasmota.PLATFORM: if not self.trigger: - raise ValueError(f'Callback {self.function_name} must have a trigger.') + raise ValueError(f'Callback "{self.function_name}" must have a trigger.') + + +class Response: + def __init__(self, value=None, send=True): + self.value = value + self.send = send diff --git a/haco/v0/haco/climate.py b/haco/v0/haco/climate.py new file mode 100644 index 0000000..da441eb --- /dev/null +++ b/haco/v0/haco/climate.py @@ -0,0 +1,112 @@ +from haco.control import Control +from haco.schema import Schema, Capability, AnnounceTopic, Tasmota +from haco.tools import get_range_pair + +CELSIUS_C = 'C' +FAHRENHEIT_F = 'F' + + +class Climate(Control): + NAME = 'climate' + + @classmethod + def get_schema(cls): + schema = Schema( + capabilities=[ + Capability( + name='mode', + type=str + ), + Capability( + name='target_humidity' + ), + Capability( + name='temperature', + alias='target_temperature' # only used for callbacks, i guess to unify/simplify them for the user. + ), + Capability( + name='temperature_high' + ), + Capability( + name='temperature_low' + ), + Capability( + name='swing_mode', + type=str + ), + Capability( + name='preset_mode', + type=str + ), + Capability( + name='current_humidity', + ha=None, + tasmota=Tasmota(announce_data=AnnounceTopic(key='{capability}_topic')) + ), + Capability( + name='current_temperature', + ha=None, + tasmota=Tasmota(announce_data=AnnounceTopic(key='{capability}_topic')) + ), + Capability( + name='action', + type=str, + ha=None, + tasmota=Tasmota(announce_data=AnnounceTopic(key='{capability}_topic')) + ) + ] + ) + return schema + + # def init(name, entity_id, icon, temperature_unit, temperature_range, humidity_range, modes, preset_modes, fan_modes, swing_modes, precision, callbacks) + + def __init__(self, name=None, icon=None, temperature_unit=None, temperature_range=None, humidity_range=None, + modes=None, preset_modes=None, fan_modes=None, swing_modes=None, precision=None): + self.temperature_unit = temperature_unit + + self.temperature_min, self.temperature_max = get_range_pair(temperature_range) + self.humidity_min, self.humidity_max = get_range_pair(humidity_range) + + self.precision = precision + # self.type = float if self.precision is None else int if self.precision == 1 else float if self.temperature_unit == 'C' else int + + self.fan_modes = fan_modes + self.modes = modes + self.preset_modes = preset_modes + self.swing_modes = swing_modes + + super().__init__(name, icon=icon) + + @property + def control_type(self): + + if self.precision == 1: + return int + + if self.precision: + return float + + unit = self.temperature_unit or CELSIUS_C + + if unit == CELSIUS_C: + return float + else: + return int + + def get_config_ha_ex(self): + data = { + + 'fan_modes': self.fan_modes, + 'preset_modes': self.preset_modes, + 'swing_modes': self.swing_modes, + 'modes': self.modes, + 'min_temp': self.temperature_min, + 'max_temp': self.temperature_max, + 'min_humidity': self.humidity_min, + 'max_humidity': self.humidity_max, + 'precision': self.precision, + 'temperature_unit': self.temperature_unit + + } + + return data diff --git a/haco/v0/haco/constants.py b/haco/v0/haco/constants.py new file mode 100644 index 0000000..3d659b2 --- /dev/null +++ b/haco/v0/haco/constants.py @@ -0,0 +1,24 @@ +import os +import string +from pathlib import Path + +CHARS_ALLOWED = string.ascii_lowercase + string.digits +SEPS = '_- /' +BRANCH = 'release' + +CAPABILITY_DEFAULT = 'default' +RECONNECT_DELAY_SEC = 5 +ON = 'ON' +OFF = 'OFF' + +CONFIGS_PATH = Path(os.environ.get('HACO_CONFIGS_PATH','/haco/config')) +OPTIONS_PATH = Path(os.environ.get('HACO_OPTIONS_PATH','/haco/data/options.json')) +MQTT_HOST = os.environ.get('MQTT_HOST','localhost') +MQTT_PORT = int(os.environ.get('MQTT_PORT',1883)) +MQTT_USERNAME = os.environ.get('MQTT_USERNAME') +MQTT_PASSWORD = os.environ.get('MQTT_PASSWORD',None) + +if (CONFIGS_PATH / '.debug').exists(): + LOG_LEVEL = 'DEBUG' +else: + LOG_LEVEL = os.environ.get('HACO_LOG_LEVEL', 'INFO') diff --git a/haco/v0/haco/control.py b/haco/v0/haco/control.py new file mode 100644 index 0000000..af6cfbe --- /dev/null +++ b/haco/v0/haco/control.py @@ -0,0 +1,116 @@ +import logging +from functools import partial + +from haco.callback import Callback +from haco.schema import Schema, Platform, Tasmota, HomeAssistant, AnnounceTopic, Capability +from haco.tools import log_publish + +import haco.constants +import haco.utils +from haco import tools, constants + + +class Control: + NAME = None + + control_type = str + + @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')) + ) + ] + ) + return schema + + def __init__(self, name, icon=None): + + from haco.device import Device + + self.name = name + + self.device: Device = None + self.schema = self.get_schema() + self.get = self.schema.get + self.schema.control = self + + self.icon = f'mdi:{icon}' if icon else icon + self.icon + + @property + def name_sanitized(self): + return haco.utils.sanitize_name(self.name) + + def callback(self, trigger=None): + return partial(self.add_callback, trigger) + + def add_callback(self, trigger, function): + + if (function_name := function.__name__) in {Tasmota.PLATFORM, HomeAssistant.PLATFORM}: + function_name = f'{constants.CAPABILITY_DEFAULT}_{function_name}' + + callback_names = self.schema.get_callback_function_names() + + if function_name not in callback_names: + msg = f'Callback function name "{function_name}" is not valid for control "{self.__class__.__name__}". Must be one of: {sorted(callback_names)}' + raise ValueError(msg) + + capability_id, platform_id = function_name.rsplit('_', 1) + callback = Callback(capability=capability_id, platform=platform_id, trigger=trigger, function=function) + platform: Platform = self.schema.get_alias(capability_id).get(platform_id) + platform.callback = callback + + def get_subscriptions(self): + return self.schema.get_subscriptions() + + def get_config_tasmota(self): + return self.schema.get_config_tasmota() + + def get_config_ha_base(self): + data = { + "unique_id": f"{self.device.name_sanitized}-{self.device.mac_short}-{self.name_sanitized}", + "name": self.name, + "availability_topic": str(self.device.data_announce.topic_lwt_prop), + "payload_off": haco.constants.OFF, + "payload_available": "Online", + "payload_on": haco.constants.ON, + "payload_not_available": "Offline", + "force_update": True, + "icon": self.icon, + # "entity_id": self.entity_id + } + data.update(self.schema.get_config_ha()) + + return data + + def get_config_ha(self): + data = self.get_config_ha_base() | self.get_config_ha_ex() + data = {k: v for k, v in data.items() if v is not None} + return data + + def get_config_ha_ex(self): + return {} + + async def process_message(self, client, capability_id, platform_id, message): + + if not message.payload: + logging.warning(f'Topic {message.topic.value} got empty payload. It may have been deleted.') + return + + platform = self.schema.get(capability_id).get(platform_id) + output = platform.handle(message) + + if output == 'DO_NOT_SEND': + logging.warning( + f'Topic {message.topic.value} callback responded with send=False. Will not publish response.') + return + + topic = str(platform.get_topic_publish()) + await log_publish(client, topic, output) + + def get_announce_topic(self): + return f"homeassistant/{self.NAME}/{self.device.name_sanitized}/{self.name_sanitized}/config" diff --git a/haco/v0/haco/debugging.py b/haco/v0/haco/debugging.py new file mode 100644 index 0000000..2a7a8e2 --- /dev/null +++ b/haco/v0/haco/debugging.py @@ -0,0 +1,57 @@ +import random +from typing import Any + +from haco.sensor import Sensor +from haco.tasmota import Tasmota +from haco.tools import get_latest + +from haco import trigger, Update, Response + + +def get_memory_sensor(): + memory_sensor = Sensor('Memory Free', uom='kB', uom_type='DATA_SIZE', data_type=int) + + @memory_sensor.callback(trigger.Cron('*/30 * * * * *')) + def tasmota(value: Tasmota[Any, 'tasmota.memory()']): + return value.get('heap_free', 'unknown') + + return memory_sensor + + +def get_tasmota_updater(): + DEFAULT_OTA_URL = 'https://ota.tasmota.com/tasmota32/release/tasmota32.bin' + + once_daily = trigger.Cron(f"0 {random.randint(0, 59)} {random.randint(0, 23)} * * *") + + update = Update('Update Tasmota') + + @update.callback() + def ha(value) -> Tasmota[str, 'tasmota.cmd("upgrade 1")']: + return value + + @update.callback(trigger=once_daily) + def latest_version_tasmota(value): + tag = get_latest('arendst', 'Tasmota') + + if not tag: + return Response(send=False) + + tag = tag.lstrip('v') + + return tag + + @update.callback(trigger=once_daily) + def tasmota(value: Tasmota[Any, 'tasmota.cmd("status 2")'], otaurl: Tasmota[Any, 'tasmota.cmd("OtaUrl")']): + + if otaurl['OtaUrl'] != DEFAULT_OTA_URL: + return Response(send=False) + + version = value.get('StatusFWR', {}).get('Version') or '' + version = version.removesuffix('(tasmota32)') + + if not version: + return Response(send=False) + + return version + + return update diff --git a/haco/v0/haco/device.py b/haco/v0/haco/device.py new file mode 100644 index 0000000..21a3cf5 --- /dev/null +++ b/haco/v0/haco/device.py @@ -0,0 +1,119 @@ +import json +from pathlib import Path +from typing import List + +from haco.device_data import DeviceData +from haco.tools import log_publish, split_into_chunks, log_subscribe + +import haco.utils +from haco import tools, constants +from haco.control import Control + + +class Device: + + def __init__(self, identifier, config_module, controls: List[Control], run_config_post=None): + + self.config_module = config_module + + self.identifier = identifier + self.run_config_post = run_config_post + self.controls = controls + + for control in self.controls: + control.device = self + + self.contols_dict = {control.name_sanitized: control for control in self.controls} + self.get = self.contols_dict.get + + self.data_announce = None + + @property + def name_sanitized(self): + return haco.utils.sanitize_name(self.data_announce.name) + + @property + def mac_short(self): + return self.data_announce.mac.replace(':', '').lower() + + def get_config_ha(self): + + data_device = { + "connections": [["mac", self.data_announce.mac]], + "identifiers": self.data_announce.mac + } + + data = {} + for control in self.controls: + data_control = control.get_config_ha() + data_control['device'] = data_device + data[control.get_announce_topic()] = data_control + + return data + + def get_config_tasmota(self): + config = [] + for control in self.controls: + config += control.get_config_tasmota() + return config + + def get_subscriptions(self): + data = {} + for control in self.controls: + data.update(control.get_subscriptions()) + + return data + + async def publish_config_ha(self, client): + data = self.get_config_ha() + for topic, data in data.items(): + await log_publish(client, topic, payload=json.dumps(data), retain=True) + + async def publish_config_tasmota(self, client): + data = self.get_config_tasmota() + + data_mqtt = {datum['trigger']: datum for datum in data if datum['type'] == 'MqttSubscription'} + data_callbacks = [datum for datum in data if datum['type'] != 'MqttSubscription'] + + tasmota_config = { + # 'id': self.config_id, + 'callbacks': data_callbacks, + 'mqtt': data_mqtt, + 'run_config_post': self.run_config_post, + + } + + self.data_announce.config_id = tools.hash_string(json.dumps(tasmota_config)) + + tasmota_config['id'] = self.data_announce.config_id + + tasmota_config_str = json.dumps(tasmota_config) + tasmota_config_topic = Path(f"haco/{constants.BRANCH}/{self.data_announce.hostname}/config") + parts = split_into_chunks(tasmota_config_str, 750) + for i, part in enumerate(parts): + part = json.dumps({"id": self.data_announce.config_id, "data": part}) + if len(part) > 1200: + raise ValueError(f'Config part too large.') + await log_publish(client, str(tasmota_config_topic / str(i)), payload=part, retain=True) + + payload_header = json.dumps({"size": len(parts), "id": self.data_announce.config_id, 'force_update': True}) + await log_publish(client, str(tasmota_config_topic), payload=payload_header, retain=True) + + payload_full = json.dumps({"size": len(parts), "id": self.data_announce.config_id, "data": tasmota_config}) + await log_publish(client, str(tasmota_config_topic / 'full'), payload=payload_full, retain=True) + + async def do_subscriptions(self, client): + data = self.get_subscriptions() + for topic in data.keys(): + await log_subscribe(client, str(topic)) + + async def bind(self, client, data_announce: DeviceData): + msg = f'Found device with matching config {self.config_module.__name__}: Hostname: {data_announce.hostname} MAC:{data_announce.mac}' + tools.logger.info(msg) + + self.data_announce = data_announce + + await self.do_subscriptions(client) + + await self.publish_config_ha(client) + await self.publish_config_tasmota(client) diff --git a/haco/v0/haco/device_data.py b/haco/v0/haco/device_data.py new file mode 100644 index 0000000..58d0c31 --- /dev/null +++ b/haco/v0/haco/device_data.py @@ -0,0 +1,48 @@ +from dataclasses import dataclass, field +from pathlib import Path +from typing import Dict + + +@dataclass +class DeviceData: + wifi: Dict[str, any] + device_name: str + fulltopic: str + hostname: str + mac: str + version: str + topic: str + config_id: str + eth: Dict[str, any] + timestamp: Dict[str, int] + prefix: Dict[str, str] + prefix_cmnd: str = field(init=False) + prefix_stat: str = field(init=False) + prefix_tele: str = field(init=False) + + name: str = field(init=False) + + def __post_init__(self): + # Unpack the 'prefix' argument into individual fields + self.prefix_cmnd = self.prefix['Prefix1'] + self.prefix_stat = self.prefix['Prefix2'] + self.prefix_tele = self.prefix['Prefix3'] + + # Replace placeholders in the fulltopic with actual values + self.fulltopic = self.fulltopic.replace('%topic%', self.topic) + + self.name = self.device_name + + @property + def identifiers(self): + return {self.wifi.get('mac'), self.eth.get('mac'), self.hostname, self.mac} + + @property + def topic_tele(self): + topic = Path(self.fulltopic.replace('%prefix%', self.prefix_tele)) + return topic + + @property + def topic_lwt_prop(self): + topic = self.topic_tele / 'LWT' + return topic diff --git a/haco/v0/haco/load_configs.py b/haco/v0/haco/load_configs.py new file mode 100644 index 0000000..ff1128d --- /dev/null +++ b/haco/v0/haco/load_configs.py @@ -0,0 +1,63 @@ +import importlib.util +import json +from importlib import reload +from pathlib import Path + +from haco.constants import CONFIGS_PATH, OPTIONS_PATH +from haco.control import Control +from haco.device import Device + +from haco import tools + + +def load_json(file_path): + with open(file_path, 'r') as json_file: + data = json.loads(json_file.read()) + return data + + +def load_controls_from_directory(): + if not CONFIGS_PATH.exists(): + tools.logger.warning(f'Configs path does not exist. Will be created: {CONFIGS_PATH}') + CONFIGS_PATH.mkdir() + + options = load_json(OPTIONS_PATH) + + controls = [] + for data in options['assignments']: + + name = data['config'] + identifier = data['identifier'] + + args = {'identifier': identifier} + + py_file = CONFIGS_PATH / Path(name).with_suffix('.py') + module_name = py_file.stem + + try: + module = importlib.import_module(f'haco.configs.{module_name}') + reload(module) + except ImportError: + spec = importlib.util.spec_from_file_location(module_name, str(py_file)) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + + args['config_module'] = module + + for obj_name in dir(module): + obj = getattr(module, obj_name) + if obj_name == 'DEVICE_CONFIG': + args.update(obj) + if isinstance(obj, Control): + args.setdefault('controls', []) + args['controls'].append(obj) + + controls.append(args) + + return controls + + +def load_devices(): + devices_args = load_controls_from_directory() + devices = [Device(**args) for args in devices_args] + return devices diff --git a/haco/v0/haco/mqtt.py b/haco/v0/haco/mqtt.py new file mode 100644 index 0000000..f1f3c1c --- /dev/null +++ b/haco/v0/haco/mqtt.py @@ -0,0 +1,76 @@ +import asyncio +import json +from pathlib import Path + +import aiomqtt +from haco.constants import MQTT_PASSWORD, MQTT_HOST, MQTT_PORT, MQTT_USERNAME +from haco.device import Device +from haco.device_data import DeviceData +from haco.load_configs import load_devices +from haco.tools import log_received, logger + +from haco import constants, tools + + +async def listen(client, devices): + TOPIC_ANNOUNCE = f"haco/{constants.BRANCH}/+/announce" + await tools.log_subscribe(client, TOPIC_ANNOUNCE) + + async with client.messages() as messages: + + async for message in messages: + await log_received(message) + if message.topic.matches(TOPIC_ANNOUNCE): + + if not message.payload: + msg = f'Topic {message.topic.value} got empty payload. It may have been deleted.' + tools.logger.info(msg) + continue + + data_announce = json.loads(message.payload) + data_announce = DeviceData(**data_announce) + + for identifier in data_announce.identifiers: + device: Device = devices.get(identifier) + if device: + break + + if not device: + msg = f"""Found device with no configuration module assigned. Assign one in Add-On Configuration: "{data_announce.name}" Hostname: {data_announce.hostname} MAC:{data_announce.mac}.""" + tools.logger.info(msg) + continue + + if device.data_announce and data_announce.config_id == device.data_announce.config_id: + msg = f'Device "{device.data_announce.name}" successfully configured. Hostname: {device.data_announce.hostname} MAC:{device.data_announce.mac}' + tools.logger.info(msg) + continue + + await device.bind(client, data_announce) + devices[device.data_announce.hostname] = device + + + else: + + if message.topic.matches('haco/release/+/config/#'): + logger.error(f'Control code got config message. Do not know why.') + continue + + _, _, device_name, _, control, capability_id, platform, io = Path(message.topic.value).parts + device = devices[device_name] + await device.get(control).process_message(client, capability_id, platform, message) + + +async def start_mqtt(): + devices = load_devices() + devices = {device.identifier: device for device in devices} + + while True: + client = aiomqtt.Client(hostname=MQTT_HOST, port=MQTT_PORT, username=MQTT_USERNAME, + password=MQTT_PASSWORD) + try: + async with client: + await asyncio.gather(listen(client, devices)) + except aiomqtt.MqttError: + msg = f"MQTT: Connection lost; Reconnecting in {constants.RECONNECT_DELAY_SEC} seconds ..." + logger.info(msg) + await asyncio.sleep(constants.RECONNECT_DELAY_SEC) diff --git a/haco/schema.py b/haco/v0/haco/schema.py similarity index 86% rename from haco/schema.py rename to haco/v0/haco/schema.py index 362eb1d..0412a9b 100644 --- a/haco/schema.py +++ b/haco/v0/haco/schema.py @@ -4,14 +4,11 @@ import typing from pathlib import Path from typing import List -from haco import tools, constants +from haco import tools, constants, callback DEVICE = 'development-eth' CONTROL = 'DEVELOPMENT-DEHUMIDIFIER' -ON = 'ON' -OFF = 'OFF' - class ControlType: ... @@ -79,6 +76,15 @@ class Platform: self.callback = None + @property + def callback_id(self): + return ( + Path() / + self.capability.schema.control.NAME / + self.capability.schema.control.name_sanitized / + self.capability.name + ) + @property def callback_function_name(self): return f'{self.capability.alias}_{self.PLATFORM}' @@ -108,10 +114,15 @@ class Platform: payload_str = message.payload.decode('utf-8') payload = self.deserialize(payload_str) - output_raw = self.get_callback_output(payload) + response = self.get_callback_output(payload) - output = self.serialize(self.convert_out(output_raw)) + if type(response) is not callback.Response: + response = callback.Response(value=response) + if not response.send: + return 'DO_NOT_SEND' + + output = self.serialize(self.convert_out(response.value)) return output def get_callback_output(self, data): @@ -122,7 +133,7 @@ class Platform: if not self.callback: return {} - return {self.get_topic_subscription(): self.get_handler_name()} + return {self.get_topic_subscription(): self.get_handler_name()} # I think this is as such because it needs to invert the subscription. so one platform gets the other's messages? def get_config_ha(self): @@ -215,7 +226,8 @@ class HomeAssistant(Platform): 'topic': None, 'trigger': str(trigger), 'function': self.callback.function_tasmota, - 'type': 'MqttSubscription' + 'type': 'MqttSubscription', + 'id': str(self.callback_id) } return config @@ -240,7 +252,7 @@ class Tasmota(Platform): extra_args = set(data.keys()) - set(sigs.keys()) for arg in extra_args: - msg = f'Callback {self.callback.function_name} got argument ({arg}={extra_args[arg]}) not in callback function. Will be ignored.' + msg = f'Callback {self.callback.function_name} got argument ({arg}={data[arg]}) not in callback function. Will be ignored.' logging.warning(msg) data.pop(arg) @@ -285,7 +297,8 @@ class Tasmota(Platform): 'topic': str(self.get_topic_subscription()), 'trigger': self.callback.trigger, 'function': self.callback.function_tasmota, - 'type': self.callback.type_id + 'type': self.callback.type_id, + 'id': str(self.callback_id) } return config @@ -297,13 +310,20 @@ class Default: class Capability: - def __init__(self, name, type=ControlType, tamota: Tasmota = Default, ha: HomeAssistant = Default, alias=None): + def __init__( + self, + name: str = constants.CAPABILITY_DEFAULT, + type=ControlType, + tasmota: typing.Optional[Tasmota] = Default, + ha: typing.Optional[HomeAssistant] = Default, + alias: typing.Optional[str] = None + ): self.name = name self.alias = alias or name self.type = type self.schema = None - self.tasmota = tamota if tamota is not Default else Tasmota() + self.tasmota = tasmota if tasmota is not Default else Tasmota() self.ha = ha if ha is not Default else HomeAssistant() self.platforms = [io for io in {self.tasmota, self.ha} if io] @@ -358,7 +378,8 @@ class Schema: return names def get_path(self): - return Path(f"haco") / constants.BRANCH / self.control.device.hostname / 'control' / self.control.name_sanitized + return Path( + f"haco") / constants.BRANCH / self.control.device.data_announce.hostname / 'control' / self.control.name_sanitized def get_config_ha(self): data = {} diff --git a/haco/start.py b/haco/v0/haco/start.py similarity index 100% rename from haco/start.py rename to haco/v0/haco/start.py diff --git a/haco/tasmota.py b/haco/v0/haco/tasmota.py similarity index 100% rename from haco/tasmota.py rename to haco/v0/haco/tasmota.py diff --git a/haco/tools.py b/haco/v0/haco/tools.py similarity index 75% rename from haco/tools.py rename to haco/v0/haco/tools.py index 2e18a75..d7ac9e7 100644 --- a/haco/tools.py +++ b/haco/v0/haco/tools.py @@ -1,7 +1,15 @@ import hashlib +import logging + +from haco.tasmota import Tasmota from haco import constants, tuya -from haco.tasmota import Tasmota + +logging.basicConfig(level=constants.LOG_LEVEL, format='%(asctime)s %(levelname)-8s %(message)s', + datefmt='%Y-%m-%d %H:%M:%S') +logger = logging.getLogger(__name__) + + def split_into_chunks(input_string, chunk_size): @@ -30,20 +38,20 @@ def truncate_middle(input_string, max_length): async def log_publish(client, topic, payload, retain=False): log_retain = '|' if retain else ' ' message = f'mqtt->{log_retain} {topic} {truncate_middle(payload, 100)}' - print(message) + logger.debug(message) await client.publish(topic=topic, payload=payload, retain=retain) async def log_subscribe(client, topic): message = f'mqtt+{topic}' - print(message) + logger.debug(message) await client.subscribe(topic=topic) async def log_received(message): log_retain = '|' if message.retain else ' ' message = f'mqtt<-{log_retain} {message.topic} {truncate_middle(message.payload.decode("utf-8"), 100)}' - print(message) + logger.debug(message) def callback_default(value, data=None): @@ -54,21 +62,7 @@ def invert_bool(value): return {True: 'ON', False: 'OFF', 'ON': True, 'OFF': False}[value] -def sanitize_name(s, sep='-'): - chars = [] - for c in s.lower(): - if c in constants.SEPS_ALLOWED: - chars.append(sep) - elif c in constants.CHARS_ALLOWED: - chars.append(c) - - sanitized = ''.join(chars) - - if not sanitized: - raise ValueError("Sanitized string is empty") - - return sanitized def add_tuya_io(control, control_type, type_id, dp_id): @@ -92,3 +86,20 @@ def hash_string(input_string, size=16): hash_result = hash_object.hexdigest()[:size] return hash_result + + +def get_latest(org, repo): + import requests + url = f"https://api.github.com/repos/{org}/{repo}/releases/latest" + + headers = { + 'Accept': 'application/vnd.github+json', + 'X-GitHub-Api-Version': '2022-11-28' + } + + response = requests.request("GET", url, headers=headers) + response_json = response.json() + + tag = response_json.get('tag_name') + + return tag diff --git a/haco/trigger.py b/haco/v0/haco/trigger.py similarity index 100% rename from haco/trigger.py rename to haco/v0/haco/trigger.py diff --git a/haco/tuya.py b/haco/v0/haco/tuya.py similarity index 100% rename from haco/tuya.py rename to haco/v0/haco/tuya.py diff --git a/haco/v0/haco/update.py b/haco/v0/haco/update.py new file mode 100644 index 0000000..e5c6dae --- /dev/null +++ b/haco/v0/haco/update.py @@ -0,0 +1,40 @@ +from haco.control import Control +from haco.schema import Schema, Capability, AnnounceTopic, Tasmota, HomeAssistant + + +class Update(Control): + NAME = 'update' + + @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='latest_version', + ha=None, + tasmota=Tasmota(announce_data=AnnounceTopic(key='{capability}_topic')) + ) + ] + ) + return schema + + # def init(name, entity_id, icon, temperature_unit, temperature_range, humidity_range, modes, preset_modes, fan_modes, swing_modes, precision, callbacks) + + def __init__(self, name=None, icon=None, release_url=None, entity_picture=None): + self.release_url = release_url + self.entity_picture = entity_picture + + super().__init__(name, icon=icon) + + def get_config_ha_ex(self): + data = { + 'entity_picture': self.entity_picture, + 'payload_install': 'INSTALL', + 'release_url': self.release_url + } + + return data diff --git a/update_version.py b/haco/v0/update_version.py similarity index 99% rename from update_version.py rename to haco/v0/update_version.py index 167cbe2..91c2eb1 100644 --- a/update_version.py +++ b/haco/v0/update_version.py @@ -1,6 +1,5 @@ -import sys - import re +import sys from pathlib import Path PATH_ROOT = Path(__file__).parent.absolute() diff --git a/haco/version b/haco/version deleted file mode 100644 index 7bcd0e3..0000000 --- a/haco/version +++ /dev/null @@ -1 +0,0 @@ -0.0.2 \ No newline at end of file diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..8e8059d --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,86 @@ +[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"] diff --git a/repository.yaml b/repository.yaml new file mode 100644 index 0000000..e267c3b --- /dev/null +++ b/repository.yaml @@ -0,0 +1,3 @@ +name: haco +url: 'https://github.com/fmtr/haco' +maintainer: Frontmatter \ No newline at end of file diff --git a/setup.py b/setup.py deleted file mode 100644 index 440ca38..0000000 --- a/setup.py +++ /dev/null @@ -1,38 +0,0 @@ -from pathlib import Path - -from setuptools import find_packages, setup - -packages = find_packages() -name = next(iter(packages)) -path_base = Path(__file__).absolute().parent -path = path_base / name / 'version' -__version__ = path.read_text().strip() - -setup( - long_description=(path_base / 'README.md').read_text(), - long_description_content_type='text/markdown', - name=name, - version=__version__, - url=f'https://link.frontmatter.ai/{name}', - license='Copyright © 2023 Frontmatter. All rights reserved.', - author='Frontmatter', - description='Home Assistant Control Objects', - keywords='homeassistant controls python tasmota', - packages=packages, - package_data={ - name: [f'version'], - }, - install_requires=[ - 'aiomqtt' - ], - extras_require={ - 'tasmota': [ - - ] - }, - entry_points={ - 'console_scripts': [ - f'{name}-daemon = {name}.start:main', - ], - } -)