mirror of
https://github.com/home-assistant/core.git
synced 2026-04-15 22:26:12 +02:00
Compare commits
89 Commits
deprecate_
...
dev
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
49e5b03c08 | ||
|
|
6bc3fcef36 | ||
|
|
e3e87185c5 | ||
|
|
6d83b73cbb | ||
|
|
533871babb | ||
|
|
1dc93a80c4 | ||
|
|
f8a94c6f22 | ||
|
|
b127d13587 | ||
|
|
1895f8ebce | ||
|
|
b6916954dc | ||
|
|
23181f5275 | ||
|
|
607a10d1e1 | ||
|
|
ecb814adb0 | ||
|
|
67df556e84 | ||
|
|
4d472418c5 | ||
|
|
cf6441561c | ||
|
|
6d8d447355 | ||
|
|
ab5ae33290 | ||
|
|
c0bf9a2bd2 | ||
|
|
d862b999ae | ||
|
|
d6be6e8810 | ||
|
|
f397f4c908 | ||
|
|
d58e7862c0 | ||
|
|
84f57f9859 | ||
|
|
c6169ec8eb | ||
|
|
c47cecf350 | ||
|
|
e31f611901 | ||
|
|
bc36b1dda2 | ||
|
|
b3967130f0 | ||
|
|
2960db3d8e | ||
|
|
a74cf69607 | ||
|
|
d3e346c728 | ||
|
|
efb93c928e | ||
|
|
b7894407d2 | ||
|
|
0b7da89e6e | ||
|
|
c765077442 | ||
|
|
efbfeb7c30 | ||
|
|
5670a12805 | ||
|
|
d88fe45393 | ||
|
|
b231742049 | ||
|
|
99dc368c79 | ||
|
|
a21a0a6577 | ||
|
|
513fff12ac | ||
|
|
4474ad0450 | ||
|
|
a5d640acdb | ||
|
|
da66632798 | ||
|
|
f5998856b4 | ||
|
|
d5441ff99e | ||
|
|
3848d4e8a6 | ||
|
|
599c548264 | ||
|
|
b18602cd18 | ||
|
|
a45e2d74ec | ||
|
|
a952636c28 | ||
|
|
ccd1d9f8ea | ||
|
|
a4d4fe3722 | ||
|
|
98b41d25f3 | ||
|
|
d8c8f82c7e | ||
|
|
8695d32b32 | ||
|
|
073d22d046 | ||
|
|
939412717f | ||
|
|
8217d3683a | ||
|
|
fa9185b755 | ||
|
|
f2f59eb8b7 | ||
|
|
16edfc9624 | ||
|
|
177d244b91 | ||
|
|
dd8a79bd0e | ||
|
|
3c46ecb93a | ||
|
|
66b2d4477b | ||
|
|
2ba66fb722 | ||
|
|
9fab53d083 | ||
|
|
41c3db9ebd | ||
|
|
3d0d048d1f | ||
|
|
c57a666921 | ||
|
|
3cd67cea53 | ||
|
|
e05622f8d0 | ||
|
|
c17d3584cb | ||
|
|
3f3b3db913 | ||
|
|
44a0e964ef | ||
|
|
d6e56b41b1 | ||
|
|
4191bbf504 | ||
|
|
041fed4b48 | ||
|
|
6311e6feec | ||
|
|
582a0a5ae3 | ||
|
|
1a3f75c6fc | ||
|
|
21301e43a9 | ||
|
|
cbe7823fd5 | ||
|
|
7a5951b72d | ||
|
|
42771ed0a7 | ||
|
|
ded34b4430 |
@@ -186,15 +186,11 @@ If `CHANGE_TYPE` IS "Breaking change" or "Deprecation", keep the `## Breaking ch
|
||||
|
||||
## Step 10: Push Branch and Create PR
|
||||
|
||||
```bash
|
||||
# Get branch name and GitHub username
|
||||
BRANCH=$(git branch --show-current)
|
||||
PUSH_REMOTE=$(git config "branch.$BRANCH.remote" 2>/dev/null || git remote | head -1)
|
||||
GITHUB_USER=$(gh api user --jq .login 2>/dev/null || git remote get-url "$PUSH_REMOTE" | sed -E 's#.*[:/]([^/]+)/([^/]+)(\.git)?$#\1#')
|
||||
Push the branch with upstream tracking, and create a PR against `home-assistant/core` with the generated title and body:
|
||||
|
||||
```bash
|
||||
# Create PR (gh pr create pushes the branch automatically)
|
||||
gh pr create --repo home-assistant/core --base dev \
|
||||
--head "$GITHUB_USER:$BRANCH" \
|
||||
--draft \
|
||||
--title "TITLE_HERE" \
|
||||
--body "$(cat <<'EOF'
|
||||
|
||||
161
.github/renovate.json
vendored
Normal file
161
.github/renovate.json
vendored
Normal file
@@ -0,0 +1,161 @@
|
||||
{
|
||||
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
|
||||
"extends": ["config:recommended"],
|
||||
|
||||
"enabledManagers": [
|
||||
"pep621",
|
||||
"pip_requirements",
|
||||
"pre-commit",
|
||||
"homeassistant-manifest"
|
||||
],
|
||||
|
||||
"pre-commit": {
|
||||
"enabled": true
|
||||
},
|
||||
|
||||
"pip_requirements": {
|
||||
"managerFilePatterns": [
|
||||
"/(^|/)requirements[\\w_-]*\\.txt$/",
|
||||
"/(^|/)homeassistant/package_constraints\\.txt$/"
|
||||
]
|
||||
},
|
||||
|
||||
"homeassistant-manifest": {
|
||||
"managerFilePatterns": [
|
||||
"/^homeassistant/components/[^/]+/manifest\\.json$/"
|
||||
]
|
||||
},
|
||||
|
||||
"minimumReleaseAge": "7 days",
|
||||
"prConcurrentLimit": 10,
|
||||
"prHourlyLimit": 2,
|
||||
"schedule": ["before 6am"],
|
||||
|
||||
"semanticCommits": "disabled",
|
||||
"commitMessageAction": "Update",
|
||||
"commitMessageTopic": "{{depName}}",
|
||||
"commitMessageExtra": "to {{newVersion}}",
|
||||
|
||||
"automerge": false,
|
||||
|
||||
"vulnerabilityAlerts": {
|
||||
"enabled": false
|
||||
},
|
||||
|
||||
"packageRules": [
|
||||
{
|
||||
"description": "Deny all by default — allowlist below re-enables specific packages",
|
||||
"matchPackageNames": ["*"],
|
||||
"enabled": false
|
||||
},
|
||||
{
|
||||
"description": "Core runtime dependencies (allowlisted)",
|
||||
"matchPackageNames": [
|
||||
"aiohttp",
|
||||
"aiohttp-fast-zlib",
|
||||
"aiohttp_cors",
|
||||
"aiohttp-asyncmdnsresolver",
|
||||
"yarl",
|
||||
"httpx",
|
||||
"requests",
|
||||
"urllib3",
|
||||
"certifi",
|
||||
"orjson",
|
||||
"PyYAML",
|
||||
"Jinja2",
|
||||
"cryptography",
|
||||
"pyOpenSSL",
|
||||
"PyJWT",
|
||||
"SQLAlchemy",
|
||||
"Pillow",
|
||||
"attrs",
|
||||
"uv",
|
||||
"voluptuous",
|
||||
"voluptuous-serialize",
|
||||
"voluptuous-openapi",
|
||||
"zeroconf"
|
||||
],
|
||||
"enabled": true,
|
||||
"labels": ["dependency", "core"]
|
||||
},
|
||||
{
|
||||
"description": "Test dependencies (allowlisted)",
|
||||
"matchPackageNames": [
|
||||
"pytest",
|
||||
"pytest-asyncio",
|
||||
"pytest-aiohttp",
|
||||
"pytest-cov",
|
||||
"pytest-freezer",
|
||||
"pytest-github-actions-annotate-failures",
|
||||
"pytest-socket",
|
||||
"pytest-sugar",
|
||||
"pytest-timeout",
|
||||
"pytest-unordered",
|
||||
"pytest-picked",
|
||||
"pytest-xdist",
|
||||
"pylint",
|
||||
"pylint-per-file-ignores",
|
||||
"astroid",
|
||||
"coverage",
|
||||
"freezegun",
|
||||
"syrupy",
|
||||
"respx",
|
||||
"requests-mock",
|
||||
"ruff",
|
||||
"codespell",
|
||||
"yamllint",
|
||||
"zizmor"
|
||||
],
|
||||
"enabled": true,
|
||||
"labels": ["dependency"]
|
||||
},
|
||||
{
|
||||
"description": "For types-* stubs, only allow patch updates. Major/minor bumps track the upstream runtime package version and must be manually coordinated with the corresponding pin.",
|
||||
"matchPackageNames": ["/^types-/"],
|
||||
"matchUpdateTypes": ["patch"],
|
||||
"enabled": true,
|
||||
"labels": ["dependency"]
|
||||
},
|
||||
{
|
||||
"description": "Pre-commit hook repos (allowlisted, matched by owner/repo)",
|
||||
"matchPackageNames": [
|
||||
"astral-sh/ruff-pre-commit",
|
||||
"codespell-project/codespell",
|
||||
"adrienverge/yamllint",
|
||||
"zizmorcore/zizmor-pre-commit"
|
||||
],
|
||||
"enabled": true,
|
||||
"labels": ["dependency"]
|
||||
},
|
||||
{
|
||||
"description": "Group ruff pre-commit hook with its PyPI twin into one PR",
|
||||
"matchPackageNames": ["astral-sh/ruff-pre-commit", "ruff"],
|
||||
"groupName": "ruff",
|
||||
"groupSlug": "ruff"
|
||||
},
|
||||
{
|
||||
"description": "Group codespell pre-commit hook with its PyPI twin into one PR",
|
||||
"matchPackageNames": ["codespell-project/codespell", "codespell"],
|
||||
"groupName": "codespell",
|
||||
"groupSlug": "codespell"
|
||||
},
|
||||
{
|
||||
"description": "Group yamllint pre-commit hook with its PyPI twin into one PR",
|
||||
"matchPackageNames": ["adrienverge/yamllint", "yamllint"],
|
||||
"groupName": "yamllint",
|
||||
"groupSlug": "yamllint"
|
||||
},
|
||||
{
|
||||
"description": "Group zizmor pre-commit hook with its PyPI twin into one PR",
|
||||
"matchPackageNames": ["zizmorcore/zizmor-pre-commit", "zizmor"],
|
||||
"groupName": "zizmor",
|
||||
"groupSlug": "zizmor"
|
||||
},
|
||||
{
|
||||
"description": "Group pylint with astroid (their versions are linked and must move together)",
|
||||
"matchPackageNames": ["pylint", "astroid"],
|
||||
"groupName": "pylint",
|
||||
"groupSlug": "pylint"
|
||||
}
|
||||
]
|
||||
}
|
||||
8
.github/workflows/ci.yaml
vendored
8
.github/workflows/ci.yaml
vendored
@@ -50,9 +50,11 @@ env:
|
||||
# - 10.10.3 is the latest (as of 6 Feb 2023)
|
||||
# 10.11 is the latest long-term-support
|
||||
# - 10.11.2 is the version currently shipped with Synology (as of 11 Oct 2023)
|
||||
# 11.4 is an LTS with support until May 2029
|
||||
# - 11.4.9 is used in Alpine 3.23 (used in latest HA base images as of 11 Apr 2026)
|
||||
# mysql 8.0.32 does not always behave the same as MariaDB
|
||||
# and some queries that work on MariaDB do not work on MySQL
|
||||
MARIADB_VERSIONS: "['mariadb:10.3.32','mariadb:10.6.10','mariadb:10.10.3','mariadb:10.11.2','mysql:8.0.32']"
|
||||
MARIADB_VERSIONS: "['mariadb:10.3.32','mariadb:10.6.10','mariadb:10.10.3','mariadb:10.11.2','mariadb:11.4.9','mysql:8.0.32']"
|
||||
# 12 is the oldest supported version
|
||||
# - 12.14 is the latest (as of 9 Feb 2023)
|
||||
# 15 is the latest version
|
||||
@@ -1062,7 +1064,9 @@ jobs:
|
||||
- 3306:3306
|
||||
env:
|
||||
MYSQL_ROOT_PASSWORD: password
|
||||
options: --health-cmd="mysqladmin ping -uroot -ppassword" --health-interval=5s --health-timeout=2s --health-retries=3
|
||||
options: >-
|
||||
--health-cmd="if command -v mariadb-admin >/dev/null; then mariadb-admin ping -uroot -ppassword; else mysqladmin ping -uroot -ppassword; fi"
|
||||
--health-interval=5s --health-timeout=2s --health-retries=3
|
||||
needs:
|
||||
- info
|
||||
- base
|
||||
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -142,5 +142,6 @@ pytest_buckets.txt
|
||||
|
||||
# AI tooling
|
||||
.claude/settings.local.json
|
||||
.claude/worktrees/
|
||||
.serena/
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ repos:
|
||||
- id: ruff-format
|
||||
files: ^((homeassistant|pylint|script|tests)/.+)?[^/]+\.(py|pyi)$
|
||||
- repo: https://github.com/codespell-project/codespell
|
||||
rev: v2.4.1
|
||||
rev: v2.4.2
|
||||
hooks:
|
||||
- id: codespell
|
||||
args:
|
||||
@@ -36,7 +36,7 @@ repos:
|
||||
- --branch=master
|
||||
- --branch=rc
|
||||
- repo: https://github.com/adrienverge/yamllint.git
|
||||
rev: v1.37.1
|
||||
rev: v1.38.0
|
||||
hooks:
|
||||
- id: yamllint
|
||||
- repo: https://github.com/rbubley/mirrors-prettier
|
||||
|
||||
4
CODEOWNERS
generated
4
CODEOWNERS
generated
@@ -1877,8 +1877,8 @@ CLAUDE.md @home-assistant/core
|
||||
/tests/components/version/ @ludeeus
|
||||
/homeassistant/components/vesync/ @markperdue @webdjoe @thegardenmonkey @cdnninja @iprak @sapuseven
|
||||
/tests/components/vesync/ @markperdue @webdjoe @thegardenmonkey @cdnninja @iprak @sapuseven
|
||||
/homeassistant/components/vicare/ @CFenner
|
||||
/tests/components/vicare/ @CFenner
|
||||
/homeassistant/components/vicare/ @CFenner @lackas
|
||||
/tests/components/vicare/ @CFenner @lackas
|
||||
/homeassistant/components/victron_ble/ @rajlaud
|
||||
/tests/components/victron_ble/ @rajlaud
|
||||
/homeassistant/components/victron_gx/ @tomer-w
|
||||
|
||||
16
Dockerfile
generated
16
Dockerfile
generated
@@ -19,25 +19,23 @@ ENV \
|
||||
UV_SYSTEM_PYTHON=true \
|
||||
UV_NO_CACHE=true
|
||||
|
||||
WORKDIR /usr/src
|
||||
|
||||
# Home Assistant S6-Overlay
|
||||
COPY rootfs /
|
||||
|
||||
# Add go2rtc binary
|
||||
COPY --from=ghcr.io/alexxit/go2rtc@sha256:675c318b23c06fd862a61d262240c9a63436b4050d177ffc68a32710d9e05bae /usr/local/bin/go2rtc /bin/go2rtc
|
||||
|
||||
RUN \
|
||||
# Verify go2rtc can be executed
|
||||
go2rtc --version \
|
||||
# Install uv
|
||||
&& pip3 install uv==0.11.1
|
||||
|
||||
WORKDIR /usr/src
|
||||
|
||||
## Setup Home Assistant Core dependencies
|
||||
COPY requirements.txt homeassistant/
|
||||
COPY homeassistant/package_constraints.txt homeassistant/homeassistant/
|
||||
RUN \
|
||||
uv pip install \
|
||||
# Verify go2rtc can be executed
|
||||
go2rtc --version \
|
||||
# Install uv at the version pinned in the requirements file
|
||||
&& pip3 install --no-cache-dir "uv==$(awk -F'==' '/^uv==/{print $2}' homeassistant/requirements.txt)" \
|
||||
&& uv pip install \
|
||||
--no-build \
|
||||
-r homeassistant/requirements.txt
|
||||
|
||||
|
||||
@@ -57,9 +57,9 @@ rules:
|
||||
entity-category: done
|
||||
entity-device-class: todo
|
||||
entity-disabled-by-default: todo
|
||||
entity-translations: todo
|
||||
entity-translations: done
|
||||
exception-translations: done
|
||||
icon-translations: todo
|
||||
icon-translations: done
|
||||
reconfiguration-flow: todo
|
||||
repair-issues:
|
||||
status: exempt
|
||||
|
||||
@@ -11,12 +11,12 @@
|
||||
"user": {
|
||||
"data": {
|
||||
"tracked_apps": "Apps",
|
||||
"tracked_custom_integrations": "Community integrations",
|
||||
"tracked_custom_integrations": "Custom integrations",
|
||||
"tracked_integrations": "Integrations"
|
||||
},
|
||||
"data_description": {
|
||||
"tracked_apps": "Select the apps you want to track",
|
||||
"tracked_custom_integrations": "Select the community integrations you want to track",
|
||||
"tracked_custom_integrations": "Select the custom integrations you want to track",
|
||||
"tracked_integrations": "Select the integrations you want to track"
|
||||
}
|
||||
}
|
||||
@@ -31,7 +31,7 @@
|
||||
"unit_of_measurement": "[%key:component::analytics_insights::entity::sensor::apps::unit_of_measurement%]"
|
||||
},
|
||||
"custom_integrations": {
|
||||
"name": "{custom_integration_domain} (community)",
|
||||
"name": "{custom_integration_domain} (custom)",
|
||||
"unit_of_measurement": "[%key:component::analytics_insights::entity::sensor::apps::unit_of_measurement%]"
|
||||
},
|
||||
"total_active_installations": {
|
||||
|
||||
@@ -143,6 +143,7 @@ _EXPERIMENTAL_CONDITION_PLATFORMS = {
|
||||
"occupancy",
|
||||
"person",
|
||||
"power",
|
||||
"remote",
|
||||
"schedule",
|
||||
"select",
|
||||
"siren",
|
||||
@@ -150,6 +151,8 @@ _EXPERIMENTAL_CONDITION_PLATFORMS = {
|
||||
"temperature",
|
||||
"text",
|
||||
"timer",
|
||||
"todo",
|
||||
"update",
|
||||
"vacuum",
|
||||
"valve",
|
||||
"water_heater",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"issues": {
|
||||
"integration_removed": {
|
||||
"description": "The BMW Connected Drive integration has been removed from Home Assistant.\n\nIn September 2025, BMW blocked third-party access to their servers by adding additional security measures. For EU-registered cars, a [community integration]({custom_component_url}) using BMW's CarData API is available as an alternative.\n\nTo resolve this issue, please remove the (now defunct) integration entries from your Home Assistant setup. [Click here to see your existing BMW Connected Drive integration entries]({entries}).",
|
||||
"description": "The BMW Connected Drive integration has been removed from Home Assistant.\n\nIn September 2025, BMW blocked third-party access to their servers by adding additional security measures. For EU-registered cars, a community-developed [custom component]({custom_component_url}) using BMW's CarData API is available as an alternative.\n\nTo resolve this issue, please remove the (now defunct) integration entries from your Home Assistant setup. [Click here to see your existing BMW Connected Drive integration entries]({entries}).",
|
||||
"title": "The BMW Connected Drive integration has been removed"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,5 +6,5 @@
|
||||
"iot_class": "local_polling",
|
||||
"loggers": ["pydoods"],
|
||||
"quality_scale": "legacy",
|
||||
"requirements": ["pydoods==1.0.2", "Pillow==12.1.1"]
|
||||
"requirements": ["pydoods==1.0.2", "Pillow==12.2.0"]
|
||||
}
|
||||
|
||||
@@ -5,5 +5,5 @@ from datetime import timedelta
|
||||
from homeassistant.const import Platform
|
||||
|
||||
DOMAIN = "duco"
|
||||
PLATFORMS = [Platform.FAN]
|
||||
PLATFORMS = [Platform.FAN, Platform.SENSOR]
|
||||
SCAN_INTERVAL = timedelta(seconds=30)
|
||||
|
||||
53
homeassistant/components/duco/diagnostics.py
Normal file
53
homeassistant/components/duco/diagnostics.py
Normal file
@@ -0,0 +1,53 @@
|
||||
"""Diagnostics support for Duco."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from dataclasses import asdict
|
||||
from typing import Any
|
||||
|
||||
from homeassistant.components.diagnostics import async_redact_data
|
||||
from homeassistant.const import CONF_HOST
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
from .coordinator import DucoConfigEntry
|
||||
|
||||
TO_REDACT = {
|
||||
CONF_HOST,
|
||||
"mac",
|
||||
"host_name",
|
||||
"serial_board_box",
|
||||
"serial_board_comm",
|
||||
"serial_duco_box",
|
||||
"serial_duco_comm",
|
||||
}
|
||||
|
||||
|
||||
async def async_get_config_entry_diagnostics(
|
||||
hass: HomeAssistant, entry: DucoConfigEntry
|
||||
) -> dict[str, Any]:
|
||||
"""Return diagnostics for a config entry."""
|
||||
coordinator = entry.runtime_data
|
||||
|
||||
board = asdict(coordinator.board_info)
|
||||
board.pop("time")
|
||||
|
||||
lan_info, duco_diags, write_remaining = await asyncio.gather(
|
||||
coordinator.client.async_get_lan_info(),
|
||||
coordinator.client.async_get_diagnostics(),
|
||||
coordinator.client.async_get_write_req_remaining(),
|
||||
)
|
||||
|
||||
return async_redact_data(
|
||||
{
|
||||
"entry_data": entry.data,
|
||||
"board_info": board,
|
||||
"lan_info": asdict(lan_info),
|
||||
"nodes": {
|
||||
str(node_id): asdict(node) for node_id, node in coordinator.data.items()
|
||||
},
|
||||
"duco_diagnostics": [asdict(d) for d in duco_diags],
|
||||
"write_requests_remaining": write_remaining,
|
||||
},
|
||||
TO_REDACT,
|
||||
)
|
||||
15
homeassistant/components/duco/icons.json
Normal file
15
homeassistant/components/duco/icons.json
Normal file
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"entity": {
|
||||
"sensor": {
|
||||
"iaq_co2": {
|
||||
"default": "mdi:molecule-co2"
|
||||
},
|
||||
"iaq_rh": {
|
||||
"default": "mdi:water-percent"
|
||||
},
|
||||
"ventilation_state": {
|
||||
"default": "mdi:tune-variant"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -45,7 +45,7 @@ rules:
|
||||
|
||||
# Gold
|
||||
devices: done
|
||||
diagnostics: todo
|
||||
diagnostics: done
|
||||
discovery-update-info:
|
||||
status: todo
|
||||
comment: >-
|
||||
@@ -71,11 +71,11 @@ rules:
|
||||
Users can pair new modules (CO2 sensors, humidity sensors, zone valves)
|
||||
to their Duco box. Dynamic device support to be added in a follow-up PR.
|
||||
entity-category: todo
|
||||
entity-device-class: todo
|
||||
entity-disabled-by-default: todo
|
||||
entity-device-class: done
|
||||
entity-disabled-by-default: done
|
||||
entity-translations: done
|
||||
exception-translations: todo
|
||||
icon-translations: todo
|
||||
exception-translations: done
|
||||
icon-translations: done
|
||||
reconfiguration-flow: todo
|
||||
repair-issues: todo
|
||||
stale-devices:
|
||||
|
||||
119
homeassistant/components/duco/sensor.py
Normal file
119
homeassistant/components/duco/sensor.py
Normal file
@@ -0,0 +1,119 @@
|
||||
"""Sensor platform for the Duco integration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
|
||||
from duco.models import Node, NodeType, VentilationState
|
||||
|
||||
from homeassistant.components.sensor import (
|
||||
SensorDeviceClass,
|
||||
SensorEntity,
|
||||
SensorEntityDescription,
|
||||
SensorStateClass,
|
||||
)
|
||||
from homeassistant.const import CONCENTRATION_PARTS_PER_MILLION, PERCENTAGE
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
|
||||
|
||||
from .coordinator import DucoConfigEntry, DucoCoordinator
|
||||
from .entity import DucoEntity
|
||||
|
||||
PARALLEL_UPDATES = 0
|
||||
|
||||
|
||||
@dataclass(frozen=True, kw_only=True)
|
||||
class DucoSensorEntityDescription(SensorEntityDescription):
|
||||
"""Duco sensor entity description."""
|
||||
|
||||
value_fn: Callable[[Node], int | float | str | None]
|
||||
node_types: tuple[NodeType, ...]
|
||||
|
||||
|
||||
SENSOR_DESCRIPTIONS: tuple[DucoSensorEntityDescription, ...] = (
|
||||
DucoSensorEntityDescription(
|
||||
key="ventilation_state",
|
||||
translation_key="ventilation_state",
|
||||
device_class=SensorDeviceClass.ENUM,
|
||||
options=[s.lower() for s in VentilationState],
|
||||
value_fn=lambda node: (
|
||||
node.ventilation.state.lower() if node.ventilation else None
|
||||
),
|
||||
node_types=(NodeType.BOX,),
|
||||
),
|
||||
DucoSensorEntityDescription(
|
||||
key="co2",
|
||||
device_class=SensorDeviceClass.CO2,
|
||||
state_class=SensorStateClass.MEASUREMENT,
|
||||
native_unit_of_measurement=CONCENTRATION_PARTS_PER_MILLION,
|
||||
value_fn=lambda node: node.sensor.co2 if node.sensor else None,
|
||||
node_types=(NodeType.UCCO2,),
|
||||
),
|
||||
DucoSensorEntityDescription(
|
||||
key="iaq_co2",
|
||||
translation_key="iaq_co2",
|
||||
native_unit_of_measurement=PERCENTAGE,
|
||||
state_class=SensorStateClass.MEASUREMENT,
|
||||
entity_registry_enabled_default=False,
|
||||
value_fn=lambda node: node.sensor.iaq_co2 if node.sensor else None,
|
||||
node_types=(NodeType.UCCO2,),
|
||||
),
|
||||
DucoSensorEntityDescription(
|
||||
key="humidity",
|
||||
device_class=SensorDeviceClass.HUMIDITY,
|
||||
state_class=SensorStateClass.MEASUREMENT,
|
||||
native_unit_of_measurement=PERCENTAGE,
|
||||
value_fn=lambda node: node.sensor.rh if node.sensor else None,
|
||||
node_types=(NodeType.BSRH,),
|
||||
),
|
||||
DucoSensorEntityDescription(
|
||||
key="iaq_rh",
|
||||
translation_key="iaq_rh",
|
||||
native_unit_of_measurement=PERCENTAGE,
|
||||
state_class=SensorStateClass.MEASUREMENT,
|
||||
entity_registry_enabled_default=False,
|
||||
value_fn=lambda node: node.sensor.iaq_rh if node.sensor else None,
|
||||
node_types=(NodeType.BSRH,),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
async def async_setup_entry(
|
||||
hass: HomeAssistant,
|
||||
entry: DucoConfigEntry,
|
||||
async_add_entities: AddConfigEntryEntitiesCallback,
|
||||
) -> None:
|
||||
"""Set up Duco sensor entities."""
|
||||
coordinator = entry.runtime_data
|
||||
|
||||
async_add_entities(
|
||||
DucoSensorEntity(coordinator, node, description)
|
||||
for node in coordinator.data.values()
|
||||
for description in SENSOR_DESCRIPTIONS
|
||||
if node.general.node_type in description.node_types
|
||||
)
|
||||
|
||||
|
||||
class DucoSensorEntity(DucoEntity, SensorEntity):
|
||||
"""Sensor entity for a Duco node."""
|
||||
|
||||
entity_description: DucoSensorEntityDescription
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
coordinator: DucoCoordinator,
|
||||
node: Node,
|
||||
description: DucoSensorEntityDescription,
|
||||
) -> None:
|
||||
"""Initialize the sensor entity."""
|
||||
super().__init__(coordinator, node)
|
||||
self.entity_description = description
|
||||
self._attr_unique_id = (
|
||||
f"{coordinator.config_entry.unique_id}_{node.node_id}_{description.key}"
|
||||
)
|
||||
|
||||
@property
|
||||
def native_value(self) -> int | float | str | None:
|
||||
"""Return the sensor value."""
|
||||
return self.entity_description.value_fn(self._node)
|
||||
@@ -29,6 +29,36 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"sensor": {
|
||||
"iaq_co2": {
|
||||
"name": "CO2 air quality index"
|
||||
},
|
||||
"iaq_rh": {
|
||||
"name": "Humidity air quality index"
|
||||
},
|
||||
"ventilation_state": {
|
||||
"name": "Ventilation state",
|
||||
"state": {
|
||||
"aut1": "Automatic boost (15 min)",
|
||||
"aut2": "Automatic boost (30 min)",
|
||||
"aut3": "Automatic boost (45 min)",
|
||||
"auto": "Automatic",
|
||||
"cnt1": "Continuous low speed",
|
||||
"cnt2": "Continuous medium speed",
|
||||
"cnt3": "Continuous high speed",
|
||||
"empt": "Empty house",
|
||||
"man1": "Manual low speed (15 min)",
|
||||
"man1x2": "Manual low speed (30 min)",
|
||||
"man1x3": "Manual low speed (45 min)",
|
||||
"man2": "Manual medium speed (15 min)",
|
||||
"man2x2": "Manual medium speed (30 min)",
|
||||
"man2x3": "Manual medium speed (45 min)",
|
||||
"man3": "Manual high speed (15 min)",
|
||||
"man3x2": "Manual high speed (30 min)",
|
||||
"man3x3": "Manual high speed (45 min)"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"exceptions": {
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
"iot_class": "local_polling",
|
||||
"loggers": ["pyenphase"],
|
||||
"quality_scale": "platinum",
|
||||
"requirements": ["pyenphase==2.4.6"],
|
||||
"requirements": ["pyenphase==2.4.8"],
|
||||
"zeroconf": [
|
||||
{
|
||||
"type": "_enphase-envoy._tcp.local."
|
||||
|
||||
@@ -22,9 +22,8 @@ CONF_LOCATION_IDX: Final = "location_idx"
|
||||
SCAN_INTERVAL_DEFAULT: Final = timedelta(seconds=300)
|
||||
SCAN_INTERVAL_MINIMUM: Final = timedelta(seconds=60)
|
||||
|
||||
ATTR_PERIOD: Final = "period" # number of days
|
||||
ATTR_DURATION: Final = "duration" # number of minutes, <24h
|
||||
|
||||
ATTR_PERIOD: Final = "period" # number of days
|
||||
ATTR_SETPOINT: Final = "setpoint"
|
||||
|
||||
|
||||
@@ -37,3 +36,4 @@ class EvoService(StrEnum):
|
||||
RESET_SYSTEM = "reset_system"
|
||||
SET_ZONE_OVERRIDE = "set_zone_override"
|
||||
CLEAR_ZONE_OVERRIDE = "clear_zone_override"
|
||||
SET_DHW_OVERRIDE = "set_dhw_override"
|
||||
|
||||
@@ -22,6 +22,9 @@
|
||||
"reset_system": {
|
||||
"service": "mdi:refresh"
|
||||
},
|
||||
"set_dhw_override": {
|
||||
"service": "mdi:water-heater"
|
||||
},
|
||||
"set_system_mode": {
|
||||
"service": "mdi:pencil"
|
||||
},
|
||||
|
||||
@@ -14,7 +14,8 @@ from evohomeasync2.schemas.const import (
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.components.climate import DOMAIN as CLIMATE_DOMAIN
|
||||
from homeassistant.const import ATTR_MODE
|
||||
from homeassistant.components.water_heater import DOMAIN as WATER_HEATER_DOMAIN
|
||||
from homeassistant.const import ATTR_MODE, ATTR_STATE
|
||||
from homeassistant.core import HomeAssistant, ServiceCall, callback
|
||||
from homeassistant.exceptions import ServiceValidationError
|
||||
from homeassistant.helpers import config_validation as cv, service
|
||||
@@ -49,6 +50,15 @@ SET_ZONE_OVERRIDE_SCHEMA: Final[dict[str | vol.Marker, Any]] = {
|
||||
),
|
||||
}
|
||||
|
||||
# DHW service schemas (registered as entity services)
|
||||
SET_DHW_OVERRIDE_SCHEMA: Final[dict[str | vol.Marker, Any]] = {
|
||||
vol.Required(ATTR_STATE): cv.boolean,
|
||||
vol.Optional(ATTR_DURATION): vol.All(
|
||||
cv.time_period,
|
||||
vol.Range(min=timedelta(days=0), max=timedelta(days=1)),
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def _register_zone_entity_services(hass: HomeAssistant) -> None:
|
||||
"""Register entity-level services for zones."""
|
||||
@@ -71,6 +81,19 @@ def _register_zone_entity_services(hass: HomeAssistant) -> None:
|
||||
)
|
||||
|
||||
|
||||
def _register_dhw_entity_services(hass: HomeAssistant) -> None:
|
||||
"""Register entity-level services for DHW zones."""
|
||||
|
||||
service.async_register_platform_entity_service(
|
||||
hass,
|
||||
DOMAIN,
|
||||
EvoService.SET_DHW_OVERRIDE,
|
||||
entity_domain=WATER_HEATER_DOMAIN,
|
||||
schema=SET_DHW_OVERRIDE_SCHEMA,
|
||||
func="async_set_dhw_override",
|
||||
)
|
||||
|
||||
|
||||
def _validate_set_system_mode_params(tcs: ControlSystem, data: dict[str, Any]) -> None:
|
||||
"""Validate that a set_system_mode service call is properly formed."""
|
||||
|
||||
@@ -156,3 +179,4 @@ def setup_service_functions(
|
||||
)
|
||||
|
||||
_register_zone_entity_services(hass)
|
||||
_register_dhw_entity_services(hass)
|
||||
|
||||
@@ -58,3 +58,19 @@ clear_zone_override:
|
||||
domain: climate
|
||||
supported_features:
|
||||
- climate.ClimateEntityFeature.TARGET_TEMPERATURE
|
||||
|
||||
set_dhw_override:
|
||||
target:
|
||||
entity:
|
||||
integration: evohome
|
||||
domain: water_heater
|
||||
fields:
|
||||
state:
|
||||
required: true
|
||||
selector:
|
||||
boolean:
|
||||
duration:
|
||||
example: "02:15"
|
||||
selector:
|
||||
duration:
|
||||
enable_second: false
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
},
|
||||
"services": {
|
||||
"clear_zone_override": {
|
||||
"description": "Sets a zone to follow its schedule.",
|
||||
"description": "Sets the zone to follow its schedule.",
|
||||
"name": "Clear zone override"
|
||||
},
|
||||
"refresh_system": {
|
||||
@@ -29,11 +29,25 @@
|
||||
"name": "Refresh system"
|
||||
},
|
||||
"reset_system": {
|
||||
"description": "Sets the system to `Auto` mode and resets all the zones to follow their schedules. Not all Evohome systems support this feature (i.e. `AutoWithReset` mode).",
|
||||
"description": "Sets the system mode to `Auto` mode and resets all the zones to follow their schedules. Not all Evohome systems support this feature (i.e. `AutoWithReset` mode).",
|
||||
"name": "Reset system"
|
||||
},
|
||||
"set_dhw_override": {
|
||||
"description": "Overrides the DHW state, either indefinitely or for a specified duration, after which it will revert to following its schedule.",
|
||||
"fields": {
|
||||
"duration": {
|
||||
"description": "The DHW will revert to its schedule after this time. If 0 the change is until the next scheduled setpoint.",
|
||||
"name": "Duration"
|
||||
},
|
||||
"state": {
|
||||
"description": "The DHW state: True (on: heat the water up to the setpoint) or False (off).",
|
||||
"name": "State"
|
||||
}
|
||||
},
|
||||
"name": "Set DHW override"
|
||||
},
|
||||
"set_system_mode": {
|
||||
"description": "Sets the system mode, either indefinitely, or for a specified period of time, after which it will revert to `Auto`. Not all systems support all modes.",
|
||||
"description": "Sets the system mode, either indefinitely or until a specified end time, after which it will revert to `Auto`. Not all systems support all modes.",
|
||||
"fields": {
|
||||
"duration": {
|
||||
"description": "The duration in hours; used only with `AutoWithEco` mode (up to 24 hours).",
|
||||
@@ -51,7 +65,7 @@
|
||||
"name": "Set system mode"
|
||||
},
|
||||
"set_zone_override": {
|
||||
"description": "Overrides the zone's setpoint, either indefinitely, or for a specified period of time, after which it will revert to following its schedule.",
|
||||
"description": "Overrides the zone setpoint, either indefinitely or for a specified duration, after which it will revert to following its schedule.",
|
||||
"fields": {
|
||||
"duration": {
|
||||
"description": "The zone will revert to its schedule after this time. If 0 the change is until the next scheduled setpoint.",
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import timedelta
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
@@ -97,6 +98,28 @@ class EvoDHW(EvoChild, WaterHeaterEntity):
|
||||
PRECISION_TENTHS if coordinator.client_v1 else PRECISION_WHOLE
|
||||
)
|
||||
|
||||
async def async_set_dhw_override(
|
||||
self, state: bool, duration: timedelta | None = None
|
||||
) -> None:
|
||||
"""Override the DHW zone's on/off state, either permanently or for a duration."""
|
||||
|
||||
if duration is None:
|
||||
until = None # indefinitely, aka permanent override
|
||||
elif duration.total_seconds() == 0:
|
||||
await self._update_schedule()
|
||||
until = self.setpoints.get("next_sp_from")
|
||||
else:
|
||||
until = dt_util.now() + duration
|
||||
|
||||
until = dt_util.as_utc(until) if until else None
|
||||
|
||||
if state:
|
||||
await self.coordinator.call_client_api(self._evo_device.set_on(until=until))
|
||||
else:
|
||||
await self.coordinator.call_client_api(
|
||||
self._evo_device.set_off(until=until)
|
||||
)
|
||||
|
||||
@property
|
||||
def current_operation(self) -> str | None:
|
||||
"""Return the current operating mode (Auto, On, or Off)."""
|
||||
|
||||
@@ -6,7 +6,7 @@ from datetime import timedelta
|
||||
from aiohttp import ClientError
|
||||
from pyfreshr import FreshrClient
|
||||
from pyfreshr.exceptions import ApiResponseError, LoginError
|
||||
from pyfreshr.models import DeviceReadings, DeviceSummary
|
||||
from pyfreshr.models import DeviceReadings, DeviceSummary, DeviceType
|
||||
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
|
||||
@@ -18,6 +18,12 @@ from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, Upda
|
||||
|
||||
from .const import DOMAIN, LOGGER
|
||||
|
||||
_DEVICE_TYPE_NAMES: dict[DeviceType, str] = {
|
||||
DeviceType.FRESH_R: "Fresh-r",
|
||||
DeviceType.FORWARD: "Fresh-r Forward",
|
||||
DeviceType.MONITOR: "Fresh-r Monitor",
|
||||
}
|
||||
|
||||
DEVICES_SCAN_INTERVAL = timedelta(hours=1)
|
||||
READINGS_SCAN_INTERVAL = timedelta(minutes=10)
|
||||
|
||||
@@ -110,6 +116,12 @@ class FreshrReadingsCoordinator(DataUpdateCoordinator[DeviceReadings]):
|
||||
)
|
||||
self._device = device
|
||||
self._client = client
|
||||
self.device_info = dr.DeviceInfo(
|
||||
identifiers={(DOMAIN, device.id)},
|
||||
name=_DEVICE_TYPE_NAMES.get(device.device_type, "Fresh-r"),
|
||||
serial_number=device.id,
|
||||
manufacturer="Fresh-r",
|
||||
)
|
||||
|
||||
@property
|
||||
def device_id(self) -> str:
|
||||
|
||||
18
homeassistant/components/freshr/entity.py
Normal file
18
homeassistant/components/freshr/entity.py
Normal file
@@ -0,0 +1,18 @@
|
||||
"""Base entity for the Fresh-r integration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from homeassistant.helpers.update_coordinator import CoordinatorEntity
|
||||
|
||||
from .coordinator import FreshrReadingsCoordinator
|
||||
|
||||
|
||||
class FreshrEntity(CoordinatorEntity[FreshrReadingsCoordinator]):
|
||||
"""Base class for Fresh-r entities."""
|
||||
|
||||
_attr_has_entity_name = True
|
||||
|
||||
def __init__(self, coordinator: FreshrReadingsCoordinator) -> None:
|
||||
"""Initialize the Fresh-r entity."""
|
||||
super().__init__(coordinator)
|
||||
self._attr_device_info = coordinator.device_info
|
||||
@@ -6,6 +6,6 @@
|
||||
"documentation": "https://www.home-assistant.io/integrations/freshr",
|
||||
"integration_type": "hub",
|
||||
"iot_class": "cloud_polling",
|
||||
"quality_scale": "silver",
|
||||
"quality_scale": "platinum",
|
||||
"requirements": ["pyfreshr==1.2.0"]
|
||||
}
|
||||
|
||||
@@ -21,12 +21,10 @@ from homeassistant.const import (
|
||||
UnitOfVolumeFlowRate,
|
||||
)
|
||||
from homeassistant.core import HomeAssistant, callback
|
||||
from homeassistant.helpers.device_registry import DeviceInfo
|
||||
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
|
||||
from homeassistant.helpers.update_coordinator import CoordinatorEntity
|
||||
|
||||
from .const import DOMAIN
|
||||
from .coordinator import FreshrConfigEntry, FreshrReadingsCoordinator
|
||||
from .entity import FreshrEntity
|
||||
|
||||
PARALLEL_UPDATES = 0
|
||||
|
||||
@@ -93,12 +91,6 @@ _TEMP = FreshrSensorEntityDescription(
|
||||
value_fn=lambda r: r.temp,
|
||||
)
|
||||
|
||||
_DEVICE_TYPE_NAMES: dict[DeviceType, str] = {
|
||||
DeviceType.FRESH_R: "Fresh-r",
|
||||
DeviceType.FORWARD: "Fresh-r Forward",
|
||||
DeviceType.MONITOR: "Fresh-r Monitor",
|
||||
}
|
||||
|
||||
SENSOR_TYPES: dict[DeviceType, tuple[FreshrSensorEntityDescription, ...]] = {
|
||||
DeviceType.FRESH_R: (_T1, _T2, _CO2, _HUM, _FLOW, _DP),
|
||||
DeviceType.FORWARD: (_T1, _T2, _CO2, _HUM, _FLOW, _DP, _TEMP),
|
||||
@@ -131,17 +123,10 @@ async def async_setup_entry(
|
||||
descriptions = SENSOR_TYPES.get(
|
||||
device.device_type, SENSOR_TYPES[DeviceType.FRESH_R]
|
||||
)
|
||||
device_info = DeviceInfo(
|
||||
identifiers={(DOMAIN, device_id)},
|
||||
name=_DEVICE_TYPE_NAMES.get(device.device_type, "Fresh-r"),
|
||||
serial_number=device_id,
|
||||
manufacturer="Fresh-r",
|
||||
)
|
||||
entities.extend(
|
||||
FreshrSensor(
|
||||
config_entry.runtime_data.readings[device_id],
|
||||
description,
|
||||
device_info,
|
||||
)
|
||||
for description in descriptions
|
||||
)
|
||||
@@ -151,22 +136,19 @@ async def async_setup_entry(
|
||||
config_entry.async_on_unload(coordinator.async_add_listener(_check_devices))
|
||||
|
||||
|
||||
class FreshrSensor(CoordinatorEntity[FreshrReadingsCoordinator], SensorEntity):
|
||||
class FreshrSensor(FreshrEntity, SensorEntity):
|
||||
"""Representation of a Fresh-r sensor."""
|
||||
|
||||
_attr_has_entity_name = True
|
||||
entity_description: FreshrSensorEntityDescription
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
coordinator: FreshrReadingsCoordinator,
|
||||
description: FreshrSensorEntityDescription,
|
||||
device_info: DeviceInfo,
|
||||
) -> None:
|
||||
"""Initialize the sensor."""
|
||||
super().__init__(coordinator)
|
||||
self.entity_description = description
|
||||
self._attr_device_info = device_info
|
||||
self._attr_unique_id = f"{coordinator.device_id}_{description.key}"
|
||||
|
||||
@property
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
|
||||
from bleak.backends.device import BLEDevice
|
||||
@@ -13,7 +12,8 @@ from gardena_bluetooth.exceptions import (
|
||||
CharacteristicNotFound,
|
||||
CommunicationFailure,
|
||||
)
|
||||
from gardena_bluetooth.parse import CharacteristicTime
|
||||
from gardena_bluetooth.parse import CharacteristicTime, ProductType
|
||||
from gardena_bluetooth.scan import async_get_manufacturer_data
|
||||
|
||||
from homeassistant.components import bluetooth
|
||||
from homeassistant.const import CONF_ADDRESS, Platform
|
||||
@@ -29,7 +29,6 @@ from .coordinator import (
|
||||
GardenaBluetoothConfigEntry,
|
||||
GardenaBluetoothCoordinator,
|
||||
)
|
||||
from .util import async_get_product_type
|
||||
|
||||
PLATFORMS: list[Platform] = [
|
||||
Platform.BINARY_SENSOR,
|
||||
@@ -76,11 +75,10 @@ async def async_setup_entry(
|
||||
|
||||
address = entry.data[CONF_ADDRESS]
|
||||
|
||||
try:
|
||||
async with asyncio.timeout(TIMEOUT):
|
||||
product_type = await async_get_product_type(hass, address)
|
||||
except TimeoutError as exception:
|
||||
raise ConfigEntryNotReady("Unable to find product type") from exception
|
||||
mfg_data = await async_get_manufacturer_data({address})
|
||||
product_type = mfg_data[address].product_type
|
||||
if product_type == ProductType.UNKNOWN:
|
||||
raise ConfigEntryNotReady("Unable to find product type")
|
||||
|
||||
client = Client(get_connection(hass, address), product_type)
|
||||
try:
|
||||
|
||||
@@ -9,6 +9,7 @@ from gardena_bluetooth.client import Client
|
||||
from gardena_bluetooth.const import PRODUCT_NAMES, DeviceInformation, ScanService
|
||||
from gardena_bluetooth.exceptions import CharacteristicNotFound, CommunicationFailure
|
||||
from gardena_bluetooth.parse import ManufacturerData, ProductType
|
||||
from gardena_bluetooth.scan import async_get_manufacturer_data
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.components.bluetooth import (
|
||||
@@ -24,41 +25,27 @@ from .const import DOMAIN
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
_SUPPORTED_PRODUCT_TYPES = {
|
||||
ProductType.PUMP,
|
||||
ProductType.VALVE,
|
||||
ProductType.WATER_COMPUTER,
|
||||
ProductType.AUTOMATS,
|
||||
ProductType.PRESSURE_TANKS,
|
||||
ProductType.AQUA_CONTOURS,
|
||||
}
|
||||
|
||||
|
||||
def _is_supported(discovery_info: BluetoothServiceInfo):
|
||||
"""Check if device is supported."""
|
||||
if ScanService not in discovery_info.service_uuids:
|
||||
return False
|
||||
|
||||
if not (data := discovery_info.manufacturer_data.get(ManufacturerData.company)):
|
||||
if discovery_info.manufacturer_data.get(ManufacturerData.company) is None:
|
||||
_LOGGER.debug("Missing manufacturer data: %s", discovery_info)
|
||||
return False
|
||||
|
||||
manufacturer_data = ManufacturerData.decode(data)
|
||||
product_type = ProductType.from_manufacturer_data(manufacturer_data)
|
||||
|
||||
if product_type not in (
|
||||
ProductType.PUMP,
|
||||
ProductType.VALVE,
|
||||
ProductType.WATER_COMPUTER,
|
||||
ProductType.AUTOMATS,
|
||||
ProductType.PRESSURE_TANKS,
|
||||
ProductType.AQUA_CONTOURS,
|
||||
):
|
||||
_LOGGER.debug("Unsupported device: %s", manufacturer_data)
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def _get_name(discovery_info: BluetoothServiceInfo):
|
||||
data = discovery_info.manufacturer_data[ManufacturerData.company]
|
||||
manufacturer_data = ManufacturerData.decode(data)
|
||||
product_type = ProductType.from_manufacturer_data(manufacturer_data)
|
||||
|
||||
return PRODUCT_NAMES.get(product_type, "Gardena Device")
|
||||
|
||||
|
||||
class GardenaBluetoothConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
"""Handle a config flow for Gardena Bluetooth."""
|
||||
|
||||
@@ -90,11 +77,13 @@ class GardenaBluetoothConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
) -> ConfigFlowResult:
|
||||
"""Handle the bluetooth discovery step."""
|
||||
_LOGGER.debug("Discovered device: %s", discovery_info)
|
||||
if not _is_supported(discovery_info):
|
||||
data = await async_get_manufacturer_data({discovery_info.address})
|
||||
product_type = data[discovery_info.address].product_type
|
||||
if product_type not in _SUPPORTED_PRODUCT_TYPES:
|
||||
return self.async_abort(reason="no_devices_found")
|
||||
|
||||
self.address = discovery_info.address
|
||||
self.devices = {discovery_info.address: _get_name(discovery_info)}
|
||||
self.devices = {discovery_info.address: PRODUCT_NAMES[product_type]}
|
||||
await self.async_set_unique_id(self.address)
|
||||
self._abort_if_unique_id_configured()
|
||||
return await self.async_step_confirm()
|
||||
@@ -131,12 +120,21 @@ class GardenaBluetoothConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
return await self.async_step_confirm()
|
||||
|
||||
current_addresses = self._async_current_ids(include_ignore=False)
|
||||
candidates = set()
|
||||
for discovery_info in async_discovered_service_info(self.hass):
|
||||
address = discovery_info.address
|
||||
if address in current_addresses or not _is_supported(discovery_info):
|
||||
continue
|
||||
candidates.add(address)
|
||||
|
||||
self.devices[address] = _get_name(discovery_info)
|
||||
data = await async_get_manufacturer_data(candidates)
|
||||
for address, mfg_data in data.items():
|
||||
if mfg_data.product_type not in _SUPPORTED_PRODUCT_TYPES:
|
||||
continue
|
||||
self.devices[address] = PRODUCT_NAMES[mfg_data.product_type]
|
||||
|
||||
# Keep selection sorted by address to ensure stable tests
|
||||
self.devices = dict(sorted(self.devices.items(), key=lambda x: x[0]))
|
||||
|
||||
if not self.devices:
|
||||
return self.async_abort(reason="no_devices_found")
|
||||
|
||||
@@ -15,5 +15,5 @@
|
||||
"integration_type": "device",
|
||||
"iot_class": "local_polling",
|
||||
"loggers": ["bleak", "bleak_esphome", "gardena_bluetooth"],
|
||||
"requirements": ["gardena-bluetooth==2.3.0"]
|
||||
"requirements": ["gardena-bluetooth==2.4.0"]
|
||||
}
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
"""Utility functions for Gardena Bluetooth integration."""
|
||||
|
||||
import asyncio
|
||||
from collections.abc import AsyncIterator
|
||||
|
||||
from gardena_bluetooth.parse import ManufacturerData, ProductType
|
||||
|
||||
from homeassistant.components import bluetooth
|
||||
|
||||
|
||||
async def _async_service_info(
|
||||
hass, address
|
||||
) -> AsyncIterator[bluetooth.BluetoothServiceInfoBleak]:
|
||||
queue = asyncio.Queue[bluetooth.BluetoothServiceInfoBleak]()
|
||||
|
||||
def _callback(
|
||||
service_info: bluetooth.BluetoothServiceInfoBleak,
|
||||
change: bluetooth.BluetoothChange,
|
||||
) -> None:
|
||||
if change != bluetooth.BluetoothChange.ADVERTISEMENT:
|
||||
return
|
||||
|
||||
queue.put_nowait(service_info)
|
||||
|
||||
service_info = bluetooth.async_last_service_info(hass, address, True)
|
||||
if service_info:
|
||||
yield service_info
|
||||
|
||||
cancel = bluetooth.async_register_callback(
|
||||
hass,
|
||||
_callback,
|
||||
{bluetooth.match.ADDRESS: address},
|
||||
bluetooth.BluetoothScanningMode.ACTIVE,
|
||||
)
|
||||
try:
|
||||
while True:
|
||||
yield await queue.get()
|
||||
finally:
|
||||
cancel()
|
||||
|
||||
|
||||
async def async_get_product_type(hass, address: str) -> ProductType:
|
||||
"""Wait for enough packets of manufacturer data to get the product type."""
|
||||
data = ManufacturerData()
|
||||
|
||||
async for service_info in _async_service_info(hass, address):
|
||||
data.update(service_info.manufacturer_data.get(ManufacturerData.company, b""))
|
||||
product_type = ProductType.from_manufacturer_data(data)
|
||||
if product_type is not ProductType.UNKNOWN:
|
||||
return product_type
|
||||
raise AssertionError("Iterator should have been infinite")
|
||||
@@ -7,5 +7,5 @@
|
||||
"documentation": "https://www.home-assistant.io/integrations/generic",
|
||||
"integration_type": "device",
|
||||
"iot_class": "local_push",
|
||||
"requirements": ["av==16.0.1", "Pillow==12.1.1"]
|
||||
"requirements": ["av==16.0.1", "Pillow==12.2.0"]
|
||||
}
|
||||
|
||||
@@ -175,6 +175,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
||||
await server.start()
|
||||
except Exception: # noqa: BLE001
|
||||
_LOGGER.warning("Could not start go2rtc server", exc_info=True)
|
||||
await session.close()
|
||||
return False
|
||||
|
||||
async def on_stop(event: Event) -> None:
|
||||
|
||||
@@ -91,10 +91,14 @@ from .const import (
|
||||
DATA_STORE,
|
||||
DATA_SUPERVISOR_INFO,
|
||||
DOMAIN,
|
||||
HASSIO_UPDATE_INTERVAL,
|
||||
HASSIO_MAIN_UPDATE_INTERVAL,
|
||||
MAIN_COORDINATOR,
|
||||
STATS_COORDINATOR,
|
||||
)
|
||||
from .coordinator import (
|
||||
HassioDataUpdateCoordinator,
|
||||
HassioAddOnDataUpdateCoordinator,
|
||||
HassioMainDataUpdateCoordinator,
|
||||
HassioStatsDataUpdateCoordinator,
|
||||
get_addons_info,
|
||||
get_addons_list,
|
||||
get_addons_stats,
|
||||
@@ -384,12 +388,6 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: # noqa:
|
||||
]
|
||||
hass.data[DATA_SUPERVISOR_INFO]["addons"] = hass.data[DATA_ADDONS_LIST]
|
||||
|
||||
async_call_later(
|
||||
hass,
|
||||
HASSIO_UPDATE_INTERVAL,
|
||||
HassJob(update_info_data, cancel_on_shutdown=True),
|
||||
)
|
||||
|
||||
# Fetch data
|
||||
update_info_task = hass.async_create_task(update_info_data(), eager_start=True)
|
||||
|
||||
@@ -436,7 +434,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: # noqa:
|
||||
# os info not yet fetched from supervisor, retry later
|
||||
async_call_later(
|
||||
hass,
|
||||
HASSIO_UPDATE_INTERVAL,
|
||||
HASSIO_MAIN_UPDATE_INTERVAL,
|
||||
async_setup_hardware_integration_job,
|
||||
)
|
||||
return
|
||||
@@ -462,9 +460,20 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: # noqa:
|
||||
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
||||
"""Set up a config entry."""
|
||||
dev_reg = dr.async_get(hass)
|
||||
coordinator = HassioDataUpdateCoordinator(hass, entry, dev_reg)
|
||||
|
||||
coordinator = HassioMainDataUpdateCoordinator(hass, entry, dev_reg)
|
||||
await coordinator.async_config_entry_first_refresh()
|
||||
hass.data[ADDONS_COORDINATOR] = coordinator
|
||||
hass.data[MAIN_COORDINATOR] = coordinator
|
||||
|
||||
addon_coordinator = HassioAddOnDataUpdateCoordinator(
|
||||
hass, entry, dev_reg, coordinator.jobs
|
||||
)
|
||||
await addon_coordinator.async_config_entry_first_refresh()
|
||||
hass.data[ADDONS_COORDINATOR] = addon_coordinator
|
||||
|
||||
stats_coordinator = HassioStatsDataUpdateCoordinator(hass, entry)
|
||||
await stats_coordinator.async_config_entry_first_refresh()
|
||||
hass.data[STATS_COORDINATOR] = stats_coordinator
|
||||
|
||||
def deprecated_setup_issue() -> None:
|
||||
os_info = get_os_info(hass)
|
||||
@@ -531,10 +540,12 @@ async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
||||
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
|
||||
|
||||
# Unload coordinator
|
||||
coordinator: HassioDataUpdateCoordinator = hass.data[ADDONS_COORDINATOR]
|
||||
coordinator: HassioMainDataUpdateCoordinator = hass.data[MAIN_COORDINATOR]
|
||||
coordinator.unload()
|
||||
|
||||
# Pop coordinator
|
||||
# Pop coordinators
|
||||
hass.data.pop(MAIN_COORDINATOR, None)
|
||||
hass.data.pop(ADDONS_COORDINATOR, None)
|
||||
hass.data.pop(STATS_COORDINATOR, None)
|
||||
|
||||
return unload_ok
|
||||
|
||||
@@ -22,6 +22,7 @@ from .const import (
|
||||
ATTR_STATE,
|
||||
DATA_KEY_ADDONS,
|
||||
DATA_KEY_MOUNTS,
|
||||
MAIN_COORDINATOR,
|
||||
)
|
||||
from .entity import HassioAddonEntity, HassioMountEntity
|
||||
|
||||
@@ -60,17 +61,18 @@ async def async_setup_entry(
|
||||
async_add_entities: AddConfigEntryEntitiesCallback,
|
||||
) -> None:
|
||||
"""Binary sensor set up for Hass.io config entry."""
|
||||
coordinator = hass.data[ADDONS_COORDINATOR]
|
||||
addons_coordinator = hass.data[ADDONS_COORDINATOR]
|
||||
coordinator = hass.data[MAIN_COORDINATOR]
|
||||
|
||||
async_add_entities(
|
||||
itertools.chain(
|
||||
[
|
||||
HassioAddonBinarySensor(
|
||||
addon=addon,
|
||||
coordinator=coordinator,
|
||||
coordinator=addons_coordinator,
|
||||
entity_description=entity_description,
|
||||
)
|
||||
for addon in coordinator.data[DATA_KEY_ADDONS].values()
|
||||
for addon in addons_coordinator.data[DATA_KEY_ADDONS].values()
|
||||
for entity_description in ADDON_ENTITY_DESCRIPTIONS
|
||||
],
|
||||
[
|
||||
|
||||
@@ -77,7 +77,9 @@ EVENT_JOB = "job"
|
||||
UPDATE_KEY_SUPERVISOR = "supervisor"
|
||||
STARTUP_COMPLETE = "complete"
|
||||
|
||||
MAIN_COORDINATOR = "hassio_main_coordinator"
|
||||
ADDONS_COORDINATOR = "hassio_addons_coordinator"
|
||||
STATS_COORDINATOR = "hassio_stats_coordinator"
|
||||
|
||||
|
||||
DATA_COMPONENT: HassKey[HassIO] = HassKey(DOMAIN)
|
||||
@@ -94,7 +96,9 @@ DATA_SUPERVISOR_STATS = "hassio_supervisor_stats"
|
||||
DATA_ADDONS_INFO = "hassio_addons_info"
|
||||
DATA_ADDONS_STATS = "hassio_addons_stats"
|
||||
DATA_ADDONS_LIST = "hassio_addons_list"
|
||||
HASSIO_UPDATE_INTERVAL = timedelta(minutes=5)
|
||||
HASSIO_MAIN_UPDATE_INTERVAL = timedelta(minutes=5)
|
||||
HASSIO_ADDON_UPDATE_INTERVAL = timedelta(minutes=15)
|
||||
HASSIO_STATS_UPDATE_INTERVAL = timedelta(seconds=60)
|
||||
|
||||
ATTR_AUTO_UPDATE = "auto_update"
|
||||
ATTR_VERSION = "version"
|
||||
|
||||
@@ -7,7 +7,7 @@ from collections import defaultdict
|
||||
from collections.abc import Awaitable
|
||||
from copy import deepcopy
|
||||
import logging
|
||||
from typing import TYPE_CHECKING, Any, cast
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from aiohasupervisor import SupervisorError, SupervisorNotFoundError
|
||||
from aiohasupervisor.models import (
|
||||
@@ -15,9 +15,9 @@ from aiohasupervisor.models import (
|
||||
CIFSMountResponse,
|
||||
InstalledAddon,
|
||||
NFSMountResponse,
|
||||
ResponseData,
|
||||
StoreInfo,
|
||||
)
|
||||
from aiohasupervisor.models.base import ResponseData
|
||||
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.const import ATTR_MANUFACTURER, ATTR_NAME
|
||||
@@ -35,13 +35,11 @@ from .const import (
|
||||
ATTR_SLUG,
|
||||
ATTR_URL,
|
||||
ATTR_VERSION,
|
||||
CONTAINER_INFO,
|
||||
CONTAINER_STATS,
|
||||
CORE_CONTAINER,
|
||||
DATA_ADDONS_INFO,
|
||||
DATA_ADDONS_LIST,
|
||||
DATA_ADDONS_STATS,
|
||||
DATA_COMPONENT,
|
||||
DATA_CORE_INFO,
|
||||
DATA_CORE_STATS,
|
||||
DATA_HOST_INFO,
|
||||
@@ -59,7 +57,9 @@ from .const import (
|
||||
DATA_SUPERVISOR_INFO,
|
||||
DATA_SUPERVISOR_STATS,
|
||||
DOMAIN,
|
||||
HASSIO_UPDATE_INTERVAL,
|
||||
HASSIO_ADDON_UPDATE_INTERVAL,
|
||||
HASSIO_MAIN_UPDATE_INTERVAL,
|
||||
HASSIO_STATS_UPDATE_INTERVAL,
|
||||
REQUEST_REFRESH_DELAY,
|
||||
SUPERVISOR_CONTAINER,
|
||||
SupervisorEntityModel,
|
||||
@@ -318,7 +318,314 @@ def async_remove_devices_from_dev_reg(
|
||||
dev_reg.async_remove_device(dev.id)
|
||||
|
||||
|
||||
class HassioDataUpdateCoordinator(DataUpdateCoordinator):
|
||||
class HassioStatsDataUpdateCoordinator(DataUpdateCoordinator[dict[str, Any]]):
|
||||
"""Class to retrieve Hass.io container stats."""
|
||||
|
||||
config_entry: ConfigEntry
|
||||
|
||||
def __init__(self, hass: HomeAssistant, config_entry: ConfigEntry) -> None:
|
||||
"""Initialize coordinator."""
|
||||
super().__init__(
|
||||
hass,
|
||||
_LOGGER,
|
||||
config_entry=config_entry,
|
||||
name=DOMAIN,
|
||||
update_interval=HASSIO_STATS_UPDATE_INTERVAL,
|
||||
request_refresh_debouncer=Debouncer(
|
||||
hass, _LOGGER, cooldown=REQUEST_REFRESH_DELAY, immediate=False
|
||||
),
|
||||
)
|
||||
self.supervisor_client = get_supervisor_client(hass)
|
||||
self._container_updates: defaultdict[str, dict[str, set[str]]] = defaultdict(
|
||||
lambda: defaultdict(set)
|
||||
)
|
||||
|
||||
async def _async_update_data(self) -> dict[str, Any]:
|
||||
"""Update stats data via library."""
|
||||
try:
|
||||
await self._fetch_stats()
|
||||
except SupervisorError as err:
|
||||
raise UpdateFailed(f"Error on Supervisor API: {err}") from err
|
||||
|
||||
new_data: dict[str, Any] = {}
|
||||
new_data[DATA_KEY_CORE] = get_core_stats(self.hass)
|
||||
new_data[DATA_KEY_SUPERVISOR] = get_supervisor_stats(self.hass)
|
||||
new_data[DATA_KEY_ADDONS] = get_addons_stats(self.hass)
|
||||
return new_data
|
||||
|
||||
async def _fetch_stats(self) -> None:
|
||||
"""Fetch container stats for subscribed entities."""
|
||||
container_updates = self._container_updates
|
||||
data = self.hass.data
|
||||
client = self.supervisor_client
|
||||
|
||||
# Fetch core and supervisor stats
|
||||
updates: dict[str, Awaitable] = {}
|
||||
if container_updates.get(CORE_CONTAINER, {}).get(CONTAINER_STATS):
|
||||
updates[DATA_CORE_STATS] = client.homeassistant.stats()
|
||||
if container_updates.get(SUPERVISOR_CONTAINER, {}).get(CONTAINER_STATS):
|
||||
updates[DATA_SUPERVISOR_STATS] = client.supervisor.stats()
|
||||
|
||||
if updates:
|
||||
api_results: list[ResponseData] = await asyncio.gather(*updates.values())
|
||||
for key, result in zip(updates, api_results, strict=True):
|
||||
data[key] = result.to_dict()
|
||||
|
||||
# Fetch addon stats
|
||||
addons_list = get_addons_list(self.hass) or []
|
||||
started_addons = {
|
||||
addon[ATTR_SLUG]
|
||||
for addon in addons_list
|
||||
if addon.get("state") in {AddonState.STARTED, AddonState.STARTUP}
|
||||
}
|
||||
|
||||
addons_stats: dict[str, Any] = data.setdefault(DATA_ADDONS_STATS, {})
|
||||
|
||||
# Clean up cache for stopped/removed addons
|
||||
for slug in addons_stats.keys() - started_addons:
|
||||
del addons_stats[slug]
|
||||
|
||||
# Fetch stats for addons with subscribed entities
|
||||
addon_stats_results = dict(
|
||||
await asyncio.gather(
|
||||
*[
|
||||
self._update_addon_stats(slug)
|
||||
for slug in started_addons
|
||||
if container_updates.get(slug, {}).get(CONTAINER_STATS)
|
||||
]
|
||||
)
|
||||
)
|
||||
addons_stats.update(addon_stats_results)
|
||||
|
||||
async def _update_addon_stats(self, slug: str) -> tuple[str, dict[str, Any] | None]:
|
||||
"""Update single addon stats."""
|
||||
try:
|
||||
stats = await self.supervisor_client.addons.addon_stats(slug)
|
||||
except SupervisorError as err:
|
||||
_LOGGER.warning("Could not fetch stats for %s: %s", slug, err)
|
||||
return (slug, None)
|
||||
return (slug, stats.to_dict())
|
||||
|
||||
@callback
|
||||
def async_enable_container_updates(
|
||||
self, slug: str, entity_id: str, types: set[str]
|
||||
) -> CALLBACK_TYPE:
|
||||
"""Enable stats updates for a container."""
|
||||
enabled_updates = self._container_updates[slug]
|
||||
for key in types:
|
||||
enabled_updates[key].add(entity_id)
|
||||
|
||||
@callback
|
||||
def _remove() -> None:
|
||||
for key in types:
|
||||
enabled_updates[key].discard(entity_id)
|
||||
if not enabled_updates[key]:
|
||||
del enabled_updates[key]
|
||||
if not enabled_updates:
|
||||
self._container_updates.pop(slug, None)
|
||||
|
||||
return _remove
|
||||
|
||||
|
||||
class HassioAddOnDataUpdateCoordinator(DataUpdateCoordinator[dict[str, Any]]):
|
||||
"""Class to retrieve Hass.io Add-on status."""
|
||||
|
||||
config_entry: ConfigEntry
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
hass: HomeAssistant,
|
||||
config_entry: ConfigEntry,
|
||||
dev_reg: dr.DeviceRegistry,
|
||||
jobs: SupervisorJobs,
|
||||
) -> None:
|
||||
"""Initialize coordinator."""
|
||||
super().__init__(
|
||||
hass,
|
||||
_LOGGER,
|
||||
config_entry=config_entry,
|
||||
name=DOMAIN,
|
||||
update_interval=HASSIO_ADDON_UPDATE_INTERVAL,
|
||||
# We don't want an immediate refresh since we want to avoid
|
||||
# hammering the Supervisor API on startup
|
||||
request_refresh_debouncer=Debouncer(
|
||||
hass, _LOGGER, cooldown=REQUEST_REFRESH_DELAY, immediate=False
|
||||
),
|
||||
)
|
||||
self.entry_id = config_entry.entry_id
|
||||
self.dev_reg = dev_reg
|
||||
self._addon_info_subscriptions: defaultdict[str, set[str]] = defaultdict(set)
|
||||
self.supervisor_client = get_supervisor_client(hass)
|
||||
self.jobs = jobs
|
||||
|
||||
async def _async_update_data(self) -> dict[str, Any]:
|
||||
"""Update data via library."""
|
||||
is_first_update = not self.data
|
||||
client = self.supervisor_client
|
||||
|
||||
try:
|
||||
installed_addons: list[InstalledAddon] = await client.addons.list()
|
||||
all_addons = {addon.slug for addon in installed_addons}
|
||||
|
||||
# Fetch addon info for all addons on first update, or only
|
||||
# for addons with subscribed entities on subsequent updates.
|
||||
addon_info_results = dict(
|
||||
await asyncio.gather(
|
||||
*[
|
||||
self._update_addon_info(slug)
|
||||
for slug in all_addons
|
||||
if is_first_update or self._addon_info_subscriptions.get(slug)
|
||||
]
|
||||
)
|
||||
)
|
||||
except SupervisorError as err:
|
||||
raise UpdateFailed(f"Error on Supervisor API: {err}") from err
|
||||
|
||||
# Update hass.data for legacy accessor functions
|
||||
data = self.hass.data
|
||||
addons_list_dicts = [addon.to_dict() for addon in installed_addons]
|
||||
data[DATA_ADDONS_LIST] = addons_list_dicts
|
||||
|
||||
# Update addon info cache in hass.data
|
||||
addon_info_cache: dict[str, Any] = data.setdefault(DATA_ADDONS_INFO, {})
|
||||
for slug in addon_info_cache.keys() - all_addons:
|
||||
del addon_info_cache[slug]
|
||||
addon_info_cache.update(addon_info_results)
|
||||
|
||||
# Deprecated 2026.4.0: Folding addons.list results into supervisor_info
|
||||
# for compatibility. Written to hass.data only, not coordinator data.
|
||||
if DATA_SUPERVISOR_INFO in data:
|
||||
data[DATA_SUPERVISOR_INFO]["addons"] = addons_list_dicts
|
||||
|
||||
# Build clean coordinator data
|
||||
store_data = get_store(self.hass)
|
||||
if store_data:
|
||||
repositories = {
|
||||
repo.slug: repo.name
|
||||
for repo in StoreInfo.from_dict(store_data).repositories
|
||||
}
|
||||
else:
|
||||
repositories = {}
|
||||
|
||||
new_data: dict[str, Any] = {}
|
||||
new_data[DATA_KEY_ADDONS] = {
|
||||
(slug := addon[ATTR_SLUG]): {
|
||||
**addon,
|
||||
ATTR_AUTO_UPDATE: (addon_info_cache.get(slug) or {}).get(
|
||||
ATTR_AUTO_UPDATE, False
|
||||
),
|
||||
ATTR_REPOSITORY: repositories.get(
|
||||
repo_slug := addon.get(ATTR_REPOSITORY, ""), repo_slug
|
||||
),
|
||||
}
|
||||
for addon in addons_list_dicts
|
||||
}
|
||||
|
||||
# If this is the initial refresh, register all addons
|
||||
if is_first_update:
|
||||
async_register_addons_in_dev_reg(
|
||||
self.entry_id, self.dev_reg, new_data[DATA_KEY_ADDONS].values()
|
||||
)
|
||||
|
||||
# Remove add-ons that are no longer installed from device registry
|
||||
supervisor_addon_devices = {
|
||||
list(device.identifiers)[0][1]
|
||||
for device in self.dev_reg.devices.get_devices_for_config_entry_id(
|
||||
self.entry_id
|
||||
)
|
||||
if device.model == SupervisorEntityModel.ADDON
|
||||
}
|
||||
if stale_addons := supervisor_addon_devices - set(new_data[DATA_KEY_ADDONS]):
|
||||
async_remove_devices_from_dev_reg(self.dev_reg, stale_addons)
|
||||
|
||||
# If there are new add-ons, we should reload the config entry so we can
|
||||
# create new devices and entities. We can return an empty dict because
|
||||
# coordinator will be recreated.
|
||||
if self.data and (
|
||||
set(new_data[DATA_KEY_ADDONS]) - set(self.data[DATA_KEY_ADDONS])
|
||||
):
|
||||
self.hass.async_create_task(
|
||||
self.hass.config_entries.async_reload(self.entry_id)
|
||||
)
|
||||
return {}
|
||||
|
||||
return new_data
|
||||
|
||||
async def get_changelog(self, addon_slug: str) -> str | None:
|
||||
"""Get the changelog for an add-on."""
|
||||
try:
|
||||
return await self.supervisor_client.store.addon_changelog(addon_slug)
|
||||
except SupervisorNotFoundError:
|
||||
return None
|
||||
|
||||
async def _update_addon_info(self, slug: str) -> tuple[str, dict[str, Any] | None]:
|
||||
"""Return the info for an addon."""
|
||||
try:
|
||||
info = await self.supervisor_client.addons.addon_info(slug)
|
||||
except SupervisorError as err:
|
||||
_LOGGER.warning("Could not fetch info for %s: %s", slug, err)
|
||||
return (slug, None)
|
||||
# Translate to legacy hassio names for compatibility
|
||||
info_dict = info.to_dict()
|
||||
info_dict["hassio_api"] = info_dict.pop("supervisor_api")
|
||||
info_dict["hassio_role"] = info_dict.pop("supervisor_role")
|
||||
return (slug, info_dict)
|
||||
|
||||
@callback
|
||||
def async_enable_addon_info_updates(
|
||||
self, slug: str, entity_id: str
|
||||
) -> CALLBACK_TYPE:
|
||||
"""Enable info updates for an add-on."""
|
||||
self._addon_info_subscriptions[slug].add(entity_id)
|
||||
|
||||
@callback
|
||||
def _remove() -> None:
|
||||
self._addon_info_subscriptions[slug].discard(entity_id)
|
||||
if not self._addon_info_subscriptions[slug]:
|
||||
del self._addon_info_subscriptions[slug]
|
||||
|
||||
return _remove
|
||||
|
||||
async def _async_refresh(
|
||||
self,
|
||||
log_failures: bool = True,
|
||||
raise_on_auth_failed: bool = False,
|
||||
scheduled: bool = False,
|
||||
raise_on_entry_error: bool = False,
|
||||
) -> None:
|
||||
"""Refresh data."""
|
||||
if not scheduled and not raise_on_auth_failed:
|
||||
# Force reloading add-on updates for non-scheduled
|
||||
# updates.
|
||||
#
|
||||
# If `raise_on_auth_failed` is set, it means this is
|
||||
# the first refresh and we do not want to delay
|
||||
# startup or cause a timeout so we only refresh the
|
||||
# updates if this is not a scheduled refresh and
|
||||
# we are not doing the first refresh.
|
||||
try:
|
||||
await self.supervisor_client.store.reload()
|
||||
except SupervisorError as err:
|
||||
_LOGGER.warning("Error on Supervisor API: %s", err)
|
||||
|
||||
await super()._async_refresh(
|
||||
log_failures, raise_on_auth_failed, scheduled, raise_on_entry_error
|
||||
)
|
||||
|
||||
async def force_addon_info_data_refresh(self, addon_slug: str) -> None:
|
||||
"""Force refresh of addon info data for a specific addon."""
|
||||
try:
|
||||
slug, info = await self._update_addon_info(addon_slug)
|
||||
if info is not None and DATA_KEY_ADDONS in self.data:
|
||||
if slug in self.data[DATA_KEY_ADDONS]:
|
||||
data = deepcopy(self.data)
|
||||
data[DATA_KEY_ADDONS][slug].update(info)
|
||||
self.async_set_updated_data(data)
|
||||
except SupervisorError as err:
|
||||
_LOGGER.warning("Could not refresh info for %s: %s", addon_slug, err)
|
||||
|
||||
|
||||
class HassioMainDataUpdateCoordinator(DataUpdateCoordinator[dict[str, Any]]):
|
||||
"""Class to retrieve Hass.io status."""
|
||||
|
||||
config_entry: ConfigEntry
|
||||
@@ -332,82 +639,77 @@ class HassioDataUpdateCoordinator(DataUpdateCoordinator):
|
||||
_LOGGER,
|
||||
config_entry=config_entry,
|
||||
name=DOMAIN,
|
||||
update_interval=HASSIO_UPDATE_INTERVAL,
|
||||
update_interval=HASSIO_MAIN_UPDATE_INTERVAL,
|
||||
# We don't want an immediate refresh since we want to avoid
|
||||
# fetching the container stats right away and avoid hammering
|
||||
# the Supervisor API on startup
|
||||
# hammering the Supervisor API on startup
|
||||
request_refresh_debouncer=Debouncer(
|
||||
hass, _LOGGER, cooldown=REQUEST_REFRESH_DELAY, immediate=False
|
||||
),
|
||||
)
|
||||
self.hassio = hass.data[DATA_COMPONENT]
|
||||
self.data = {}
|
||||
self.entry_id = config_entry.entry_id
|
||||
self.dev_reg = dev_reg
|
||||
self.is_hass_os = (get_info(self.hass) or {}).get("hassos") is not None
|
||||
self._container_updates: defaultdict[str, dict[str, set[str]]] = defaultdict(
|
||||
lambda: defaultdict(set)
|
||||
)
|
||||
self.supervisor_client = get_supervisor_client(hass)
|
||||
self.jobs = SupervisorJobs(hass)
|
||||
|
||||
async def _async_update_data(self) -> dict[str, Any]:
|
||||
"""Update data via library."""
|
||||
is_first_update = not self.data
|
||||
client = self.supervisor_client
|
||||
|
||||
try:
|
||||
await self.force_data_refresh(is_first_update)
|
||||
(
|
||||
info,
|
||||
core_info,
|
||||
supervisor_info,
|
||||
os_info,
|
||||
host_info,
|
||||
store_info,
|
||||
network_info,
|
||||
) = await asyncio.gather(
|
||||
client.info(),
|
||||
client.homeassistant.info(),
|
||||
client.supervisor.info(),
|
||||
client.os.info(),
|
||||
client.host.info(),
|
||||
client.store.info(),
|
||||
client.network.info(),
|
||||
)
|
||||
mounts_info = await client.mounts.info()
|
||||
await self.jobs.refresh_data(is_first_update)
|
||||
except SupervisorError as err:
|
||||
raise UpdateFailed(f"Error on Supervisor API: {err}") from err
|
||||
|
||||
# Build clean coordinator data
|
||||
new_data: dict[str, Any] = {}
|
||||
supervisor_info = get_supervisor_info(self.hass) or {}
|
||||
addons_info = get_addons_info(self.hass) or {}
|
||||
addons_stats = get_addons_stats(self.hass)
|
||||
store_data = get_store(self.hass)
|
||||
mounts_info = await self.supervisor_client.mounts.info()
|
||||
addons_list = get_addons_list(self.hass) or []
|
||||
|
||||
if store_data:
|
||||
repositories = {
|
||||
repo.slug: repo.name
|
||||
for repo in StoreInfo.from_dict(store_data).repositories
|
||||
}
|
||||
else:
|
||||
repositories = {}
|
||||
|
||||
new_data[DATA_KEY_ADDONS] = {
|
||||
(slug := addon[ATTR_SLUG]): {
|
||||
**addon,
|
||||
**(addons_stats.get(slug) or {}),
|
||||
ATTR_AUTO_UPDATE: (addons_info.get(slug) or {}).get(
|
||||
ATTR_AUTO_UPDATE, False
|
||||
),
|
||||
ATTR_REPOSITORY: repositories.get(
|
||||
repo_slug := addon.get(ATTR_REPOSITORY, ""), repo_slug
|
||||
),
|
||||
}
|
||||
for addon in addons_list
|
||||
}
|
||||
if self.is_hass_os:
|
||||
new_data[DATA_KEY_OS] = get_os_info(self.hass)
|
||||
|
||||
new_data[DATA_KEY_CORE] = {
|
||||
**(get_core_info(self.hass) or {}),
|
||||
**get_core_stats(self.hass),
|
||||
}
|
||||
new_data[DATA_KEY_SUPERVISOR] = {
|
||||
**supervisor_info,
|
||||
**get_supervisor_stats(self.hass),
|
||||
}
|
||||
new_data[DATA_KEY_HOST] = get_host_info(self.hass) or {}
|
||||
new_data[DATA_KEY_CORE] = core_info.to_dict()
|
||||
new_data[DATA_KEY_SUPERVISOR] = supervisor_info.to_dict()
|
||||
new_data[DATA_KEY_HOST] = host_info.to_dict()
|
||||
new_data[DATA_KEY_MOUNTS] = {mount.name: mount for mount in mounts_info.mounts}
|
||||
if self.is_hass_os:
|
||||
new_data[DATA_KEY_OS] = os_info.to_dict()
|
||||
|
||||
# If this is the initial refresh, register all addons and return the dict
|
||||
# Update hass.data for legacy accessor functions
|
||||
data = self.hass.data
|
||||
data[DATA_INFO] = info.to_dict()
|
||||
data[DATA_CORE_INFO] = new_data[DATA_KEY_CORE]
|
||||
data[DATA_OS_INFO] = new_data.get(DATA_KEY_OS, os_info.to_dict())
|
||||
data[DATA_HOST_INFO] = new_data[DATA_KEY_HOST]
|
||||
data[DATA_STORE] = store_info.to_dict()
|
||||
data[DATA_NETWORK_INFO] = network_info.to_dict()
|
||||
# Separate dict for hass.data supervisor info since we add deprecated
|
||||
# compat keys that should not be in coordinator data
|
||||
supervisor_info_dict = supervisor_info.to_dict()
|
||||
# Deprecated 2026.4.0: Folding repositories and addons into
|
||||
# supervisor_info for compatibility. Written to hass.data only, not
|
||||
# coordinator data. Preserve the addons key from the addon coordinator.
|
||||
supervisor_info_dict["repositories"] = data[DATA_STORE][ATTR_REPOSITORIES]
|
||||
if (prev := data.get(DATA_SUPERVISOR_INFO)) and "addons" in prev:
|
||||
supervisor_info_dict["addons"] = prev["addons"]
|
||||
data[DATA_SUPERVISOR_INFO] = supervisor_info_dict
|
||||
|
||||
# If this is the initial refresh, register all main components
|
||||
if is_first_update:
|
||||
async_register_addons_in_dev_reg(
|
||||
self.entry_id, self.dev_reg, new_data[DATA_KEY_ADDONS].values()
|
||||
)
|
||||
async_register_mounts_in_dev_reg(
|
||||
self.entry_id, self.dev_reg, new_data[DATA_KEY_MOUNTS].values()
|
||||
)
|
||||
@@ -423,17 +725,6 @@ class HassioDataUpdateCoordinator(DataUpdateCoordinator):
|
||||
self.entry_id, self.dev_reg, new_data[DATA_KEY_OS]
|
||||
)
|
||||
|
||||
# Remove add-ons that are no longer installed from device registry
|
||||
supervisor_addon_devices = {
|
||||
list(device.identifiers)[0][1]
|
||||
for device in self.dev_reg.devices.get_devices_for_config_entry_id(
|
||||
self.entry_id
|
||||
)
|
||||
if device.model == SupervisorEntityModel.ADDON
|
||||
}
|
||||
if stale_addons := supervisor_addon_devices - set(new_data[DATA_KEY_ADDONS]):
|
||||
async_remove_devices_from_dev_reg(self.dev_reg, stale_addons)
|
||||
|
||||
# Remove mounts that no longer exists from device registry
|
||||
supervisor_mount_devices = {
|
||||
device.name
|
||||
@@ -453,12 +744,11 @@ class HassioDataUpdateCoordinator(DataUpdateCoordinator):
|
||||
# Remove the OS device if it exists and the installation is not hassos
|
||||
self.dev_reg.async_remove_device(dev.id)
|
||||
|
||||
# If there are new add-ons or mounts, we should reload the config entry so we can
|
||||
# If there are new mounts, we should reload the config entry so we can
|
||||
# create new devices and entities. We can return an empty dict because
|
||||
# coordinator will be recreated.
|
||||
if self.data and (
|
||||
set(new_data[DATA_KEY_ADDONS]) - set(self.data[DATA_KEY_ADDONS])
|
||||
or set(new_data[DATA_KEY_MOUNTS]) - set(self.data[DATA_KEY_MOUNTS])
|
||||
set(new_data[DATA_KEY_MOUNTS]) - set(self.data.get(DATA_KEY_MOUNTS, {}))
|
||||
):
|
||||
self.hass.async_create_task(
|
||||
self.hass.config_entries.async_reload(self.entry_id)
|
||||
@@ -467,146 +757,6 @@ class HassioDataUpdateCoordinator(DataUpdateCoordinator):
|
||||
|
||||
return new_data
|
||||
|
||||
async def get_changelog(self, addon_slug: str) -> str | None:
|
||||
"""Get the changelog for an add-on."""
|
||||
try:
|
||||
return await self.supervisor_client.store.addon_changelog(addon_slug)
|
||||
except SupervisorNotFoundError:
|
||||
return None
|
||||
|
||||
async def force_data_refresh(self, first_update: bool) -> None:
|
||||
"""Force update of the addon info."""
|
||||
container_updates = self._container_updates
|
||||
|
||||
data = self.hass.data
|
||||
client = self.supervisor_client
|
||||
|
||||
updates: dict[str, Awaitable[ResponseData]] = {
|
||||
DATA_INFO: client.info(),
|
||||
DATA_CORE_INFO: client.homeassistant.info(),
|
||||
DATA_SUPERVISOR_INFO: client.supervisor.info(),
|
||||
DATA_OS_INFO: client.os.info(),
|
||||
DATA_STORE: client.store.info(),
|
||||
}
|
||||
if CONTAINER_STATS in container_updates[CORE_CONTAINER]:
|
||||
updates[DATA_CORE_STATS] = client.homeassistant.stats()
|
||||
if CONTAINER_STATS in container_updates[SUPERVISOR_CONTAINER]:
|
||||
updates[DATA_SUPERVISOR_STATS] = client.supervisor.stats()
|
||||
|
||||
# Pull off addons.list results for further processing before caching
|
||||
addons_list, *results = await asyncio.gather(
|
||||
client.addons.list(), *updates.values()
|
||||
)
|
||||
for key, result in zip(updates, cast(list[ResponseData], results), strict=True):
|
||||
data[key] = result.to_dict()
|
||||
|
||||
installed_addons = cast(list[InstalledAddon], addons_list)
|
||||
data[DATA_ADDONS_LIST] = [addon.to_dict() for addon in installed_addons]
|
||||
|
||||
# Deprecated 2026.4.0: Folding repositories and addons.list results into supervisor_info for compatibility
|
||||
# Can drop this after removal period
|
||||
data[DATA_SUPERVISOR_INFO].update(
|
||||
{
|
||||
"repositories": data[DATA_STORE][ATTR_REPOSITORIES],
|
||||
"addons": [addon.to_dict() for addon in installed_addons],
|
||||
}
|
||||
)
|
||||
|
||||
all_addons = {addon.slug for addon in installed_addons}
|
||||
started_addons = {
|
||||
addon.slug
|
||||
for addon in installed_addons
|
||||
if addon.state in {AddonState.STARTED, AddonState.STARTUP}
|
||||
}
|
||||
|
||||
#
|
||||
# Update addon info if its the first update or
|
||||
# there is at least one entity that needs the data.
|
||||
#
|
||||
# When entities are added they call async_enable_container_updates
|
||||
# to enable updates for the endpoints they need via
|
||||
# async_added_to_hass. This ensures that we only update
|
||||
# the data for the endpoints that are needed to avoid unnecessary
|
||||
# API calls since otherwise we would fetch stats for all containers
|
||||
# and throw them away.
|
||||
#
|
||||
for data_key, update_func, enabled_key, wanted_addons, needs_first_update in (
|
||||
(
|
||||
DATA_ADDONS_STATS,
|
||||
self._update_addon_stats,
|
||||
CONTAINER_STATS,
|
||||
started_addons,
|
||||
False,
|
||||
),
|
||||
(
|
||||
DATA_ADDONS_INFO,
|
||||
self._update_addon_info,
|
||||
CONTAINER_INFO,
|
||||
all_addons,
|
||||
True,
|
||||
),
|
||||
):
|
||||
container_data: dict[str, Any] = data.setdefault(data_key, {})
|
||||
|
||||
# Clean up cache
|
||||
for slug in container_data.keys() - wanted_addons:
|
||||
del container_data[slug]
|
||||
|
||||
# Update cache from API
|
||||
container_data.update(
|
||||
dict(
|
||||
await asyncio.gather(
|
||||
*[
|
||||
update_func(slug)
|
||||
for slug in wanted_addons
|
||||
if (first_update and needs_first_update)
|
||||
or enabled_key in container_updates[slug]
|
||||
]
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
# Refresh jobs data
|
||||
await self.jobs.refresh_data(first_update)
|
||||
|
||||
async def _update_addon_stats(self, slug: str) -> tuple[str, dict[str, Any] | None]:
|
||||
"""Update single addon stats."""
|
||||
try:
|
||||
stats = await self.supervisor_client.addons.addon_stats(slug)
|
||||
except SupervisorError as err:
|
||||
_LOGGER.warning("Could not fetch stats for %s: %s", slug, err)
|
||||
return (slug, None)
|
||||
return (slug, stats.to_dict())
|
||||
|
||||
async def _update_addon_info(self, slug: str) -> tuple[str, dict[str, Any] | None]:
|
||||
"""Return the info for an addon."""
|
||||
try:
|
||||
info = await self.supervisor_client.addons.addon_info(slug)
|
||||
except SupervisorError as err:
|
||||
_LOGGER.warning("Could not fetch info for %s: %s", slug, err)
|
||||
return (slug, None)
|
||||
# Translate to legacy hassio names for compatibility
|
||||
info_dict = info.to_dict()
|
||||
info_dict["hassio_api"] = info_dict.pop("supervisor_api")
|
||||
info_dict["hassio_role"] = info_dict.pop("supervisor_role")
|
||||
return (slug, info_dict)
|
||||
|
||||
@callback
|
||||
def async_enable_container_updates(
|
||||
self, slug: str, entity_id: str, types: set[str]
|
||||
) -> CALLBACK_TYPE:
|
||||
"""Enable updates for an add-on."""
|
||||
enabled_updates = self._container_updates[slug]
|
||||
for key in types:
|
||||
enabled_updates[key].add(entity_id)
|
||||
|
||||
@callback
|
||||
def _remove() -> None:
|
||||
for key in types:
|
||||
enabled_updates[key].remove(entity_id)
|
||||
|
||||
return _remove
|
||||
|
||||
async def _async_refresh(
|
||||
self,
|
||||
log_failures: bool = True,
|
||||
@@ -616,14 +766,16 @@ class HassioDataUpdateCoordinator(DataUpdateCoordinator):
|
||||
) -> None:
|
||||
"""Refresh data."""
|
||||
if not scheduled and not raise_on_auth_failed:
|
||||
# Force refreshing updates for non-scheduled updates
|
||||
# Force reloading updates of main components for
|
||||
# non-scheduled updates.
|
||||
#
|
||||
# If `raise_on_auth_failed` is set, it means this is
|
||||
# the first refresh and we do not want to delay
|
||||
# startup or cause a timeout so we only refresh the
|
||||
# updates if this is not a scheduled refresh and
|
||||
# we are not doing the first refresh.
|
||||
try:
|
||||
await self.supervisor_client.refresh_updates()
|
||||
await self.supervisor_client.reload_updates()
|
||||
except SupervisorError as err:
|
||||
_LOGGER.warning("Error on Supervisor API: %s", err)
|
||||
|
||||
@@ -631,18 +783,6 @@ class HassioDataUpdateCoordinator(DataUpdateCoordinator):
|
||||
log_failures, raise_on_auth_failed, scheduled, raise_on_entry_error
|
||||
)
|
||||
|
||||
async def force_addon_info_data_refresh(self, addon_slug: str) -> None:
|
||||
"""Force refresh of addon info data for a specific addon."""
|
||||
try:
|
||||
slug, info = await self._update_addon_info(addon_slug)
|
||||
if info is not None and DATA_KEY_ADDONS in self.data:
|
||||
if slug in self.data[DATA_KEY_ADDONS]:
|
||||
data = deepcopy(self.data)
|
||||
data[DATA_KEY_ADDONS][slug].update(info)
|
||||
self.async_set_updated_data(data)
|
||||
except SupervisorError as err:
|
||||
_LOGGER.warning("Could not refresh info for %s: %s", addon_slug, err)
|
||||
|
||||
@callback
|
||||
def unload(self) -> None:
|
||||
"""Clean up when config entry unloaded."""
|
||||
|
||||
@@ -11,8 +11,12 @@ from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers import device_registry as dr, entity_registry as er
|
||||
|
||||
from .const import ADDONS_COORDINATOR
|
||||
from .coordinator import HassioDataUpdateCoordinator
|
||||
from .const import ADDONS_COORDINATOR, MAIN_COORDINATOR, STATS_COORDINATOR
|
||||
from .coordinator import (
|
||||
HassioAddOnDataUpdateCoordinator,
|
||||
HassioMainDataUpdateCoordinator,
|
||||
HassioStatsDataUpdateCoordinator,
|
||||
)
|
||||
|
||||
|
||||
async def async_get_config_entry_diagnostics(
|
||||
@@ -20,7 +24,9 @@ async def async_get_config_entry_diagnostics(
|
||||
config_entry: ConfigEntry,
|
||||
) -> dict[str, Any]:
|
||||
"""Return diagnostics for a config entry."""
|
||||
coordinator: HassioDataUpdateCoordinator = hass.data[ADDONS_COORDINATOR]
|
||||
coordinator: HassioMainDataUpdateCoordinator = hass.data[MAIN_COORDINATOR]
|
||||
addons_coordinator: HassioAddOnDataUpdateCoordinator = hass.data[ADDONS_COORDINATOR]
|
||||
stats_coordinator: HassioStatsDataUpdateCoordinator = hass.data[STATS_COORDINATOR]
|
||||
device_registry = dr.async_get(hass)
|
||||
entity_registry = er.async_get(hass)
|
||||
|
||||
@@ -53,5 +59,7 @@ async def async_get_config_entry_diagnostics(
|
||||
|
||||
return {
|
||||
"coordinator_data": coordinator.data,
|
||||
"addons_coordinator_data": addons_coordinator.data,
|
||||
"stats_coordinator_data": stats_coordinator.data,
|
||||
"devices": devices,
|
||||
}
|
||||
|
||||
@@ -13,7 +13,6 @@ from homeassistant.helpers.update_coordinator import CoordinatorEntity
|
||||
from .const import (
|
||||
ATTR_SLUG,
|
||||
CONTAINER_STATS,
|
||||
CORE_CONTAINER,
|
||||
DATA_KEY_ADDONS,
|
||||
DATA_KEY_CORE,
|
||||
DATA_KEY_HOST,
|
||||
@@ -21,20 +20,79 @@ from .const import (
|
||||
DATA_KEY_OS,
|
||||
DATA_KEY_SUPERVISOR,
|
||||
DOMAIN,
|
||||
KEY_TO_UPDATE_TYPES,
|
||||
SUPERVISOR_CONTAINER,
|
||||
)
|
||||
from .coordinator import HassioDataUpdateCoordinator
|
||||
from .coordinator import (
|
||||
HassioAddOnDataUpdateCoordinator,
|
||||
HassioMainDataUpdateCoordinator,
|
||||
HassioStatsDataUpdateCoordinator,
|
||||
)
|
||||
|
||||
|
||||
class HassioAddonEntity(CoordinatorEntity[HassioDataUpdateCoordinator]):
|
||||
class HassioStatsEntity(CoordinatorEntity[HassioStatsDataUpdateCoordinator]):
|
||||
"""Base entity for container stats (CPU, memory)."""
|
||||
|
||||
_attr_has_entity_name = True
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
coordinator: HassioStatsDataUpdateCoordinator,
|
||||
entity_description: EntityDescription,
|
||||
*,
|
||||
container_id: str,
|
||||
data_key: str,
|
||||
device_id: str,
|
||||
unique_id_prefix: str,
|
||||
) -> None:
|
||||
"""Initialize base entity."""
|
||||
super().__init__(coordinator)
|
||||
self.entity_description = entity_description
|
||||
self._container_id = container_id
|
||||
self._data_key = data_key
|
||||
self._attr_unique_id = f"{unique_id_prefix}_{entity_description.key}"
|
||||
self._attr_device_info = DeviceInfo(identifiers={(DOMAIN, device_id)})
|
||||
|
||||
@property
|
||||
def available(self) -> bool:
|
||||
"""Return True if entity is available."""
|
||||
if self._data_key == DATA_KEY_ADDONS:
|
||||
return (
|
||||
super().available
|
||||
and DATA_KEY_ADDONS in self.coordinator.data
|
||||
and self.entity_description.key
|
||||
in (
|
||||
self.coordinator.data[DATA_KEY_ADDONS].get(self._container_id) or {}
|
||||
)
|
||||
)
|
||||
return (
|
||||
super().available
|
||||
and self._data_key in self.coordinator.data
|
||||
and self.entity_description.key in self.coordinator.data[self._data_key]
|
||||
)
|
||||
|
||||
async def async_added_to_hass(self) -> None:
|
||||
"""Subscribe to stats updates."""
|
||||
await super().async_added_to_hass()
|
||||
self.async_on_remove(
|
||||
self.coordinator.async_enable_container_updates(
|
||||
self._container_id, self.entity_id, {CONTAINER_STATS}
|
||||
)
|
||||
)
|
||||
# Stats are only fetched for containers with subscribed entities.
|
||||
# The first coordinator refresh (before entities exist) has no
|
||||
# subscribers, so no stats are fetched. Schedule a debounced
|
||||
# refresh so that all stats entities registering during platform
|
||||
# setup are batched into a single API call.
|
||||
await self.coordinator.async_request_refresh()
|
||||
|
||||
|
||||
class HassioAddonEntity(CoordinatorEntity[HassioAddOnDataUpdateCoordinator]):
|
||||
"""Base entity for a Hass.io add-on."""
|
||||
|
||||
_attr_has_entity_name = True
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
coordinator: HassioDataUpdateCoordinator,
|
||||
coordinator: HassioAddOnDataUpdateCoordinator,
|
||||
entity_description: EntityDescription,
|
||||
addon: dict[str, Any],
|
||||
) -> None:
|
||||
@@ -56,26 +114,23 @@ class HassioAddonEntity(CoordinatorEntity[HassioDataUpdateCoordinator]):
|
||||
)
|
||||
|
||||
async def async_added_to_hass(self) -> None:
|
||||
"""Subscribe to updates."""
|
||||
"""Subscribe to addon info updates."""
|
||||
await super().async_added_to_hass()
|
||||
update_types = KEY_TO_UPDATE_TYPES[self.entity_description.key]
|
||||
self.async_on_remove(
|
||||
self.coordinator.async_enable_container_updates(
|
||||
self._addon_slug, self.entity_id, update_types
|
||||
self.coordinator.async_enable_addon_info_updates(
|
||||
self._addon_slug, self.entity_id
|
||||
)
|
||||
)
|
||||
if CONTAINER_STATS in update_types:
|
||||
await self.coordinator.async_request_refresh()
|
||||
|
||||
|
||||
class HassioOSEntity(CoordinatorEntity[HassioDataUpdateCoordinator]):
|
||||
class HassioOSEntity(CoordinatorEntity[HassioMainDataUpdateCoordinator]):
|
||||
"""Base Entity for Hass.io OS."""
|
||||
|
||||
_attr_has_entity_name = True
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
coordinator: HassioDataUpdateCoordinator,
|
||||
coordinator: HassioMainDataUpdateCoordinator,
|
||||
entity_description: EntityDescription,
|
||||
) -> None:
|
||||
"""Initialize base entity."""
|
||||
@@ -94,14 +149,14 @@ class HassioOSEntity(CoordinatorEntity[HassioDataUpdateCoordinator]):
|
||||
)
|
||||
|
||||
|
||||
class HassioHostEntity(CoordinatorEntity[HassioDataUpdateCoordinator]):
|
||||
class HassioHostEntity(CoordinatorEntity[HassioMainDataUpdateCoordinator]):
|
||||
"""Base Entity for Hass.io host."""
|
||||
|
||||
_attr_has_entity_name = True
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
coordinator: HassioDataUpdateCoordinator,
|
||||
coordinator: HassioMainDataUpdateCoordinator,
|
||||
entity_description: EntityDescription,
|
||||
) -> None:
|
||||
"""Initialize base entity."""
|
||||
@@ -120,14 +175,14 @@ class HassioHostEntity(CoordinatorEntity[HassioDataUpdateCoordinator]):
|
||||
)
|
||||
|
||||
|
||||
class HassioSupervisorEntity(CoordinatorEntity[HassioDataUpdateCoordinator]):
|
||||
class HassioSupervisorEntity(CoordinatorEntity[HassioMainDataUpdateCoordinator]):
|
||||
"""Base Entity for Supervisor."""
|
||||
|
||||
_attr_has_entity_name = True
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
coordinator: HassioDataUpdateCoordinator,
|
||||
coordinator: HassioMainDataUpdateCoordinator,
|
||||
entity_description: EntityDescription,
|
||||
) -> None:
|
||||
"""Initialize base entity."""
|
||||
@@ -146,27 +201,15 @@ class HassioSupervisorEntity(CoordinatorEntity[HassioDataUpdateCoordinator]):
|
||||
in self.coordinator.data[DATA_KEY_SUPERVISOR]
|
||||
)
|
||||
|
||||
async def async_added_to_hass(self) -> None:
|
||||
"""Subscribe to updates."""
|
||||
await super().async_added_to_hass()
|
||||
update_types = KEY_TO_UPDATE_TYPES[self.entity_description.key]
|
||||
self.async_on_remove(
|
||||
self.coordinator.async_enable_container_updates(
|
||||
SUPERVISOR_CONTAINER, self.entity_id, update_types
|
||||
)
|
||||
)
|
||||
if CONTAINER_STATS in update_types:
|
||||
await self.coordinator.async_request_refresh()
|
||||
|
||||
|
||||
class HassioCoreEntity(CoordinatorEntity[HassioDataUpdateCoordinator]):
|
||||
class HassioCoreEntity(CoordinatorEntity[HassioMainDataUpdateCoordinator]):
|
||||
"""Base Entity for Core."""
|
||||
|
||||
_attr_has_entity_name = True
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
coordinator: HassioDataUpdateCoordinator,
|
||||
coordinator: HassioMainDataUpdateCoordinator,
|
||||
entity_description: EntityDescription,
|
||||
) -> None:
|
||||
"""Initialize base entity."""
|
||||
@@ -184,27 +227,15 @@ class HassioCoreEntity(CoordinatorEntity[HassioDataUpdateCoordinator]):
|
||||
and self.entity_description.key in self.coordinator.data[DATA_KEY_CORE]
|
||||
)
|
||||
|
||||
async def async_added_to_hass(self) -> None:
|
||||
"""Subscribe to updates."""
|
||||
await super().async_added_to_hass()
|
||||
update_types = KEY_TO_UPDATE_TYPES[self.entity_description.key]
|
||||
self.async_on_remove(
|
||||
self.coordinator.async_enable_container_updates(
|
||||
CORE_CONTAINER, self.entity_id, update_types
|
||||
)
|
||||
)
|
||||
if CONTAINER_STATS in update_types:
|
||||
await self.coordinator.async_request_refresh()
|
||||
|
||||
|
||||
class HassioMountEntity(CoordinatorEntity[HassioDataUpdateCoordinator]):
|
||||
class HassioMountEntity(CoordinatorEntity[HassioMainDataUpdateCoordinator]):
|
||||
"""Base Entity for Mount."""
|
||||
|
||||
_attr_has_entity_name = True
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
coordinator: HassioDataUpdateCoordinator,
|
||||
coordinator: HassioMainDataUpdateCoordinator,
|
||||
entity_description: EntityDescription,
|
||||
mount: CIFSMountResponse | NFSMountResponse,
|
||||
) -> None:
|
||||
|
||||
@@ -28,7 +28,6 @@ from homeassistant.helpers.issue_registry import (
|
||||
)
|
||||
|
||||
from .const import (
|
||||
ADDONS_COORDINATOR,
|
||||
ATTR_DATA,
|
||||
ATTR_HEALTHY,
|
||||
ATTR_SLUG,
|
||||
@@ -54,6 +53,7 @@ from .const import (
|
||||
ISSUE_KEY_SYSTEM_DOCKER_CONFIG,
|
||||
ISSUE_KEY_SYSTEM_FREE_SPACE,
|
||||
ISSUE_MOUNT_MOUNT_FAILED,
|
||||
MAIN_COORDINATOR,
|
||||
PLACEHOLDER_KEY_ADDON,
|
||||
PLACEHOLDER_KEY_ADDON_URL,
|
||||
PLACEHOLDER_KEY_FREE_SPACE,
|
||||
@@ -62,7 +62,7 @@ from .const import (
|
||||
STARTUP_COMPLETE,
|
||||
UPDATE_KEY_SUPERVISOR,
|
||||
)
|
||||
from .coordinator import HassioDataUpdateCoordinator, get_addons_list, get_host_info
|
||||
from .coordinator import HassioMainDataUpdateCoordinator, get_addons_list, get_host_info
|
||||
from .handler import get_supervisor_client
|
||||
|
||||
ISSUE_KEY_UNHEALTHY = "unhealthy"
|
||||
@@ -417,8 +417,8 @@ class SupervisorIssues:
|
||||
|
||||
def _async_coordinator_refresh(self) -> None:
|
||||
"""Refresh coordinator to update latest data in entities."""
|
||||
coordinator: HassioDataUpdateCoordinator | None
|
||||
if coordinator := self._hass.data.get(ADDONS_COORDINATOR):
|
||||
coordinator: HassioMainDataUpdateCoordinator | None
|
||||
if coordinator := self._hass.data.get(MAIN_COORDINATOR):
|
||||
coordinator.config_entry.async_create_task(
|
||||
self._hass, coordinator.async_refresh()
|
||||
)
|
||||
|
||||
@@ -17,20 +17,24 @@ from .const import (
|
||||
ADDONS_COORDINATOR,
|
||||
ATTR_CPU_PERCENT,
|
||||
ATTR_MEMORY_PERCENT,
|
||||
ATTR_SLUG,
|
||||
ATTR_VERSION,
|
||||
ATTR_VERSION_LATEST,
|
||||
CORE_CONTAINER,
|
||||
DATA_KEY_ADDONS,
|
||||
DATA_KEY_CORE,
|
||||
DATA_KEY_HOST,
|
||||
DATA_KEY_OS,
|
||||
DATA_KEY_SUPERVISOR,
|
||||
MAIN_COORDINATOR,
|
||||
STATS_COORDINATOR,
|
||||
SUPERVISOR_CONTAINER,
|
||||
)
|
||||
from .entity import (
|
||||
HassioAddonEntity,
|
||||
HassioCoreEntity,
|
||||
HassioHostEntity,
|
||||
HassioOSEntity,
|
||||
HassioSupervisorEntity,
|
||||
HassioStatsEntity,
|
||||
)
|
||||
|
||||
COMMON_ENTITY_DESCRIPTIONS = (
|
||||
@@ -63,10 +67,7 @@ STATS_ENTITY_DESCRIPTIONS = (
|
||||
),
|
||||
)
|
||||
|
||||
ADDON_ENTITY_DESCRIPTIONS = COMMON_ENTITY_DESCRIPTIONS + STATS_ENTITY_DESCRIPTIONS
|
||||
CORE_ENTITY_DESCRIPTIONS = STATS_ENTITY_DESCRIPTIONS
|
||||
OS_ENTITY_DESCRIPTIONS = COMMON_ENTITY_DESCRIPTIONS
|
||||
SUPERVISOR_ENTITY_DESCRIPTIONS = STATS_ENTITY_DESCRIPTIONS
|
||||
|
||||
HOST_ENTITY_DESCRIPTIONS = (
|
||||
SensorEntityDescription(
|
||||
@@ -114,36 +115,64 @@ async def async_setup_entry(
|
||||
async_add_entities: AddConfigEntryEntitiesCallback,
|
||||
) -> None:
|
||||
"""Sensor set up for Hass.io config entry."""
|
||||
coordinator = hass.data[ADDONS_COORDINATOR]
|
||||
addons_coordinator = hass.data[ADDONS_COORDINATOR]
|
||||
coordinator = hass.data[MAIN_COORDINATOR]
|
||||
stats_coordinator = hass.data[STATS_COORDINATOR]
|
||||
|
||||
entities: list[
|
||||
HassioOSSensor | HassioAddonSensor | CoreSensor | SupervisorSensor | HostSensor
|
||||
] = [
|
||||
entities: list[SensorEntity] = []
|
||||
|
||||
# Add-on non-stats sensors (version, version_latest)
|
||||
entities.extend(
|
||||
HassioAddonSensor(
|
||||
addon=addon,
|
||||
coordinator=coordinator,
|
||||
coordinator=addons_coordinator,
|
||||
entity_description=entity_description,
|
||||
)
|
||||
for addon in coordinator.data[DATA_KEY_ADDONS].values()
|
||||
for entity_description in ADDON_ENTITY_DESCRIPTIONS
|
||||
]
|
||||
|
||||
entities.extend(
|
||||
CoreSensor(
|
||||
coordinator=coordinator,
|
||||
entity_description=entity_description,
|
||||
)
|
||||
for entity_description in CORE_ENTITY_DESCRIPTIONS
|
||||
for addon in addons_coordinator.data[DATA_KEY_ADDONS].values()
|
||||
for entity_description in COMMON_ENTITY_DESCRIPTIONS
|
||||
)
|
||||
|
||||
# Add-on stats sensors (cpu_percent, memory_percent)
|
||||
entities.extend(
|
||||
SupervisorSensor(
|
||||
coordinator=coordinator,
|
||||
HassioStatsSensor(
|
||||
coordinator=stats_coordinator,
|
||||
entity_description=entity_description,
|
||||
container_id=addon[ATTR_SLUG],
|
||||
data_key=DATA_KEY_ADDONS,
|
||||
device_id=addon[ATTR_SLUG],
|
||||
unique_id_prefix=addon[ATTR_SLUG],
|
||||
)
|
||||
for entity_description in SUPERVISOR_ENTITY_DESCRIPTIONS
|
||||
for addon in addons_coordinator.data[DATA_KEY_ADDONS].values()
|
||||
for entity_description in STATS_ENTITY_DESCRIPTIONS
|
||||
)
|
||||
|
||||
# Core stats sensors
|
||||
entities.extend(
|
||||
HassioStatsSensor(
|
||||
coordinator=stats_coordinator,
|
||||
entity_description=entity_description,
|
||||
container_id=CORE_CONTAINER,
|
||||
data_key=DATA_KEY_CORE,
|
||||
device_id="core",
|
||||
unique_id_prefix="home_assistant_core",
|
||||
)
|
||||
for entity_description in STATS_ENTITY_DESCRIPTIONS
|
||||
)
|
||||
|
||||
# Supervisor stats sensors
|
||||
entities.extend(
|
||||
HassioStatsSensor(
|
||||
coordinator=stats_coordinator,
|
||||
entity_description=entity_description,
|
||||
container_id=SUPERVISOR_CONTAINER,
|
||||
data_key=DATA_KEY_SUPERVISOR,
|
||||
device_id="supervisor",
|
||||
unique_id_prefix="home_assistant_supervisor",
|
||||
)
|
||||
for entity_description in STATS_ENTITY_DESCRIPTIONS
|
||||
)
|
||||
|
||||
# Host sensors
|
||||
entities.extend(
|
||||
HostSensor(
|
||||
coordinator=coordinator,
|
||||
@@ -152,6 +181,7 @@ async def async_setup_entry(
|
||||
for entity_description in HOST_ENTITY_DESCRIPTIONS
|
||||
)
|
||||
|
||||
# OS sensors
|
||||
if coordinator.is_hass_os:
|
||||
entities.extend(
|
||||
HassioOSSensor(
|
||||
@@ -175,8 +205,21 @@ class HassioAddonSensor(HassioAddonEntity, SensorEntity):
|
||||
]
|
||||
|
||||
|
||||
class HassioStatsSensor(HassioStatsEntity, SensorEntity):
|
||||
"""Sensor to track container stats."""
|
||||
|
||||
@property
|
||||
def native_value(self) -> str:
|
||||
"""Return native value of entity."""
|
||||
if self._data_key == DATA_KEY_ADDONS:
|
||||
return self.coordinator.data[DATA_KEY_ADDONS][self._container_id][
|
||||
self.entity_description.key
|
||||
]
|
||||
return self.coordinator.data[self._data_key][self.entity_description.key]
|
||||
|
||||
|
||||
class HassioOSSensor(HassioOSEntity, SensorEntity):
|
||||
"""Sensor to track a Hass.io add-on attribute."""
|
||||
"""Sensor to track a Hass.io OS attribute."""
|
||||
|
||||
@property
|
||||
def native_value(self) -> str:
|
||||
@@ -184,24 +227,6 @@ class HassioOSSensor(HassioOSEntity, SensorEntity):
|
||||
return self.coordinator.data[DATA_KEY_OS][self.entity_description.key]
|
||||
|
||||
|
||||
class CoreSensor(HassioCoreEntity, SensorEntity):
|
||||
"""Sensor to track a core attribute."""
|
||||
|
||||
@property
|
||||
def native_value(self) -> str:
|
||||
"""Return native value of entity."""
|
||||
return self.coordinator.data[DATA_KEY_CORE][self.entity_description.key]
|
||||
|
||||
|
||||
class SupervisorSensor(HassioSupervisorEntity, SensorEntity):
|
||||
"""Sensor to track a supervisor attribute."""
|
||||
|
||||
@property
|
||||
def native_value(self) -> str:
|
||||
"""Return native value of entity."""
|
||||
return self.coordinator.data[DATA_KEY_SUPERVISOR][self.entity_description.key]
|
||||
|
||||
|
||||
class HostSensor(HassioHostEntity, SensorEntity):
|
||||
"""Sensor to track a host attribute."""
|
||||
|
||||
|
||||
@@ -32,7 +32,6 @@ from homeassistant.helpers import (
|
||||
from homeassistant.util.dt import now
|
||||
|
||||
from .const import (
|
||||
ADDONS_COORDINATOR,
|
||||
ATTR_ADDON,
|
||||
ATTR_ADDONS,
|
||||
ATTR_APP,
|
||||
@@ -46,9 +45,10 @@ from .const import (
|
||||
ATTR_PASSWORD,
|
||||
ATTR_SLUG,
|
||||
DOMAIN,
|
||||
MAIN_COORDINATOR,
|
||||
SupervisorEntityModel,
|
||||
)
|
||||
from .coordinator import HassioDataUpdateCoordinator, get_addons_info
|
||||
from .coordinator import HassioMainDataUpdateCoordinator, get_addons_info
|
||||
|
||||
SERVICE_ADDON_START = "addon_start"
|
||||
SERVICE_ADDON_STOP = "addon_stop"
|
||||
@@ -406,7 +406,7 @@ def async_register_network_storage_services(
|
||||
|
||||
async def async_mount_reload(service: ServiceCall) -> None:
|
||||
"""Handle service calls for Hass.io."""
|
||||
coordinator: HassioDataUpdateCoordinator | None = None
|
||||
coordinator: HassioMainDataUpdateCoordinator | None = None
|
||||
|
||||
if (device := dev_reg.async_get(service.data[ATTR_DEVICE_ID])) is None:
|
||||
raise ServiceValidationError(
|
||||
@@ -417,7 +417,7 @@ def async_register_network_storage_services(
|
||||
if (
|
||||
device.name is None
|
||||
or device.model != SupervisorEntityModel.MOUNT
|
||||
or (coordinator := hass.data.get(ADDONS_COORDINATOR)) is None
|
||||
or (coordinator := hass.data.get(MAIN_COORDINATOR)) is None
|
||||
or coordinator.entry_id not in device.config_entries
|
||||
):
|
||||
raise ServiceValidationError(
|
||||
|
||||
@@ -29,6 +29,7 @@ from .const import (
|
||||
DATA_KEY_CORE,
|
||||
DATA_KEY_OS,
|
||||
DATA_KEY_SUPERVISOR,
|
||||
MAIN_COORDINATOR,
|
||||
)
|
||||
from .entity import (
|
||||
HassioAddonEntity,
|
||||
@@ -51,9 +52,9 @@ async def async_setup_entry(
|
||||
async_add_entities: AddConfigEntryEntitiesCallback,
|
||||
) -> None:
|
||||
"""Set up Supervisor update based on a config entry."""
|
||||
coordinator = hass.data[ADDONS_COORDINATOR]
|
||||
coordinator = hass.data[MAIN_COORDINATOR]
|
||||
|
||||
entities = [
|
||||
entities: list[UpdateEntity] = [
|
||||
SupervisorSupervisorUpdateEntity(
|
||||
coordinator=coordinator,
|
||||
entity_description=ENTITY_DESCRIPTION,
|
||||
@@ -64,15 +65,6 @@ async def async_setup_entry(
|
||||
),
|
||||
]
|
||||
|
||||
entities.extend(
|
||||
SupervisorAddonUpdateEntity(
|
||||
addon=addon,
|
||||
coordinator=coordinator,
|
||||
entity_description=ENTITY_DESCRIPTION,
|
||||
)
|
||||
for addon in coordinator.data[DATA_KEY_ADDONS].values()
|
||||
)
|
||||
|
||||
if coordinator.is_hass_os:
|
||||
entities.append(
|
||||
SupervisorOSUpdateEntity(
|
||||
@@ -81,6 +73,16 @@ async def async_setup_entry(
|
||||
)
|
||||
)
|
||||
|
||||
addons_coordinator = hass.data[ADDONS_COORDINATOR]
|
||||
entities.extend(
|
||||
SupervisorAddonUpdateEntity(
|
||||
addon=addon,
|
||||
coordinator=addons_coordinator,
|
||||
entity_description=ENTITY_DESCRIPTION,
|
||||
)
|
||||
for addon in addons_coordinator.data[DATA_KEY_ADDONS].values()
|
||||
)
|
||||
|
||||
async_add_entities(entities)
|
||||
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from homeassistant.core import callback
|
||||
from homeassistant.helpers.entity import Entity
|
||||
|
||||
from .const import DOMAIN, EVENT_HDMI_CEC_UNAVAILABLE
|
||||
@@ -55,9 +56,10 @@ class CecEntity(Entity):
|
||||
else:
|
||||
self._attr_name = f"{self._device.type_name} {self._logical_address} ({self._device.osd_name})"
|
||||
|
||||
@callback
|
||||
def _hdmi_cec_unavailable(self, callback_event):
|
||||
self._attr_available = False
|
||||
self.schedule_update_ha_state(False)
|
||||
self.async_write_ha_state()
|
||||
|
||||
async def async_added_to_hass(self) -> None:
|
||||
"""Register HDMI callbacks after initialization."""
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from pycec.commands import CecCommand, KeyPressCommand, KeyReleaseCommand
|
||||
from pycec.const import (
|
||||
@@ -31,7 +30,6 @@ from homeassistant.components.media_player import (
|
||||
MediaPlayerEntity,
|
||||
MediaPlayerEntityFeature,
|
||||
MediaPlayerState,
|
||||
MediaType,
|
||||
)
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
||||
@@ -45,20 +43,20 @@ _LOGGER = logging.getLogger(__name__)
|
||||
ENTITY_ID_FORMAT = MP_DOMAIN + ".{}"
|
||||
|
||||
|
||||
def setup_platform(
|
||||
async def async_setup_platform(
|
||||
hass: HomeAssistant,
|
||||
config: ConfigType,
|
||||
add_entities: AddEntitiesCallback,
|
||||
async_add_entities: AddEntitiesCallback,
|
||||
discovery_info: DiscoveryInfoType | None = None,
|
||||
) -> None:
|
||||
"""Find and return HDMI devices as +switches."""
|
||||
"""Find and return HDMI devices as media players."""
|
||||
if discovery_info and ATTR_NEW in discovery_info:
|
||||
_LOGGER.debug("Setting up HDMI devices %s", discovery_info[ATTR_NEW])
|
||||
entities = []
|
||||
for device in discovery_info[ATTR_NEW]:
|
||||
hdmi_device = hass.data[DOMAIN][device]
|
||||
entities.append(CecPlayerEntity(hdmi_device, hdmi_device.logical_address))
|
||||
add_entities(entities, True)
|
||||
async_add_entities(entities, True)
|
||||
|
||||
|
||||
class CecPlayerEntity(CecEntity, MediaPlayerEntity):
|
||||
@@ -79,78 +77,61 @@ class CecPlayerEntity(CecEntity, MediaPlayerEntity):
|
||||
|
||||
def send_playback(self, key):
|
||||
"""Send playback status to CEC adapter."""
|
||||
self._device.async_send_command(CecCommand(key, dst=self._logical_address))
|
||||
self._device.send_command(CecCommand(key, dst=self._logical_address))
|
||||
|
||||
def mute_volume(self, mute: bool) -> None:
|
||||
async def async_mute_volume(self, mute: bool) -> None:
|
||||
"""Mute volume."""
|
||||
self.send_keypress(KEY_MUTE_TOGGLE)
|
||||
|
||||
def media_previous_track(self) -> None:
|
||||
async def async_media_previous_track(self) -> None:
|
||||
"""Go to previous track."""
|
||||
self.send_keypress(KEY_BACKWARD)
|
||||
|
||||
def turn_on(self) -> None:
|
||||
async def async_turn_on(self) -> None:
|
||||
"""Turn device on."""
|
||||
self._device.turn_on()
|
||||
self._attr_state = MediaPlayerState.ON
|
||||
self.async_write_ha_state()
|
||||
|
||||
def clear_playlist(self) -> None:
|
||||
"""Clear players playlist."""
|
||||
raise NotImplementedError
|
||||
|
||||
def turn_off(self) -> None:
|
||||
async def async_turn_off(self) -> None:
|
||||
"""Turn device off."""
|
||||
self._device.turn_off()
|
||||
self._attr_state = MediaPlayerState.OFF
|
||||
self.async_write_ha_state()
|
||||
|
||||
def media_stop(self) -> None:
|
||||
async def async_media_stop(self) -> None:
|
||||
"""Stop playback."""
|
||||
self.send_keypress(KEY_STOP)
|
||||
self._attr_state = MediaPlayerState.IDLE
|
||||
self.async_write_ha_state()
|
||||
|
||||
def play_media(
|
||||
self, media_type: MediaType | str, media_id: str, **kwargs: Any
|
||||
) -> None:
|
||||
"""Not supported."""
|
||||
raise NotImplementedError
|
||||
|
||||
def media_next_track(self) -> None:
|
||||
async def async_media_next_track(self) -> None:
|
||||
"""Skip to next track."""
|
||||
self.send_keypress(KEY_FORWARD)
|
||||
|
||||
def media_seek(self, position: float) -> None:
|
||||
"""Not supported."""
|
||||
raise NotImplementedError
|
||||
|
||||
def set_volume_level(self, volume: float) -> None:
|
||||
"""Set volume level, range 0..1."""
|
||||
raise NotImplementedError
|
||||
|
||||
def media_pause(self) -> None:
|
||||
async def async_media_pause(self) -> None:
|
||||
"""Pause playback."""
|
||||
self.send_keypress(KEY_PAUSE)
|
||||
self._attr_state = MediaPlayerState.PAUSED
|
||||
self.async_write_ha_state()
|
||||
|
||||
def select_source(self, source: str) -> None:
|
||||
"""Not supported."""
|
||||
raise NotImplementedError
|
||||
|
||||
def media_play(self) -> None:
|
||||
async def async_media_play(self) -> None:
|
||||
"""Start playback."""
|
||||
self.send_keypress(KEY_PLAY)
|
||||
self._attr_state = MediaPlayerState.PLAYING
|
||||
self.async_write_ha_state()
|
||||
|
||||
def volume_up(self) -> None:
|
||||
async def async_volume_up(self) -> None:
|
||||
"""Increase volume."""
|
||||
_LOGGER.debug("%s: volume up", self._logical_address)
|
||||
self.send_keypress(KEY_VOLUME_UP)
|
||||
|
||||
def volume_down(self) -> None:
|
||||
async def async_volume_down(self) -> None:
|
||||
"""Decrease volume."""
|
||||
_LOGGER.debug("%s: volume down", self._logical_address)
|
||||
self.send_keypress(KEY_VOLUME_DOWN)
|
||||
|
||||
def update(self) -> None:
|
||||
async def async_update(self) -> None:
|
||||
"""Update device status."""
|
||||
device = self._device
|
||||
if device.power_status in [POWER_OFF, 3]:
|
||||
|
||||
@@ -20,10 +20,10 @@ _LOGGER = logging.getLogger(__name__)
|
||||
ENTITY_ID_FORMAT = SWITCH_DOMAIN + ".{}"
|
||||
|
||||
|
||||
def setup_platform(
|
||||
async def async_setup_platform(
|
||||
hass: HomeAssistant,
|
||||
config: ConfigType,
|
||||
add_entities: AddEntitiesCallback,
|
||||
async_add_entities: AddEntitiesCallback,
|
||||
discovery_info: DiscoveryInfoType | None = None,
|
||||
) -> None:
|
||||
"""Find and return HDMI devices as switches."""
|
||||
@@ -33,7 +33,7 @@ def setup_platform(
|
||||
for device in discovery_info[ATTR_NEW]:
|
||||
hdmi_device = hass.data[DOMAIN][device]
|
||||
entities.append(CecSwitchEntity(hdmi_device, hdmi_device.logical_address))
|
||||
add_entities(entities, True)
|
||||
async_add_entities(entities, True)
|
||||
|
||||
|
||||
class CecSwitchEntity(CecEntity, SwitchEntity):
|
||||
@@ -44,19 +44,19 @@ class CecSwitchEntity(CecEntity, SwitchEntity):
|
||||
CecEntity.__init__(self, device, logical)
|
||||
self.entity_id = f"{SWITCH_DOMAIN}.hdmi_{hex(self._logical_address)[2:]}"
|
||||
|
||||
def turn_on(self, **kwargs: Any) -> None:
|
||||
async def async_turn_on(self, **kwargs: Any) -> None:
|
||||
"""Turn device on."""
|
||||
self._device.turn_on()
|
||||
self._attr_is_on = True
|
||||
self.schedule_update_ha_state(force_refresh=False)
|
||||
self.async_write_ha_state()
|
||||
|
||||
def turn_off(self, **kwargs: Any) -> None:
|
||||
async def async_turn_off(self, **kwargs: Any) -> None:
|
||||
"""Turn device off."""
|
||||
self._device.turn_off()
|
||||
self._attr_is_on = False
|
||||
self.schedule_update_ha_state(force_refresh=False)
|
||||
self.async_write_ha_state()
|
||||
|
||||
def update(self) -> None:
|
||||
async def async_update(self) -> None:
|
||||
"""Update device status."""
|
||||
device = self._device
|
||||
if device.power_status in {POWER_OFF, 3}:
|
||||
|
||||
@@ -148,7 +148,7 @@
|
||||
},
|
||||
"step": {
|
||||
"init": {
|
||||
"description": "The integration `{domain}` could not be found. This happens when a (community) integration was removed from Home Assistant, but there are still configurations for this `integration`. Please use the buttons below to either remove the previous configurations for `{domain}` or ignore this.",
|
||||
"description": "The integration `{domain}` could not be found. This happens when a (custom) integration was removed from Home Assistant, but there are still configurations for this `integration`. Please use the buttons below to either remove the previous configurations for `{domain}` or ignore this.",
|
||||
"menu_options": {
|
||||
"confirm": "Remove previous configurations",
|
||||
"ignore": "Ignore"
|
||||
@@ -236,7 +236,7 @@
|
||||
"description": "Restarts Home Assistant.",
|
||||
"fields": {
|
||||
"safe_mode": {
|
||||
"description": "Disable community integrations and community cards.",
|
||||
"description": "Disable custom integrations and custom cards.",
|
||||
"name": "Safe mode"
|
||||
}
|
||||
},
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
"documentation": "https://www.home-assistant.io/integrations/homeassistant_hardware",
|
||||
"integration_type": "system",
|
||||
"requirements": [
|
||||
"serialx==1.1.1",
|
||||
"serialx==1.2.2",
|
||||
"universal-silabs-flasher==1.0.3",
|
||||
"ha-silabs-firmware-client==0.3.0"
|
||||
]
|
||||
|
||||
@@ -625,10 +625,13 @@ def _get_test_socket() -> socket.socket:
|
||||
@callback
|
||||
def async_port_is_available(port: int) -> bool:
|
||||
"""Check to see if a port is available."""
|
||||
test_socket = _get_test_socket()
|
||||
try:
|
||||
_get_test_socket().bind(("", port))
|
||||
test_socket.bind(("", port))
|
||||
except OSError:
|
||||
return False
|
||||
finally:
|
||||
test_socket.close()
|
||||
return True
|
||||
|
||||
|
||||
|
||||
@@ -7,5 +7,5 @@
|
||||
"integration_type": "hub",
|
||||
"iot_class": "cloud_push",
|
||||
"loggers": ["homematicip"],
|
||||
"requirements": ["homematicip==2.7.0"]
|
||||
"requirements": ["homematicip==2.8.0"]
|
||||
}
|
||||
|
||||
@@ -13,5 +13,5 @@
|
||||
"documentation": "https://www.home-assistant.io/integrations/husqvarna_automower_ble",
|
||||
"integration_type": "device",
|
||||
"iot_class": "local_polling",
|
||||
"requirements": ["automower-ble==0.2.8", "gardena-bluetooth==2.3.0"]
|
||||
"requirements": ["automower-ble==0.2.8", "gardena-bluetooth==2.4.0"]
|
||||
}
|
||||
|
||||
@@ -42,7 +42,6 @@ class HassAqualinkBinarySensor(
|
||||
) -> None:
|
||||
"""Initialize AquaLink binary sensor."""
|
||||
super().__init__(coordinator, dev)
|
||||
self._attr_name = dev.label
|
||||
if dev.label == "Freeze Protection":
|
||||
self._attr_device_class = BinarySensorDeviceClass.COLD
|
||||
|
||||
|
||||
@@ -57,7 +57,6 @@ class HassAqualinkThermostat(AqualinkEntity[AqualinkThermostat], ClimateEntity):
|
||||
) -> None:
|
||||
"""Initialize AquaLink thermostat."""
|
||||
super().__init__(coordinator, dev)
|
||||
self._attr_name = dev.label.split(" ")[0]
|
||||
self._attr_temperature_unit = (
|
||||
UnitOfTemperature.FAHRENHEIT
|
||||
if dev.unit == "F"
|
||||
|
||||
@@ -22,6 +22,9 @@ class AqualinkEntity[AqualinkDeviceT: AqualinkDevice](
|
||||
entity update flow.
|
||||
"""
|
||||
|
||||
_attr_has_entity_name = True
|
||||
_attr_name = None
|
||||
|
||||
def __init__(
|
||||
self, coordinator: AqualinkDataUpdateCoordinator, dev: AqualinkDeviceT
|
||||
) -> None:
|
||||
|
||||
@@ -46,7 +46,6 @@ class HassAqualinkLight(AqualinkEntity[AqualinkLight], LightEntity):
|
||||
) -> None:
|
||||
"""Initialize AquaLink light."""
|
||||
super().__init__(coordinator, dev)
|
||||
self._attr_name = dev.label
|
||||
if dev.supports_effect:
|
||||
self._attr_effect_list = list(dev.supported_effects)
|
||||
self._attr_supported_features = LightEntityFeature.EFFECT
|
||||
|
||||
@@ -38,7 +38,6 @@ class HassAqualinkSensor(AqualinkEntity[AqualinkSensor], SensorEntity):
|
||||
) -> None:
|
||||
"""Initialize AquaLink sensor."""
|
||||
super().__init__(coordinator, dev)
|
||||
self._attr_name = dev.label
|
||||
if not dev.name.endswith("_temp"):
|
||||
return
|
||||
self._attr_device_class = SensorDeviceClass.TEMPERATURE
|
||||
|
||||
@@ -40,7 +40,7 @@ class HassAqualinkSwitch(AqualinkEntity[AqualinkSwitch], SwitchEntity):
|
||||
) -> None:
|
||||
"""Initialize AquaLink switch."""
|
||||
super().__init__(coordinator, dev)
|
||||
name = self._attr_name = dev.label
|
||||
name = dev.label
|
||||
if name == "Cleaner":
|
||||
self._attr_icon = "mdi:robot-vacuum"
|
||||
elif name == "Waterfall" or name.endswith("Dscnt"):
|
||||
|
||||
@@ -7,5 +7,5 @@
|
||||
"documentation": "https://www.home-assistant.io/integrations/image_upload",
|
||||
"integration_type": "system",
|
||||
"quality_scale": "internal",
|
||||
"requirements": ["Pillow==12.1.1"]
|
||||
"requirements": ["Pillow==12.2.0"]
|
||||
}
|
||||
|
||||
@@ -92,83 +92,15 @@ async def async_setup_entry(
|
||||
for area in lutron_client.areas:
|
||||
_LOGGER.debug("Working on area %s", area.name)
|
||||
for output in area.outputs:
|
||||
platform = None
|
||||
_LOGGER.debug("Working on output %s", output.type)
|
||||
if output.type == "SYSTEM_SHADE":
|
||||
entry_data.covers.append((area.name, output))
|
||||
platform = Platform.COVER
|
||||
elif output.type == "CEILING_FAN_TYPE":
|
||||
entry_data.fans.append((area.name, output))
|
||||
platform = Platform.FAN
|
||||
elif output.is_dimmable:
|
||||
entry_data.lights.append((area.name, output))
|
||||
platform = Platform.LIGHT
|
||||
else:
|
||||
entry_data.switches.append((area.name, output))
|
||||
platform = Platform.SWITCH
|
||||
|
||||
_async_check_entity_unique_id(
|
||||
hass,
|
||||
entity_registry,
|
||||
platform,
|
||||
output.uuid,
|
||||
output.legacy_uuid,
|
||||
entry_data.client.guid,
|
||||
)
|
||||
_async_check_device_identifiers(
|
||||
hass,
|
||||
device_registry,
|
||||
output.uuid,
|
||||
output.legacy_uuid,
|
||||
entry_data.client.guid,
|
||||
_setup_output(
|
||||
hass, entry_data, output, area.name, entity_registry, device_registry
|
||||
)
|
||||
|
||||
for keypad in area.keypads:
|
||||
_async_check_keypad_identifiers(
|
||||
hass,
|
||||
device_registry,
|
||||
keypad.id,
|
||||
keypad.uuid,
|
||||
keypad.legacy_uuid,
|
||||
entry_data.client.guid,
|
||||
_setup_keypad(
|
||||
hass, entry_data, keypad, area.name, entity_registry, device_registry
|
||||
)
|
||||
for button in keypad.buttons:
|
||||
# If the button has a function assigned to it, add it as a scene
|
||||
if button.name != "Unknown Button" and button.button_type in (
|
||||
"SingleAction",
|
||||
"Toggle",
|
||||
"SingleSceneRaiseLower",
|
||||
"MasterRaiseLower",
|
||||
"AdvancedToggle",
|
||||
):
|
||||
# Associate an LED with a button if there is one
|
||||
led = next(
|
||||
(led for led in keypad.leds if led.number == button.number),
|
||||
None,
|
||||
)
|
||||
entry_data.scenes.append((area.name, keypad, button, led))
|
||||
|
||||
platform = Platform.SCENE
|
||||
_async_check_entity_unique_id(
|
||||
hass,
|
||||
entity_registry,
|
||||
platform,
|
||||
button.uuid,
|
||||
button.legacy_uuid,
|
||||
entry_data.client.guid,
|
||||
)
|
||||
if led is not None:
|
||||
platform = Platform.SWITCH
|
||||
_async_check_entity_unique_id(
|
||||
hass,
|
||||
entity_registry,
|
||||
platform,
|
||||
led.uuid,
|
||||
led.legacy_uuid,
|
||||
entry_data.client.guid,
|
||||
)
|
||||
if button.button_type:
|
||||
entry_data.buttons.append((area.name, keypad, button))
|
||||
if area.occupancy_group is not None:
|
||||
entry_data.binary_sensors.append((area.name, area.occupancy_group))
|
||||
platform = Platform.BINARY_SENSOR
|
||||
@@ -202,6 +134,99 @@ async def async_setup_entry(
|
||||
return True
|
||||
|
||||
|
||||
def _setup_output(
|
||||
hass: HomeAssistant,
|
||||
entry_data: LutronData,
|
||||
output: Output,
|
||||
area_name: str,
|
||||
entity_registry: er.EntityRegistry,
|
||||
device_registry: dr.DeviceRegistry,
|
||||
) -> None:
|
||||
"""Set up a Lutron output."""
|
||||
_LOGGER.debug("Working on output %s", output.type)
|
||||
if output.type == "SYSTEM_SHADE":
|
||||
entry_data.covers.append((area_name, output))
|
||||
platform = Platform.COVER
|
||||
elif output.type == "CEILING_FAN_TYPE":
|
||||
entry_data.fans.append((area_name, output))
|
||||
platform = Platform.FAN
|
||||
elif output.is_dimmable:
|
||||
entry_data.lights.append((area_name, output))
|
||||
platform = Platform.LIGHT
|
||||
else:
|
||||
entry_data.switches.append((area_name, output))
|
||||
platform = Platform.SWITCH
|
||||
|
||||
_async_check_entity_unique_id(
|
||||
hass,
|
||||
entity_registry,
|
||||
platform,
|
||||
output.uuid,
|
||||
output.legacy_uuid,
|
||||
entry_data.client.guid,
|
||||
)
|
||||
_async_check_device_identifiers(
|
||||
hass,
|
||||
device_registry,
|
||||
output.uuid,
|
||||
output.legacy_uuid,
|
||||
entry_data.client.guid,
|
||||
)
|
||||
|
||||
|
||||
def _setup_keypad(
|
||||
hass: HomeAssistant,
|
||||
entry_data: LutronData,
|
||||
keypad: Keypad,
|
||||
area_name: str,
|
||||
entity_registry: er.EntityRegistry,
|
||||
device_registry: dr.DeviceRegistry,
|
||||
) -> None:
|
||||
"""Set up a Lutron keypad."""
|
||||
|
||||
_async_check_keypad_identifiers(
|
||||
hass,
|
||||
device_registry,
|
||||
keypad.id,
|
||||
keypad.uuid,
|
||||
keypad.legacy_uuid,
|
||||
entry_data.client.guid,
|
||||
)
|
||||
leds_by_number = {led.number: led for led in keypad.leds}
|
||||
for button in keypad.buttons:
|
||||
# If the button has a function assigned to it, add it as a scene
|
||||
if button.name != "Unknown Button" and button.button_type in (
|
||||
"SingleAction",
|
||||
"Toggle",
|
||||
"SingleSceneRaiseLower",
|
||||
"MasterRaiseLower",
|
||||
"AdvancedToggle",
|
||||
):
|
||||
# Associate an LED with a button if there is one
|
||||
led = leds_by_number.get(button.number)
|
||||
entry_data.scenes.append((area_name, keypad, button, led))
|
||||
|
||||
_async_check_entity_unique_id(
|
||||
hass,
|
||||
entity_registry,
|
||||
Platform.SCENE,
|
||||
button.uuid,
|
||||
button.legacy_uuid,
|
||||
entry_data.client.guid,
|
||||
)
|
||||
if led is not None:
|
||||
_async_check_entity_unique_id(
|
||||
hass,
|
||||
entity_registry,
|
||||
Platform.SWITCH,
|
||||
led.uuid,
|
||||
led.legacy_uuid,
|
||||
entry_data.client.guid,
|
||||
)
|
||||
if button.button_type:
|
||||
entry_data.buttons.append((area_name, keypad, button))
|
||||
|
||||
|
||||
def _async_check_entity_unique_id(
|
||||
hass: HomeAssistant,
|
||||
entity_registry: er.EntityRegistry,
|
||||
|
||||
@@ -127,6 +127,12 @@ CONFIG_SCHEMA = vol.Schema(
|
||||
)
|
||||
|
||||
|
||||
def _read_image_size(image_path: str) -> tuple[int, int]:
|
||||
"""Open image to determine image size."""
|
||||
with Image.open(image_path) as image:
|
||||
return image.size
|
||||
|
||||
|
||||
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
||||
"""Set up the Matrix bot component."""
|
||||
config = config[DOMAIN]
|
||||
@@ -504,8 +510,9 @@ class MatrixBot:
|
||||
return
|
||||
|
||||
# Get required image metadata.
|
||||
image = await self.hass.async_add_executor_job(Image.open, image_path)
|
||||
(width, height) = image.size
|
||||
(width, height) = await self.hass.async_add_executor_job(
|
||||
_read_image_size, image_path
|
||||
)
|
||||
mime_type = mimetypes.guess_type(image_path)[0]
|
||||
file_stat = await aiofiles.os.stat(image_path)
|
||||
|
||||
|
||||
@@ -6,5 +6,5 @@
|
||||
"iot_class": "cloud_push",
|
||||
"loggers": ["matrix_client"],
|
||||
"quality_scale": "legacy",
|
||||
"requirements": ["matrix-nio==0.25.2", "Pillow==12.1.1", "aiofiles==24.1.0"]
|
||||
"requirements": ["matrix-nio==0.25.2", "Pillow==12.2.0", "aiofiles==24.1.0"]
|
||||
}
|
||||
|
||||
@@ -24,6 +24,8 @@ See https://modelcontextprotocol.io/docs/concepts/transports
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
from collections.abc import AsyncGenerator
|
||||
from contextlib import asynccontextmanager
|
||||
from dataclasses import dataclass
|
||||
from http import HTTPStatus
|
||||
import logging
|
||||
@@ -102,17 +104,29 @@ class Streams:
|
||||
write_stream: MemoryObjectSendStream[SessionMessage]
|
||||
write_stream_reader: MemoryObjectReceiveStream[SessionMessage]
|
||||
|
||||
async def aclose(self) -> None:
|
||||
"""Close open memory streams."""
|
||||
await self.read_stream.aclose()
|
||||
await self.read_stream_writer.aclose()
|
||||
await self.write_stream.aclose()
|
||||
await self.write_stream_reader.aclose()
|
||||
|
||||
def create_streams() -> Streams:
|
||||
|
||||
@asynccontextmanager
|
||||
async def create_streams() -> AsyncGenerator[Streams]:
|
||||
"""Create a new pair of streams for MCP server communication."""
|
||||
read_stream_writer, read_stream = anyio.create_memory_object_stream(0)
|
||||
write_stream, write_stream_reader = anyio.create_memory_object_stream(0)
|
||||
return Streams(
|
||||
streams = Streams(
|
||||
read_stream=read_stream,
|
||||
read_stream_writer=read_stream_writer,
|
||||
write_stream=write_stream,
|
||||
write_stream_reader=write_stream_reader,
|
||||
)
|
||||
try:
|
||||
yield streams
|
||||
finally:
|
||||
await streams.aclose()
|
||||
|
||||
|
||||
async def create_mcp_server(
|
||||
@@ -155,9 +169,9 @@ class ModelContextProtocolSSEView(HomeAssistantView):
|
||||
session_manager = entry.runtime_data
|
||||
|
||||
server, options = await create_mcp_server(hass, self.context(request), entry)
|
||||
streams = create_streams()
|
||||
|
||||
async with (
|
||||
create_streams() as streams,
|
||||
sse_response(request) as response,
|
||||
session_manager.create(Session(streams.read_stream_writer)) as session_id,
|
||||
):
|
||||
@@ -261,21 +275,24 @@ class ModelContextProtocolStreamableView(HomeAssistantView):
|
||||
# request is sent to the MCP server and we wait for a single response
|
||||
# then shut down the server.
|
||||
server, options = await create_mcp_server(hass, self.context(request), entry)
|
||||
streams = create_streams()
|
||||
|
||||
async def run_server() -> None:
|
||||
await server.run(
|
||||
streams.read_stream, streams.write_stream, options, stateless=True
|
||||
async with create_streams() as streams:
|
||||
|
||||
async def run_server() -> None:
|
||||
await server.run(
|
||||
streams.read_stream, streams.write_stream, options, stateless=True
|
||||
)
|
||||
|
||||
async with asyncio.timeout(TIMEOUT), anyio.create_task_group() as tg:
|
||||
tg.start_soon(run_server)
|
||||
|
||||
await streams.read_stream_writer.send(SessionMessage(message))
|
||||
session_message = await anext(streams.write_stream_reader)
|
||||
tg.cancel_scope.cancel()
|
||||
|
||||
_LOGGER.debug("Sending response: %s", session_message)
|
||||
return web.json_response(
|
||||
data=session_message.message.model_dump(
|
||||
by_alias=True, exclude_none=True
|
||||
),
|
||||
)
|
||||
|
||||
async with asyncio.timeout(TIMEOUT), anyio.create_task_group() as tg:
|
||||
tg.start_soon(run_server)
|
||||
|
||||
await streams.read_stream_writer.send(SessionMessage(message))
|
||||
session_message = await anext(streams.write_stream_reader)
|
||||
tg.cancel_scope.cancel()
|
||||
|
||||
_LOGGER.debug("Sending response: %s", session_message)
|
||||
return web.json_response(
|
||||
data=session_message.message.model_dump(by_alias=True, exclude_none=True),
|
||||
)
|
||||
|
||||
@@ -75,7 +75,6 @@ from .const import ( # noqa: F401
|
||||
ATTR_GROUP_MEMBERS,
|
||||
ATTR_INPUT_SOURCE,
|
||||
ATTR_INPUT_SOURCE_LIST,
|
||||
ATTR_LAST_NON_BUFFERING_STATE,
|
||||
ATTR_MEDIA_ALBUM_ARTIST,
|
||||
ATTR_MEDIA_ALBUM_NAME,
|
||||
ATTR_MEDIA_ANNOUNCE,
|
||||
@@ -588,8 +587,6 @@ class MediaPlayerEntity(Entity, cached_properties=CACHED_PROPERTIES_WITH_ATTR_):
|
||||
_attr_volume_level: float | None = None
|
||||
_attr_volume_step: float
|
||||
|
||||
__last_non_buffering_state: MediaPlayerState | None = None
|
||||
|
||||
# Implement these for your media player
|
||||
@cached_property
|
||||
def device_class(self) -> MediaPlayerDeviceClass | None:
|
||||
@@ -1127,12 +1124,7 @@ class MediaPlayerEntity(Entity, cached_properties=CACHED_PROPERTIES_WITH_ATTR_):
|
||||
@property
|
||||
def state_attributes(self) -> dict[str, Any]:
|
||||
"""Return the state attributes."""
|
||||
if (state := self.state) != MediaPlayerState.BUFFERING:
|
||||
self.__last_non_buffering_state = state
|
||||
|
||||
state_attr: dict[str, Any] = {
|
||||
ATTR_LAST_NON_BUFFERING_STATE: self.__last_non_buffering_state
|
||||
}
|
||||
state_attr: dict[str, Any] = {}
|
||||
|
||||
if self.support_grouping:
|
||||
state_attr[ATTR_GROUP_MEMBERS] = self.group_members
|
||||
|
||||
@@ -13,7 +13,6 @@ ATTR_ENTITY_PICTURE_LOCAL = "entity_picture_local"
|
||||
ATTR_GROUP_MEMBERS = "group_members"
|
||||
ATTR_INPUT_SOURCE = "source"
|
||||
ATTR_INPUT_SOURCE_LIST = "source_list"
|
||||
ATTR_LAST_NON_BUFFERING_STATE = "last_non_buffering_state"
|
||||
ATTR_MEDIA_ANNOUNCE = "announce"
|
||||
ATTR_MEDIA_ALBUM_ARTIST = "media_album_artist"
|
||||
ATTR_MEDIA_ALBUM_NAME = "media_album_name"
|
||||
|
||||
@@ -123,8 +123,20 @@
|
||||
}
|
||||
},
|
||||
"triggers": {
|
||||
"paused_playing": {
|
||||
"trigger": "mdi:pause"
|
||||
},
|
||||
"started_playing": {
|
||||
"trigger": "mdi:play"
|
||||
},
|
||||
"stopped_playing": {
|
||||
"trigger": "mdi:stop"
|
||||
},
|
||||
"turned_off": {
|
||||
"trigger": "mdi:power"
|
||||
},
|
||||
"turned_on": {
|
||||
"trigger": "mdi:power"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -433,14 +433,50 @@
|
||||
},
|
||||
"title": "Media player",
|
||||
"triggers": {
|
||||
"paused_playing": {
|
||||
"description": "Triggers after one or more media players pause playing.",
|
||||
"fields": {
|
||||
"behavior": {
|
||||
"name": "[%key:component::media_player::common::trigger_behavior_name%]"
|
||||
}
|
||||
},
|
||||
"name": "Media player paused playing"
|
||||
},
|
||||
"started_playing": {
|
||||
"description": "Triggers after one or more media players start playing.",
|
||||
"fields": {
|
||||
"behavior": {
|
||||
"name": "[%key:component::media_player::common::trigger_behavior_name%]"
|
||||
}
|
||||
},
|
||||
"name": "Media player started playing"
|
||||
},
|
||||
"stopped_playing": {
|
||||
"description": "Triggers after one or more media players stop playing media.",
|
||||
"description": "Triggers after one or more media players stop playing.",
|
||||
"fields": {
|
||||
"behavior": {
|
||||
"name": "[%key:component::media_player::common::trigger_behavior_name%]"
|
||||
}
|
||||
},
|
||||
"name": "Media player stopped playing"
|
||||
},
|
||||
"turned_off": {
|
||||
"description": "Triggers after one or more media players turn off.",
|
||||
"fields": {
|
||||
"behavior": {
|
||||
"name": "[%key:component::media_player::common::trigger_behavior_name%]"
|
||||
}
|
||||
},
|
||||
"name": "Media player turned off"
|
||||
},
|
||||
"turned_on": {
|
||||
"description": "Triggers after one or more media players turn on.",
|
||||
"fields": {
|
||||
"behavior": {
|
||||
"name": "[%key:component::media_player::common::trigger_behavior_name%]"
|
||||
}
|
||||
},
|
||||
"name": "Media player turned on"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,29 @@ from . import MediaPlayerState
|
||||
from .const import DOMAIN
|
||||
|
||||
TRIGGERS: dict[str, type[Trigger]] = {
|
||||
"paused_playing": make_entity_transition_trigger(
|
||||
DOMAIN,
|
||||
from_states={
|
||||
MediaPlayerState.BUFFERING,
|
||||
MediaPlayerState.PLAYING,
|
||||
},
|
||||
to_states={
|
||||
MediaPlayerState.PAUSED,
|
||||
},
|
||||
),
|
||||
"started_playing": make_entity_transition_trigger(
|
||||
DOMAIN,
|
||||
from_states={
|
||||
MediaPlayerState.IDLE,
|
||||
MediaPlayerState.OFF,
|
||||
MediaPlayerState.ON,
|
||||
MediaPlayerState.PAUSED,
|
||||
},
|
||||
to_states={
|
||||
MediaPlayerState.BUFFERING,
|
||||
MediaPlayerState.PLAYING,
|
||||
},
|
||||
),
|
||||
"stopped_playing": make_entity_transition_trigger(
|
||||
DOMAIN,
|
||||
from_states={
|
||||
@@ -20,6 +43,32 @@ TRIGGERS: dict[str, type[Trigger]] = {
|
||||
MediaPlayerState.ON,
|
||||
},
|
||||
),
|
||||
"turned_off": make_entity_transition_trigger(
|
||||
DOMAIN,
|
||||
from_states={
|
||||
MediaPlayerState.BUFFERING,
|
||||
MediaPlayerState.IDLE,
|
||||
MediaPlayerState.ON,
|
||||
MediaPlayerState.PAUSED,
|
||||
MediaPlayerState.PLAYING,
|
||||
},
|
||||
to_states={
|
||||
MediaPlayerState.OFF,
|
||||
},
|
||||
),
|
||||
"turned_on": make_entity_transition_trigger(
|
||||
DOMAIN,
|
||||
from_states={
|
||||
MediaPlayerState.OFF,
|
||||
},
|
||||
to_states={
|
||||
MediaPlayerState.BUFFERING,
|
||||
MediaPlayerState.IDLE,
|
||||
MediaPlayerState.ON,
|
||||
MediaPlayerState.PAUSED,
|
||||
MediaPlayerState.PLAYING,
|
||||
},
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
stopped_playing:
|
||||
.trigger_common: &trigger_common
|
||||
target:
|
||||
entity:
|
||||
domain: media_player
|
||||
@@ -13,3 +13,9 @@ stopped_playing:
|
||||
- first
|
||||
- last
|
||||
- any
|
||||
|
||||
paused_playing: *trigger_common
|
||||
started_playing: *trigger_common
|
||||
stopped_playing: *trigger_common
|
||||
turned_off: *trigger_common
|
||||
turned_on: *trigger_common
|
||||
|
||||
@@ -19,7 +19,12 @@ from homeassistant.helpers.update_coordinator import UpdateFailed
|
||||
|
||||
from .coordinator import MelCloudConfigEntry, MelCloudDeviceUpdateCoordinator
|
||||
|
||||
PLATFORMS = [Platform.CLIMATE, Platform.SENSOR, Platform.WATER_HEATER]
|
||||
PLATFORMS = [
|
||||
Platform.BINARY_SENSOR,
|
||||
Platform.CLIMATE,
|
||||
Platform.SENSOR,
|
||||
Platform.WATER_HEATER,
|
||||
]
|
||||
|
||||
|
||||
async def async_setup_entry(hass: HomeAssistant, entry: MelCloudConfigEntry) -> bool:
|
||||
|
||||
175
homeassistant/components/melcloud/binary_sensor.py
Normal file
175
homeassistant/components/melcloud/binary_sensor.py
Normal file
@@ -0,0 +1,175 @@
|
||||
"""Support for MelCloud device binary sensors."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
import dataclasses
|
||||
from typing import Any
|
||||
|
||||
from pymelcloud import DEVICE_TYPE_ATW
|
||||
|
||||
from homeassistant.components.binary_sensor import (
|
||||
BinarySensorDeviceClass,
|
||||
BinarySensorEntity,
|
||||
BinarySensorEntityDescription,
|
||||
)
|
||||
from homeassistant.const import EntityCategory
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
|
||||
|
||||
from .coordinator import MelCloudConfigEntry, MelCloudDeviceUpdateCoordinator
|
||||
from .entity import MelCloudEntity
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True, kw_only=True)
|
||||
class MelcloudBinarySensorEntityDescription(BinarySensorEntityDescription):
|
||||
"""Describes Melcloud binary sensor entity."""
|
||||
|
||||
value_fn: Callable[[Any], bool | None]
|
||||
enabled: Callable[[Any], bool]
|
||||
|
||||
|
||||
ATW_BINARY_SENSORS: tuple[MelcloudBinarySensorEntityDescription, ...] = (
|
||||
MelcloudBinarySensorEntityDescription(
|
||||
key="boiler_status",
|
||||
translation_key="boiler_status",
|
||||
device_class=BinarySensorDeviceClass.RUNNING,
|
||||
entity_category=EntityCategory.DIAGNOSTIC,
|
||||
value_fn=lambda data: data.device.boiler_status,
|
||||
enabled=lambda data: data.device.boiler_status is not None,
|
||||
),
|
||||
MelcloudBinarySensorEntityDescription(
|
||||
key="booster_heater1_status",
|
||||
translation_key="booster_heater_status",
|
||||
translation_placeholders={"number": "1"},
|
||||
device_class=BinarySensorDeviceClass.RUNNING,
|
||||
entity_category=EntityCategory.DIAGNOSTIC,
|
||||
value_fn=lambda data: data.device.booster_heater1_status,
|
||||
enabled=lambda data: data.device.booster_heater1_status is not None,
|
||||
),
|
||||
MelcloudBinarySensorEntityDescription(
|
||||
key="booster_heater2_status",
|
||||
translation_key="booster_heater_status",
|
||||
translation_placeholders={"number": "2"},
|
||||
device_class=BinarySensorDeviceClass.RUNNING,
|
||||
entity_category=EntityCategory.DIAGNOSTIC,
|
||||
entity_registry_enabled_default=False,
|
||||
value_fn=lambda data: data.device.booster_heater2_status,
|
||||
enabled=lambda data: data.device.booster_heater2_status is not None,
|
||||
),
|
||||
MelcloudBinarySensorEntityDescription(
|
||||
key="booster_heater2plus_status",
|
||||
translation_key="booster_heater_status",
|
||||
translation_placeholders={"number": "2+"},
|
||||
device_class=BinarySensorDeviceClass.RUNNING,
|
||||
entity_category=EntityCategory.DIAGNOSTIC,
|
||||
entity_registry_enabled_default=False,
|
||||
value_fn=lambda data: data.device.booster_heater2plus_status,
|
||||
enabled=lambda data: data.device.booster_heater2plus_status is not None,
|
||||
),
|
||||
MelcloudBinarySensorEntityDescription(
|
||||
key="immersion_heater_status",
|
||||
translation_key="immersion_heater_status",
|
||||
device_class=BinarySensorDeviceClass.RUNNING,
|
||||
entity_category=EntityCategory.DIAGNOSTIC,
|
||||
value_fn=lambda data: data.device.immersion_heater_status,
|
||||
enabled=lambda data: data.device.immersion_heater_status is not None,
|
||||
),
|
||||
MelcloudBinarySensorEntityDescription(
|
||||
key="water_pump1_status",
|
||||
translation_key="water_pump_status",
|
||||
translation_placeholders={"number": "1"},
|
||||
device_class=BinarySensorDeviceClass.RUNNING,
|
||||
entity_category=EntityCategory.DIAGNOSTIC,
|
||||
value_fn=lambda data: data.device.water_pump1_status,
|
||||
enabled=lambda data: data.device.water_pump1_status is not None,
|
||||
),
|
||||
MelcloudBinarySensorEntityDescription(
|
||||
key="water_pump2_status",
|
||||
translation_key="water_pump_status",
|
||||
translation_placeholders={"number": "2"},
|
||||
device_class=BinarySensorDeviceClass.RUNNING,
|
||||
entity_category=EntityCategory.DIAGNOSTIC,
|
||||
value_fn=lambda data: data.device.water_pump2_status,
|
||||
enabled=lambda data: data.device.water_pump2_status is not None,
|
||||
),
|
||||
MelcloudBinarySensorEntityDescription(
|
||||
key="water_pump3_status",
|
||||
translation_key="water_pump_status",
|
||||
translation_placeholders={"number": "3"},
|
||||
device_class=BinarySensorDeviceClass.RUNNING,
|
||||
entity_category=EntityCategory.DIAGNOSTIC,
|
||||
entity_registry_enabled_default=False,
|
||||
value_fn=lambda data: data.device.water_pump3_status,
|
||||
enabled=lambda data: data.device.water_pump3_status is not None,
|
||||
),
|
||||
MelcloudBinarySensorEntityDescription(
|
||||
key="water_pump4_status",
|
||||
translation_key="water_pump_status",
|
||||
translation_placeholders={"number": "4"},
|
||||
device_class=BinarySensorDeviceClass.RUNNING,
|
||||
entity_category=EntityCategory.DIAGNOSTIC,
|
||||
entity_registry_enabled_default=False,
|
||||
value_fn=lambda data: data.device.water_pump4_status,
|
||||
enabled=lambda data: data.device.water_pump4_status is not None,
|
||||
),
|
||||
MelcloudBinarySensorEntityDescription(
|
||||
key="valve_3way_status",
|
||||
translation_key="valve_3way_status",
|
||||
entity_category=EntityCategory.DIAGNOSTIC,
|
||||
value_fn=lambda data: data.device.valve_3way_status,
|
||||
enabled=lambda data: data.device.valve_3way_status is not None,
|
||||
),
|
||||
MelcloudBinarySensorEntityDescription(
|
||||
key="valve_2way_status",
|
||||
translation_key="valve_2way_status",
|
||||
entity_category=EntityCategory.DIAGNOSTIC,
|
||||
entity_registry_enabled_default=False,
|
||||
value_fn=lambda data: data.device.valve_2way_status,
|
||||
enabled=lambda data: data.device.valve_2way_status is not None,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
async def async_setup_entry(
|
||||
_hass: HomeAssistant,
|
||||
entry: MelCloudConfigEntry,
|
||||
async_add_entities: AddConfigEntryEntitiesCallback,
|
||||
) -> None:
|
||||
"""Set up MELCloud device binary sensors based on config_entry."""
|
||||
coordinator = entry.runtime_data
|
||||
|
||||
if DEVICE_TYPE_ATW not in coordinator:
|
||||
return
|
||||
|
||||
entities: list[MelDeviceBinarySensor] = [
|
||||
MelDeviceBinarySensor(coord, description)
|
||||
for description in ATW_BINARY_SENSORS
|
||||
for coord in coordinator[DEVICE_TYPE_ATW]
|
||||
if description.enabled(coord)
|
||||
]
|
||||
async_add_entities(entities)
|
||||
|
||||
|
||||
class MelDeviceBinarySensor(MelCloudEntity, BinarySensorEntity):
|
||||
"""Representation of a Binary Sensor."""
|
||||
|
||||
entity_description: MelcloudBinarySensorEntityDescription
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
coordinator: MelCloudDeviceUpdateCoordinator,
|
||||
description: MelcloudBinarySensorEntityDescription,
|
||||
) -> None:
|
||||
"""Initialize the binary sensor."""
|
||||
super().__init__(coordinator)
|
||||
self.entity_description = description
|
||||
self._attr_unique_id = (
|
||||
f"{coordinator.device.serial}-{coordinator.device.mac}-{description.key}"
|
||||
)
|
||||
self._attr_device_info = coordinator.device_info
|
||||
|
||||
@property
|
||||
def is_on(self) -> bool | None:
|
||||
"""Return the state of the binary sensor."""
|
||||
return self.entity_description.value_fn(self.coordinator)
|
||||
@@ -1,5 +1,25 @@
|
||||
{
|
||||
"entity": {
|
||||
"binary_sensor": {
|
||||
"boiler_status": {
|
||||
"default": "mdi:water-boiler-off",
|
||||
"state": {
|
||||
"on": "mdi:water-boiler"
|
||||
}
|
||||
},
|
||||
"valve_2way_status": {
|
||||
"default": "mdi:valve-closed",
|
||||
"state": {
|
||||
"on": "mdi:valve-open"
|
||||
}
|
||||
},
|
||||
"valve_3way_status": {
|
||||
"default": "mdi:valve-closed",
|
||||
"state": {
|
||||
"on": "mdi:valve-open"
|
||||
}
|
||||
}
|
||||
},
|
||||
"sensor": {
|
||||
"energy_consumed": {
|
||||
"default": "mdi:factory"
|
||||
|
||||
@@ -42,6 +42,26 @@
|
||||
}
|
||||
},
|
||||
"entity": {
|
||||
"binary_sensor": {
|
||||
"boiler_status": {
|
||||
"name": "Boiler"
|
||||
},
|
||||
"booster_heater_status": {
|
||||
"name": "Booster heater {number}"
|
||||
},
|
||||
"immersion_heater_status": {
|
||||
"name": "Immersion heater"
|
||||
},
|
||||
"valve_2way_status": {
|
||||
"name": "2-way valve"
|
||||
},
|
||||
"valve_3way_status": {
|
||||
"name": "3-way valve"
|
||||
},
|
||||
"water_pump_status": {
|
||||
"name": "Water pump {number}"
|
||||
}
|
||||
},
|
||||
"sensor": {
|
||||
"condensing_temperature": {
|
||||
"name": "Condensing temperature"
|
||||
|
||||
@@ -11,6 +11,7 @@ from homeassistant.components.weather import (
|
||||
ATTR_FORECAST_NATIVE_PRECIPITATION,
|
||||
ATTR_FORECAST_NATIVE_TEMP,
|
||||
ATTR_FORECAST_NATIVE_TEMP_LOW,
|
||||
ATTR_FORECAST_NATIVE_WIND_GUST_SPEED,
|
||||
ATTR_FORECAST_NATIVE_WIND_SPEED,
|
||||
ATTR_FORECAST_TIME,
|
||||
ATTR_FORECAST_WIND_BEARING,
|
||||
@@ -184,6 +185,9 @@ class MeteoFranceWeather(
|
||||
ATTR_FORECAST_NATIVE_TEMP: forecast["T"]["value"],
|
||||
ATTR_FORECAST_NATIVE_PRECIPITATION: forecast["rain"].get("1h"),
|
||||
ATTR_FORECAST_NATIVE_WIND_SPEED: forecast["wind"]["speed"],
|
||||
ATTR_FORECAST_NATIVE_WIND_GUST_SPEED: forecast["wind"].get(
|
||||
"gust"
|
||||
),
|
||||
ATTR_FORECAST_WIND_BEARING: forecast["wind"]["direction"]
|
||||
if forecast["wind"]["direction"] != -1
|
||||
else None,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"""Device tracker for Mobile app."""
|
||||
|
||||
from collections.abc import Callable
|
||||
from typing import Any
|
||||
|
||||
from homeassistant.components.device_tracker import (
|
||||
@@ -53,11 +54,11 @@ async def async_setup_entry(
|
||||
class MobileAppEntity(TrackerEntity, RestoreEntity):
|
||||
"""Represent a tracked device."""
|
||||
|
||||
def __init__(self, entry, data=None):
|
||||
def __init__(self, entry: ConfigEntry) -> None:
|
||||
"""Set up Mobile app entity."""
|
||||
self._entry = entry
|
||||
self._data = data
|
||||
self._dispatch_unsub = None
|
||||
self._data: dict[str, Any] = {}
|
||||
self._dispatch_unsub: Callable[[], None] | None = None
|
||||
|
||||
@property
|
||||
def unique_id(self) -> str:
|
||||
@@ -132,12 +133,7 @@ class MobileAppEntity(TrackerEntity, RestoreEntity):
|
||||
self.update_data,
|
||||
)
|
||||
|
||||
# Don't restore if we got set up with data.
|
||||
if self._data is not None:
|
||||
return
|
||||
|
||||
if (state := await self.async_get_last_state()) is None:
|
||||
self._data = {}
|
||||
return
|
||||
|
||||
attr = state.attributes
|
||||
@@ -158,7 +154,7 @@ class MobileAppEntity(TrackerEntity, RestoreEntity):
|
||||
self._dispatch_unsub = None
|
||||
|
||||
@callback
|
||||
def update_data(self, data):
|
||||
def update_data(self, data: dict[str, Any]) -> None:
|
||||
"""Mark the device as seen."""
|
||||
self._data = data
|
||||
self.async_write_ha_state()
|
||||
|
||||
@@ -54,7 +54,7 @@ class MotionMountErrorStatusSensor(MotionMountEntity, SensorEntity):
|
||||
def __init__(
|
||||
self, mm: motionmount.MotionMount, config_entry: MotionMountConfigEntry
|
||||
) -> None:
|
||||
"""Initialize sensor entiry."""
|
||||
"""Initialize sensor entity."""
|
||||
super().__init__(mm, config_entry)
|
||||
self._attr_unique_id = f"{self._base_unique_id}-error-status"
|
||||
|
||||
|
||||
@@ -154,6 +154,8 @@ class OctoPrintConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
except ApiError as err:
|
||||
_LOGGER.error("Failed to connect to printer")
|
||||
raise CannotConnect from err
|
||||
finally:
|
||||
await self._sessions.pop().close()
|
||||
|
||||
await self.async_set_unique_id(discovery.upnp_uuid, raise_on_progress=False)
|
||||
self._abort_if_unique_id_configured()
|
||||
@@ -262,9 +264,12 @@ class OctoPrintConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
assert self._user_input is not None
|
||||
octoprint = self._get_octoprint_client(self._user_input)
|
||||
|
||||
self._user_input[CONF_API_KEY] = await octoprint.request_app_key(
|
||||
"Home Assistant", self._user_input[CONF_USERNAME], 300
|
||||
)
|
||||
try:
|
||||
self._user_input[CONF_API_KEY] = await octoprint.request_app_key(
|
||||
"Home Assistant", self._user_input[CONF_USERNAME], 300
|
||||
)
|
||||
finally:
|
||||
await self._sessions.pop().close()
|
||||
|
||||
def _get_octoprint_client(self, user_input: dict[str, Any]) -> OctoprintClient:
|
||||
"""Build an octoprint client from the user_input."""
|
||||
@@ -287,11 +292,6 @@ class OctoPrintConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
path=user_input[CONF_PATH],
|
||||
)
|
||||
|
||||
def async_remove(self) -> None:
|
||||
"""Detach the session."""
|
||||
for session in self._sessions:
|
||||
session.detach()
|
||||
|
||||
|
||||
class CannotConnect(HomeAssistantError):
|
||||
"""Error to indicate we cannot connect."""
|
||||
|
||||
@@ -23,7 +23,6 @@ import voluptuous as vol
|
||||
|
||||
from homeassistant.components import webhook
|
||||
from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.const import (
|
||||
CONF_SCAN_INTERVAL,
|
||||
CONF_TOKEN,
|
||||
@@ -39,21 +38,15 @@ from .const import (
|
||||
CONF_DEVICE_NAME,
|
||||
CONF_DEVICE_TYPE,
|
||||
CONF_USE_WEBHOOK,
|
||||
COORDINATOR,
|
||||
DEFAULT_SCAN_INTERVAL,
|
||||
DEVICE,
|
||||
DEVICE_ID,
|
||||
DEVICE_NAME,
|
||||
DEVICE_TYPE,
|
||||
DOMAIN,
|
||||
PLATFORMS,
|
||||
SENSOR_DATA,
|
||||
UNDO_UPDATE_LISTENER,
|
||||
)
|
||||
from .coordinator import PlaatoCoordinator
|
||||
from .coordinator import PlaatoConfigEntry, PlaatoCoordinator, PlaatoData
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
DEPENDENCIES = ["webhook"]
|
||||
|
||||
SENSOR_UPDATE = f"{DOMAIN}_sensor_update"
|
||||
@@ -82,15 +75,15 @@ WEBHOOK_SCHEMA = vol.Schema(
|
||||
)
|
||||
|
||||
|
||||
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
||||
async def async_setup_entry(hass: HomeAssistant, entry: PlaatoConfigEntry) -> bool:
|
||||
"""Configure based on config entry."""
|
||||
hass.data.setdefault(DOMAIN, {})
|
||||
|
||||
if entry.data[CONF_USE_WEBHOOK]:
|
||||
async_setup_webhook(hass, entry)
|
||||
else:
|
||||
await async_setup_coordinator(hass, entry)
|
||||
|
||||
entry.async_on_unload(entry.add_update_listener(_async_update_listener))
|
||||
|
||||
await hass.config_entries.async_forward_entry_setups(
|
||||
entry, [platform for platform in PLATFORMS if entry.options.get(platform, True)]
|
||||
)
|
||||
@@ -99,19 +92,26 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
||||
|
||||
|
||||
@callback
|
||||
def async_setup_webhook(hass: HomeAssistant, entry: ConfigEntry):
|
||||
def async_setup_webhook(hass: HomeAssistant, entry: PlaatoConfigEntry) -> None:
|
||||
"""Init webhook based on config entry."""
|
||||
webhook_id = entry.data[CONF_WEBHOOK_ID]
|
||||
device_name = entry.data[CONF_DEVICE_NAME]
|
||||
|
||||
_set_entry_data(entry, hass)
|
||||
entry.runtime_data = PlaatoData(
|
||||
coordinator=None,
|
||||
device_name=entry.data[CONF_DEVICE_NAME],
|
||||
device_type=entry.data[CONF_DEVICE_TYPE],
|
||||
device_id=None,
|
||||
)
|
||||
|
||||
webhook.async_register(
|
||||
hass, DOMAIN, f"{DOMAIN}.{device_name}", webhook_id, handle_webhook
|
||||
)
|
||||
|
||||
|
||||
async def async_setup_coordinator(hass: HomeAssistant, entry: ConfigEntry):
|
||||
async def async_setup_coordinator(
|
||||
hass: HomeAssistant, entry: PlaatoConfigEntry
|
||||
) -> None:
|
||||
"""Init auth token based on config entry."""
|
||||
auth_token = entry.data[CONF_TOKEN]
|
||||
device_type = entry.data[CONF_DEVICE_TYPE]
|
||||
@@ -126,62 +126,44 @@ async def async_setup_coordinator(hass: HomeAssistant, entry: ConfigEntry):
|
||||
)
|
||||
await coordinator.async_config_entry_first_refresh()
|
||||
|
||||
_set_entry_data(entry, hass, coordinator, auth_token)
|
||||
entry.runtime_data = PlaatoData(
|
||||
coordinator=coordinator,
|
||||
device_name=entry.data[CONF_DEVICE_NAME],
|
||||
device_type=entry.data[CONF_DEVICE_TYPE],
|
||||
device_id=auth_token,
|
||||
)
|
||||
|
||||
for platform in PLATFORMS:
|
||||
if entry.options.get(platform, True):
|
||||
coordinator.platforms.append(platform)
|
||||
|
||||
|
||||
def _set_entry_data(entry, hass, coordinator=None, device_id=None):
|
||||
device = {
|
||||
DEVICE_NAME: entry.data[CONF_DEVICE_NAME],
|
||||
DEVICE_TYPE: entry.data[CONF_DEVICE_TYPE],
|
||||
DEVICE_ID: device_id,
|
||||
}
|
||||
|
||||
hass.data[DOMAIN][entry.entry_id] = {
|
||||
COORDINATOR: coordinator,
|
||||
DEVICE: device,
|
||||
SENSOR_DATA: None,
|
||||
UNDO_UPDATE_LISTENER: entry.add_update_listener(_async_update_listener),
|
||||
}
|
||||
|
||||
|
||||
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
||||
async def async_unload_entry(hass: HomeAssistant, entry: PlaatoConfigEntry) -> bool:
|
||||
"""Unload a config entry."""
|
||||
use_webhook = entry.data[CONF_USE_WEBHOOK]
|
||||
hass.data[DOMAIN][entry.entry_id][UNDO_UPDATE_LISTENER]()
|
||||
|
||||
if use_webhook:
|
||||
if entry.data[CONF_USE_WEBHOOK]:
|
||||
return await async_unload_webhook(hass, entry)
|
||||
|
||||
return await async_unload_coordinator(hass, entry)
|
||||
|
||||
|
||||
async def async_unload_webhook(hass: HomeAssistant, entry: ConfigEntry):
|
||||
async def async_unload_webhook(hass: HomeAssistant, entry: PlaatoConfigEntry) -> bool:
|
||||
"""Unload webhook based entry."""
|
||||
if entry.data[CONF_WEBHOOK_ID] is not None:
|
||||
webhook.async_unregister(hass, entry.data[CONF_WEBHOOK_ID])
|
||||
return await async_unload_platforms(hass, entry, PLATFORMS)
|
||||
return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
|
||||
|
||||
|
||||
async def async_unload_coordinator(hass: HomeAssistant, entry: ConfigEntry):
|
||||
async def async_unload_coordinator(
|
||||
hass: HomeAssistant, entry: PlaatoConfigEntry
|
||||
) -> bool:
|
||||
"""Unload auth token based entry."""
|
||||
coordinator = hass.data[DOMAIN][entry.entry_id][COORDINATOR]
|
||||
return await async_unload_platforms(hass, entry, coordinator.platforms)
|
||||
coordinator = entry.runtime_data.coordinator
|
||||
return await hass.config_entries.async_unload_platforms(
|
||||
entry, coordinator.platforms if coordinator else PLATFORMS
|
||||
)
|
||||
|
||||
|
||||
async def async_unload_platforms(hass: HomeAssistant, entry: ConfigEntry, platforms):
|
||||
"""Unload platforms."""
|
||||
unloaded = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
|
||||
if unloaded:
|
||||
hass.data[DOMAIN].pop(entry.entry_id)
|
||||
|
||||
return unloaded
|
||||
|
||||
|
||||
async def _async_update_listener(hass: HomeAssistant, entry: ConfigEntry) -> None:
|
||||
async def _async_update_listener(hass: HomeAssistant, entry: PlaatoConfigEntry) -> None:
|
||||
"""Handle options update."""
|
||||
await hass.config_entries.async_reload(entry.entry_id)
|
||||
|
||||
|
||||
@@ -8,17 +8,17 @@ from homeassistant.components.binary_sensor import (
|
||||
BinarySensorDeviceClass,
|
||||
BinarySensorEntity,
|
||||
)
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
|
||||
|
||||
from .const import CONF_USE_WEBHOOK, COORDINATOR, DOMAIN
|
||||
from .const import CONF_USE_WEBHOOK
|
||||
from .coordinator import PlaatoConfigEntry, PlaatoCoordinator, PlaatoData
|
||||
from .entity import PlaatoEntity
|
||||
|
||||
|
||||
async def async_setup_entry(
|
||||
hass: HomeAssistant,
|
||||
config_entry: ConfigEntry,
|
||||
config_entry: PlaatoConfigEntry,
|
||||
async_add_entities: AddConfigEntryEntitiesCallback,
|
||||
) -> None:
|
||||
"""Set up Plaato from a config entry."""
|
||||
@@ -26,10 +26,12 @@ async def async_setup_entry(
|
||||
if config_entry.data[CONF_USE_WEBHOOK]:
|
||||
return
|
||||
|
||||
coordinator = hass.data[DOMAIN][config_entry.entry_id][COORDINATOR]
|
||||
entry_data = config_entry.runtime_data
|
||||
coordinator = entry_data.coordinator
|
||||
assert coordinator is not None
|
||||
async_add_entities(
|
||||
PlaatoBinarySensor(
|
||||
hass.data[DOMAIN][config_entry.entry_id],
|
||||
entry_data,
|
||||
sensor_type,
|
||||
coordinator,
|
||||
)
|
||||
@@ -40,7 +42,12 @@ async def async_setup_entry(
|
||||
class PlaatoBinarySensor(PlaatoEntity, BinarySensorEntity):
|
||||
"""Representation of a Binary Sensor."""
|
||||
|
||||
def __init__(self, data, sensor_type, coordinator=None) -> None:
|
||||
def __init__(
|
||||
self,
|
||||
data: PlaatoData,
|
||||
sensor_type: str,
|
||||
coordinator: PlaatoCoordinator | None = None,
|
||||
) -> None:
|
||||
"""Initialize plaato binary sensor."""
|
||||
super().__init__(data, sensor_type, coordinator)
|
||||
if sensor_type is PlaatoKeg.Pins.LEAK_DETECTION:
|
||||
|
||||
@@ -19,13 +19,7 @@ PLACEHOLDER_DEVICE_TYPE = "device_type"
|
||||
PLACEHOLDER_DEVICE_NAME = "device_name"
|
||||
DOCS_URL = "https://www.home-assistant.io/integrations/plaato/"
|
||||
PLATFORMS = [Platform.BINARY_SENSOR, Platform.SENSOR]
|
||||
SENSOR_DATA = "sensor_data"
|
||||
COORDINATOR = "coordinator"
|
||||
DEVICE = "device"
|
||||
DEVICE_NAME = "device_name"
|
||||
DEVICE_TYPE = "device_type"
|
||||
DEVICE_ID = "device_id"
|
||||
UNDO_UPDATE_LISTENER = "undo_update_listener"
|
||||
|
||||
DEFAULT_SCAN_INTERVAL = 5
|
||||
MIN_UPDATE_INTERVAL = timedelta(minutes=1)
|
||||
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
"""Coordinator for Plaato devices."""
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import timedelta
|
||||
import logging
|
||||
|
||||
from pyplaato.models.device import PlaatoDevice
|
||||
from pyplaato.plaato import Plaato, PlaatoDeviceType
|
||||
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
@@ -16,15 +18,29 @@ from .const import DOMAIN
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class PlaatoCoordinator(DataUpdateCoordinator):
|
||||
@dataclass
|
||||
class PlaatoData:
|
||||
"""Runtime data for the Plaato integration."""
|
||||
|
||||
coordinator: PlaatoCoordinator | None
|
||||
device_name: str
|
||||
device_type: str
|
||||
device_id: str | None
|
||||
sensor_data: PlaatoDevice | None = field(default=None)
|
||||
|
||||
|
||||
type PlaatoConfigEntry = ConfigEntry[PlaatoData]
|
||||
|
||||
|
||||
class PlaatoCoordinator(DataUpdateCoordinator[PlaatoDevice]):
|
||||
"""Class to manage fetching data from the API."""
|
||||
|
||||
config_entry: ConfigEntry
|
||||
config_entry: PlaatoConfigEntry
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
hass: HomeAssistant,
|
||||
config_entry: ConfigEntry,
|
||||
config_entry: PlaatoConfigEntry,
|
||||
auth_token: str,
|
||||
device_type: PlaatoDeviceType,
|
||||
update_interval: timedelta,
|
||||
@@ -42,7 +58,7 @@ class PlaatoCoordinator(DataUpdateCoordinator):
|
||||
update_interval=update_interval,
|
||||
)
|
||||
|
||||
async def _async_update_data(self):
|
||||
async def _async_update_data(self) -> PlaatoDevice:
|
||||
"""Update data via library."""
|
||||
return await self.api.get_data(
|
||||
session=aiohttp_client.async_get_clientsession(self.hass),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""PlaatoEntity class."""
|
||||
|
||||
from typing import Any
|
||||
from typing import Any, cast
|
||||
|
||||
from pyplaato.models.device import PlaatoDevice
|
||||
|
||||
@@ -8,16 +8,8 @@ from homeassistant.helpers import entity
|
||||
from homeassistant.helpers.device_registry import DeviceInfo
|
||||
from homeassistant.helpers.dispatcher import async_dispatcher_connect
|
||||
|
||||
from .const import (
|
||||
DEVICE,
|
||||
DEVICE_ID,
|
||||
DEVICE_NAME,
|
||||
DEVICE_TYPE,
|
||||
DOMAIN,
|
||||
EXTRA_STATE_ATTRIBUTES,
|
||||
SENSOR_DATA,
|
||||
SENSOR_SIGNAL,
|
||||
)
|
||||
from .const import DOMAIN, EXTRA_STATE_ATTRIBUTES, SENSOR_SIGNAL
|
||||
from .coordinator import PlaatoCoordinator, PlaatoData
|
||||
|
||||
|
||||
class PlaatoEntity(entity.Entity):
|
||||
@@ -25,14 +17,20 @@ class PlaatoEntity(entity.Entity):
|
||||
|
||||
_attr_should_poll = False
|
||||
|
||||
def __init__(self, data, sensor_type, coordinator=None):
|
||||
def __init__(
|
||||
self,
|
||||
data: PlaatoData,
|
||||
sensor_type: str,
|
||||
coordinator: PlaatoCoordinator | None = None,
|
||||
) -> None:
|
||||
"""Initialize the sensor."""
|
||||
self._coordinator = coordinator
|
||||
self._entry_data = data
|
||||
self._sensor_type = sensor_type
|
||||
self._device_id = data[DEVICE][DEVICE_ID]
|
||||
self._device_type = data[DEVICE][DEVICE_TYPE]
|
||||
self._device_name = data[DEVICE][DEVICE_NAME]
|
||||
assert self._entry_data.device_id is not None
|
||||
self._device_id = cast(str, data.device_id)
|
||||
self._device_type = data.device_type
|
||||
self._device_name = data.device_name
|
||||
self._attr_unique_id = f"{self._device_id}_{self._sensor_type}"
|
||||
self._attr_name = f"{DOMAIN} {self._device_type} {self._device_name} {self._sensor_name}".title()
|
||||
sw_version = None
|
||||
@@ -58,7 +56,7 @@ class PlaatoEntity(entity.Entity):
|
||||
def _sensor_data(self) -> PlaatoDevice:
|
||||
if self._coordinator:
|
||||
return self._coordinator.data
|
||||
return self._entry_data[SENSOR_DATA]
|
||||
return self._entry_data.sensor_data
|
||||
|
||||
@property
|
||||
def extra_state_attributes(self) -> dict[str, Any] | None:
|
||||
|
||||
@@ -6,7 +6,6 @@ from pyplaato.models.device import PlaatoDevice
|
||||
from pyplaato.plaato import PlaatoKeg
|
||||
|
||||
from homeassistant.components.sensor import SensorDeviceClass, SensorEntity
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.core import HomeAssistant, callback
|
||||
from homeassistant.helpers.dispatcher import (
|
||||
async_dispatcher_connect,
|
||||
@@ -19,15 +18,8 @@ from homeassistant.helpers.entity_platform import (
|
||||
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
|
||||
|
||||
from . import ATTR_TEMP, SENSOR_UPDATE
|
||||
from .const import (
|
||||
CONF_USE_WEBHOOK,
|
||||
COORDINATOR,
|
||||
DEVICE,
|
||||
DEVICE_ID,
|
||||
DOMAIN,
|
||||
SENSOR_DATA,
|
||||
SENSOR_SIGNAL,
|
||||
)
|
||||
from .const import CONF_USE_WEBHOOK, SENSOR_SIGNAL
|
||||
from .coordinator import PlaatoConfigEntry, PlaatoCoordinator, PlaatoData
|
||||
from .entity import PlaatoEntity
|
||||
|
||||
|
||||
@@ -42,19 +34,19 @@ async def async_setup_platform(
|
||||
|
||||
async def async_setup_entry(
|
||||
hass: HomeAssistant,
|
||||
entry: ConfigEntry,
|
||||
entry: PlaatoConfigEntry,
|
||||
async_add_entities: AddConfigEntryEntitiesCallback,
|
||||
) -> None:
|
||||
"""Set up Plaato from a config entry."""
|
||||
entry_data = hass.data[DOMAIN][entry.entry_id]
|
||||
entry_data = entry.runtime_data
|
||||
|
||||
@callback
|
||||
def _async_update_from_webhook(device_id, sensor_data: PlaatoDevice):
|
||||
"""Update/Create the sensors."""
|
||||
entry_data[SENSOR_DATA] = sensor_data
|
||||
entry_data.sensor_data = sensor_data
|
||||
|
||||
if device_id != entry_data[DEVICE][DEVICE_ID]:
|
||||
entry_data[DEVICE][DEVICE_ID] = device_id
|
||||
if device_id != entry_data.device_id:
|
||||
entry_data.device_id = device_id
|
||||
async_add_entities(
|
||||
[
|
||||
PlaatoSensor(entry_data, sensor_type)
|
||||
@@ -68,7 +60,8 @@ async def async_setup_entry(
|
||||
if entry.data[CONF_USE_WEBHOOK]:
|
||||
async_dispatcher_connect(hass, SENSOR_UPDATE, _async_update_from_webhook)
|
||||
else:
|
||||
coordinator = entry_data[COORDINATOR]
|
||||
coordinator = entry_data.coordinator
|
||||
assert coordinator is not None
|
||||
async_add_entities(
|
||||
PlaatoSensor(entry_data, sensor_type, coordinator)
|
||||
for sensor_type in coordinator.data.sensors
|
||||
@@ -78,18 +71,23 @@ async def async_setup_entry(
|
||||
class PlaatoSensor(PlaatoEntity, SensorEntity):
|
||||
"""Representation of a Plaato Sensor."""
|
||||
|
||||
def __init__(self, data, sensor_type, coordinator=None) -> None:
|
||||
def __init__(
|
||||
self,
|
||||
data: PlaatoData,
|
||||
sensor_type: str,
|
||||
coordinator: PlaatoCoordinator | None = None,
|
||||
) -> None:
|
||||
"""Initialize plaato sensor."""
|
||||
super().__init__(data, sensor_type, coordinator)
|
||||
if sensor_type is PlaatoKeg.Pins.TEMPERATURE or sensor_type == ATTR_TEMP:
|
||||
self._attr_device_class = SensorDeviceClass.TEMPERATURE
|
||||
|
||||
@property
|
||||
def native_value(self):
|
||||
def native_value(self) -> str | int | float | None:
|
||||
"""Return the state of the sensor."""
|
||||
return self._sensor_data.sensors.get(self._sensor_type)
|
||||
|
||||
@property
|
||||
def native_unit_of_measurement(self):
|
||||
def native_unit_of_measurement(self) -> str | None:
|
||||
"""Return the unit of measurement."""
|
||||
return self._sensor_data.get_unit_of_measurement(self._sensor_type)
|
||||
|
||||
@@ -4,5 +4,5 @@
|
||||
"codeowners": [],
|
||||
"documentation": "https://www.home-assistant.io/integrations/proxy",
|
||||
"quality_scale": "legacy",
|
||||
"requirements": ["Pillow==12.1.1"]
|
||||
"requirements": ["Pillow==12.2.0"]
|
||||
}
|
||||
|
||||
@@ -2,7 +2,14 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pvo import PVOutput, PVOutputAuthenticationError, PVOutputNoDataError, Status
|
||||
from pvo import (
|
||||
PVOutput,
|
||||
PVOutputAuthenticationError,
|
||||
PVOutputConnectionError,
|
||||
PVOutputError,
|
||||
PVOutputNoDataError,
|
||||
Status,
|
||||
)
|
||||
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.const import CONF_API_KEY
|
||||
@@ -37,7 +44,20 @@ class PVOutputDataUpdateCoordinator(DataUpdateCoordinator[Status]):
|
||||
"""Fetch system status from PVOutput."""
|
||||
try:
|
||||
return await self.pvoutput.status()
|
||||
except PVOutputNoDataError as err:
|
||||
raise UpdateFailed("PVOutput has no data available") from err
|
||||
except PVOutputAuthenticationError as err:
|
||||
raise ConfigEntryAuthFailed from err
|
||||
except PVOutputNoDataError as err:
|
||||
raise UpdateFailed(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="no_data_available",
|
||||
) from err
|
||||
except PVOutputConnectionError as err:
|
||||
raise UpdateFailed(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="communication_error",
|
||||
) from err
|
||||
except PVOutputError as err:
|
||||
raise UpdateFailed(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="unknown_error",
|
||||
) from err
|
||||
|
||||
@@ -42,5 +42,16 @@
|
||||
"name": "Power generation"
|
||||
}
|
||||
}
|
||||
},
|
||||
"exceptions": {
|
||||
"communication_error": {
|
||||
"message": "An error occurred while communicating with the PVOutput service."
|
||||
},
|
||||
"no_data_available": {
|
||||
"message": "The PVOutput service has no data available for this system."
|
||||
},
|
||||
"unknown_error": {
|
||||
"message": "An unknown error occurred while communicating with the PVOutput service."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,5 +6,5 @@
|
||||
"iot_class": "calculated",
|
||||
"loggers": ["pyzbar"],
|
||||
"quality_scale": "legacy",
|
||||
"requirements": ["Pillow==12.1.1", "pyzbar==0.1.7"]
|
||||
"requirements": ["Pillow==12.2.0", "pyzbar==0.1.7"]
|
||||
}
|
||||
|
||||
@@ -192,7 +192,7 @@ ID_TYPE = BigInteger().with_variant(sqlite.INTEGER, "sqlite")
|
||||
# For MariaDB and MySQL we can use an unsigned integer type since it will fit 2**32
|
||||
# for sqlite and postgresql we use a bigint
|
||||
UINT_32_TYPE = BigInteger().with_variant(
|
||||
mysql.INTEGER(unsigned=True), # type: ignore[no-untyped-call]
|
||||
mysql.INTEGER(unsigned=True),
|
||||
"mysql",
|
||||
"mariadb",
|
||||
)
|
||||
@@ -206,12 +206,12 @@ JSONB_VARIANT_CAST = Text().with_variant(
|
||||
)
|
||||
DATETIME_TYPE = (
|
||||
DateTime(timezone=True)
|
||||
.with_variant(mysql.DATETIME(timezone=True, fsp=6), "mysql", "mariadb") # type: ignore[no-untyped-call]
|
||||
.with_variant(mysql.DATETIME(timezone=True, fsp=6), "mysql", "mariadb")
|
||||
.with_variant(FAST_PYSQLITE_DATETIME(), "sqlite") # type: ignore[no-untyped-call]
|
||||
)
|
||||
DOUBLE_TYPE = (
|
||||
Float()
|
||||
.with_variant(mysql.DOUBLE(asdecimal=False), "mysql", "mariadb") # type: ignore[no-untyped-call]
|
||||
.with_variant(mysql.DOUBLE(asdecimal=False), "mysql", "mariadb")
|
||||
.with_variant(oracle.DOUBLE_PRECISION(), "oracle")
|
||||
.with_variant(postgresql.DOUBLE_PRECISION(), "postgresql")
|
||||
)
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
"iot_class": "local_push",
|
||||
"quality_scale": "internal",
|
||||
"requirements": [
|
||||
"SQLAlchemy==2.0.41",
|
||||
"SQLAlchemy==2.0.49",
|
||||
"fnv-hash-fast==2.0.0",
|
||||
"psutil-home-assistant==0.0.1"
|
||||
]
|
||||
|
||||
@@ -447,10 +447,10 @@ def setup_connection_for_dialect(
|
||||
slow_dependent_subquery = False
|
||||
if dialect_name == SupportedDialect.SQLITE:
|
||||
if first_connection:
|
||||
old_isolation = dbapi_connection.isolation_level # type: ignore[attr-defined]
|
||||
dbapi_connection.isolation_level = None # type: ignore[attr-defined]
|
||||
old_isolation = dbapi_connection.isolation_level
|
||||
dbapi_connection.isolation_level = None
|
||||
execute_on_connection(dbapi_connection, "PRAGMA journal_mode=WAL")
|
||||
dbapi_connection.isolation_level = old_isolation # type: ignore[attr-defined]
|
||||
dbapi_connection.isolation_level = old_isolation
|
||||
# WAL mode only needs to be setup once
|
||||
# instead of every time we open the sqlite connection
|
||||
# as its persistent and isn't free to call every time.
|
||||
|
||||
17
homeassistant/components/remote/condition.py
Normal file
17
homeassistant/components/remote/condition.py
Normal file
@@ -0,0 +1,17 @@
|
||||
"""Provides conditions for remotes."""
|
||||
|
||||
from homeassistant.const import STATE_OFF, STATE_ON
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers.condition import Condition, make_entity_state_condition
|
||||
|
||||
from . import DOMAIN
|
||||
|
||||
CONDITIONS: dict[str, type[Condition]] = {
|
||||
"is_off": make_entity_state_condition(DOMAIN, STATE_OFF),
|
||||
"is_on": make_entity_state_condition(DOMAIN, STATE_ON),
|
||||
}
|
||||
|
||||
|
||||
async def async_get_conditions(hass: HomeAssistant) -> dict[str, type[Condition]]:
|
||||
"""Return the remote conditions."""
|
||||
return CONDITIONS
|
||||
17
homeassistant/components/remote/conditions.yaml
Normal file
17
homeassistant/components/remote/conditions.yaml
Normal file
@@ -0,0 +1,17 @@
|
||||
.condition_common: &condition_common
|
||||
target:
|
||||
entity:
|
||||
domain: remote
|
||||
fields:
|
||||
behavior:
|
||||
required: true
|
||||
default: any
|
||||
selector:
|
||||
select:
|
||||
translation_key: condition_behavior
|
||||
options:
|
||||
- all
|
||||
- any
|
||||
|
||||
is_off: *condition_common
|
||||
is_on: *condition_common
|
||||
@@ -1,4 +1,12 @@
|
||||
{
|
||||
"conditions": {
|
||||
"is_off": {
|
||||
"condition": "mdi:remote-off"
|
||||
},
|
||||
"is_on": {
|
||||
"condition": "mdi:remote"
|
||||
}
|
||||
},
|
||||
"entity_component": {
|
||||
"_": {
|
||||
"default": "mdi:remote",
|
||||
|
||||
@@ -1,7 +1,28 @@
|
||||
{
|
||||
"common": {
|
||||
"condition_behavior_name": "Condition passes if",
|
||||
"trigger_behavior_name": "Trigger when"
|
||||
},
|
||||
"conditions": {
|
||||
"is_off": {
|
||||
"description": "Tests if one or more remotes are off.",
|
||||
"fields": {
|
||||
"behavior": {
|
||||
"name": "[%key:component::remote::common::condition_behavior_name%]"
|
||||
}
|
||||
},
|
||||
"name": "Remote is off"
|
||||
},
|
||||
"is_on": {
|
||||
"description": "Tests if one or more remotes are on.",
|
||||
"fields": {
|
||||
"behavior": {
|
||||
"name": "[%key:component::remote::common::condition_behavior_name%]"
|
||||
}
|
||||
},
|
||||
"name": "Remote is on"
|
||||
}
|
||||
},
|
||||
"device_automation": {
|
||||
"action_type": {
|
||||
"toggle": "[%key:common::device_automation::action_type::toggle%]",
|
||||
@@ -31,6 +52,12 @@
|
||||
}
|
||||
},
|
||||
"selector": {
|
||||
"condition_behavior": {
|
||||
"options": {
|
||||
"all": "All",
|
||||
"any": "Any"
|
||||
}
|
||||
},
|
||||
"trigger_behavior": {
|
||||
"options": {
|
||||
"any": "Any",
|
||||
|
||||
@@ -21,6 +21,8 @@ from .const import DOMAIN
|
||||
from .coordinator import RitualsDataUpdateCoordinator
|
||||
from .entity import DiffuserEntity
|
||||
|
||||
PARALLEL_UPDATES = 0
|
||||
|
||||
|
||||
@dataclass(frozen=True, kw_only=True)
|
||||
class RitualsBinarySensorEntityDescription(BinarySensorEntityDescription):
|
||||
|
||||
@@ -17,6 +17,8 @@ from .const import DOMAIN
|
||||
from .coordinator import RitualsDataUpdateCoordinator
|
||||
from .entity import DiffuserEntity
|
||||
|
||||
PARALLEL_UPDATES = 1
|
||||
|
||||
|
||||
@dataclass(frozen=True, kw_only=True)
|
||||
class RitualsNumberEntityDescription(NumberEntityDescription):
|
||||
|
||||
@@ -17,6 +17,8 @@ from .const import DOMAIN
|
||||
from .coordinator import RitualsDataUpdateCoordinator
|
||||
from .entity import DiffuserEntity
|
||||
|
||||
PARALLEL_UPDATES = 1
|
||||
|
||||
|
||||
@dataclass(frozen=True, kw_only=True)
|
||||
class RitualsSelectEntityDescription(SelectEntityDescription):
|
||||
|
||||
@@ -21,6 +21,8 @@ from .const import DOMAIN
|
||||
from .coordinator import RitualsDataUpdateCoordinator
|
||||
from .entity import DiffuserEntity
|
||||
|
||||
PARALLEL_UPDATES = 0
|
||||
|
||||
|
||||
@dataclass(frozen=True, kw_only=True)
|
||||
class RitualsSensorEntityDescription(SensorEntityDescription):
|
||||
|
||||
@@ -17,6 +17,8 @@ from .const import DOMAIN
|
||||
from .coordinator import RitualsDataUpdateCoordinator
|
||||
from .entity import DiffuserEntity
|
||||
|
||||
PARALLEL_UPDATES = 1
|
||||
|
||||
|
||||
@dataclass(frozen=True, kw_only=True)
|
||||
class RitualsSwitchEntityDescription(SwitchEntityDescription):
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user