diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml new file mode 100644 index 0000000..6556dfc --- /dev/null +++ b/.github/workflows/main.yml @@ -0,0 +1,76 @@ +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 deleted file mode 120000 index 612588c..0000000 --- a/CHANGELOG.md +++ /dev/null @@ -1 +0,0 @@ -docs/changelog/0.4.7.md \ No newline at end of file diff --git a/haco/v0/Dockerfile b/Dockerfile similarity index 88% rename from haco/v0/Dockerfile rename to Dockerfile index 37602f6..ad53ec5 100644 --- a/haco/v0/Dockerfile +++ b/Dockerfile @@ -1,7 +1,7 @@ ARG VERSION ARG TYPE=development -FROM fmtr/python as base +FROM edwardbrown/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-daemon +CMD haco diff --git a/README.md b/README.md index e7c780a..e69de29 100644 --- a/README.md +++ b/README.md @@ -1,27 +0,0 @@ -# `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/haco/v0/berry/haco.be b/berry/haco.be similarity index 84% rename from haco/v0/berry/haco.be rename to berry/haco.be index 21951b1..2c2b793 100644 --- a/haco/v0/berry/haco.be +++ b/berry/haco.be @@ -2,17 +2,8 @@ import tools, string, json, mqtt var mod = module("haco") -import haco_version +var logger=tools.logger.logger -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' @@ -47,18 +38,16 @@ class ConfigDownloader if self.id_downloading && self.id_downloading==id - logger.debug(string.format("Got duplicate new config (same as currently being downloaded) ID: %s. Will be ignored.",id)) + logger.error(string.format("Got duplicate new config (same as currently being download) 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...']) @@ -173,7 +162,7 @@ class Daemon def init() - logger.info(string.format('Starting haco daemon (v%s) in %s seconds...',haco_version.VERSION, self.DELAY_SUBSCRIBE)) + logger.info(['Starting haco daemon...']) self.registry_daemon=tools.callbacks.Registry() self.registry_config=tools.callbacks.Registry() @@ -187,7 +176,7 @@ class Daemon def subscribe_daemon() - var rule_announce=tools.callbacks.Rule('mqtt#connected',/->self.publish_announce()) + var rule_announce=tools.callbacks.Rule('mqtt#connected',/->print('announced called by mqtt#connected',self.publish_announce())) self.registry_daemon.add(rule_announce) var rule_config=tools.callbacks.MqttSubscription( @@ -198,8 +187,6 @@ 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) @@ -222,16 +209,12 @@ 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 @@ -265,7 +248,7 @@ class Daemon if self.config_id==nil var rule_control=tools.callbacks.MqttSubscription( self.TOPIC_CONTROL, - /value,data->tasmota.set_timer(0,/->self.handle_control_message(value,data)) + /value,data->self.handle_control_message(value,data) ) self.registry_daemon.add(rule_control) end @@ -273,7 +256,7 @@ class Daemon self.config_id=id self.publish_announce() - logger.info(string.format('New config ID %s applied successfully.',id)) + logger.info(string.format('New config ID %s applied.',id)) end @@ -306,7 +289,6 @@ 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 @@ -315,14 +297,11 @@ 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->tasmota.set_timer(0,/->self.publish_output(function,value,data,topic)), - id - ) + + return callback_type(trigger,/value data->self.publish_output(function,value,data,topic)) end @@ -334,7 +313,8 @@ class Daemon end -mod.Daemon=Daemon -mod.daemon=nil + +mod.daemon=Daemon() + return mod \ No newline at end of file diff --git a/berry/haco_version.be b/berry/haco_version.be new file mode 100644 index 0000000..85fad4a --- /dev/null +++ b/berry/haco_version.be @@ -0,0 +1,5 @@ +var VERSION='0.0.2' + +var mod = module("haco_version") +mod.VERSION=VERSION +return mod \ No newline at end of file diff --git a/haco/v0/berry/manifest.yaml b/berry/manifest.yaml similarity index 79% rename from haco/v0/berry/manifest.yaml rename to berry/manifest.yaml index ead57de..3187968 100644 --- a/haco/v0/berry/manifest.yaml +++ b/berry/manifest.yaml @@ -26,7 +26,3 @@ 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/docs/changelog/0.3.0.md b/docs/changelog/0.3.0.md deleted file mode 100644 index 1502b84..0000000 --- a/docs/changelog/0.3.0.md +++ /dev/null @@ -1,6 +0,0 @@ -- Refactored core models from `dataclass` to Pydantic across active entities (`Base`, `Device`, `Control`, `Capability`, topic models, and concrete control types like `Switch`, `Climate`, `Sensor`, etc.). -- Replaced dataclass-specific field metadata (`metadata=dict(exclude=True)`, `field(...)`, `__post_init__`) with native Pydantic patterns (`Field(...)`, `model_post_init`, class inheritance from `corio.dm.Base`). -- Updated parent/back-reference handling to follow the parent-typing pattern, including explicit in-`__init__` imports for forward references (e.g. `Device.parent: ClientHaco | None`). -- Reworked `Base.model_dump()` to preserve discovery behavior by merging class `DATA`, defaulting to `exclude_none=True`, and excluding runtime extra attributes so dynamic callbacks do not leak into HA announce payloads. -- Cleaned up dataclass leftovers by removing the unused `Metadata` helper from `haco/utils.py` and simplifying related imports. -- Added packaging metadata and testing support updates: `pyproject.toml` project metadata/uv source config, `setup.py` test extras (`pytest`, `pytest-cov`), and initial `haco/tests` package scaffolding. diff --git a/docs/changelog/0.3.4.md b/docs/changelog/0.3.4.md deleted file mode 100644 index 58b84ad..0000000 --- a/docs/changelog/0.3.4.md +++ /dev/null @@ -1,3 +0,0 @@ -- Updated for `corio` module refactors by switching imports to current paths (`corio.iterator`, `corio.jsn`, `corio.datatype`, and `corio.logs`) across capabilities, control serialization, converters, and logging setup. -- Added `haco/tests/test_pydantic_models.py` coverage to verify Home Assistant announce payload shape for `Switch` and `Climate`, runtime-attribute exclusion from `model_dump()`, and parent/subscription wiring behavior. - diff --git a/docs/changelog/0.4.3.md b/docs/changelog/0.4.3.md deleted file mode 100644 index 0b09f2b..0000000 --- a/docs/changelog/0.4.3.md +++ /dev/null @@ -1 +0,0 @@ -- 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 deleted file mode 100644 index be96460..0000000 --- a/docs/changelog/0.4.4.md +++ /dev/null @@ -1,2 +0,0 @@ -- 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 deleted file mode 100644 index cbe3fb3..0000000 --- a/docs/changelog/0.4.5.md +++ /dev/null @@ -1,2 +0,0 @@ -- 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 deleted file mode 100644 index 1885d7a..0000000 --- a/docs/changelog/0.4.6.md +++ /dev/null @@ -1 +0,0 @@ -- 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 deleted file mode 100644 index ef5baae..0000000 --- a/docs/changelog/0.4.7.md +++ /dev/null @@ -1 +0,0 @@ -- 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 deleted file mode 100644 index 07beb5c..0000000 --- a/docs/controls.md +++ /dev/null @@ -1,99 +0,0 @@ -`haco` provides several control types that correspond to Home Assistant platforms. Each control typically has a -`state` and a `command` method that you can override to handle communication. - -# Supported Controls - -## Button - -A button in Home Assistant that can be pressed to trigger an action in your script. - -- **Platform**: `button` -- **Overridable Methods**: - - `command(self, value)`: Called when the button is pressed in Home Assistant. - -```python -from haco import Button - -class MyButton(Button): - def command(self, value): - print("Button was pressed!") -``` - -## Switch - -A toggle switch that can be turned on or off. - -- **Platform**: `switch` -- **Overridable Methods**: - - `state(self, value)`: Should return the current state of the switch (`True` for on, `False` for off). - - `command(self, value)`: Called when the switch is toggled in Home Assistant. - -```python -from haco import Switch - -class MySwitch(Switch): - def __init__(self, **kwargs): - super().__init__(**kwargs) - self._on = False - - def state(self, value): - return self._on - - def command(self, value): - self._on = value - print(f"Switch is now {'ON' if self._on else 'OFF'}") -``` - -## Sensor - -A read-only sensor that displays a value in Home Assistant. - -- **Platform**: `sensor` -- **Overridable Methods**: - - `state(self, value)`: Should return the current value of the sensor. - -```python -from haco import Sensor - -class MySensor(Sensor): - def state(self, value): - return 42 # Or some dynamic value -``` - -## Number - -A slider or input box for numeric values. - -- **Platform**: `number` -- **Overridable Methods**: - - `state(self, value)`: Should return the current numeric value. - - `command(self, value)`: Called when the value is changed in Home Assistant. - -## Select - -A dropdown list of options. - -- **Platform**: `select` -- **Parameters**: `options` (list of strings) -- **Overridable Methods**: - - `state(self, value)`: Should return the currently selected option. - - `command(self, value)`: Called when a new option is selected in Home Assistant. - -# Customizing Controls - -Most controls accept common parameters in their constructor: - -- `name`: The display name in Home Assistant. -- `icon`: An optional MDI icon (e.g., `mdi:lightbulb` or just `lightbulb`). - -Example: - -```python -btn = Button(name="Panic Button", icon="alert") -``` - -# Advanced: Custom Capabilities - -For more complex platforms like `climate`, -`haco` uses "Capabilities". A capability groups a state and a command topic. You can see how these are implemented in -`haco/climate.py`. diff --git a/docs/index.md b/docs/index.md deleted file mode 100644 index 2ffdb68..0000000 --- a/docs/index.md +++ /dev/null @@ -1,7 +0,0 @@ -!!! 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 deleted file mode 100644 index 28be7b8..0000000 --- a/docs/quick-start.md +++ /dev/null @@ -1,48 +0,0 @@ -The easiest way to get started with `haco` is to define a simple device and run the client. - -# Installation - -`haco` can be installed via pip: - -```bash -pip install haco -``` - -!!! tip "MQTT Broker Required" - - `haco` communicates with Home Assistant via MQTT. Ensure you have an MQTT broker (like Mosquitto) running and accessible. - -# Basic Usage - -Here is a minimal example that creates a device with a single button: - -```python -import asyncio -from haco import Button, Device, ClientHaco - -async def main(): - # 1. Define your controls - btn = Button(name="My Awesome Button") - - # 2. Group them into a device - device = Device(name="My Cool Device", controls=[btn]) - - # 3. Create and start the client - # Replace 'mqtt.service' with your MQTT broker's address - client = ClientHaco(hostname='mqtt.service', device=device) - - print("Starting haco client...") - await client.start() - -if __name__ == "__main__": - asyncio.run(main()) -``` - -# What Happens Next? - -1. **Discovery**: When the script runs, it sends discovery messages to Home Assistant. -2. **Entity Created - **: A new device named "My Cool Device" will appear in Home Assistant with a button entity named "My Awesome Button". -3. **Control**: When you press the button in the Home Assistant UI, - `haco` will receive the command. You can then handle this command in your Python script by overriding the - `command` method or providing a callback (see [Control Types](controls.md) for more details). diff --git a/haco/v0/ha/addon/CHANGELOG.md b/ha/addon/CHANGELOG.md similarity index 62% rename from haco/v0/ha/addon/CHANGELOG.md rename to ha/addon/CHANGELOG.md index 47f41bd..5bf094e 100644 --- a/haco/v0/ha/addon/CHANGELOG.md +++ b/ha/addon/CHANGELOG.md @@ -1 +1 @@ -For the latest changes, see **[the project releases page](https://fmtr.link/haco/changes)**. \ No newline at end of file +For the latest changes, see **[the project releases page](https://link.frontmatter.ai/haco/changes)**. \ No newline at end of file diff --git a/ha/addon/DOCS.md b/ha/addon/DOCS.md new file mode 100644 index 0000000..67c5929 --- /dev/null +++ b/ha/addon/DOCS.md @@ -0,0 +1 @@ +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 new file mode 100644 index 0000000..4d743a4 --- /dev/null +++ b/ha/addon/Dockerfile @@ -0,0 +1,10 @@ +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 new file mode 100644 index 0000000..fe84005 --- /dev/null +++ b/ha/addon/README.md @@ -0,0 +1 @@ +../../README.md \ No newline at end of file diff --git a/ha/addon/config.yaml b/ha/addon/config.yaml new file mode 100644 index 0000000..e22a05a --- /dev/null +++ b/ha/addon/config.yaml @@ -0,0 +1,19 @@ +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/haco/v0/ha/addon/run.sh b/ha/addon/run.sh similarity index 84% rename from haco/v0/ha/addon/run.sh rename to ha/addon/run.sh index 4419205..5a084cf 100644 --- a/haco/v0/ha/addon/run.sh +++ b/ha/addon/run.sh @@ -2,7 +2,6 @@ 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/ha/addon/translations/en.yaml b/ha/addon/translations/en.yaml new file mode 100644 index 0000000..d7356f1 --- /dev/null +++ b/ha/addon/translations/en.yaml @@ -0,0 +1,2 @@ +--- +configuration: diff --git a/haco/base.py b/haco/base.py deleted file mode 100644 index 5a3d662..0000000 --- a/haco/base.py +++ /dev/null @@ -1,39 +0,0 @@ -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/v0/haco/berry.py b/haco/berry.py similarity index 100% rename from haco/v0/haco/berry.py rename to haco/berry.py diff --git a/haco/binary_sensor.py b/haco/binary_sensor.py deleted file mode 100644 index fe3e23c..0000000 --- a/haco/binary_sensor.py +++ /dev/null @@ -1,83 +0,0 @@ -from enum import StrEnum -from typing import ClassVar - -from haco.capabilities import Capability -from haco.control import Control - - -class DeviceClass(StrEnum): - """ - - Sourced from: - https://www.home-assistant.io/integrations/binary_sensor/#device-class - - """ - - BATTERY = "battery" # on means low, off means normal - BATTERY_CHARGING = "battery_charging" # on means charging, off means not charging - CARBON_MONOXIDE = "carbon_monoxide" # on means carbon monoxide detected, off no carbon monoxide (clear) - COLD = "cold" # on means cold, off means normal - CONNECTIVITY = "connectivity" # on means connected, off means disconnected - DOOR = "door" # on means open, off means closed - GARAGE_DOOR = "garage_door" # on means open, off means closed - GAS = "gas" # on means gas detected, off means no gas (clear) - HEAT = "heat" # on means hot, off means normal - LIGHT = "light" # on means light detected, off means no light - LOCK = "lock" # on means open (unlocked), off means closed (locked) - MOISTURE = "moisture" # on means moisture detected (wet), off means no moisture (dry) - MOTION = "motion" # on means motion detected, off means no motion (clear) - MOVING = "moving" # on means moving, off means not moving (stopped) - OCCUPANCY = "occupancy" # on means occupied (detected), off means not occupied (clear) - OPENING = "opening" # on means open, off means closed - PLUG = "plug" # on means device is plugged in, off means device is unplugged - POWER = "power" # on means power detected, off means no power - PRESENCE = "presence" # on means home, off means away - PROBLEM = "problem" # on means problem detected, off means no problem (OK) - RUNNING = "running" # on means running, off means not running - SAFETY = "safety" # on means unsafe, off means safe - SMOKE = "smoke" # on means smoke detected, off means no smoke (clear) - SOUND = "sound" # on means sound detected, off means no sound (clear) - TAMPER = "tamper" # on means tampering detected, off means no tampering (clear) - UPDATE = "update" # on means update available, off means up-to-date - VIBRATION = "vibration" # on means vibration detected, off means no vibration (clear) - WINDOW = "window" # on means open, off means closed - - -class BinarySensor(Control): - """ - - A binary sensor for reporting on/off states to Home Assistant. - - """ - DATA: ClassVar[dict] = dict( - platform='binary_sensor' - ) - - device_class: DeviceClass | None = None - - def command(self, value: bool): - """ - - Binary sensors do not support commands. - - """ - raise NotImplementedError() - - def state(self, value: bool | None) -> bool: - """ - - Return the current state of the binary sensor. - - """ - raise NotImplementedError() - - @classmethod - def get_capabilities(cls) -> list[Capability]: - """ - - Get the capabilities for the binary sensor (state only). - - """ - return [ - Capability(name=None, command=None) - ] diff --git a/haco/button.py b/haco/button.py deleted file mode 100644 index 113fbf6..0000000 --- a/haco/button.py +++ /dev/null @@ -1,34 +0,0 @@ -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/v0/haco/callback.py b/haco/callback.py similarity index 86% rename from haco/v0/haco/callback.py rename to haco/callback.py index 6728c83..b149f16 100644 --- a/haco/v0/haco/callback.py +++ b/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 == schema.Tasmota.PLATFORM: + if self.platform == 'tasmota': 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,12 +104,6 @@ class Callback: self.function_tasmota - if self.platform == schema.Tasmota.PLATFORM: + if self.platform == 'tasmota': if not self.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 + raise ValueError(f'Callback {self.function_name} must have a trigger.') diff --git a/haco/capabilities.py b/haco/capabilities.py deleted file mode 100644 index 17b1d83..0000000 --- a/haco/capabilities.py +++ /dev/null @@ -1,89 +0,0 @@ -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 deleted file mode 100644 index 02d1654..0000000 --- a/haco/client.py +++ /dev/null @@ -1,70 +0,0 @@ -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 c616fff..0387355 100644 --- a/haco/climate.py +++ b/haco/climate.py @@ -1,92 +1,112 @@ -from typing import Literal, ClassVar - -from haco.capabilities import Capability 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): - """ - - 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() + NAME = 'climate' @classmethod - def get_capabilities(cls) -> list[Capability]: - """ + 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 - Get the capabilities for the climate control. + # def init(name, entity_id, icon, temperature_unit, temperature_range, humidity_range, modes, preset_modes, fan_modes, swing_modes, precision, callbacks) - """ - 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"), - ] + 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/tests/__init__.py b/haco/configs/__init__.py similarity index 100% rename from haco/tests/__init__.py rename to haco/configs/__init__.py diff --git a/haco/v0/configs/proscenic_t21.py b/haco/configs/air_fryer.py similarity index 68% rename from haco/v0/configs/proscenic_t21.py rename to haco/configs/air_fryer.py index ba192bf..087d615 100644 --- a/haco/v0/configs/proscenic_t21.py +++ b/haco/configs/air_fryer.py @@ -1,12 +1,14 @@ import math -from haco.debugging import get_tasmota_updater -from haco.tools import add_tuya_io -from haco import Tasmota, Number, Sensor, Select, Switch, tuya +from haco import tuya +from haco.pulldown import Pulldown +from haco.sensor import Sensor +from haco.tasmota import Tasmota +from haco.tools import add_tuya_io OPTIONS = ['Default', 'Fries', 'Shrimp', 'Pizza', 'Chicken', 'Fish', 'Steak', 'Cake', 'Bacon', 'Preheat', 'Custom'] -cookbook = Select('Cookbook', options=OPTIONS, icon='chef-hat') +cookbook = Pulldown('Cookbook', options=OPTIONS, icon='mdi:chef-hat') @cookbook.callback() @@ -21,10 +23,9 @@ def tasmota(value: int): time_remaining = Sensor( name='Time Remaining', - uom=Sensor.UOM.TIME_MINUTES, - uom_type=Sensor.UOM_TYPE.DURATION, - icon='timer', - + uom='minutes', + icon='mdi:timer', + device_class='DURATION' ) @@ -33,12 +34,16 @@ 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=Number.UOM.TIME_MINUTES, - mode='box', - icon='timer' + uom='minutes', + icon='mdi:timer' ) @@ -51,12 +56,31 @@ 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=Number.UOM.TEMP_FAHRENHEIT, - icon='temperature-fahrenheit' + uom='°F', + icon='mdi:temperature-fahrenheit' ) @@ -74,8 +98,8 @@ cooking_temp_c = Number( 'Cooking Temperature (C)', number_range=range(77, 204), mode='slider', - uom=Number.UOM.TEMP_CELSIUS, - icon='temperature-celsius' + uom='°C', + icon='mdi:temperature-celsius' ) @@ -91,14 +115,14 @@ def tasmota(value: float): cook_pause = Switch( name='Cook/Pause', - icon='play-pause' + icon='mdi:play-pause' ) add_tuya_io(cook_pause, int, 1, 2) power = Switch( name='Power', - icon='power' + icon='mdi:power' ) add_tuya_io(power, int, 1, 1) @@ -106,34 +130,31 @@ add_tuya_io(power, int, 1, 1) delay_time = Number( name='Delay Time', number_range=range(0, 720), - uom=Sensor.UOM.TIME_MINUTES, - mode='box', - icon='timer-pause' + uom='minutes', + icon='mdi:timer-pause' ) add_tuya_io(delay_time, int, 2, 6) status = Sensor( name='Status', - icon='playlist-play', - uom_type=Sensor.UOM_TYPE.ENUM + icon='mdi:playlist-play', + device_class='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/development.py b/haco/configs/development.py similarity index 87% rename from haco/v0/configs/development.py rename to haco/configs/development.py index 2293e3f..39468c6 100644 --- a/haco/v0/configs/development.py +++ b/haco/configs/development.py @@ -1,5 +1,11 @@ -from haco import Number, Tasmota, Select, Sensor, Text, Password, Climate - +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 number = Number( 'Dev Number Test Control', @@ -119,7 +125,7 @@ def temperature_low_tasmota(value: int): return value -pulldown = Select( +pulldown = Pulldown( 'Dev Select Test Control', options=list('ABC') ) @@ -146,6 +152,9 @@ 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))']: @@ -167,6 +176,7 @@ def tasmota(value: str): return value -from haco.debugging import get_tasmota_updater - -update = get_tasmota_updater() +dev_dehum = Device( + mac='8C:4B:14:85:8D:98', + controls=[number, climate, text, password, sensor, pulldown, get_memory_sensor()] +) diff --git a/haco/constants.py b/haco/constants.py index 989496f..bac17ee 100644 --- a/haco/constants.py +++ b/haco/constants.py @@ -1,24 +1,5 @@ -""" +import string -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' +CHARS_ALLOWED = string.ascii_lowercase + string.digits +SEPS_ALLOWED = '_- ' +BRANCH = 'release' diff --git a/haco/control.py b/haco/control.py index 114d62e..c09743d 100644 --- a/haco/control.py +++ b/haco/control.py @@ -1,178 +1,107 @@ -from __future__ import annotations +import logging +from functools import partial -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") +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 -class Control(Base, Generic[DeviceT]): - """ +class Control: + NAME = None - Base class for Home Assistant controls. - - """ - converters: ClassVar[Type[Converters]] = ConvertersBool - - name: str - icon: str | None = None - device: DeviceT | None = Field(default=None, repr=False) - capabilities: list = Field(default_factory=list, exclude=True, repr=False) - unique_id: str | None = None - availability_topic: str | None = None - - subscriptions: dict | None = Field(default=None, exclude=True, repr=False) - - def model_post_init(self, __context): - self.capabilities = self.get_capabilities() - - if not self.icon: - return - - if not self.icon.startswith(PREFIX_MDI): - self.icon = f"{PREFIX_MDI}{self.icon}" - - def set_parent(self, device: DeviceT): - """ - - Set the parent device for the control and its capabilities. - - """ - 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 + control_type = str @classmethod - def get_capabilities(cls) -> list[Capability]: - """ + 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 - Get the capabilities of the control. + def __init__(self, name, icon=None): - """ - return [ - Capability(name=None) - ] + from device import Device - def get_unique_id(self) -> str: - return f"{self.device.name_san}-{self.name_san}" + self.name = name + + self.device: Device = None + self.schema = self.get_schema() + self.get = self.schema.get + self.schema.control = self + + self.icon = icon @property - def name_san(self) -> str: - """ + def name_sanitized(self): + return tools.sanitize_name(self.name) - Sanitized name of the control. + def callback(self, trigger=None): + return partial(self.add_callback, trigger) - """ - return sanitize_name(self.name) + def add_callback(self, trigger, function): - @property - def topic(self) -> Path: - """ + if (function_name := function.__name__) in {Tasmota.PLATFORM, HomeAssistant.PLATFORM}: + function_name = f'state_{function_name}' - The MQTT topic prefix for the control. + callback_names = self.schema.get_callback_function_names() - """ - return self.device.topic / self.name_san + 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) - @property - def announce_topic(self) -> str: - """ + 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 - The MQTT topic for discovery announcement. + def get_subscriptions(self): + return self.schema.get_subscriptions() - """ - return f"homeassistant/{self.DATA['platform']}/{self.unique_id}/config" + def get_config_tasmota(self): + return self.schema.get_config_tasmota() - 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() + 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 - async def initialise(self): - """ + 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 - Initialise the control by announcing it and setting its initial state. + def get_config_ha_ex(self): + return {} - """ - await self.announce() - for capability in self.capabilities: - if not capability.state: - continue - await capability.state.handle(value=None) + async def process_message(self, client, capability_id, platform_id, message): - async def announce(self): - """ + if not message.payload: + logging.warning(f'Topic {message.topic.value} got empty payload. It may have been deleted.') + return - Announce the control to Home Assistant via MQTT discovery. + 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) - """ - 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 + def get_announce_topic(self): + return f"homeassistant/{self.NAME}/{self.device.name_sanitized}/{self.name_sanitized}/config" diff --git a/haco/debugging.py b/haco/debugging.py new file mode 100644 index 0000000..9db48ea --- /dev/null +++ b/haco/debugging.py @@ -0,0 +1,15 @@ +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 64f8d6b..0d2d161 100644 --- a/haco/device.py +++ b/haco/device.py @@ -1,117 +1,114 @@ -from __future__ import annotations - -from functools import cached_property +import json from pathlib import Path -from typing import List, TYPE_CHECKING +from typing import List -from pydantic import Field - -from haco.base import Base +from haco import tools, constants from haco.control import Control -from haco.utils import sanitize_name - -if TYPE_CHECKING: - from haco.client import ClientHaco +from haco.tools import log_publish, split_into_chunks, log_subscribe -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] +class Device: + 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.set_parent(self) - self.subscriptions = self.get_subscriptions() + control.device = self - @cached_property - def topic(self) -> Path: - """ - - The MQTT topic prefix for the device. - - """ - return self.client.topic / self.name_san + self.contols_dict = {control.name_sanitized: control for control in self.controls} + self.get = self.contols_dict.get @property - def name_san(self) -> str: - """ - - Sanitized name of the device. - - """ - return sanitize_name(self.name) - - async def announce(self): - """ - - Announce all controls of the device to Home Assistant. - - """ - for control in self.controls: - await control.announce() - - async def initialise(self): - """ - - Initialise all controls of the device. - - """ - for control in self.controls: - await control.initialise() - + def name_sanitized(self): + return tools.sanitize_name(self.name) @property - def client(self) -> ClientHaco: - """ + def mac_short(self): + return self.mac.replace(':', '').lower() - The parent client of the device. + def get_config_ha(self): - """ - return self.parent + data_device = { + "connections": [["mac", self.mac]], + "identifiers": self.mac + } - def get_subscriptions(self) -> dict: - """ - - Get all MQTT topic subscriptions for the device's controls. - - """ data = {} for control in self.controls: - data |= control.subscriptions + 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 -if __name__ == "__main__": - control = Control(name="test", platform="test") - device = Device(name="test", parent=None, controls=[control]) - data = device.model_dump() - print(device.topic) + 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) diff --git a/haco/fan.py b/haco/fan.py deleted file mode 100644 index b46d4cd..0000000 --- a/haco/fan.py +++ /dev/null @@ -1,100 +0,0 @@ -from typing import ClassVar - -from haco.capabilities import Capability -from haco.control import Control -from haco.utils import ON, OFF, ConvertersNumeric, ConvertersString - - -class Fan(Control): - """ - - A fan control with support for speed percentage, preset modes, and oscillation. - - """ - DATA: ClassVar[dict] = dict( - platform="fan" - ) - - speed_range_min: int | None = None - speed_range_max: int | None = None - preset_modes: list[str] | None = None - payload_oscillation_on: str = ON - payload_oscillation_off: str = OFF - - def command(self, value: bool) -> bool: - """ - - Handle on/off commands for the fan. - - """ - raise NotImplementedError() - - def state(self, value: bool | None) -> bool: - """ - - Return the current on/off state of the fan. - - """ - raise NotImplementedError() - - def preset_mode_command(self, value: str) -> str: - """ - - Handle preset mode commands. - - """ - raise NotImplementedError() - - def preset_mode_state(self, value: str | None) -> str: - """ - - Return the current preset mode. - - """ - raise NotImplementedError() - - def percentage_command(self, value: int) -> int: - """ - - Handle percentage (speed) commands. - - """ - raise NotImplementedError() - - def percentage_state(self, value: int | None) -> int: - """ - - Return the current speed percentage. - - """ - raise NotImplementedError() - - def oscillation_command(self, value: bool) -> bool: - """ - - Handle oscillation toggle commands. - - """ - raise NotImplementedError() - - def oscillation_state(self, value: bool | None) -> bool: - """ - - Return the current oscillation state. - - """ - raise NotImplementedError() - - @classmethod - def get_capabilities(cls) -> list[Capability]: - """ - - Get the capabilities for the fan control. - - """ - return [ - Capability(name=None), - Capability(name="preset_mode", converters=ConvertersString), - Capability(name="percentage", converters=ConvertersNumeric), - Capability(name="oscillation"), - ] diff --git a/haco/load_configs.py b/haco/load_configs.py new file mode 100644 index 0000000..90fd275 --- /dev/null +++ b/haco/load_configs.py @@ -0,0 +1,62 @@ +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 new file mode 100644 index 0000000..ecb2110 --- /dev/null +++ b/haco/mqtt.py @@ -0,0 +1,62 @@ +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 e7e58d4..c87057b 100644 --- a/haco/number.py +++ b/haco/number.py @@ -1,45 +1,36 @@ -from enum import StrEnum -from typing import ClassVar, Type - from haco.control import Control -from haco.uom import Uom -from haco.utils import Converters, ConvertersNumeric - -class Mode(StrEnum): - BOX = "box" - SLIDER = "slider" +from haco.tools import get_range_pair class Number(Control): - """ + NAME = 'number' - A number control (slider or box) for numeric input in Home Assistant. + # 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): - """ - DATA: ClassVar[dict] = dict( - platform='number' - ) - converters: ClassVar[Type[Converters]] = ConvertersNumeric + self.min, self.max = get_range_pair(number_range) + self.mode = mode + self.step = step + self.uom = uom - min: float = 0. - max: float = 100. - mode: Mode = Mode.SLIDER - step: float = 1. - uom: Uom | None = None + super().__init__(name, icon=icon) - def command(self, value: float) -> float: - """ + @property + def control_type(self): - Handle numeric value commands from Home Assistant. + if self.step is None or self.step == 1: + return int + else: + return float - """ - raise NotImplementedError() + def get_config_ha_ex(self): + data = { + 'min': self.min, + 'max': self.max, + 'mode': self.mode, + 'unit_of_measurement': self.uom, + 'step': self.step + } - def state(self, value: float | None) -> float: - """ - - Return the current numeric state. - - """ - raise NotImplementedError() + return data diff --git a/haco/obs.py b/haco/obs.py deleted file mode 100644 index 3dc4036..0000000 --- a/haco/obs.py +++ /dev/null @@ -1,12 +0,0 @@ -""" - -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 deleted file mode 100644 index 25f0abf..0000000 --- a/haco/paths.py +++ /dev/null @@ -1,8 +0,0 @@ -""" - -Path definitions for the haco library. - -""" -from corio import paths - -paths = paths.PackagePaths() diff --git a/haco/pulldown.py b/haco/pulldown.py new file mode 100644 index 0000000..b5276ee --- /dev/null +++ b/haco/pulldown.py @@ -0,0 +1,18 @@ +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 deleted file mode 120000 index 1e11d78..0000000 --- a/haco/pyproject.package.toml +++ /dev/null @@ -1 +0,0 @@ -../pyproject.toml \ No newline at end of file diff --git a/haco/sb3.py b/haco/sb3.py deleted file mode 100644 index ba65113..0000000 --- a/haco/sb3.py +++ /dev/null @@ -1,35 +0,0 @@ -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/v0/haco/schema.py b/haco/schema.py similarity index 86% rename from haco/v0/haco/schema.py rename to haco/schema.py index 0412a9b..362eb1d 100644 --- a/haco/v0/haco/schema.py +++ b/haco/schema.py @@ -4,11 +4,14 @@ import typing from pathlib import Path from typing import List -from haco import tools, constants, callback +from haco import tools, constants DEVICE = 'development-eth' CONTROL = 'DEVELOPMENT-DEHUMIDIFIER' +ON = 'ON' +OFF = 'OFF' + class ControlType: ... @@ -76,15 +79,6 @@ 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}' @@ -114,15 +108,10 @@ class Platform: payload_str = message.payload.decode('utf-8') payload = self.deserialize(payload_str) - response = self.get_callback_output(payload) + output_raw = self.get_callback_output(payload) - if type(response) is not callback.Response: - response = callback.Response(value=response) + output = self.serialize(self.convert_out(output_raw)) - if not response.send: - return 'DO_NOT_SEND' - - output = self.serialize(self.convert_out(response.value)) return output def get_callback_output(self, data): @@ -133,7 +122,7 @@ class Platform: if not self.callback: return {} - 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? + return {self.get_topic_subscription(): self.get_handler_name()} def get_config_ha(self): @@ -226,8 +215,7 @@ class HomeAssistant(Platform): 'topic': None, 'trigger': str(trigger), 'function': self.callback.function_tasmota, - 'type': 'MqttSubscription', - 'id': str(self.callback_id) + 'type': 'MqttSubscription' } return config @@ -252,7 +240,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}={data[arg]}) not in callback function. Will be ignored.' + msg = f'Callback {self.callback.function_name} got argument ({arg}={extra_args[arg]}) not in callback function. Will be ignored.' logging.warning(msg) data.pop(arg) @@ -297,8 +285,7 @@ class Tasmota(Platform): 'topic': str(self.get_topic_subscription()), 'trigger': self.callback.trigger, 'function': self.callback.function_tasmota, - 'type': self.callback.type_id, - 'id': str(self.callback_id) + 'type': self.callback.type_id } return config @@ -310,20 +297,13 @@ class Default: class Capability: - 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 - ): + def __init__(self, name, type=ControlType, tamota: Tasmota = Default, ha: HomeAssistant = Default, alias=None): self.name = name self.alias = alias or name self.type = type self.schema = None - self.tasmota = tasmota if tasmota is not Default else Tasmota() + self.tasmota = tamota if tamota 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] @@ -378,8 +358,7 @@ class Schema: return names def get_path(self): - return Path( - f"haco") / constants.BRANCH / self.control.device.data_announce.hostname / 'control' / self.control.name_sanitized + return Path(f"haco") / constants.BRANCH / self.control.device.hostname / 'control' / self.control.name_sanitized def get_config_ha(self): data = {} diff --git a/haco/select.py b/haco/select.py deleted file mode 100644 index e6c8235..0000000 --- a/haco/select.py +++ /dev/null @@ -1,34 +0,0 @@ -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 6b5451d..2fd5c33 100644 --- a/haco/sensor.py +++ b/haco/sensor.py @@ -1,108 +1,37 @@ -from enum import StrEnum -from typing import Any, ClassVar - -from haco.capabilities import Capability +import schema from haco.control import Control -from haco.uom import Uom -from haco.utils import ConvertersString - - -class DeviceClass(StrEnum): - """ - - Sourced from: https://www.home-assistant.io/integrations/sensor/#device-class - - """ - - APPARENT_POWER = "apparent_power" # Apparent power in VA. - AQI = "aqi" # Air Quality Index (unitless). - ATMOSPHERIC_PRESSURE = "atmospheric_pressure" # Atmospheric pressure in cbar, bar, hPa, inHg, kPa, mbar, Pa, or psi. - BATTERY = "battery" # Battery percentage in %. - CARBON_DIOXIDE = "carbon_dioxide" # CO₂ in ppm. - CARBON_MONOXIDE = "carbon_monoxide" # CO in ppm. - CURRENT = "current" # Current in A or mA. - DATA_RATE = "data_rate" # Data rate in bit/s, kbit/s, Mbit/s, Gbit/s, B/s, kB/s, MB/s, GB/s, KiB/s, MiB/s, or GiB/s. - DATA_SIZE = "data_size" # Data size in bit, kbit, Mbit, Gbit, B, kB, MB, GB, TB, PB, EB, ZB, YB, KiB, MiB, GiB, TiB, PiB, EiB, ZiB, or YiB. - DATE = "date" # ISO 8601 date string. - DISTANCE = "distance" # Distance in km, m, cm, mm, mi, yd, or in. - DURATION = "duration" # Duration in d, h, min, or s. - ENERGY = "energy" # Energy in Wh, kWh, MWh, MJ, or GJ. - ENERGY_STORAGE = "energy_storage" # Stored energy in Wh, kWh, MWh, MJ, or GJ. - ENUM = "enum" # Limited set of non-numeric states. - FREQUENCY = "frequency" # Frequency in Hz, kHz, MHz, or GHz. - GAS = "gas" # Gas volume in m³, ft³, or CCF. - HUMIDITY = "humidity" # Humidity in %. - ILLUMINANCE = "illuminance" # Light level in lx. - IRRADIANCE = "irradiance" # Irradiance in W/m² or BTU/(h⋅ft²). - MOISTURE = "moisture" # Water content in %. - MONETARY = "monetary" # Monetary value (ISO 4217). - NITROGEN_DIOXIDE = "nitrogen_dioxide" # NO₂ in µg/m³. - NITROGEN_MONOXIDE = "nitrogen_monoxide" # NO in µg/m³. - NITROUS_OXIDE = "nitrous_oxide" # N₂O in µg/m³. - OZONE = "ozone" # O₃ in µg/m³. - PH = "ph" # pH value. - PM1 = "pm1" # Particulate matter <1µm in µg/m³. - PM25 = "pm25" # Particulate matter <2.5µm in µg/m³. - PM10 = "pm10" # Particulate matter <10µm in µg/m³. - POWER_FACTOR = "power_factor" # Power factor (unitless or %). - POWER = "power" # Power in W or kW. - PRECIPITATION = "precipitation" # Accumulated precipitation. - PRECIPITATION_INTENSITY = "precipitation_intensity" # Precipitation rate. - PRESSURE = "pressure" # Pressure in Pa, kPa, hPa, bar, cbar, mbar, mmHg, inHg, or psi. - REACTIVE_POWER = "reactive_power" # Reactive power in var. - SIGNAL_STRENGTH = "signal_strength" # Signal strength in dB or dBm. - SOUND_PRESSURE = "sound_pressure" # Sound pressure in dB or dBA. - SPEED = "speed" # Speed in ft/s, in/d, in/h, km/h, kn, m/s, mph, or mm/d. - SULPHUR_DIOXIDE = "sulphur_dioxide" # SO₂ in µg/m³. - TEMPERATURE = "temperature" # Temperature in °C, °F, or K. - TIMESTAMP = "timestamp" # Datetime object or ISO 8601 string. - VOLATILE_ORGANIC_COMPOUNDS = "volatile_organic_compounds" # VOC in µg/m³. - VOLATILE_ORGANIC_COMPOUNDS_PARTS = "volatile_organic_compounds_parts" # VOC in ppm or ppb. - VOLTAGE = "voltage" # Voltage in V or mV. - VOLUME = "volume" # Volume in L, mL, gal, fl. oz., m³, ft³, or CCF. - VOLUME_STORAGE = "volume_storage" # Stored volume. - WATER = "water" # Water consumption in L, gal, m³, ft³, or CCF. - WEIGHT = "weight" # Mass in kg, g, mg, µg, oz, lb, or st. - WIND_SPEED = "wind_speed" # Wind speed in ft/s, km/h, kn, m/s, or mph. class Sensor(Control): - """ - - A sensor control for reporting numeric or string values to Home Assistant. - - """ - DATA: ClassVar[dict] = dict( - platform='sensor' - ) - converters = ConvertersString - - unit_of_measurement: Uom | None = None - device_class: DeviceClass | None = None - - def command(self, value: Any): - """ - - Sensors do not support commands. - - """ - raise NotImplementedError() - - def state(self, value: Any) -> Any: - """ - - Return the current state of the sensor. - - """ - raise NotImplementedError() + NAME = 'sensor' @classmethod - def get_capabilities(cls) -> list[Capability]: - """ + 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')) + ) + ] + ) - Get the capabilities for the sensor (state only). + 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 - """ - return [ - Capability(name=None, command=None) - ] + 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 diff --git a/haco/v0/haco/start.py b/haco/start.py similarity index 100% rename from haco/v0/haco/start.py rename to haco/start.py diff --git a/haco/switch.py b/haco/switch.py index 4e15d09..2cb2320 100644 --- a/haco/switch.py +++ b/haco/switch.py @@ -1,30 +1,14 @@ -from typing import ClassVar - from haco.control import Control +from haco.tools import invert_bool + class Switch(Control): - """ + NAME = 'switch' - A switch control that can be toggled on or off. + def __init__(self, name, icon=None): + super().__init__(name, icon=icon) - """ - 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() + @property + def control_type(self): + return invert_bool diff --git a/haco/v0/haco/tasmota.py b/haco/tasmota.py similarity index 100% rename from haco/v0/haco/tasmota.py rename to haco/tasmota.py diff --git a/haco/tests/test_move_complete.py b/haco/tests/test_move_complete.py deleted file mode 100644 index 47d2bbe..0000000 --- a/haco/tests/test_move_complete.py +++ /dev/null @@ -1,155 +0,0 @@ -from __future__ import annotations - -import asyncio -from types import SimpleNamespace -from unittest.mock import AsyncMock - -import pytest - -from corio import Path - -from haco.device import Device -from haco.switch import Switch - - -def run(coro): - return asyncio.run(coro) - - -def message(payload: str) -> SimpleNamespace: - return SimpleNamespace(payload=payload.encode("utf-8")) - - -@pytest.fixture -def client_stub(): - return SimpleNamespace( - topic=Path("root/client"), - will=SimpleNamespace(topic="root/status"), - publish=AsyncMock(), - ) - - -_UNSET = object() - - -def build_switch(client_stub, *, command=_UNSET, state=_UNSET): - switch = Switch(name="Main") - if command is not _UNSET: - switch.command = command - if state is not _UNSET: - switch.state = state - - device = Device(name="Dev", controls=[switch]) - device.set_parent(client_stub) - return switch - - -def test_move_complete_sync_command_updates_state_and_publishes(client_stub): - seen_command = [] - seen_state = [] - - def command(value): - seen_command.append(value) - return value - - def state(value): - seen_state.append(value) - return value - - switch = build_switch(client_stub, command=command, state=state) - command_topic = switch.capabilities[0].command - - run(command_topic.handle(message("ON"))) - - assert seen_command == [True] - assert seen_state == [True] - client_stub.publish.assert_awaited_once_with( - "root/client/dev/main/default/state", - "ON", - retain=True, - ) - - -def test_move_complete_async_command_updates_state_and_publishes(client_stub): - seen_command = [] - seen_state = [] - - async def command(value): - seen_command.append(value) - return not value - - async def state(value): - seen_state.append(value) - return value - - switch = build_switch(client_stub, command=command, state=state) - command_topic = switch.capabilities[0].command - - run(command_topic.handle(message("OFF"))) - - assert seen_command == [False] - assert seen_state == [True] - client_stub.publish.assert_awaited_once_with( - "root/client/dev/main/default/state", - "ON", - retain=True, - ) - - -def test_move_complete_state_handler_sync_publish_path(client_stub): - seen_state = [] - - def state(value): - seen_state.append(value) - return value - - switch = build_switch(client_stub, state=state) - state_topic = switch.capabilities[0].state - - value_raw = run(state_topic.handle(False)) - - assert seen_state == [False] - assert value_raw == "OFF" - client_stub.publish.assert_awaited_once_with( - "root/client/dev/main/default/state", - "OFF", - retain=True, - ) - - -def test_move_complete_command_missing_handler_stops_before_state(client_stub): - seen_state = [] - switch = build_switch( - client_stub, - command=None, - state=lambda value: seen_state.append(value) or value, - ) - command_topic = switch.capabilities[0].command - - result = run(command_topic.handle(message("ON"))) - - assert result is None - assert seen_state == [] - client_stub.publish.assert_not_awaited() - - -def test_move_complete_state_missing_handler_stops(client_stub): - switch = build_switch(client_stub, state=None) - state_topic = switch.capabilities[0].state - - result = run(state_topic.handle(True)) - - assert result is None - client_stub.publish.assert_not_awaited() - - -def test_move_complete_not_implemented_command_stops_before_state(client_stub): - seen_state = [] - switch = build_switch(client_stub, state=lambda value: seen_state.append(value) or value) - command_topic = switch.capabilities[0].command - - result = run(command_topic.handle(message("ON"))) - - assert result is None - assert seen_state == [] - client_stub.publish.assert_not_awaited() diff --git a/haco/tests/test_pydantic_models.py b/haco/tests/test_pydantic_models.py deleted file mode 100644 index 7893131..0000000 --- a/haco/tests/test_pydantic_models.py +++ /dev/null @@ -1,112 +0,0 @@ -from __future__ import annotations - -from types import SimpleNamespace - -import pytest - -from corio import Path - -from haco.climate import Climate -from haco.device import Device -from haco.switch import Switch - - -@pytest.fixture -def client_stub(): - return SimpleNamespace( - topic=Path("root/client"), - will=SimpleNamespace(topic="root/status"), - ) - - -def test_switch_announce_payload_matches_expected(client_stub): - switch = Switch(name="Main", icon="power") - device = Device(name="Dev", controls=[switch]) - device.set_parent(client_stub) - - data = switch.get_announce() - assert data == { - "platform": "switch", - "name": "Main", - "icon": "mdi:power", - "unique_id": "dev-main", - "availability_topic": "root/status", - "device": { - "name": "Dev", - "identifiers": ["dev"], - }, - "state_topic": "root/client/dev/main/default/state", - "command_topic": "root/client/dev/main/default/command", - } - - -def test_climate_announce_payload_has_expected_ha_keys(client_stub): - climate = Climate(name="Cl") - device = Device(name="Dev", controls=[climate]) - device.set_parent(client_stub) - - data = climate.get_announce() - - expected_subset = { - "platform", - "name", - "unique_id", - "availability_topic", - "temperature_unit", - "temperature_min", - "temperature_max", - "mode_command_topic", - "mode_state_topic", - "temperature_command_topic", - "temperature_state_topic", - "power_command_topic", - "power_state_topic", - } - assert expected_subset.issubset(set(data)) - assert not any(key in data for key in {"capabilities", "subscriptions", "parent"}) - assert not any(callable(value) for value in data.values()) - - -def test_control_announce_includes_device_announce_data(client_stub): - switch = Switch(name="Main") - device = Device( - name="Dev", - manufacturer="ACME", - model="Model X", - sw_version="1.2.3", - controls=[switch], - ) - device.set_parent(client_stub) - - data = switch.get_announce() - assert data["device"] == { - "name": "Dev", - "manufacturer": "ACME", - "model": "Model X", - "sw_version": "1.2.3", - "identifiers": ["dev"], - } - assert "controls" not in data["device"] - assert "parent" not in data["device"] - assert "subscriptions" not in data["device"] - - -def test_model_dump_excludes_runtime_extra_attributes(): - switch = Switch(name="Main") - switch.dynamic_callback = lambda value: value - - dumped = switch.model_dump() - assert "dynamic_callback" not in dumped - - -def test_parent_wiring_sets_control_subscriptions(client_stub): - switch = Switch(name="Main") - device = Device(name="Dev", controls=[switch]) - device.set_parent(client_stub) - - assert switch.unique_id == "dev-main" - assert switch.availability_topic == "root/status" - assert device.subscriptions is not None - assert "root/client/dev/main/default/command" in device.subscriptions - handler = device.subscriptions["root/client/dev/main/default/command"] - assert hasattr(handler, "handle") diff --git a/haco/text.py b/haco/text.py index 237fffd..8a21b55 100644 --- a/haco/text.py +++ b/haco/text.py @@ -1,43 +1,27 @@ -from enum import StrEnum -from typing import ClassVar - from haco.control import Control -from haco.utils import ConvertersString - -class Mode(StrEnum): - TEXT = "text" - PASSWORD = "password" +from haco.tools import get_range_pair class Text(Control): - """ + NAME = 'text' - A text control for text input in Home Assistant. + 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 - """ - DATA: ClassVar[dict] = dict( - platform='text' - ) - converters = ConvertersString + super().__init__(name, icon=icon) - pattern: str | None = None - min: int | None = None - max: int | None = None - mode: Mode = Mode.TEXT + def get_config_ha_ex(self): + data = { + 'min': self.min, + 'max': self.max, + 'pattern': self.pattern, + 'mode': self.__class__.__name__.lower() + } - def command(self, value: str) -> str: - """ + return data - Handle text input commands from Home Assistant. - """ - raise NotImplementedError() - - def state(self, value: str | None) -> str: - """ - - Return the current text state. - - """ - raise NotImplementedError() +class Password(Text): + ... diff --git a/haco/v0/haco/tools.py b/haco/tools.py similarity index 75% rename from haco/v0/haco/tools.py rename to haco/tools.py index d7ac9e7..2e18a75 100644 --- a/haco/v0/haco/tools.py +++ b/haco/tools.py @@ -1,15 +1,7 @@ import hashlib -import logging - -from haco.tasmota import Tasmota from haco import constants, tuya - -logging.basicConfig(level=constants.LOG_LEVEL, format='%(asctime)s %(levelname)-8s %(message)s', - datefmt='%Y-%m-%d %H:%M:%S') -logger = logging.getLogger(__name__) - - +from haco.tasmota import Tasmota def split_into_chunks(input_string, chunk_size): @@ -38,20 +30,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)}' - logger.debug(message) + print(message) await client.publish(topic=topic, payload=payload, retain=retain) async def log_subscribe(client, topic): message = f'mqtt+{topic}' - logger.debug(message) + print(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)}' - logger.debug(message) + print(message) def callback_default(value, data=None): @@ -62,7 +54,21 @@ 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): @@ -86,20 +92,3 @@ 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/topics.py b/haco/topics.py deleted file mode 100644 index 72894fb..0000000 --- a/haco/topics.py +++ /dev/null @@ -1,208 +0,0 @@ -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/v0/haco/trigger.py b/haco/trigger.py similarity index 100% rename from haco/v0/haco/trigger.py rename to haco/trigger.py diff --git a/haco/v0/haco/tuya.py b/haco/tuya.py similarity index 100% rename from haco/v0/haco/tuya.py rename to haco/tuya.py diff --git a/haco/uom.py b/haco/uom.py deleted file mode 100644 index dc579ac..0000000 --- a/haco/uom.py +++ /dev/null @@ -1,144 +0,0 @@ -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 deleted file mode 100644 index 67dc687..0000000 --- a/haco/utils.py +++ /dev/null @@ -1,88 +0,0 @@ -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/haco/v0/assets/air_fryer_cookbook.png b/haco/v0/assets/air_fryer_cookbook.png deleted file mode 100644 index fb2bfbe..0000000 Binary files a/haco/v0/assets/air_fryer_cookbook.png and /dev/null differ diff --git a/haco/v0/assets/greeter_select.png b/haco/v0/assets/greeter_select.png deleted file mode 100644 index ff3546f..0000000 Binary files a/haco/v0/assets/greeter_select.png and /dev/null differ diff --git a/haco/v0/assets/memory_sensor.png b/haco/v0/assets/memory_sensor.png deleted file mode 100644 index 6297a7e..0000000 Binary files a/haco/v0/assets/memory_sensor.png and /dev/null differ diff --git a/haco/v0/assets/restart_button.png b/haco/v0/assets/restart_button.png deleted file mode 100644 index 0a447fd..0000000 Binary files a/haco/v0/assets/restart_button.png and /dev/null differ diff --git a/haco/v0/assets/weblog_select.png b/haco/v0/assets/weblog_select.png deleted file mode 100644 index a407421..0000000 Binary files a/haco/v0/assets/weblog_select.png and /dev/null differ diff --git a/haco/v0/berry/haco_autoexec.be b/haco/v0/berry/haco_autoexec.be deleted file mode 100644 index 4d0f0ad..0000000 --- a/haco/v0/berry/haco_autoexec.be +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 1701bfd..0000000 --- a/haco/v0/berry/haco_version.be +++ /dev/null @@ -1,8 +0,0 @@ -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/haco/v0/configs/__init__.py b/haco/v0/configs/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/haco/v0/configs/demo.py b/haco/v0/configs/demo.py deleted file mode 100644 index 74b85a0..0000000 --- a/haco/v0/configs/demo.py +++ /dev/null @@ -1,45 +0,0 @@ -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/v0/configs/test.py b/haco/v0/configs/test.py deleted file mode 100644 index a1eccc7..0000000 --- a/haco/v0/configs/test.py +++ /dev/null @@ -1,25 +0,0 @@ -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 deleted file mode 100644 index e69de29..0000000 diff --git a/haco/v0/data/type_binary_sensor.py b/haco/v0/data/type_binary_sensor.py deleted file mode 100644 index dc4b1b0..0000000 --- a/haco/v0/data/type_binary_sensor.py +++ /dev/null @@ -1,36 +0,0 @@ -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 deleted file mode 100644 index 3ba873e..0000000 --- a/haco/v0/data/type_sensor.py +++ /dev/null @@ -1,58 +0,0 @@ -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 deleted file mode 100755 index 45e6945..0000000 --- a/haco/v0/docker-compose.yml +++ /dev/null @@ -1,13 +0,0 @@ -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/haco/v0/ha/addon/DOCS.md b/haco/v0/ha/addon/DOCS.md deleted file mode 100644 index bfffc09..0000000 --- a/haco/v0/ha/addon/DOCS.md +++ /dev/null @@ -1 +0,0 @@ -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 deleted file mode 100644 index 61e4d62..0000000 --- a/haco/v0/ha/addon/Dockerfile +++ /dev/null @@ -1,11 +0,0 @@ -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 deleted file mode 120000 index fe84005..0000000 --- a/haco/v0/ha/addon/README.md +++ /dev/null @@ -1 +0,0 @@ -../../README.md \ No newline at end of file diff --git a/haco/v0/ha/addon/config.yaml b/haco/v0/ha/addon/config.yaml deleted file mode 100644 index 0083fa5..0000000 --- a/haco/v0/ha/addon/config.yaml +++ /dev/null @@ -1,25 +0,0 @@ -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 deleted file mode 100644 index 083550a..0000000 Binary files a/haco/v0/ha/addon/icon.png and /dev/null differ diff --git a/haco/v0/ha/addon/logo.png b/haco/v0/ha/addon/logo.png deleted file mode 100644 index f1cd97e..0000000 Binary files a/haco/v0/ha/addon/logo.png and /dev/null differ diff --git a/haco/v0/haco/__init__.py b/haco/v0/haco/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/haco/v0/haco/button.py b/haco/v0/haco/button.py deleted file mode 100644 index b7b7216..0000000 --- a/haco/v0/haco/button.py +++ /dev/null @@ -1,22 +0,0 @@ -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/v0/haco/climate.py b/haco/v0/haco/climate.py deleted file mode 100644 index da441eb..0000000 --- a/haco/v0/haco/climate.py +++ /dev/null @@ -1,112 +0,0 @@ -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 deleted file mode 100644 index 3d659b2..0000000 --- a/haco/v0/haco/constants.py +++ /dev/null @@ -1,24 +0,0 @@ -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 deleted file mode 100644 index af6cfbe..0000000 --- a/haco/v0/haco/control.py +++ /dev/null @@ -1,116 +0,0 @@ -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 deleted file mode 100644 index 2a7a8e2..0000000 --- a/haco/v0/haco/debugging.py +++ /dev/null @@ -1,57 +0,0 @@ -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 deleted file mode 100644 index 21a3cf5..0000000 --- a/haco/v0/haco/device.py +++ /dev/null @@ -1,119 +0,0 @@ -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 deleted file mode 100644 index 58d0c31..0000000 --- a/haco/v0/haco/device_data.py +++ /dev/null @@ -1,48 +0,0 @@ -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 deleted file mode 100644 index ff1128d..0000000 --- a/haco/v0/haco/load_configs.py +++ /dev/null @@ -1,63 +0,0 @@ -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 deleted file mode 100644 index f1f3c1c..0000000 --- a/haco/v0/haco/mqtt.py +++ /dev/null @@ -1,76 +0,0 @@ -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/v0/haco/update.py b/haco/v0/haco/update.py deleted file mode 100644 index e5c6dae..0000000 --- a/haco/v0/haco/update.py +++ /dev/null @@ -1,40 +0,0 @@ -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/haco/version b/haco/version new file mode 100644 index 0000000..7bcd0e3 --- /dev/null +++ b/haco/version @@ -0,0 +1 @@ +0.0.2 \ No newline at end of file diff --git a/pyproject.toml b/pyproject.toml deleted file mode 100644 index 8e8059d..0000000 --- a/pyproject.toml +++ /dev/null @@ -1,86 +0,0 @@ -[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 deleted file mode 100644 index e267c3b..0000000 --- a/repository.yaml +++ /dev/null @@ -1,3 +0,0 @@ -name: haco -url: 'https://github.com/fmtr/haco' -maintainer: Frontmatter \ No newline at end of file diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..440ca38 --- /dev/null +++ b/setup.py @@ -0,0 +1,38 @@ +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', + ], + } +) diff --git a/haco/v0/update_version.py b/update_version.py similarity index 99% rename from haco/v0/update_version.py rename to update_version.py index 91c2eb1..167cbe2 100644 --- a/haco/v0/update_version.py +++ b/update_version.py @@ -1,5 +1,6 @@ -import re import sys + +import re from pathlib import Path PATH_ROOT = Path(__file__).parent.absolute()