mirror of
https://github.com/fmtr/haco.git
synced 2026-12-04 22:00:13 -05:00
117 lines
2.5 KiB
Python
117 lines
2.5 KiB
Python
from __future__ import annotations
|
|
|
|
from functools import cached_property
|
|
from pathlib import Path
|
|
from typing import List, TYPE_CHECKING
|
|
|
|
from pydantic import Field
|
|
|
|
from haco.base import Base
|
|
from haco.control import Control
|
|
from haco.utils import sanitize_name
|
|
|
|
if TYPE_CHECKING:
|
|
from haco.client import ClientHaco
|
|
|
|
|
|
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]
|
|
|
|
for control in self.controls:
|
|
control.set_parent(self)
|
|
self.subscriptions = self.get_subscriptions()
|
|
|
|
@cached_property
|
|
def topic(self) -> Path:
|
|
"""
|
|
|
|
The MQTT topic prefix for the device.
|
|
|
|
"""
|
|
return self.client.topic / self.name_san
|
|
|
|
@property
|
|
def name_san(self) -> str:
|
|
"""
|
|
|
|
Sanitized name of the device.
|
|
|
|
"""
|
|
return sanitize_name(self.name)
|
|
|
|
async def announce(self):
|
|
"""
|
|
|
|
Announce all controls of the device to Home Assistant.
|
|
|
|
"""
|
|
for control in self.controls:
|
|
await control.announce()
|
|
|
|
async def initialise(self):
|
|
"""
|
|
|
|
Initialise all controls of the device.
|
|
|
|
"""
|
|
for control in self.controls:
|
|
await control.initialise()
|
|
|
|
|
|
@property
|
|
def client(self) -> ClientHaco:
|
|
"""
|
|
|
|
The parent client of the device.
|
|
|
|
"""
|
|
return self.parent
|
|
|
|
def get_subscriptions(self) -> dict:
|
|
"""
|
|
|
|
Get all MQTT topic subscriptions for the device's controls.
|
|
|
|
"""
|
|
data = {}
|
|
for control in self.controls:
|
|
data |= control.subscriptions
|
|
|
|
return data
|
|
|
|
|
|
if __name__ == "__main__":
|
|
control = Control(name="test", platform="test")
|
|
device = Device(name="test", parent=None, controls=[control])
|
|
data = device.model_dump()
|
|
print(device.topic)
|