Compare commits

..

1 Commits

Author SHA1 Message Date
epenet
2d8771532d Remove unnecessary suppress in importlib helper 2026-02-27 14:18:12 +00:00
290 changed files with 10096 additions and 36541 deletions

View File

@@ -605,7 +605,7 @@ jobs:
with:
persist-credentials: false
- name: Dependency review
uses: actions/dependency-review-action@05fe4576374b728f0c523d6a13d64c25081e0803 # v4.8.3
uses: actions/dependency-review-action@3c4e3dcb1aa7874d2c16be7d79418e9b7efd6261 # v4.8.2
with:
license-check: false # We use our own license audit checks

View File

@@ -28,11 +28,11 @@ jobs:
persist-credentials: false
- name: Initialize CodeQL
uses: github/codeql-action/init@89a39a4e59826350b863aa6b6252a07ad50cf83e # v4.32.4
uses: github/codeql-action/init@9e907b5e64f6b83e7804b09294d44122997950d6 # v4.32.3
with:
languages: python
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@89a39a4e59826350b863aa6b6252a07ad50cf83e # v4.32.4
uses: github/codeql-action/analyze@9e907b5e64f6b83e7804b09294d44122997950d6 # v4.32.3
with:
category: "/language:python"

View File

@@ -545,7 +545,6 @@ homeassistant.components.tcp.*
homeassistant.components.technove.*
homeassistant.components.tedee.*
homeassistant.components.telegram_bot.*
homeassistant.components.teslemetry.*
homeassistant.components.text.*
homeassistant.components.thethingsnetwork.*
homeassistant.components.threshold.*

6
CODEOWNERS generated
View File

@@ -401,6 +401,8 @@ build.json @home-assistant/supervisor
/tests/components/dsmr_reader/ @sorted-bits @glodenox @erwindouna
/homeassistant/components/duckdns/ @tr4nt0r
/tests/components/duckdns/ @tr4nt0r
/homeassistant/components/duke_energy/ @hunterjm
/tests/components/duke_energy/ @hunterjm
/homeassistant/components/duotecno/ @cereal2nd
/tests/components/duotecno/ @cereal2nd
/homeassistant/components/dwd_weather_warnings/ @runningman84 @stephan192
@@ -1899,8 +1901,8 @@ build.json @home-assistant/supervisor
/tests/components/withings/ @joostlek
/homeassistant/components/wiz/ @sbidy @arturpragacz
/tests/components/wiz/ @sbidy @arturpragacz
/homeassistant/components/wled/ @frenck @mik-laj
/tests/components/wled/ @frenck @mik-laj
/homeassistant/components/wled/ @frenck
/tests/components/wled/ @frenck
/homeassistant/components/wmspro/ @mback2k
/tests/components/wmspro/ @mback2k
/homeassistant/components/wolflink/ @adamkrol93 @mtielen

View File

@@ -191,7 +191,7 @@ class AccuWeatherEntity(
{
ATTR_FORECAST_TIME: utc_from_timestamp(item["EpochDate"]).isoformat(),
ATTR_FORECAST_CLOUD_COVERAGE: item["CloudCoverDay"],
ATTR_FORECAST_HUMIDITY: item["RelativeHumidityDay"].get("Average"),
ATTR_FORECAST_HUMIDITY: item["RelativeHumidityDay"]["Average"],
ATTR_FORECAST_NATIVE_TEMP: item["TemperatureMax"][ATTR_VALUE],
ATTR_FORECAST_NATIVE_TEMP_LOW: item["TemperatureMin"][ATTR_VALUE],
ATTR_FORECAST_NATIVE_APPARENT_TEMP: item["RealFeelTemperatureMax"][

View File

@@ -93,6 +93,7 @@ class AirobotNumber(AirobotEntity, NumberEntity):
raise ServiceValidationError(
translation_domain=DOMAIN,
translation_key="set_value_failed",
translation_placeholders={"error": str(err)},
) from err
else:
await self.coordinator.async_request_refresh()

View File

@@ -112,7 +112,7 @@
"message": "Failed to set temperature to {temperature}."
},
"set_value_failed": {
"message": "Failed to set value."
"message": "Failed to set value: {error}"
},
"switch_turn_off_failed": {
"message": "Failed to turn off {switch}."

View File

@@ -8,5 +8,5 @@
"iot_class": "cloud_polling",
"loggers": ["aioamazondevices"],
"quality_scale": "platinum",
"requirements": ["aioamazondevices==12.0.2"]
"requirements": ["aioamazondevices==12.0.0"]
}

View File

@@ -400,8 +400,8 @@ def _convert_content(
# If there is only one text block, simplify the content to a string
messages[-1]["content"] = messages[-1]["content"][0]["text"]
else:
# Note: We don't pass SystemContent here as it's passed to the API as the prompt
raise HomeAssistantError("Unexpected content type in chat log")
# Note: We don't pass SystemContent here as its passed to the API as the prompt
raise TypeError(f"Unexpected content type: {type(content)}")
return messages, container_id
@@ -442,8 +442,8 @@ async def _transform_stream( # noqa: C901 - This is complex, but better to have
Each message could contain multiple blocks of the same type.
"""
if stream is None or not hasattr(stream, "__aiter__"):
raise HomeAssistantError("Expected a stream of messages")
if stream is None:
raise TypeError("Expected a stream of messages")
current_tool_block: ToolUseBlockParam | ServerToolUseBlockParam | None = None
current_tool_args: str
@@ -456,6 +456,8 @@ async def _transform_stream( # noqa: C901 - This is complex, but better to have
LOGGER.debug("Received response: %s", response)
if isinstance(response, RawMessageStartEvent):
if response.message.role != "assistant":
raise ValueError("Unexpected message role")
input_usage = response.message.usage
first_block = True
elif isinstance(response, RawContentBlockStartEvent):
@@ -664,7 +666,7 @@ class AnthropicBaseLLMEntity(Entity):
system = chat_log.content[0]
if not isinstance(system, conversation.SystemContent):
raise HomeAssistantError("First message must be a system message")
raise TypeError("First message must be a system message")
# System prompt with caching enabled
system_prompt: list[TextBlockParam] = [

View File

@@ -31,7 +31,10 @@ rules:
test-before-setup: done
unique-config-entry: done
# Silver
action-exceptions: done
action-exceptions:
status: todo
comment: |
Reevaluate exceptions for entity services.
config-entry-unloading: done
docs-configuration-parameters: done
docs-installation-parameters: done

View File

@@ -117,7 +117,6 @@ class SharpAquosTVDevice(MediaPlayerEntity):
| MediaPlayerEntityFeature.VOLUME_SET
| MediaPlayerEntityFeature.PLAY
)
_attr_volume_step = 2 / 60
def __init__(
self, name: str, remote: sharp_aquos_rc.TV, power_on_enabled: bool = False
@@ -162,6 +161,22 @@ class SharpAquosTVDevice(MediaPlayerEntity):
"""Turn off tvplayer."""
self._remote.power(0)
@_retry
def volume_up(self) -> None:
"""Volume up the media player."""
if self.volume_level is None:
_LOGGER.debug("Unknown volume in volume_up")
return
self._remote.volume(int(self.volume_level * 60) + 2)
@_retry
def volume_down(self) -> None:
"""Volume down media player."""
if self.volume_level is None:
_LOGGER.debug("Unknown volume in volume_down")
return
self._remote.volume(int(self.volume_level * 60) - 2)
@_retry
def set_volume_level(self, volume: float) -> None:
"""Set Volume media player."""

View File

@@ -30,5 +30,5 @@
"integration_type": "hub",
"iot_class": "cloud_push",
"loggers": ["pubnub", "yalexs"],
"requirements": ["yalexs==9.2.0", "yalexs-ble==3.2.7"]
"requirements": ["yalexs==9.2.0", "yalexs-ble==3.2.4"]
}

View File

@@ -85,7 +85,6 @@ class BluesoundPlayer(CoordinatorEntity[BluesoundCoordinator], MediaPlayerEntity
_attr_media_content_type = MediaType.MUSIC
_attr_has_entity_name = True
_attr_name = None
_attr_volume_step = 0.01
def __init__(
self,
@@ -689,6 +688,24 @@ class BluesoundPlayer(CoordinatorEntity[BluesoundCoordinator], MediaPlayerEntity
await self._player.play_url(url)
async def async_volume_up(self) -> None:
"""Volume up the media player."""
if self.volume_level is None:
return
new_volume = self.volume_level + 0.01
new_volume = min(1, new_volume)
await self.async_set_volume_level(new_volume)
async def async_volume_down(self) -> None:
"""Volume down the media player."""
if self.volume_level is None:
return
new_volume = self.volume_level - 0.01
new_volume = max(0, new_volume)
await self.async_set_volume_level(new_volume)
async def async_set_volume_level(self, volume: float) -> None:
"""Send volume_up command to media player."""
volume = int(round(volume * 100))

View File

@@ -64,8 +64,6 @@ SENSOR_TYPES: tuple[BSBLanSensorEntityDescription, ...] = (
device_class=SensorDeviceClass.ENERGY,
native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR,
state_class=SensorStateClass.TOTAL_INCREASING,
suggested_display_precision=0,
entity_registry_enabled_default=False,
value_fn=lambda data: (
data.sensor.total_energy.value
if data.sensor.total_energy is not None

View File

@@ -807,7 +807,6 @@ class CastMediaPlayerEntity(CastDevice, MediaPlayerEntity):
# The lovelace app loops media to prevent timing out, don't show that
if self.app_id == CAST_APP_ID_HOMEASSISTANT_LOVELACE:
return MediaPlayerState.PLAYING
if (media_status := self._media_status()[0]) is not None:
if media_status.player_state == MEDIA_PLAYER_STATE_PLAYING:
return MediaPlayerState.PLAYING
@@ -818,19 +817,19 @@ class CastMediaPlayerEntity(CastDevice, MediaPlayerEntity):
if media_status.player_is_idle:
return MediaPlayerState.IDLE
if self.app_id in APP_IDS_UNRELIABLE_MEDIA_INFO:
# Some apps don't report media status, show the player as playing
return MediaPlayerState.PLAYING
if self.app_id is not None and self.app_id != pychromecast.config.APP_BACKDROP:
# We have an active app
return MediaPlayerState.IDLE
if self._chromecast is not None and self._chromecast.is_idle:
# If library consider us idle, that is our off state
# it takes HDMI status into account for cast devices.
return MediaPlayerState.OFF
if self.app_id in APP_IDS_UNRELIABLE_MEDIA_INFO:
# Some apps don't report media status, show the player as playing
return MediaPlayerState.PLAYING
if self.app_id is not None:
# We have an active app
return MediaPlayerState.IDLE
return None
@property

View File

@@ -139,6 +139,18 @@ class AbstractDemoPlayer(MediaPlayerEntity):
self._attr_is_volume_muted = mute
self.schedule_update_ha_state()
def volume_up(self) -> None:
"""Increase volume."""
assert self.volume_level is not None
self._attr_volume_level = min(1.0, self.volume_level + 0.1)
self.schedule_update_ha_state()
def volume_down(self) -> None:
"""Decrease volume."""
assert self.volume_level is not None
self._attr_volume_level = max(0.0, self.volume_level - 0.1)
self.schedule_update_ha_state()
def set_volume_level(self, volume: float) -> None:
"""Set the volume level, range 0..1."""
self._attr_volume_level = volume

View File

@@ -7,5 +7,5 @@
"integration_type": "hub",
"iot_class": "local_push",
"loggers": ["dsmr_parser"],
"requirements": ["dsmr-parser==1.5.0"]
"requirements": ["dsmr-parser==1.4.3"]
}

View File

@@ -0,0 +1,22 @@
"""The Duke Energy integration."""
from __future__ import annotations
from homeassistant.core import HomeAssistant
from .coordinator import DukeEnergyConfigEntry, DukeEnergyCoordinator
async def async_setup_entry(hass: HomeAssistant, entry: DukeEnergyConfigEntry) -> bool:
"""Set up Duke Energy from a config entry."""
coordinator = DukeEnergyCoordinator(hass, entry)
await coordinator.async_config_entry_first_refresh()
entry.runtime_data = coordinator
return True
async def async_unload_entry(hass: HomeAssistant, entry: DukeEnergyConfigEntry) -> bool:
"""Unload a config entry."""
return True

View File

@@ -0,0 +1,67 @@
"""Config flow for Duke Energy integration."""
from __future__ import annotations
import logging
from typing import Any
from aiodukeenergy import DukeEnergy
from aiohttp import ClientError, ClientResponseError
import voluptuous as vol
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
from homeassistant.const import CONF_EMAIL, CONF_PASSWORD, CONF_USERNAME
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
STEP_USER_DATA_SCHEMA = vol.Schema(
{
vol.Required(CONF_USERNAME): str,
vol.Required(CONF_PASSWORD): str,
}
)
class DukeEnergyConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a config flow for Duke Energy."""
VERSION = 1
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle the initial step."""
errors: dict[str, str] = {}
if user_input is not None:
session = async_get_clientsession(self.hass)
api = DukeEnergy(
user_input[CONF_USERNAME], user_input[CONF_PASSWORD], session
)
try:
auth = await api.authenticate()
except ClientResponseError as e:
errors["base"] = "invalid_auth" if e.status == 404 else "cannot_connect"
except ClientError, TimeoutError:
errors["base"] = "cannot_connect"
except Exception:
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
else:
username = auth["internalUserID"].lower()
await self.async_set_unique_id(username)
self._abort_if_unique_id_configured()
email = auth["loginEmailAddress"].lower()
data = {
CONF_EMAIL: email,
CONF_USERNAME: username,
CONF_PASSWORD: user_input[CONF_PASSWORD],
}
self._async_abort_entries_match(data)
return self.async_create_entry(title=email, data=data)
return self.async_show_form(
step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors
)

View File

@@ -0,0 +1,3 @@
"""Constants for the Duke Energy integration."""
DOMAIN = "duke_energy"

View File

@@ -0,0 +1,222 @@
"""Coordinator to handle Duke Energy connections."""
from datetime import datetime, timedelta
import logging
from typing import Any, cast
from aiodukeenergy import DukeEnergy
from aiohttp import ClientError
from homeassistant.components.recorder import get_instance
from homeassistant.components.recorder.models import (
StatisticData,
StatisticMeanType,
StatisticMetaData,
)
from homeassistant.components.recorder.statistics import (
async_add_external_statistics,
get_last_statistics,
statistics_during_period,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME, UnitOfEnergy, UnitOfVolume
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
from homeassistant.util import dt as dt_util
from homeassistant.util.unit_conversion import EnergyConverter
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
_SUPPORTED_METER_TYPES = ("ELECTRIC",)
type DukeEnergyConfigEntry = ConfigEntry[DukeEnergyCoordinator]
class DukeEnergyCoordinator(DataUpdateCoordinator[None]):
"""Handle inserting statistics."""
config_entry: DukeEnergyConfigEntry
def __init__(
self, hass: HomeAssistant, config_entry: DukeEnergyConfigEntry
) -> None:
"""Initialize the data handler."""
super().__init__(
hass,
_LOGGER,
config_entry=config_entry,
name="Duke Energy",
# Data is updated daily on Duke Energy.
# Refresh every 12h to be at most 12h behind.
update_interval=timedelta(hours=12),
)
self.api = DukeEnergy(
config_entry.data[CONF_USERNAME],
config_entry.data[CONF_PASSWORD],
async_get_clientsession(hass),
)
self._statistic_ids: set = set()
@callback
def _dummy_listener() -> None:
pass
# Force the coordinator to periodically update by registering at least one listener.
# Duke Energy does not provide forecast data, so all information is historical.
# This makes _async_update_data get periodically called so we can insert statistics.
self.async_add_listener(_dummy_listener)
self.config_entry.async_on_unload(self._clear_statistics)
def _clear_statistics(self) -> None:
"""Clear statistics."""
get_instance(self.hass).async_clear_statistics(list(self._statistic_ids))
async def _async_update_data(self) -> None:
"""Insert Duke Energy statistics."""
meters: dict[str, dict[str, Any]] = await self.api.get_meters()
for serial_number, meter in meters.items():
if (
not isinstance(meter["serviceType"], str)
or meter["serviceType"] not in _SUPPORTED_METER_TYPES
):
_LOGGER.debug(
"Skipping unsupported meter type %s", meter["serviceType"]
)
continue
id_prefix = f"{meter['serviceType'].lower()}_{serial_number}"
consumption_statistic_id = f"{DOMAIN}:{id_prefix}_energy_consumption"
self._statistic_ids.add(consumption_statistic_id)
_LOGGER.debug(
"Updating Statistics for %s",
consumption_statistic_id,
)
last_stat = await get_instance(self.hass).async_add_executor_job(
get_last_statistics, self.hass, 1, consumption_statistic_id, True, set()
)
if not last_stat:
_LOGGER.debug("Updating statistic for the first time")
usage = await self._async_get_energy_usage(meter)
consumption_sum = 0.0
last_stats_time = None
else:
usage = await self._async_get_energy_usage(
meter,
last_stat[consumption_statistic_id][0]["start"],
)
if not usage:
_LOGGER.debug("No recent usage data. Skipping update")
continue
stats = await get_instance(self.hass).async_add_executor_job(
statistics_during_period,
self.hass,
min(usage.keys()),
None,
{consumption_statistic_id},
"hour",
None,
{"sum"},
)
consumption_sum = cast(float, stats[consumption_statistic_id][0]["sum"])
last_stats_time = stats[consumption_statistic_id][0]["start"]
consumption_statistics = []
for start, data in usage.items():
if last_stats_time is not None and start.timestamp() <= last_stats_time:
continue
consumption_sum += data["energy"]
consumption_statistics.append(
StatisticData(
start=start, state=data["energy"], sum=consumption_sum
)
)
name_prefix = (
f"Duke Energy {meter['serviceType'].capitalize()} {serial_number}"
)
consumption_metadata = StatisticMetaData(
mean_type=StatisticMeanType.NONE,
has_sum=True,
name=f"{name_prefix} Consumption",
source=DOMAIN,
statistic_id=consumption_statistic_id,
unit_class=EnergyConverter.UNIT_CLASS,
unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR
if meter["serviceType"] == "ELECTRIC"
else UnitOfVolume.CENTUM_CUBIC_FEET,
)
_LOGGER.debug(
"Adding %s statistics for %s",
len(consumption_statistics),
consumption_statistic_id,
)
async_add_external_statistics(
self.hass, consumption_metadata, consumption_statistics
)
async def _async_get_energy_usage(
self, meter: dict[str, Any], start_time: float | None = None
) -> dict[datetime, dict[str, float | int]]:
"""Get energy usage.
If start_time is None, get usage since account activation (or as far back as possible),
otherwise since start_time - 30 days to allow corrections in data.
Duke Energy provides hourly data all the way back to ~3 years.
"""
# All of Duke Energy Service Areas are currently in America/New_York timezone
# May need to re-think this if that ever changes and determine timezone based
# on the service address somehow.
tz = await dt_util.async_get_time_zone("America/New_York")
lookback = timedelta(days=30)
one = timedelta(days=1)
if start_time is None:
# Max 3 years of data
start = dt_util.now(tz) - timedelta(days=3 * 365)
else:
start = datetime.fromtimestamp(start_time, tz=tz) - lookback
agreement_date = dt_util.parse_datetime(meter["agreementActiveDate"])
if agreement_date is not None:
start = max(agreement_date.replace(tzinfo=tz), start)
start = start.replace(hour=0, minute=0, second=0, microsecond=0)
end = dt_util.now(tz).replace(hour=0, minute=0, second=0, microsecond=0) - one
_LOGGER.debug("Data lookup range: %s - %s", start, end)
start_step = max(end - lookback, start)
end_step = end
usage: dict[datetime, dict[str, float | int]] = {}
while True:
_LOGGER.debug("Getting hourly usage: %s - %s", start_step, end_step)
try:
# Get data
results = await self.api.get_energy_usage(
meter["serialNum"], "HOURLY", "DAY", start_step, end_step
)
usage = {**results["data"], **usage}
for missing in results["missing"]:
_LOGGER.debug("Missing data: %s", missing)
# Set next range
end_step = start_step - one
start_step = max(start_step - lookback, start)
# Make sure we don't go back too far
if end_step < start:
break
except TimeoutError, ClientError:
# ClientError is raised when there is no more data for the range
break
_LOGGER.debug("Got %s meter usage reads", len(usage))
return usage

View File

@@ -0,0 +1,11 @@
{
"domain": "duke_energy",
"name": "Duke Energy",
"codeowners": ["@hunterjm"],
"config_flow": true,
"dependencies": ["recorder"],
"documentation": "https://www.home-assistant.io/integrations/duke_energy",
"integration_type": "service",
"iot_class": "cloud_polling",
"requirements": ["aiodukeenergy==0.3.0"]
}

View File

@@ -0,0 +1,20 @@
{
"config": {
"abort": {
"already_configured": "[%key:common::config_flow::abort::already_configured_device%]"
},
"error": {
"cannot_connect": "[%key:common::config_flow::error::cannot_connect%]",
"invalid_auth": "[%key:common::config_flow::error::invalid_auth%]",
"unknown": "[%key:common::config_flow::error::unknown%]"
},
"step": {
"user": {
"data": {
"password": "[%key:common::config_flow::data::password%]",
"username": "[%key:common::config_flow::data::username%]"
}
}
}
}
}

View File

@@ -33,8 +33,6 @@ DUNEHD_PLAYER_SUPPORT: Final[MediaPlayerEntityFeature] = (
| MediaPlayerEntityFeature.PLAY
| MediaPlayerEntityFeature.PLAY_MEDIA
| MediaPlayerEntityFeature.BROWSE_MEDIA
| MediaPlayerEntityFeature.VOLUME_STEP
| MediaPlayerEntityFeature.VOLUME_MUTE
)

View File

@@ -405,13 +405,8 @@ CT_SENSORS = (
)
for cttype, key in (
(CtType.NET_CONSUMPTION, "lifetime_net_consumption"),
(CtType.PRODUCTION, "production_ct_energy_delivered"),
# Production CT energy_delivered is not used
(CtType.STORAGE, "lifetime_battery_discharged"),
(CtType.TOTAL_CONSUMPTION, "total_consumption_ct_energy_delivered"),
(CtType.BACKFEED, "backfeed_ct_energy_delivered"),
(CtType.LOAD, "load_ct_energy_delivered"),
(CtType.EVSE, "evse_ct_energy_delivered"),
(CtType.PV3P, "pv3p_ct_energy_delivered"),
)
]
+ [
@@ -428,13 +423,8 @@ CT_SENSORS = (
)
for cttype, key in (
(CtType.NET_CONSUMPTION, "lifetime_net_production"),
(CtType.PRODUCTION, "production_ct_energy_received"),
# Production CT energy_received is not used
(CtType.STORAGE, "lifetime_battery_charged"),
(CtType.TOTAL_CONSUMPTION, "total_consumption_ct_energy_received"),
(CtType.BACKFEED, "backfeed_ct_energy_received"),
(CtType.LOAD, "load_ct_energy_received"),
(CtType.EVSE, "evse_ct_energy_received"),
(CtType.PV3P, "pv3p_ct_energy_received"),
)
]
+ [
@@ -451,13 +441,8 @@ CT_SENSORS = (
)
for cttype, key in (
(CtType.NET_CONSUMPTION, "net_consumption"),
(CtType.PRODUCTION, "production_ct_power"),
# Production CT active_power is not used
(CtType.STORAGE, "battery_discharge"),
(CtType.TOTAL_CONSUMPTION, "total_consumption_ct_power"),
(CtType.BACKFEED, "backfeed_ct_power"),
(CtType.LOAD, "load_ct_power"),
(CtType.EVSE, "evse_ct_power"),
(CtType.PV3P, "pv3p_ct_power"),
)
]
+ [
@@ -476,11 +461,6 @@ CT_SENSORS = (
(CtType.NET_CONSUMPTION, "frequency", "net_ct_frequency"),
(CtType.PRODUCTION, "production_ct_frequency", ""),
(CtType.STORAGE, "storage_ct_frequency", ""),
(CtType.TOTAL_CONSUMPTION, "total_consumption_ct_frequency", ""),
(CtType.BACKFEED, "backfeed_ct_frequency", ""),
(CtType.LOAD, "load_ct_frequency", ""),
(CtType.EVSE, "evse_ct_frequency", ""),
(CtType.PV3P, "pv3p_ct_frequency", ""),
)
]
+ [
@@ -500,11 +480,6 @@ CT_SENSORS = (
(CtType.NET_CONSUMPTION, "voltage", "net_ct_voltage"),
(CtType.PRODUCTION, "production_ct_voltage", ""),
(CtType.STORAGE, "storage_voltage", "storage_ct_voltage"),
(CtType.TOTAL_CONSUMPTION, "total_consumption_ct_voltage", ""),
(CtType.BACKFEED, "backfeed_ct_voltage", ""),
(CtType.LOAD, "load_ct_voltage", ""),
(CtType.EVSE, "evse_ct_voltage", ""),
(CtType.PV3P, "pv3p_ct_voltage", ""),
)
]
+ [
@@ -524,11 +499,6 @@ CT_SENSORS = (
(CtType.NET_CONSUMPTION, "net_ct_current"),
(CtType.PRODUCTION, "production_ct_current"),
(CtType.STORAGE, "storage_ct_current"),
(CtType.TOTAL_CONSUMPTION, "total_consumption_ct_current"),
(CtType.BACKFEED, "backfeed_ct_current"),
(CtType.LOAD, "load_ct_current"),
(CtType.EVSE, "evse_ct_current"),
(CtType.PV3P, "pv3p_ct_current"),
)
]
+ [
@@ -546,11 +516,6 @@ CT_SENSORS = (
(CtType.NET_CONSUMPTION, "net_ct_powerfactor"),
(CtType.PRODUCTION, "production_ct_powerfactor"),
(CtType.STORAGE, "storage_ct_powerfactor"),
(CtType.TOTAL_CONSUMPTION, "total_consumption_ct_powerfactor"),
(CtType.BACKFEED, "backfeed_ct_powerfactor"),
(CtType.LOAD, "load_ct_powerfactor"),
(CtType.EVSE, "evse_ct_powerfactor"),
(CtType.PV3P, "pv3p_ct_powerfactor"),
)
]
+ [
@@ -572,11 +537,6 @@ CT_SENSORS = (
),
(CtType.PRODUCTION, "production_ct_metering_status", ""),
(CtType.STORAGE, "storage_ct_metering_status", ""),
(CtType.TOTAL_CONSUMPTION, "total_consumption_ct_metering_status", ""),
(CtType.BACKFEED, "backfeed_ct_metering_status", ""),
(CtType.LOAD, "load_ct_metering_status", ""),
(CtType.EVSE, "evse_ct_metering_status", ""),
(CtType.PV3P, "pv3p_ct_metering_status", ""),
)
]
+ [
@@ -597,11 +557,6 @@ CT_SENSORS = (
),
(CtType.PRODUCTION, "production_ct_status_flags", ""),
(CtType.STORAGE, "storage_ct_status_flags", ""),
(CtType.TOTAL_CONSUMPTION, "total_consumption_ct_status_flags", ""),
(CtType.BACKFEED, "backfeed_ct_status_flags", ""),
(CtType.LOAD, "load_ct_status_flags", ""),
(CtType.EVSE, "evse_ct_status_flags", ""),
(CtType.PV3P, "pv3p_ct_status_flags", ""),
)
]
)

View File

@@ -160,60 +160,6 @@
"available_energy": {
"name": "Available battery energy"
},
"backfeed_ct_current": {
"name": "Backfeed CT current"
},
"backfeed_ct_current_phase": {
"name": "Backfeed CT current {phase_name}"
},
"backfeed_ct_energy_delivered": {
"name": "Backfeed CT energy delivered"
},
"backfeed_ct_energy_delivered_phase": {
"name": "Backfeed CT energy delivered {phase_name}"
},
"backfeed_ct_energy_received": {
"name": "Backfeed CT energy received"
},
"backfeed_ct_energy_received_phase": {
"name": "Backfeed CT energy received {phase_name}"
},
"backfeed_ct_frequency": {
"name": "Frequency backfeed CT"
},
"backfeed_ct_frequency_phase": {
"name": "Frequency backfeed CT {phase_name}"
},
"backfeed_ct_metering_status": {
"name": "Metering status backfeed CT"
},
"backfeed_ct_metering_status_phase": {
"name": "Metering status backfeed CT {phase_name}"
},
"backfeed_ct_power": {
"name": "Backfeed CT power"
},
"backfeed_ct_power_phase": {
"name": "Backfeed CT power {phase_name}"
},
"backfeed_ct_powerfactor": {
"name": "Power factor backfeed CT"
},
"backfeed_ct_powerfactor_phase": {
"name": "Power factor backfeed CT {phase_name}"
},
"backfeed_ct_status_flags": {
"name": "Meter status flags active backfeed CT"
},
"backfeed_ct_status_flags_phase": {
"name": "Meter status flags active backfeed CT {phase_name}"
},
"backfeed_ct_voltage": {
"name": "Voltage backfeed CT"
},
"backfeed_ct_voltage_phase": {
"name": "Voltage backfeed CT {phase_name}"
},
"balanced_net_consumption": {
"name": "Balanced net power consumption"
},
@@ -265,60 +211,6 @@
"energy_today": {
"name": "[%key:component::enphase_envoy::entity::sensor::daily_production::name%]"
},
"evse_ct_current": {
"name": "EVSE CT current"
},
"evse_ct_current_phase": {
"name": "EVSE CT current {phase_name}"
},
"evse_ct_energy_delivered": {
"name": "EVSE CT energy delivered"
},
"evse_ct_energy_delivered_phase": {
"name": "EVSE CT energy delivered {phase_name}"
},
"evse_ct_energy_received": {
"name": "EVSE CT energy received"
},
"evse_ct_energy_received_phase": {
"name": "EVSE CT energy received {phase_name}"
},
"evse_ct_frequency": {
"name": "Frequency EVSE CT"
},
"evse_ct_frequency_phase": {
"name": "Frequency EVSE CT {phase_name}"
},
"evse_ct_metering_status": {
"name": "Metering status EVSE CT"
},
"evse_ct_metering_status_phase": {
"name": "Metering status EVSE CT {phase_name}"
},
"evse_ct_power": {
"name": "EVSE CT power"
},
"evse_ct_power_phase": {
"name": "EVSE CT power {phase_name}"
},
"evse_ct_powerfactor": {
"name": "Power factor EVSE CT"
},
"evse_ct_powerfactor_phase": {
"name": "Power factor EVSE CT {phase_name}"
},
"evse_ct_status_flags": {
"name": "Meter status flags active EVSE CT"
},
"evse_ct_status_flags_phase": {
"name": "Meter status flags active EVSE CT {phase_name}"
},
"evse_ct_voltage": {
"name": "Voltage EVSE CT"
},
"evse_ct_voltage_phase": {
"name": "Voltage EVSE CT {phase_name}"
},
"grid_status": {
"name": "[%key:component::enphase_envoy::entity::binary_sensor::grid_status::name%]",
"state": {
@@ -378,60 +270,6 @@
"lifetime_production_phase": {
"name": "Lifetime energy production {phase_name}"
},
"load_ct_current": {
"name": "Load CT current"
},
"load_ct_current_phase": {
"name": "Load CT current {phase_name}"
},
"load_ct_energy_delivered": {
"name": "Load CT energy delivered"
},
"load_ct_energy_delivered_phase": {
"name": "Load CT energy delivered {phase_name}"
},
"load_ct_energy_received": {
"name": "Load CT energy received"
},
"load_ct_energy_received_phase": {
"name": "Load CT energy received {phase_name}"
},
"load_ct_frequency": {
"name": "Frequency load CT"
},
"load_ct_frequency_phase": {
"name": "Frequency load CT {phase_name}"
},
"load_ct_metering_status": {
"name": "Metering status load CT"
},
"load_ct_metering_status_phase": {
"name": "Metering status load CT {phase_name}"
},
"load_ct_power": {
"name": "Load CT power"
},
"load_ct_power_phase": {
"name": "Load CT power {phase_name}"
},
"load_ct_powerfactor": {
"name": "Power factor load CT"
},
"load_ct_powerfactor_phase": {
"name": "Power factor load CT {phase_name}"
},
"load_ct_status_flags": {
"name": "Meter status flags active load CT"
},
"load_ct_status_flags_phase": {
"name": "Meter status flags active load CT {phase_name}"
},
"load_ct_voltage": {
"name": "Voltage load CT"
},
"load_ct_voltage_phase": {
"name": "Voltage load CT {phase_name}"
},
"max_capacity": {
"name": "Battery capacity"
},
@@ -493,18 +331,6 @@
"production_ct_current_phase": {
"name": "Production CT current {phase_name}"
},
"production_ct_energy_delivered": {
"name": "Production CT energy delivered"
},
"production_ct_energy_delivered_phase": {
"name": "Production CT energy delivered {phase_name}"
},
"production_ct_energy_received": {
"name": "Production CT energy received"
},
"production_ct_energy_received_phase": {
"name": "Production CT energy received {phase_name}"
},
"production_ct_frequency": {
"name": "Frequency production CT"
},
@@ -517,12 +343,6 @@
"production_ct_metering_status_phase": {
"name": "Metering status production CT {phase_name}"
},
"production_ct_power": {
"name": "Production CT power"
},
"production_ct_power_phase": {
"name": "Production CT power {phase_name}"
},
"production_ct_powerfactor": {
"name": "Power factor production CT"
},
@@ -541,60 +361,6 @@
"production_ct_voltage_phase": {
"name": "Voltage production CT {phase_name}"
},
"pv3p_ct_current": {
"name": "PV3P CT current"
},
"pv3p_ct_current_phase": {
"name": "PV3P CT current {phase_name}"
},
"pv3p_ct_energy_delivered": {
"name": "PV3P CT energy delivered"
},
"pv3p_ct_energy_delivered_phase": {
"name": "PV3P CT energy delivered {phase_name}"
},
"pv3p_ct_energy_received": {
"name": "PV3P CT energy received"
},
"pv3p_ct_energy_received_phase": {
"name": "PV3P CT energy received {phase_name}"
},
"pv3p_ct_frequency": {
"name": "Frequency PV3P CT"
},
"pv3p_ct_frequency_phase": {
"name": "Frequency PV3P CT {phase_name}"
},
"pv3p_ct_metering_status": {
"name": "Metering status PV3P CT"
},
"pv3p_ct_metering_status_phase": {
"name": "Metering status PV3P CT {phase_name}"
},
"pv3p_ct_power": {
"name": "PV3P CT power"
},
"pv3p_ct_power_phase": {
"name": "PV3P CT power {phase_name}"
},
"pv3p_ct_powerfactor": {
"name": "Power factor PV3P CT"
},
"pv3p_ct_powerfactor_phase": {
"name": "Power factor PV3P CT {phase_name}"
},
"pv3p_ct_status_flags": {
"name": "Meter status flags active PV3P CT"
},
"pv3p_ct_status_flags_phase": {
"name": "Meter status flags active PV3P CT {phase_name}"
},
"pv3p_ct_voltage": {
"name": "Voltage PV3P CT"
},
"pv3p_ct_voltage_phase": {
"name": "Voltage PV3P CT {phase_name}"
},
"reserve_energy": {
"name": "Reserve battery energy"
},
@@ -648,60 +414,6 @@
},
"storage_ct_voltage_phase": {
"name": "Voltage storage CT {phase_name}"
},
"total_consumption_ct_current": {
"name": "Total consumption CT current"
},
"total_consumption_ct_current_phase": {
"name": "Total consumption CT current {phase_name}"
},
"total_consumption_ct_energy_delivered": {
"name": "Total consumption CT energy delivered"
},
"total_consumption_ct_energy_delivered_phase": {
"name": "Total consumption CT energy delivered {phase_name}"
},
"total_consumption_ct_energy_received": {
"name": "Total consumption CT energy received"
},
"total_consumption_ct_energy_received_phase": {
"name": "Total consumption CT energy received {phase_name}"
},
"total_consumption_ct_frequency": {
"name": "Frequency total consumption CT"
},
"total_consumption_ct_frequency_phase": {
"name": "Frequency total consumption CT {phase_name}"
},
"total_consumption_ct_metering_status": {
"name": "Metering status total consumption CT"
},
"total_consumption_ct_metering_status_phase": {
"name": "Metering status total consumption CT {phase_name}"
},
"total_consumption_ct_power": {
"name": "Total consumption CT power"
},
"total_consumption_ct_power_phase": {
"name": "Total consumption CT power {phase_name}"
},
"total_consumption_ct_powerfactor": {
"name": "Power factor total consumption CT"
},
"total_consumption_ct_powerfactor_phase": {
"name": "Power factor total consumption CT {phase_name}"
},
"total_consumption_ct_status_flags": {
"name": "Meter status flags active total consumption CT"
},
"total_consumption_ct_status_flags_phase": {
"name": "Meter status flags active total consumption CT {phase_name}"
},
"total_consumption_ct_voltage": {
"name": "Voltage total consumption CT"
},
"total_consumption_ct_voltage_phase": {
"name": "Voltage total consumption CT {phase_name}"
}
},
"switch": {

View File

@@ -7,5 +7,5 @@
"integration_type": "service",
"iot_class": "cloud_polling",
"loggers": ["env_canada"],
"requirements": ["env-canada==0.13.2"]
"requirements": ["env-canada==0.12.4"]
}

View File

@@ -1,7 +1,7 @@
{
"exceptions": {
"zone_only_service": {
"message": "Only zones support the `{service}` action"
"message": "Only zones support the `{service}` service"
}
},
"services": {

View File

@@ -14,5 +14,5 @@
"iot_class": "local_polling",
"mqtt": ["fully/deviceInfo/+"],
"quality_scale": "bronze",
"requirements": ["python-fullykiosk==0.0.15"]
"requirements": ["python-fullykiosk==0.0.14"]
}

View File

@@ -78,12 +78,6 @@ query ($owner: String!, $repository: String!) {
number
}
}
merged_pull_request: pullRequests(
first:1
states: MERGED
) {
total: totalCount
}
release: latestRelease {
name
url

View File

@@ -28,9 +28,6 @@
"latest_tag": {
"default": "mdi:tag"
},
"merged_pulls_count": {
"default": "mdi:source-merge"
},
"pulls_count": {
"default": "mdi:source-pull"
},

View File

@@ -7,5 +7,5 @@
"integration_type": "service",
"iot_class": "cloud_polling",
"loggers": ["aiogithubapi"],
"requirements": ["aiogithubapi==26.0.0"]
"requirements": ["aiogithubapi==24.6.0"]
}

View File

@@ -75,13 +75,6 @@ SENSOR_DESCRIPTIONS: tuple[GitHubSensorEntityDescription, ...] = (
state_class=SensorStateClass.MEASUREMENT,
value_fn=lambda data: data["pull_request"]["total"],
),
GitHubSensorEntityDescription(
key="merged_pulls_count",
translation_key="merged_pulls_count",
entity_category=EntityCategory.DIAGNOSTIC,
state_class=SensorStateClass.TOTAL,
value_fn=lambda data: data["merged_pull_request"]["total"],
),
GitHubSensorEntityDescription(
key="latest_commit",
translation_key="latest_commit",

View File

@@ -48,10 +48,6 @@
"latest_tag": {
"name": "Latest tag"
},
"merged_pulls_count": {
"name": "Merged pull requests",
"unit_of_measurement": "pull requests"
},
"pulls_count": {
"name": "Pull requests",
"unit_of_measurement": "pull requests"

View File

@@ -140,5 +140,5 @@
"documentation": "https://www.home-assistant.io/integrations/govee_ble",
"integration_type": "device",
"iot_class": "local_push",
"requirements": ["govee-ble==1.2.0"]
"requirements": ["govee-ble==0.44.0"]
}

View File

@@ -6,12 +6,6 @@
}
},
"number": {
"audio_unmute": {
"default": "mdi:volume-high"
},
"earc_unmute": {
"default": "mdi:volume-high"
},
"oled_fade": {
"default": "mdi:cellphone-information"
},

View File

@@ -31,32 +31,6 @@ class HDFuryNumberEntityDescription(NumberEntityDescription):
NUMBERS: tuple[HDFuryNumberEntityDescription, ...] = (
HDFuryNumberEntityDescription(
key="unmutecnt",
translation_key="audio_unmute",
entity_registry_enabled_default=False,
mode=NumberMode.BOX,
native_min_value=50,
native_max_value=1000,
native_step=1,
device_class=NumberDeviceClass.DURATION,
native_unit_of_measurement=UnitOfTime.MILLISECONDS,
entity_category=EntityCategory.CONFIG,
set_value_fn=lambda client, value: client.set_audio_unmute(value),
),
HDFuryNumberEntityDescription(
key="earcunmutecnt",
translation_key="earc_unmute",
entity_registry_enabled_default=False,
mode=NumberMode.BOX,
native_min_value=0,
native_max_value=1000,
native_step=1,
device_class=NumberDeviceClass.DURATION,
native_unit_of_measurement=UnitOfTime.MILLISECONDS,
entity_category=EntityCategory.CONFIG,
set_value_fn=lambda client, value: client.set_earc_unmute(value),
),
HDFuryNumberEntityDescription(
key="oledfade",
translation_key="oled_fade",

View File

@@ -41,12 +41,6 @@
}
},
"number": {
"audio_unmute": {
"name": "Unmute delay"
},
"earc_unmute": {
"name": "eARC unmute delay"
},
"oled_fade": {
"name": "OLED fade timer"
},

View File

@@ -10,5 +10,5 @@
"integration_type": "hub",
"iot_class": "cloud_polling",
"loggers": ["apyhiveapi"],
"requirements": ["pyhive-integration==1.0.8"]
"requirements": ["pyhive-integration==1.0.7"]
}

View File

@@ -57,8 +57,8 @@
"battery_charge_discharge_state": {
"name": "Battery charge/discharge state",
"state": {
"charging": "[%key:common::state::charging%]",
"discharging": "[%key:common::state::discharging%]",
"charging": "Charging",
"discharging": "Discharging",
"static": "Static"
}
},

View File

@@ -2,8 +2,6 @@
import logging
from chip.clusters import Objects as clusters
ADDON_SLUG = "core_matter_server"
CONF_INTEGRATION_CREATED_ADDON = "integration_created_addon"
@@ -17,100 +15,3 @@ ID_TYPE_DEVICE_ID = "deviceid"
ID_TYPE_SERIAL = "serial"
FEATUREMAP_ATTRIBUTE_ID = 65532
# --- Lock domain constants ---
# Shared field keys
ATTR_CREDENTIAL_RULE = "credential_rule"
ATTR_MAX_CREDENTIALS_PER_USER = "max_credentials_per_user"
ATTR_MAX_PIN_USERS = "max_pin_users"
ATTR_MAX_RFID_USERS = "max_rfid_users"
ATTR_MAX_USERS = "max_users"
ATTR_SUPPORTS_USER_MGMT = "supports_user_management"
ATTR_USER_INDEX = "user_index"
ATTR_USER_NAME = "user_name"
ATTR_USER_STATUS = "user_status"
ATTR_USER_TYPE = "user_type"
# Magic values
CLEAR_ALL_INDEX = 0xFFFE # Matter spec: pass to ClearUser/ClearCredential to clear all
# Timed request timeout for lock commands that modify state.
# 10 seconds accounts for Thread network latency and retransmissions.
LOCK_TIMED_REQUEST_TIMEOUT_MS = 10000
# Credential field keys
ATTR_CREDENTIAL_DATA = "credential_data"
ATTR_CREDENTIAL_INDEX = "credential_index"
ATTR_CREDENTIAL_TYPE = "credential_type"
# Credential type strings
CRED_TYPE_FACE = "face"
CRED_TYPE_FINGERPRINT = "fingerprint"
CRED_TYPE_FINGER_VEIN = "finger_vein"
CRED_TYPE_PIN = "pin"
CRED_TYPE_RFID = "rfid"
# User status mapping (Matter DoorLock UserStatusEnum)
_UserStatus = clusters.DoorLock.Enums.UserStatusEnum
USER_STATUS_MAP: dict[int, str] = {
_UserStatus.kAvailable: "available",
_UserStatus.kOccupiedEnabled: "occupied_enabled",
_UserStatus.kOccupiedDisabled: "occupied_disabled",
}
USER_STATUS_REVERSE_MAP: dict[str, int] = {v: k for k, v in USER_STATUS_MAP.items()}
# User type mapping (Matter DoorLock UserTypeEnum)
_UserType = clusters.DoorLock.Enums.UserTypeEnum
USER_TYPE_MAP: dict[int, str] = {
_UserType.kUnrestrictedUser: "unrestricted_user",
_UserType.kYearDayScheduleUser: "year_day_schedule_user",
_UserType.kWeekDayScheduleUser: "week_day_schedule_user",
_UserType.kProgrammingUser: "programming_user",
_UserType.kNonAccessUser: "non_access_user",
_UserType.kForcedUser: "forced_user",
_UserType.kDisposableUser: "disposable_user",
_UserType.kExpiringUser: "expiring_user",
_UserType.kScheduleRestrictedUser: "schedule_restricted_user",
_UserType.kRemoteOnlyUser: "remote_only_user",
}
USER_TYPE_REVERSE_MAP: dict[str, int] = {v: k for k, v in USER_TYPE_MAP.items()}
# Credential type mapping (Matter DoorLock CredentialTypeEnum)
_CredentialType = clusters.DoorLock.Enums.CredentialTypeEnum
CREDENTIAL_TYPE_MAP: dict[int, str] = {
_CredentialType.kProgrammingPIN: "programming_pin",
_CredentialType.kPin: CRED_TYPE_PIN,
_CredentialType.kRfid: CRED_TYPE_RFID,
_CredentialType.kFingerprint: CRED_TYPE_FINGERPRINT,
_CredentialType.kFingerVein: CRED_TYPE_FINGER_VEIN,
_CredentialType.kFace: CRED_TYPE_FACE,
_CredentialType.kAliroCredentialIssuerKey: "aliro_credential_issuer_key",
_CredentialType.kAliroEvictableEndpointKey: "aliro_evictable_endpoint_key",
_CredentialType.kAliroNonEvictableEndpointKey: "aliro_non_evictable_endpoint_key",
}
# Credential rule mapping (Matter DoorLock CredentialRuleEnum)
_CredentialRule = clusters.DoorLock.Enums.CredentialRuleEnum
CREDENTIAL_RULE_MAP: dict[int, str] = {
_CredentialRule.kSingle: "single",
_CredentialRule.kDual: "dual",
_CredentialRule.kTri: "tri",
}
CREDENTIAL_RULE_REVERSE_MAP: dict[str, int] = {
v: k for k, v in CREDENTIAL_RULE_MAP.items()
}
# Reverse mapping for credential types (str -> int)
CREDENTIAL_TYPE_REVERSE_MAP: dict[str, int] = {
v: k for k, v in CREDENTIAL_TYPE_MAP.items()
}
# Credential types allowed in set/clear services (excludes programming_pin, aliro_*)
SERVICE_CREDENTIAL_TYPES = [
CRED_TYPE_PIN,
CRED_TYPE_RFID,
CRED_TYPE_FINGERPRINT,
CRED_TYPE_FINGER_VEIN,
CRED_TYPE_FACE,
]

View File

@@ -174,27 +174,6 @@
}
},
"services": {
"clear_lock_credential": {
"service": "mdi:key-remove"
},
"clear_lock_user": {
"service": "mdi:account-remove"
},
"get_lock_credential_status": {
"service": "mdi:key-chain"
},
"get_lock_info": {
"service": "mdi:lock-question"
},
"get_lock_users": {
"service": "mdi:account-multiple"
},
"set_lock_credential": {
"service": "mdi:key-plus"
},
"set_lock_user": {
"service": "mdi:account-lock"
},
"water_heater_boost": {
"service": "mdi:water-boiler"
}

View File

@@ -7,7 +7,6 @@ from dataclasses import dataclass
from typing import Any
from chip.clusters import Objects as clusters
from matter_server.common.errors import MatterError
from matter_server.common.models import EventType, MatterNodeEvent
from homeassistant.components.lock import (
@@ -18,56 +17,32 @@ from homeassistant.components.lock import (
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ATTR_CODE, Platform
from homeassistant.core import HomeAssistant, callback
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .const import (
ATTR_CREDENTIAL_DATA,
ATTR_CREDENTIAL_INDEX,
ATTR_CREDENTIAL_RULE,
ATTR_CREDENTIAL_TYPE,
ATTR_USER_INDEX,
ATTR_USER_NAME,
ATTR_USER_STATUS,
ATTR_USER_TYPE,
LOCK_TIMED_REQUEST_TIMEOUT_MS,
LOGGER,
)
from .const import LOGGER
from .entity import MatterEntity, MatterEntityDescription
from .helpers import get_matter
from .lock_helpers import (
DoorLockFeature,
GetLockCredentialStatusResult,
GetLockInfoResult,
GetLockUsersResult,
SetLockCredentialResult,
clear_lock_credential,
clear_lock_user,
get_lock_credential_status,
get_lock_info,
get_lock_users,
set_lock_credential,
set_lock_user,
)
from .models import MatterDiscoverySchema
# Door lock operation source mapping (Matter DoorLock OperationSourceEnum)
_OperationSource = clusters.DoorLock.Enums.OperationSourceEnum
DOOR_LOCK_OPERATION_SOURCE: dict[int, str] = {
_OperationSource.kUnspecified: "Unspecified",
_OperationSource.kManual: "Manual",
_OperationSource.kProprietaryRemote: "Proprietary Remote",
_OperationSource.kKeypad: "Keypad",
_OperationSource.kAuto: "Auto",
_OperationSource.kButton: "Button",
_OperationSource.kSchedule: "Schedule",
_OperationSource.kRemote: "Remote",
_OperationSource.kRfid: "RFID",
_OperationSource.kBiometric: "Biometric",
_OperationSource.kAliro: "Aliro",
DOOR_LOCK_OPERATION_SOURCE = {
# mapping from operation source id's to textual representation
0: "Unspecified",
1: "Manual", # [Optional]
2: "Proprietary Remote", # [Optional]
3: "Keypad", # [Optional]
4: "Auto", # [Optional]
5: "Button", # [Optional]
6: "Schedule", # [HDSCH]
7: "Remote", # [M]
8: "RFID", # [RID]
9: "Biometric", # [USR]
10: "Aliro", # [Aliro]
}
DoorLockFeature = clusters.DoorLock.Bitmaps.Feature
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
@@ -123,15 +98,17 @@ class MatterLock(MatterEntity, LockEntity):
node_event.data,
)
# Handle the DoorLock events
# handle the DoorLock events
node_event_data: dict[str, int] = node_event.data or {}
match node_event.event_id:
case clusters.DoorLock.Events.LockOperation.event_id:
case (
clusters.DoorLock.Events.LockOperation.event_id
): # Lock cluster event 2
# update the changed_by attribute to indicate lock operation source
operation_source: int = node_event_data.get("operationSource", -1)
source_name = DOOR_LOCK_OPERATION_SOURCE.get(
self._attr_changed_by = DOOR_LOCK_OPERATION_SOURCE.get(
operation_source, "Unknown"
)
self._attr_changed_by = source_name
self.async_write_ha_state()
@property
@@ -169,7 +146,7 @@ class MatterLock(MatterEntity, LockEntity):
code_bytes = code.encode() if code else None
await self.send_device_command(
command=clusters.DoorLock.Commands.LockDoor(code_bytes),
timed_request_timeout_ms=LOCK_TIMED_REQUEST_TIMEOUT_MS,
timed_request_timeout_ms=1000,
)
async def async_unlock(self, **kwargs: Any) -> None:
@@ -191,12 +168,12 @@ class MatterLock(MatterEntity, LockEntity):
# and unlatch on the HA 'open' command.
await self.send_device_command(
command=clusters.DoorLock.Commands.UnboltDoor(code_bytes),
timed_request_timeout_ms=LOCK_TIMED_REQUEST_TIMEOUT_MS,
timed_request_timeout_ms=1000,
)
else:
await self.send_device_command(
command=clusters.DoorLock.Commands.UnlockDoor(code_bytes),
timed_request_timeout_ms=LOCK_TIMED_REQUEST_TIMEOUT_MS,
timed_request_timeout_ms=1000,
)
async def async_open(self, **kwargs: Any) -> None:
@@ -213,7 +190,7 @@ class MatterLock(MatterEntity, LockEntity):
code_bytes = code.encode() if code else None
await self.send_device_command(
command=clusters.DoorLock.Commands.UnlockDoor(code_bytes),
timed_request_timeout_ms=LOCK_TIMED_REQUEST_TIMEOUT_MS,
timed_request_timeout_ms=1000,
)
@callback
@@ -279,109 +256,6 @@ class MatterLock(MatterEntity, LockEntity):
supported_features |= LockEntityFeature.OPEN
self._attr_supported_features = supported_features
# --- Entity service methods ---
async def async_set_lock_user(self, **kwargs: Any) -> None:
"""Set a lock user (full CRUD)."""
try:
await set_lock_user(
self.matter_client,
self._endpoint.node,
user_index=kwargs.get(ATTR_USER_INDEX),
user_name=kwargs.get(ATTR_USER_NAME),
user_type=kwargs.get(ATTR_USER_TYPE),
credential_rule=kwargs.get(ATTR_CREDENTIAL_RULE),
)
except MatterError as err:
raise HomeAssistantError(
f"Failed to set lock user on {self.entity_id}: {err}"
) from err
async def async_clear_lock_user(self, **kwargs: Any) -> None:
"""Clear a lock user."""
try:
await clear_lock_user(
self.matter_client,
self._endpoint.node,
kwargs[ATTR_USER_INDEX],
)
except MatterError as err:
raise HomeAssistantError(
f"Failed to clear lock user on {self.entity_id}: {err}"
) from err
async def async_get_lock_info(self) -> GetLockInfoResult:
"""Get lock capabilities and configuration info."""
try:
return await get_lock_info(
self.matter_client,
self._endpoint.node,
)
except MatterError as err:
raise HomeAssistantError(
f"Failed to get lock info for {self.entity_id}: {err}"
) from err
async def async_get_lock_users(self) -> GetLockUsersResult:
"""Get all users from the lock."""
try:
return await get_lock_users(
self.matter_client,
self._endpoint.node,
)
except MatterError as err:
raise HomeAssistantError(
f"Failed to get lock users for {self.entity_id}: {err}"
) from err
async def async_set_lock_credential(self, **kwargs: Any) -> SetLockCredentialResult:
"""Set a credential on the lock."""
try:
return await set_lock_credential(
self.matter_client,
self._endpoint.node,
credential_type=kwargs[ATTR_CREDENTIAL_TYPE],
credential_data=kwargs[ATTR_CREDENTIAL_DATA],
credential_index=kwargs.get(ATTR_CREDENTIAL_INDEX),
user_index=kwargs.get(ATTR_USER_INDEX),
user_status=kwargs.get(ATTR_USER_STATUS),
user_type=kwargs.get(ATTR_USER_TYPE),
)
except MatterError as err:
raise HomeAssistantError(
f"Failed to set lock credential on {self.entity_id}: {err}"
) from err
async def async_clear_lock_credential(self, **kwargs: Any) -> None:
"""Clear a credential from the lock."""
try:
await clear_lock_credential(
self.matter_client,
self._endpoint.node,
credential_type=kwargs[ATTR_CREDENTIAL_TYPE],
credential_index=kwargs[ATTR_CREDENTIAL_INDEX],
)
except MatterError as err:
raise HomeAssistantError(
f"Failed to clear lock credential on {self.entity_id}: {err}"
) from err
async def async_get_lock_credential_status(
self, **kwargs: Any
) -> GetLockCredentialStatusResult:
"""Get the status of a credential slot on the lock."""
try:
return await get_lock_credential_status(
self.matter_client,
self._endpoint.node,
credential_type=kwargs[ATTR_CREDENTIAL_TYPE],
credential_index=kwargs[ATTR_CREDENTIAL_INDEX],
)
except MatterError as err:
raise HomeAssistantError(
f"Failed to get credential status for {self.entity_id}: {err}"
) from err
DISCOVERY_SCHEMAS = [
MatterDiscoverySchema(

View File

@@ -1,897 +0,0 @@
"""Lock-specific helpers for the Matter integration.
Provides DoorLock cluster endpoint resolution, feature detection, and
business logic for lock user/credential management.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Any, TypedDict
from chip.clusters import Objects as clusters
from chip.clusters.Types import NullValue
from homeassistant.exceptions import HomeAssistantError, ServiceValidationError
from .const import (
CLEAR_ALL_INDEX,
CRED_TYPE_FACE,
CRED_TYPE_FINGER_VEIN,
CRED_TYPE_FINGERPRINT,
CRED_TYPE_PIN,
CRED_TYPE_RFID,
CREDENTIAL_RULE_MAP,
CREDENTIAL_RULE_REVERSE_MAP,
CREDENTIAL_TYPE_MAP,
CREDENTIAL_TYPE_REVERSE_MAP,
LOCK_TIMED_REQUEST_TIMEOUT_MS,
USER_STATUS_MAP,
USER_STATUS_REVERSE_MAP,
USER_TYPE_MAP,
USER_TYPE_REVERSE_MAP,
)
# Error translation keys (used in ServiceValidationError/HomeAssistantError)
ERR_CREDENTIAL_TYPE_NOT_SUPPORTED = "credential_type_not_supported"
ERR_INVALID_CREDENTIAL_DATA = "invalid_credential_data"
# SetCredential response status mapping (Matter DlStatus)
_DlStatus = clusters.DoorLock.Enums.DlStatus
SET_CREDENTIAL_STATUS_MAP: dict[int, str] = {
_DlStatus.kSuccess: "success",
_DlStatus.kFailure: "failure",
_DlStatus.kDuplicate: "duplicate",
_DlStatus.kOccupied: "occupied",
}
if TYPE_CHECKING:
from matter_server.client import MatterClient
from matter_server.client.models.node import MatterEndpoint, MatterNode
# DoorLock Feature bitmap from Matter SDK
DoorLockFeature = clusters.DoorLock.Bitmaps.Feature
# --- TypedDicts for service action responses ---
class LockUserCredentialData(TypedDict):
"""Credential data within a user response."""
type: str
index: int | None
class LockUserData(TypedDict):
"""User data returned from lock queries."""
user_index: int | None
user_name: str | None
user_unique_id: int | None
user_status: str
user_type: str
credential_rule: str
credentials: list[LockUserCredentialData]
next_user_index: int | None
class SetLockUserResult(TypedDict):
"""Result of set_lock_user service action."""
user_index: int
class GetLockUsersResult(TypedDict):
"""Result of get_lock_users service action."""
max_users: int
users: list[LockUserData]
class GetLockInfoResult(TypedDict):
"""Result of get_lock_info service action."""
supports_user_management: bool
supported_credential_types: list[str]
max_users: int | None
max_pin_users: int | None
max_rfid_users: int | None
max_credentials_per_user: int | None
min_pin_length: int | None
max_pin_length: int | None
min_rfid_length: int | None
max_rfid_length: int | None
class SetLockCredentialResult(TypedDict):
"""Result of set_lock_credential service action."""
credential_index: int
user_index: int | None
next_credential_index: int | None
class GetLockCredentialStatusResult(TypedDict):
"""Result of get_lock_credential_status service action."""
credential_exists: bool
user_index: int | None
next_credential_index: int | None
def _get_lock_endpoint_from_node(node: MatterNode) -> MatterEndpoint | None:
"""Get the DoorLock endpoint from a node.
Returns the first endpoint that has the DoorLock cluster, or None if not found.
"""
for endpoint in node.endpoints.values():
if endpoint.has_cluster(clusters.DoorLock):
return endpoint
return None
def _get_feature_map(endpoint: MatterEndpoint) -> int | None:
"""Read the DoorLock FeatureMap attribute from an endpoint."""
value: int | None = endpoint.get_attribute_value(
None, clusters.DoorLock.Attributes.FeatureMap
)
return value
def _lock_supports_usr_feature(endpoint: MatterEndpoint) -> bool:
"""Check if lock endpoint supports USR (User) feature.
The USR feature indicates the lock supports user and credential management
commands like SetUser, GetUser, SetCredential, etc.
"""
feature_map = _get_feature_map(endpoint)
if feature_map is None:
return False
return bool(feature_map & DoorLockFeature.kUser)
# --- Pure utility functions ---
def _get_attr(obj: Any, attr: str) -> Any:
"""Get attribute from object or dict.
Matter SDK responses can be either dataclass objects or dicts depending on
the SDK version and serialization context. NullValue (a truthy,
non-iterable singleton) is normalized to None.
"""
if isinstance(obj, dict):
value = obj.get(attr)
else:
value = getattr(obj, attr, None)
# The Matter SDK uses NullValue for nullable fields instead of None.
if value is NullValue:
return None
return value
def _get_supported_credential_types(feature_map: int) -> list[str]:
"""Get list of supported credential types from feature map."""
types = []
if feature_map & DoorLockFeature.kPinCredential:
types.append(CRED_TYPE_PIN)
if feature_map & DoorLockFeature.kRfidCredential:
types.append(CRED_TYPE_RFID)
if feature_map & DoorLockFeature.kFingerCredentials:
types.append(CRED_TYPE_FINGERPRINT)
if feature_map & DoorLockFeature.kFaceCredentials:
types.append(CRED_TYPE_FACE)
return types
def _format_user_response(user_data: Any) -> LockUserData | None:
"""Format GetUser response to API response format.
Returns None if the user slot is empty (no userStatus).
"""
if user_data is None:
return None
user_status = _get_attr(user_data, "userStatus")
if user_status is None:
return None
creds = _get_attr(user_data, "credentials")
credentials: list[LockUserCredentialData] = [
LockUserCredentialData(
type=CREDENTIAL_TYPE_MAP.get(_get_attr(cred, "credentialType"), "unknown"),
index=_get_attr(cred, "credentialIndex"),
)
for cred in (creds or [])
]
return LockUserData(
user_index=_get_attr(user_data, "userIndex"),
user_name=_get_attr(user_data, "userName"),
user_unique_id=_get_attr(user_data, "userUniqueID"),
user_status=USER_STATUS_MAP.get(user_status, "unknown"),
user_type=USER_TYPE_MAP.get(_get_attr(user_data, "userType"), "unknown"),
credential_rule=CREDENTIAL_RULE_MAP.get(
_get_attr(user_data, "credentialRule"), "unknown"
),
credentials=credentials,
next_user_index=_get_attr(user_data, "nextUserIndex"),
)
# --- Credential management helpers ---
async def _clear_user_credentials(
matter_client: MatterClient,
node_id: int,
endpoint_id: int,
user_index: int,
) -> None:
"""Clear all credentials for a specific user.
Fetches the user to get credential list, then clears each credential.
"""
get_user_response = await matter_client.send_device_command(
node_id=node_id,
endpoint_id=endpoint_id,
command=clusters.DoorLock.Commands.GetUser(userIndex=user_index),
)
creds = _get_attr(get_user_response, "credentials")
if not creds:
return
for cred in creds:
cred_type = _get_attr(cred, "credentialType")
cred_index = _get_attr(cred, "credentialIndex")
await matter_client.send_device_command(
node_id=node_id,
endpoint_id=endpoint_id,
command=clusters.DoorLock.Commands.ClearCredential(
credential=clusters.DoorLock.Structs.CredentialStruct(
credentialType=cred_type,
credentialIndex=cred_index,
),
),
timed_request_timeout_ms=LOCK_TIMED_REQUEST_TIMEOUT_MS,
)
class LockEndpointNotFoundError(HomeAssistantError):
"""Lock endpoint not found on node."""
class UsrFeatureNotSupportedError(ServiceValidationError):
"""Lock does not support USR (user management) feature."""
class UserSlotEmptyError(ServiceValidationError):
"""User slot is empty."""
class NoAvailableUserSlotsError(ServiceValidationError):
"""No available user slots on the lock."""
class CredentialTypeNotSupportedError(ServiceValidationError):
"""Lock does not support the requested credential type."""
class CredentialDataInvalidError(ServiceValidationError):
"""Credential data fails validation."""
class SetCredentialFailedError(HomeAssistantError):
"""SetCredential command returned a non-success status."""
def _get_lock_endpoint_or_raise(node: MatterNode) -> MatterEndpoint:
"""Get the DoorLock endpoint from a node or raise an error."""
lock_endpoint = _get_lock_endpoint_from_node(node)
if lock_endpoint is None:
raise LockEndpointNotFoundError("No lock endpoint found on this device")
return lock_endpoint
def _ensure_usr_support(lock_endpoint: MatterEndpoint) -> None:
"""Ensure the lock endpoint supports USR (user management) feature.
Raises UsrFeatureNotSupportedError if the lock doesn't support user management.
"""
if not _lock_supports_usr_feature(lock_endpoint):
raise UsrFeatureNotSupportedError(
"Lock does not support user/credential management"
)
# --- High-level business logic functions ---
async def get_lock_info(
matter_client: MatterClient,
node: MatterNode,
) -> GetLockInfoResult:
"""Get lock capabilities and configuration info.
Returns a typed dict with lock capability information.
Raises HomeAssistantError if lock endpoint not found.
"""
lock_endpoint = _get_lock_endpoint_or_raise(node)
supports_usr = _lock_supports_usr_feature(lock_endpoint)
# Get feature map for credential type detection
feature_map = (
lock_endpoint.get_attribute_value(None, clusters.DoorLock.Attributes.FeatureMap)
or 0
)
result = GetLockInfoResult(
supports_user_management=supports_usr,
supported_credential_types=_get_supported_credential_types(feature_map),
max_users=None,
max_pin_users=None,
max_rfid_users=None,
max_credentials_per_user=None,
min_pin_length=None,
max_pin_length=None,
min_rfid_length=None,
max_rfid_length=None,
)
# Populate capacity info if USR feature is supported
if supports_usr:
result["max_users"] = lock_endpoint.get_attribute_value(
None, clusters.DoorLock.Attributes.NumberOfTotalUsersSupported
)
result["max_pin_users"] = lock_endpoint.get_attribute_value(
None, clusters.DoorLock.Attributes.NumberOfPINUsersSupported
)
result["max_rfid_users"] = lock_endpoint.get_attribute_value(
None, clusters.DoorLock.Attributes.NumberOfRFIDUsersSupported
)
result["max_credentials_per_user"] = lock_endpoint.get_attribute_value(
None, clusters.DoorLock.Attributes.NumberOfCredentialsSupportedPerUser
)
result["min_pin_length"] = lock_endpoint.get_attribute_value(
None, clusters.DoorLock.Attributes.MinPINCodeLength
)
result["max_pin_length"] = lock_endpoint.get_attribute_value(
None, clusters.DoorLock.Attributes.MaxPINCodeLength
)
result["min_rfid_length"] = lock_endpoint.get_attribute_value(
None, clusters.DoorLock.Attributes.MinRFIDCodeLength
)
result["max_rfid_length"] = lock_endpoint.get_attribute_value(
None, clusters.DoorLock.Attributes.MaxRFIDCodeLength
)
return result
async def set_lock_user(
matter_client: MatterClient,
node: MatterNode,
*,
user_index: int | None = None,
user_name: str | None = None,
user_unique_id: int | None = None,
user_status: str | None = None,
user_type: str | None = None,
credential_rule: str | None = None,
) -> SetLockUserResult:
"""Add or update a user on the lock.
When user_status, user_type, or credential_rule is None, defaults are used
for new users and existing values are preserved for modifications.
Returns typed dict with user_index on success.
Raises HomeAssistantError on failure.
"""
lock_endpoint = _get_lock_endpoint_or_raise(node)
_ensure_usr_support(lock_endpoint)
if user_index is None:
# Adding new user - find first available slot
max_users = (
lock_endpoint.get_attribute_value(
None, clusters.DoorLock.Attributes.NumberOfTotalUsersSupported
)
or 0
)
for idx in range(1, max_users + 1):
get_user_response = await matter_client.send_device_command(
node_id=node.node_id,
endpoint_id=lock_endpoint.endpoint_id,
command=clusters.DoorLock.Commands.GetUser(userIndex=idx),
)
if _get_attr(get_user_response, "userStatus") is None:
user_index = idx
break
if user_index is None:
raise NoAvailableUserSlotsError("No available user slots on the lock")
user_status_enum = (
USER_STATUS_REVERSE_MAP.get(
user_status,
clusters.DoorLock.Enums.UserStatusEnum.kOccupiedEnabled,
)
if user_status is not None
else clusters.DoorLock.Enums.UserStatusEnum.kOccupiedEnabled
)
await matter_client.send_device_command(
node_id=node.node_id,
endpoint_id=lock_endpoint.endpoint_id,
command=clusters.DoorLock.Commands.SetUser(
operationType=clusters.DoorLock.Enums.DataOperationTypeEnum.kAdd,
userIndex=user_index,
userName=user_name,
userUniqueID=user_unique_id,
userStatus=user_status_enum,
userType=USER_TYPE_REVERSE_MAP.get(
user_type,
clusters.DoorLock.Enums.UserTypeEnum.kUnrestrictedUser,
)
if user_type is not None
else clusters.DoorLock.Enums.UserTypeEnum.kUnrestrictedUser,
credentialRule=CREDENTIAL_RULE_REVERSE_MAP.get(
credential_rule,
clusters.DoorLock.Enums.CredentialRuleEnum.kSingle,
)
if credential_rule is not None
else clusters.DoorLock.Enums.CredentialRuleEnum.kSingle,
),
timed_request_timeout_ms=LOCK_TIMED_REQUEST_TIMEOUT_MS,
)
else:
# Updating existing user - preserve existing values when not specified
get_user_response = await matter_client.send_device_command(
node_id=node.node_id,
endpoint_id=lock_endpoint.endpoint_id,
command=clusters.DoorLock.Commands.GetUser(userIndex=user_index),
)
if _get_attr(get_user_response, "userStatus") is None:
raise UserSlotEmptyError(f"User slot {user_index} is empty")
resolved_user_name = (
user_name
if user_name is not None
else _get_attr(get_user_response, "userName")
)
resolved_unique_id = (
user_unique_id
if user_unique_id is not None
else _get_attr(get_user_response, "userUniqueID")
)
resolved_status = (
USER_STATUS_REVERSE_MAP[user_status]
if user_status is not None
else _get_attr(get_user_response, "userStatus")
)
resolved_type = (
USER_TYPE_REVERSE_MAP[user_type]
if user_type is not None
else _get_attr(get_user_response, "userType")
)
resolved_rule = (
CREDENTIAL_RULE_REVERSE_MAP[credential_rule]
if credential_rule is not None
else _get_attr(get_user_response, "credentialRule")
)
await matter_client.send_device_command(
node_id=node.node_id,
endpoint_id=lock_endpoint.endpoint_id,
command=clusters.DoorLock.Commands.SetUser(
operationType=clusters.DoorLock.Enums.DataOperationTypeEnum.kModify,
userIndex=user_index,
userName=resolved_user_name,
userUniqueID=resolved_unique_id,
userStatus=resolved_status,
userType=resolved_type,
credentialRule=resolved_rule,
),
timed_request_timeout_ms=LOCK_TIMED_REQUEST_TIMEOUT_MS,
)
return SetLockUserResult(user_index=user_index)
async def get_lock_users(
matter_client: MatterClient,
node: MatterNode,
) -> GetLockUsersResult:
"""Get all users from the lock.
Returns typed dict with users list and max_users capacity.
Raises HomeAssistantError on failure.
"""
lock_endpoint = _get_lock_endpoint_or_raise(node)
_ensure_usr_support(lock_endpoint)
max_users = (
lock_endpoint.get_attribute_value(
None, clusters.DoorLock.Attributes.NumberOfTotalUsersSupported
)
or 0
)
users: list[LockUserData] = []
current_index = 1
# Iterate through users using next_user_index for efficiency
while current_index is not None and current_index <= max_users:
get_user_response = await matter_client.send_device_command(
node_id=node.node_id,
endpoint_id=lock_endpoint.endpoint_id,
command=clusters.DoorLock.Commands.GetUser(
userIndex=current_index,
),
)
user_data = _format_user_response(get_user_response)
if user_data is not None:
users.append(user_data)
# Move to next user index
next_index = _get_attr(get_user_response, "nextUserIndex")
if next_index is None or next_index <= current_index:
break
current_index = next_index
return GetLockUsersResult(
max_users=max_users,
users=users,
)
async def clear_lock_user(
matter_client: MatterClient,
node: MatterNode,
user_index: int,
) -> None:
"""Clear a user from the lock, cleaning up credentials first.
Use index 0xFFFE (CLEAR_ALL_INDEX) to clear all users.
Raises HomeAssistantError on failure.
"""
lock_endpoint = _get_lock_endpoint_or_raise(node)
_ensure_usr_support(lock_endpoint)
if user_index == CLEAR_ALL_INDEX:
# Clear all: clear all credentials first, then all users
await matter_client.send_device_command(
node_id=node.node_id,
endpoint_id=lock_endpoint.endpoint_id,
command=clusters.DoorLock.Commands.ClearCredential(
credential=None,
),
timed_request_timeout_ms=LOCK_TIMED_REQUEST_TIMEOUT_MS,
)
else:
# Clear credentials for this specific user before deleting them
await _clear_user_credentials(
matter_client,
node.node_id,
lock_endpoint.endpoint_id,
user_index,
)
await matter_client.send_device_command(
node_id=node.node_id,
endpoint_id=lock_endpoint.endpoint_id,
command=clusters.DoorLock.Commands.ClearUser(
userIndex=user_index,
),
timed_request_timeout_ms=LOCK_TIMED_REQUEST_TIMEOUT_MS,
)
# --- Credential validation helpers ---
# Map credential type strings to the feature bit that must be set
_CREDENTIAL_TYPE_FEATURE_MAP: dict[str, int] = {
CRED_TYPE_PIN: DoorLockFeature.kPinCredential,
CRED_TYPE_RFID: DoorLockFeature.kRfidCredential,
CRED_TYPE_FINGERPRINT: DoorLockFeature.kFingerCredentials,
CRED_TYPE_FINGER_VEIN: DoorLockFeature.kFingerCredentials,
CRED_TYPE_FACE: DoorLockFeature.kFaceCredentials,
}
# Map credential type strings to the capacity attribute for slot iteration.
# Biometric types have no dedicated capacity attribute; fall back to total users.
_CREDENTIAL_TYPE_CAPACITY_ATTR = {
CRED_TYPE_PIN: clusters.DoorLock.Attributes.NumberOfPINUsersSupported,
CRED_TYPE_RFID: clusters.DoorLock.Attributes.NumberOfRFIDUsersSupported,
}
def _validate_credential_type_support(
lock_endpoint: MatterEndpoint, credential_type: str
) -> None:
"""Validate the lock supports the requested credential type.
Raises CredentialTypeNotSupportedError if not supported.
"""
required_bit = _CREDENTIAL_TYPE_FEATURE_MAP.get(credential_type)
if required_bit is None:
raise CredentialTypeNotSupportedError(
translation_domain="matter",
translation_key=ERR_CREDENTIAL_TYPE_NOT_SUPPORTED,
translation_placeholders={"credential_type": credential_type},
)
feature_map = _get_feature_map(lock_endpoint) or 0
if not (feature_map & required_bit):
raise CredentialTypeNotSupportedError(
translation_domain="matter",
translation_key=ERR_CREDENTIAL_TYPE_NOT_SUPPORTED,
translation_placeholders={"credential_type": credential_type},
)
def _validate_credential_data(
lock_endpoint: MatterEndpoint, credential_type: str, credential_data: str
) -> None:
"""Validate credential data against lock constraints.
For PIN: checks digits-only and length against Min/MaxPINCodeLength.
For RFID: checks valid hex and byte length against Min/MaxRFIDCodeLength.
Raises CredentialDataInvalidError on failure.
"""
if credential_type == CRED_TYPE_PIN:
if not credential_data.isdigit():
raise CredentialDataInvalidError(
translation_domain="matter",
translation_key=ERR_INVALID_CREDENTIAL_DATA,
translation_placeholders={"reason": "PIN must contain only digits"},
)
min_len = (
lock_endpoint.get_attribute_value(
None, clusters.DoorLock.Attributes.MinPINCodeLength
)
or 0
)
max_len = (
lock_endpoint.get_attribute_value(
None, clusters.DoorLock.Attributes.MaxPINCodeLength
)
or 255
)
if not min_len <= len(credential_data) <= max_len:
raise CredentialDataInvalidError(
translation_domain="matter",
translation_key=ERR_INVALID_CREDENTIAL_DATA,
translation_placeholders={
"reason": (f"PIN length must be between {min_len} and {max_len}")
},
)
elif credential_type == CRED_TYPE_RFID:
try:
rfid_bytes = bytes.fromhex(credential_data)
except ValueError as err:
raise CredentialDataInvalidError(
translation_domain="matter",
translation_key=ERR_INVALID_CREDENTIAL_DATA,
translation_placeholders={
"reason": "RFID data must be valid hexadecimal"
},
) from err
min_len = (
lock_endpoint.get_attribute_value(
None, clusters.DoorLock.Attributes.MinRFIDCodeLength
)
or 0
)
max_len = (
lock_endpoint.get_attribute_value(
None, clusters.DoorLock.Attributes.MaxRFIDCodeLength
)
or 255
)
if not min_len <= len(rfid_bytes) <= max_len:
raise CredentialDataInvalidError(
translation_domain="matter",
translation_key=ERR_INVALID_CREDENTIAL_DATA,
translation_placeholders={
"reason": (
f"RFID data length must be between"
f" {min_len} and {max_len} bytes"
)
},
)
def _credential_data_to_bytes(credential_type: str, credential_data: str) -> bytes:
"""Convert credential data string to bytes for the Matter command."""
if credential_type == CRED_TYPE_RFID:
return bytes.fromhex(credential_data)
# PIN and other types: encode as UTF-8
return credential_data.encode()
# --- Credential business logic functions ---
async def set_lock_credential(
matter_client: MatterClient,
node: MatterNode,
*,
credential_type: str,
credential_data: str,
credential_index: int | None = None,
user_index: int | None = None,
user_status: str | None = None,
user_type: str | None = None,
) -> SetLockCredentialResult:
"""Add or modify a credential on the lock.
Returns typed dict with credential_index, user_index, and next_credential_index.
Raises ServiceValidationError for validation failures.
Raises HomeAssistantError for device communication failures.
"""
lock_endpoint = _get_lock_endpoint_or_raise(node)
_ensure_usr_support(lock_endpoint)
_validate_credential_type_support(lock_endpoint, credential_type)
_validate_credential_data(lock_endpoint, credential_type, credential_data)
cred_type_int = CREDENTIAL_TYPE_REVERSE_MAP[credential_type]
cred_data_bytes = _credential_data_to_bytes(credential_type, credential_data)
# Determine operation type and credential index
operation_type = clusters.DoorLock.Enums.DataOperationTypeEnum.kAdd
if credential_index is None:
# Auto-find first available credential slot.
# Use the credential-type-specific capacity as the upper bound.
max_creds_attr = _CREDENTIAL_TYPE_CAPACITY_ATTR.get(
credential_type,
clusters.DoorLock.Attributes.NumberOfTotalUsersSupported,
)
max_creds_raw = lock_endpoint.get_attribute_value(None, max_creds_attr)
max_creds = (
max_creds_raw if isinstance(max_creds_raw, int) and max_creds_raw > 0 else 5
)
for idx in range(1, max_creds + 1):
status_response = await matter_client.send_device_command(
node_id=node.node_id,
endpoint_id=lock_endpoint.endpoint_id,
command=clusters.DoorLock.Commands.GetCredentialStatus(
credential=clusters.DoorLock.Structs.CredentialStruct(
credentialType=cred_type_int,
credentialIndex=idx,
),
),
)
if not _get_attr(status_response, "credentialExists"):
credential_index = idx
break
if credential_index is None:
raise NoAvailableUserSlotsError("No available credential slots on the lock")
else:
# Check if slot is occupied to determine Add vs Modify
status_response = await matter_client.send_device_command(
node_id=node.node_id,
endpoint_id=lock_endpoint.endpoint_id,
command=clusters.DoorLock.Commands.GetCredentialStatus(
credential=clusters.DoorLock.Structs.CredentialStruct(
credentialType=cred_type_int,
credentialIndex=credential_index,
),
),
)
if _get_attr(status_response, "credentialExists"):
operation_type = clusters.DoorLock.Enums.DataOperationTypeEnum.kModify
# Resolve optional user_status and user_type enums
resolved_user_status = (
USER_STATUS_REVERSE_MAP.get(user_status) if user_status is not None else None
)
resolved_user_type = (
USER_TYPE_REVERSE_MAP.get(user_type) if user_type is not None else None
)
set_cred_response = await matter_client.send_device_command(
node_id=node.node_id,
endpoint_id=lock_endpoint.endpoint_id,
command=clusters.DoorLock.Commands.SetCredential(
operationType=operation_type,
credential=clusters.DoorLock.Structs.CredentialStruct(
credentialType=cred_type_int,
credentialIndex=credential_index,
),
credentialData=cred_data_bytes,
userIndex=user_index,
userStatus=resolved_user_status,
userType=resolved_user_type,
),
timed_request_timeout_ms=LOCK_TIMED_REQUEST_TIMEOUT_MS,
)
status_code = _get_attr(set_cred_response, "status")
status_str = SET_CREDENTIAL_STATUS_MAP.get(status_code, f"unknown({status_code})")
if status_str != "success":
raise SetCredentialFailedError(
translation_domain="matter",
translation_key="set_credential_failed",
translation_placeholders={"status": status_str},
)
return SetLockCredentialResult(
credential_index=credential_index,
user_index=_get_attr(set_cred_response, "userIndex"),
next_credential_index=_get_attr(set_cred_response, "nextCredentialIndex"),
)
async def clear_lock_credential(
matter_client: MatterClient,
node: MatterNode,
*,
credential_type: str,
credential_index: int,
) -> None:
"""Clear a credential from the lock.
Raises HomeAssistantError on failure.
"""
lock_endpoint = _get_lock_endpoint_or_raise(node)
_ensure_usr_support(lock_endpoint)
cred_type_int = CREDENTIAL_TYPE_REVERSE_MAP[credential_type]
await matter_client.send_device_command(
node_id=node.node_id,
endpoint_id=lock_endpoint.endpoint_id,
command=clusters.DoorLock.Commands.ClearCredential(
credential=clusters.DoorLock.Structs.CredentialStruct(
credentialType=cred_type_int,
credentialIndex=credential_index,
),
),
timed_request_timeout_ms=LOCK_TIMED_REQUEST_TIMEOUT_MS,
)
async def get_lock_credential_status(
matter_client: MatterClient,
node: MatterNode,
*,
credential_type: str,
credential_index: int,
) -> GetLockCredentialStatusResult:
"""Get the status of a credential slot on the lock.
Returns typed dict with credential_exists, user_index, next_credential_index.
Raises HomeAssistantError on failure.
"""
lock_endpoint = _get_lock_endpoint_or_raise(node)
_ensure_usr_support(lock_endpoint)
cred_type_int = CREDENTIAL_TYPE_REVERSE_MAP[credential_type]
response = await matter_client.send_device_command(
node_id=node.node_id,
endpoint_id=lock_endpoint.endpoint_id,
command=clusters.DoorLock.Commands.GetCredentialStatus(
credential=clusters.DoorLock.Structs.CredentialStruct(
credentialType=cred_type_int,
credentialIndex=credential_index,
),
),
)
return GetLockCredentialStatusResult(
credential_exists=bool(_get_attr(response, "credentialExists")),
user_index=_get_attr(response, "userIndex"),
next_credential_index=_get_attr(response, "nextCredentialIndex"),
)

View File

@@ -4,27 +4,11 @@ from __future__ import annotations
import voluptuous as vol
from homeassistant.components.lock import DOMAIN as LOCK_DOMAIN
from homeassistant.components.water_heater import DOMAIN as WATER_HEATER_DOMAIN
from homeassistant.core import HomeAssistant, SupportsResponse, callback
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv, service
from .const import (
ATTR_CREDENTIAL_DATA,
ATTR_CREDENTIAL_INDEX,
ATTR_CREDENTIAL_RULE,
ATTR_CREDENTIAL_TYPE,
ATTR_USER_INDEX,
ATTR_USER_NAME,
ATTR_USER_STATUS,
ATTR_USER_TYPE,
CLEAR_ALL_INDEX,
CREDENTIAL_RULE_REVERSE_MAP,
CREDENTIAL_TYPE_REVERSE_MAP,
DOMAIN,
SERVICE_CREDENTIAL_TYPES,
USER_TYPE_REVERSE_MAP,
)
from .const import DOMAIN
ATTR_DURATION = "duration"
ATTR_EMERGENCY_BOOST = "emergency_boost"
@@ -52,108 +36,3 @@ def async_setup_services(hass: HomeAssistant) -> None:
},
func="async_set_boost",
)
# Lock services - Full user CRUD
service.async_register_platform_entity_service(
hass,
DOMAIN,
"set_lock_user",
entity_domain=LOCK_DOMAIN,
schema={
vol.Optional(ATTR_USER_INDEX): vol.All(vol.Coerce(int), vol.Range(min=1)),
vol.Optional(ATTR_USER_NAME): vol.Any(str, None),
vol.Optional(ATTR_USER_TYPE): vol.In(USER_TYPE_REVERSE_MAP.keys()),
vol.Optional(ATTR_CREDENTIAL_RULE): vol.In(
CREDENTIAL_RULE_REVERSE_MAP.keys()
),
},
func="async_set_lock_user",
)
service.async_register_platform_entity_service(
hass,
DOMAIN,
"clear_lock_user",
entity_domain=LOCK_DOMAIN,
schema={
vol.Required(ATTR_USER_INDEX): vol.All(
vol.Coerce(int),
vol.Any(vol.Range(min=1), CLEAR_ALL_INDEX),
),
},
func="async_clear_lock_user",
)
# Lock services - Query operations
service.async_register_platform_entity_service(
hass,
DOMAIN,
"get_lock_info",
entity_domain=LOCK_DOMAIN,
schema={},
func="async_get_lock_info",
supports_response=SupportsResponse.ONLY,
)
service.async_register_platform_entity_service(
hass,
DOMAIN,
"get_lock_users",
entity_domain=LOCK_DOMAIN,
schema={},
func="async_get_lock_users",
supports_response=SupportsResponse.ONLY,
)
# Lock services - Credential management
service.async_register_platform_entity_service(
hass,
DOMAIN,
"set_lock_credential",
entity_domain=LOCK_DOMAIN,
schema={
vol.Required(ATTR_CREDENTIAL_TYPE): vol.In(SERVICE_CREDENTIAL_TYPES),
vol.Required(ATTR_CREDENTIAL_DATA): str,
vol.Optional(ATTR_CREDENTIAL_INDEX): vol.All(
vol.Coerce(int), vol.Range(min=0)
),
vol.Optional(ATTR_USER_INDEX): vol.All(vol.Coerce(int), vol.Range(min=1)),
vol.Optional(ATTR_USER_STATUS): vol.In(
["occupied_enabled", "occupied_disabled"]
),
vol.Optional(ATTR_USER_TYPE): vol.In(USER_TYPE_REVERSE_MAP.keys()),
},
func="async_set_lock_credential",
supports_response=SupportsResponse.ONLY,
)
service.async_register_platform_entity_service(
hass,
DOMAIN,
"clear_lock_credential",
entity_domain=LOCK_DOMAIN,
schema={
vol.Required(ATTR_CREDENTIAL_TYPE): vol.In(SERVICE_CREDENTIAL_TYPES),
vol.Required(ATTR_CREDENTIAL_INDEX): vol.All(
vol.Coerce(int), vol.Range(min=0)
),
},
func="async_clear_lock_credential",
)
service.async_register_platform_entity_service(
hass,
DOMAIN,
"get_lock_credential_status",
entity_domain=LOCK_DOMAIN,
schema={
vol.Required(ATTR_CREDENTIAL_TYPE): vol.In(
CREDENTIAL_TYPE_REVERSE_MAP.keys()
),
vol.Required(ATTR_CREDENTIAL_INDEX): vol.All(
vol.Coerce(int), vol.Range(min=0)
),
},
func="async_get_lock_credential_status",
supports_response=SupportsResponse.ONLY,
)

View File

@@ -1,177 +1,3 @@
clear_lock_credential:
target:
entity:
domain: lock
integration: matter
fields:
credential_type:
selector:
select:
options:
- pin
- rfid
- fingerprint
- finger_vein
- face
required: true
credential_index:
selector:
number:
min: 0
max: 65534
step: 1
mode: box
required: true
clear_lock_user:
target:
entity:
domain: lock
integration: matter
fields:
user_index:
selector:
number:
min: 1
max: 65534
step: 1
mode: box
required: true
get_lock_credential_status:
target:
entity:
domain: lock
integration: matter
fields:
credential_type:
selector:
select:
options:
- programming_pin
- pin
- rfid
- fingerprint
- finger_vein
- face
- aliro_credential_issuer_key
- aliro_evictable_endpoint_key
- aliro_non_evictable_endpoint_key
required: true
credential_index:
selector:
number:
min: 0
max: 65534
step: 1
mode: box
required: true
get_lock_info:
target:
entity:
domain: lock
integration: matter
get_lock_users:
target:
entity:
domain: lock
integration: matter
set_lock_credential:
target:
entity:
domain: lock
integration: matter
fields:
credential_type:
selector:
select:
options:
- pin
- rfid
- fingerprint
- finger_vein
- face
required: true
credential_data:
selector:
text:
required: true
credential_index:
selector:
number:
min: 0
max: 65534
step: 1
mode: box
user_index:
selector:
number:
min: 1
max: 65534
step: 1
mode: box
user_status:
selector:
select:
options:
- occupied_enabled
- occupied_disabled
user_type:
selector:
select:
options:
- unrestricted_user
- year_day_schedule_user
- week_day_schedule_user
- programming_user
- non_access_user
- forced_user
- disposable_user
- expiring_user
- schedule_restricted_user
- remote_only_user
set_lock_user:
target:
entity:
domain: lock
integration: matter
fields:
user_index:
selector:
number:
min: 1
max: 255
step: 1
mode: box
user_name:
selector:
text:
user_type:
selector:
select:
options:
- unrestricted_user
- year_day_schedule_user
- week_day_schedule_user
- programming_user
- non_access_user
- forced_user
- disposable_user
- expiring_user
- schedule_restricted_user
- remote_only_user
credential_rule:
selector:
select:
options:
- single
- dual
- tri
water_heater_boost:
target:
entity:

View File

@@ -619,17 +619,6 @@
}
}
},
"exceptions": {
"credential_type_not_supported": {
"message": "The lock does not support credential type `{credential_type}`."
},
"invalid_credential_data": {
"message": "Invalid credential data: {reason}."
},
"set_credential_failed": {
"message": "Failed to set credential: lock returned status `{status}`."
}
},
"issues": {
"server_version_version_too_new": {
"description": "The version of the Matter Server you are currently running is too new for this version of Home Assistant. Please update Home Assistant or downgrade the Matter Server to an older version to fix this issue.",
@@ -641,52 +630,6 @@
}
},
"services": {
"clear_lock_credential": {
"description": "Removes a credential from a lock.",
"fields": {
"credential_index": {
"description": "The credential slot index to clear.",
"name": "Credential index"
},
"credential_type": {
"description": "The type of credential to clear.",
"name": "Credential type"
}
},
"name": "Clear lock credential"
},
"clear_lock_user": {
"description": "Deletes a lock user and all associated credentials. Use index 65534 to clear all users.",
"fields": {
"user_index": {
"description": "The user slot index (1-based) to clear, or 65534 to clear all.",
"name": "User index"
}
},
"name": "Clear lock user"
},
"get_lock_credential_status": {
"description": "Returns the status of a credential slot on a lock.",
"fields": {
"credential_index": {
"description": "The credential slot index to query.",
"name": "Credential index"
},
"credential_type": {
"description": "The type of credential to query.",
"name": "Credential type"
}
},
"name": "Get lock credential status"
},
"get_lock_info": {
"description": "Returns lock capabilities including supported credential types, user capacity, and PIN length constraints.",
"name": "Get lock info"
},
"get_lock_users": {
"description": "Returns all users configured on a lock with their credentials.",
"name": "Get lock users"
},
"open_commissioning_window": {
"description": "Allows adding one of your devices to another Matter network by opening the commissioning window for this Matter device for 60 seconds.",
"fields": {
@@ -697,58 +640,6 @@
},
"name": "Open commissioning window"
},
"set_lock_credential": {
"description": "Adds or updates a credential on a lock.",
"fields": {
"credential_data": {
"description": "The credential data. For PIN: digits only. For RFID: hexadecimal string.",
"name": "Credential data"
},
"credential_index": {
"description": "The credential slot index. Leave empty to auto-find an available slot.",
"name": "Credential index"
},
"credential_type": {
"description": "The type of credential (e.g., pin, rfid, fingerprint).",
"name": "Credential type"
},
"user_index": {
"description": "The user index to associate the credential with. Leave empty for automatic assignment.",
"name": "User index"
},
"user_status": {
"description": "The user status to set when creating a new user for this credential.",
"name": "User status"
},
"user_type": {
"description": "The user type to set when creating a new user for this credential.",
"name": "User type"
}
},
"name": "Set lock credential"
},
"set_lock_user": {
"description": "Creates or updates a lock user.",
"fields": {
"credential_rule": {
"description": "The credential rule for the user.",
"name": "Credential rule"
},
"user_index": {
"description": "The user slot index (1-based). Leave empty to auto-find an available slot.",
"name": "User index"
},
"user_name": {
"description": "The name for the user.",
"name": "User name"
},
"user_type": {
"description": "The type of user to create.",
"name": "User type"
}
},
"name": "Set lock user"
},
"water_heater_boost": {
"description": "Enables water heater boost for a specific duration.",
"fields": {

View File

@@ -168,9 +168,8 @@ class MatterVacuum(MatterEntity, StateVacuumEntity):
segments: dict[str, Segment] = {}
for area in supported_areas:
area_name = None
location_info = area.areaInfo.locationInfo
if location_info not in (None, clusters.NullValue):
area_name = location_info.locationName
if area.areaInfo and area.areaInfo.locationInfo:
area_name = area.areaInfo.locationInfo.locationName
if area_name:
segment_id = str(area.areaID)

View File

@@ -3,17 +3,19 @@
from __future__ import annotations
from homeassistant.components import bluetooth
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady
from .coordinator import MedcomBleConfigEntry, MedcomBleUpdateCoordinator
from .const import DOMAIN
from .coordinator import MedcomBleUpdateCoordinator
# Supported platforms
PLATFORMS: list[Platform] = [Platform.SENSOR]
async def async_setup_entry(hass: HomeAssistant, entry: MedcomBleConfigEntry) -> bool:
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Medcom BLE radiation monitor from a config entry."""
address = entry.unique_id
@@ -29,13 +31,16 @@ async def async_setup_entry(hass: HomeAssistant, entry: MedcomBleConfigEntry) ->
await coordinator.async_config_entry_first_refresh()
entry.runtime_data = coordinator
hass.data.setdefault(DOMAIN, {})[entry.entry_id] = coordinator
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
return True
async def async_unload_entry(hass: HomeAssistant, entry: MedcomBleConfigEntry) -> bool:
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS):
hass.data[DOMAIN].pop(entry.entry_id)
return unload_ok

View File

@@ -18,17 +18,13 @@ from .const import DEFAULT_SCAN_INTERVAL, DOMAIN
_LOGGER = logging.getLogger(__name__)
type MedcomBleConfigEntry = ConfigEntry[MedcomBleUpdateCoordinator]
class MedcomBleUpdateCoordinator(DataUpdateCoordinator[MedcomBleDevice]):
"""Coordinator for Medcom BLE radiation monitor data."""
config_entry: MedcomBleConfigEntry
config_entry: ConfigEntry
def __init__(
self, hass: HomeAssistant, entry: MedcomBleConfigEntry, address: str
) -> None:
def __init__(self, hass: HomeAssistant, entry: ConfigEntry, address: str) -> None:
"""Initialize the coordinator."""
super().__init__(
hass,

View File

@@ -4,6 +4,7 @@ from __future__ import annotations
import logging
from homeassistant import config_entries
from homeassistant.components.sensor import (
SensorEntity,
SensorEntityDescription,
@@ -14,8 +15,8 @@ from homeassistant.helpers.device_registry import CONNECTION_BLUETOOTH, DeviceIn
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import UNIT_CPM
from .coordinator import MedcomBleConfigEntry, MedcomBleUpdateCoordinator
from .const import DOMAIN, UNIT_CPM
from .coordinator import MedcomBleUpdateCoordinator
_LOGGER = logging.getLogger(__name__)
@@ -31,12 +32,12 @@ SENSORS_MAPPING_TEMPLATE: dict[str, SensorEntityDescription] = {
async def async_setup_entry(
hass: HomeAssistant,
entry: MedcomBleConfigEntry,
entry: config_entries.ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up Medcom BLE radiation monitor sensors."""
coordinator = entry.runtime_data
coordinator: MedcomBleUpdateCoordinator = hass.data[DOMAIN][entry.entry_id]
entities = []
_LOGGER.debug("got sensors: %s", coordinator.data.sensors)

View File

@@ -1,27 +1,25 @@
"""Support for Meteoclimatic weather data."""
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from .const import PLATFORMS
from .coordinator import MeteoclimaticConfigEntry, MeteoclimaticUpdateCoordinator
from .const import DOMAIN, PLATFORMS
from .coordinator import MeteoclimaticUpdateCoordinator
async def async_setup_entry(
hass: HomeAssistant, entry: MeteoclimaticConfigEntry
) -> bool:
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up a Meteoclimatic entry."""
coordinator = MeteoclimaticUpdateCoordinator(hass, entry)
await coordinator.async_config_entry_first_refresh()
entry.runtime_data = coordinator
hass.data.setdefault(DOMAIN, {})
hass.data[DOMAIN][entry.entry_id] = coordinator
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
return True
async def async_unload_entry(
hass: HomeAssistant, entry: MeteoclimaticConfigEntry
) -> bool:
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)

View File

@@ -14,15 +14,13 @@ from .const import CONF_STATION_CODE, SCAN_INTERVAL
_LOGGER = logging.getLogger(__name__)
type MeteoclimaticConfigEntry = ConfigEntry[MeteoclimaticUpdateCoordinator]
class MeteoclimaticUpdateCoordinator(DataUpdateCoordinator[dict[str, Any]]):
"""Coordinator for Meteoclimatic weather data."""
config_entry: MeteoclimaticConfigEntry
config_entry: ConfigEntry
def __init__(self, hass: HomeAssistant, entry: MeteoclimaticConfigEntry) -> None:
def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Initialize the coordinator."""
self._station_code = entry.data[CONF_STATION_CODE]
super().__init__(

View File

@@ -6,6 +6,7 @@ from homeassistant.components.sensor import (
SensorEntityDescription,
SensorStateClass,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
DEGREE,
PERCENTAGE,
@@ -20,7 +21,7 @@ from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import ATTRIBUTION, DOMAIN, MANUFACTURER, MODEL
from .coordinator import MeteoclimaticConfigEntry, MeteoclimaticUpdateCoordinator
from .coordinator import MeteoclimaticUpdateCoordinator
SENSOR_TYPES: tuple[SensorEntityDescription, ...] = (
SensorEntityDescription(
@@ -112,11 +113,11 @@ SENSOR_TYPES: tuple[SensorEntityDescription, ...] = (
async def async_setup_entry(
hass: HomeAssistant,
entry: MeteoclimaticConfigEntry,
entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the Meteoclimatic sensor platform."""
coordinator = entry.runtime_data
coordinator: MeteoclimaticUpdateCoordinator = hass.data[DOMAIN][entry.entry_id]
async_add_entities(
[MeteoclimaticSensor(coordinator, description) for description in SENSOR_TYPES],

View File

@@ -5,6 +5,7 @@ from typing import TYPE_CHECKING
from meteoclimatic import Condition
from homeassistant.components.weather import WeatherEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import UnitOfPressure, UnitOfSpeed, UnitOfTemperature
from homeassistant.core import HomeAssistant
from homeassistant.helpers.device_registry import DeviceEntryType, DeviceInfo
@@ -12,7 +13,7 @@ from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import ATTRIBUTION, CONDITION_MAP, DOMAIN, MANUFACTURER, MODEL
from .coordinator import MeteoclimaticConfigEntry, MeteoclimaticUpdateCoordinator
from .coordinator import MeteoclimaticUpdateCoordinator
def format_condition(condition):
@@ -26,11 +27,11 @@ def format_condition(condition):
async def async_setup_entry(
hass: HomeAssistant,
entry: MeteoclimaticConfigEntry,
entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the Meteoclimatic weather platform."""
coordinator = entry.runtime_data
coordinator: MeteoclimaticUpdateCoordinator = hass.data[DOMAIN][entry.entry_id]
async_add_entities([MeteoclimaticWeather(coordinator)], False)

View File

@@ -3,7 +3,9 @@
from __future__ import annotations
import asyncio
import logging
from datapoint.Forecast import Forecast
from datapoint.Manager import Manager
from homeassistant.config_entries import ConfigEntry
@@ -17,8 +19,10 @@ from homeassistant.const import (
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr
from homeassistant.helpers.device_registry import DeviceInfo
from homeassistant.helpers.update_coordinator import TimestampDataUpdateCoordinator
from .const import (
DEFAULT_SCAN_INTERVAL,
DOMAIN,
METOFFICE_COORDINATES,
METOFFICE_DAILY_COORDINATOR,
@@ -26,7 +30,9 @@ from .const import (
METOFFICE_NAME,
METOFFICE_TWICE_DAILY_COORDINATOR,
)
from .coordinator import MetOfficeUpdateCoordinator
from .helpers import fetch_data
_LOGGER = logging.getLogger(__name__)
PLATFORMS = [Platform.SENSOR, Platform.WEATHER]
@@ -34,43 +40,55 @@ PLATFORMS = [Platform.SENSOR, Platform.WEATHER]
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up a Met Office entry."""
latitude: float = entry.data[CONF_LATITUDE]
longitude: float = entry.data[CONF_LONGITUDE]
api_key: str = entry.data[CONF_API_KEY]
site_name: str = entry.data[CONF_NAME]
latitude = entry.data[CONF_LATITUDE]
longitude = entry.data[CONF_LONGITUDE]
api_key = entry.data[CONF_API_KEY]
site_name = entry.data[CONF_NAME]
coordinates = f"{latitude}_{longitude}"
connection = Manager(api_key=api_key)
metoffice_hourly_coordinator = MetOfficeUpdateCoordinator(
async def async_update_hourly() -> Forecast:
return await hass.async_add_executor_job(
fetch_data, connection, latitude, longitude, "hourly"
)
async def async_update_daily() -> Forecast:
return await hass.async_add_executor_job(
fetch_data, connection, latitude, longitude, "daily"
)
async def async_update_twice_daily() -> Forecast:
return await hass.async_add_executor_job(
fetch_data, connection, latitude, longitude, "twice-daily"
)
metoffice_hourly_coordinator = TimestampDataUpdateCoordinator(
hass,
entry,
_LOGGER,
config_entry=entry,
name=f"MetOffice Hourly Coordinator for {site_name}",
connection=connection,
latitude=latitude,
longitude=longitude,
frequency="hourly",
update_method=async_update_hourly,
update_interval=DEFAULT_SCAN_INTERVAL,
)
metoffice_daily_coordinator = MetOfficeUpdateCoordinator(
metoffice_daily_coordinator = TimestampDataUpdateCoordinator(
hass,
entry,
_LOGGER,
config_entry=entry,
name=f"MetOffice Daily Coordinator for {site_name}",
connection=connection,
latitude=latitude,
longitude=longitude,
frequency="daily",
update_method=async_update_daily,
update_interval=DEFAULT_SCAN_INTERVAL,
)
metoffice_twice_daily_coordinator = MetOfficeUpdateCoordinator(
metoffice_twice_daily_coordinator = TimestampDataUpdateCoordinator(
hass,
entry,
_LOGGER,
config_entry=entry,
name=f"MetOffice Twice Daily Coordinator for {site_name}",
connection=connection,
latitude=latitude,
longitude=longitude,
frequency="twice-daily",
update_method=async_update_twice_daily,
update_interval=DEFAULT_SCAN_INTERVAL,
)
metoffice_hass_data = hass.data.setdefault(DOMAIN, {})

View File

@@ -1,82 +0,0 @@
"""Data update coordinator for the Met Office integration."""
from __future__ import annotations
import logging
from typing import Literal
from datapoint.exceptions import APIException
from datapoint.Forecast import Forecast
from datapoint.Manager import Manager
from requests import HTTPError
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryAuthFailed
from homeassistant.helpers.update_coordinator import (
TimestampDataUpdateCoordinator,
UpdateFailed,
)
from .const import DEFAULT_SCAN_INTERVAL
_LOGGER = logging.getLogger(__name__)
class MetOfficeUpdateCoordinator(TimestampDataUpdateCoordinator[Forecast]):
"""Coordinator for Met Office forecast data."""
config_entry: ConfigEntry
def __init__(
self,
hass: HomeAssistant,
entry: ConfigEntry,
name: str,
connection: Manager,
latitude: float,
longitude: float,
frequency: Literal["daily", "twice-daily", "hourly"],
) -> None:
"""Initialize the coordinator."""
super().__init__(
hass,
_LOGGER,
name=name,
config_entry=entry,
update_interval=DEFAULT_SCAN_INTERVAL,
)
self._connection = connection
self._latitude = latitude
self._longitude = longitude
self._frequency = frequency
async def _async_update_data(self) -> Forecast:
"""Get data from Met Office."""
return await self.hass.async_add_executor_job(
fetch_data,
self._connection,
self._latitude,
self._longitude,
self._frequency,
)
def fetch_data(
connection: Manager,
latitude: float,
longitude: float,
frequency: Literal["daily", "twice-daily", "hourly"],
) -> Forecast:
"""Fetch weather and forecast from Datapoint API."""
try:
return connection.get_forecast(
latitude, longitude, frequency, convert_weather_code=False
)
except (ValueError, APIException) as err:
_LOGGER.error("Check Met Office connection: %s", err.args)
raise UpdateFailed from err
except HTTPError as err:
if err.response.status_code == 401:
raise ConfigEntryAuthFailed from err
raise

View File

@@ -2,7 +2,38 @@
from __future__ import annotations
from typing import Any
import logging
from typing import Any, Literal
from datapoint.exceptions import APIException
from datapoint.Forecast import Forecast
from datapoint.Manager import Manager
from requests import HTTPError
from homeassistant.exceptions import ConfigEntryAuthFailed
from homeassistant.helpers.update_coordinator import UpdateFailed
_LOGGER = logging.getLogger(__name__)
def fetch_data(
connection: Manager,
latitude: float,
longitude: float,
frequency: Literal["daily", "twice-daily", "hourly"],
) -> Forecast:
"""Fetch weather and forecast from Datapoint API."""
try:
return connection.get_forecast(
latitude, longitude, frequency, convert_weather_code=False
)
except (ValueError, APIException) as err:
_LOGGER.error("Check Met Office connection: %s", err.args)
raise UpdateFailed from err
except HTTPError as err:
if err.response.status_code == 401:
raise ConfigEntryAuthFailed from err
raise
def get_attribute(data: dict[str, Any] | None, attr_name: str) -> Any | None:

View File

@@ -5,6 +5,8 @@ from __future__ import annotations
from dataclasses import dataclass
from typing import Any
from datapoint.Forecast import Forecast
from homeassistant.components.sensor import (
DOMAIN as SENSOR_DOMAIN,
EntityCategory,
@@ -27,7 +29,10 @@ from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.typing import StateType
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from homeassistant.helpers.update_coordinator import (
CoordinatorEntity,
DataUpdateCoordinator,
)
from . import get_device_info
from .const import (
@@ -38,7 +43,6 @@ from .const import (
METOFFICE_HOURLY_COORDINATOR,
METOFFICE_NAME,
)
from .coordinator import MetOfficeUpdateCoordinator
from .helpers import get_attribute
ATTR_LAST_UPDATE = "last_update"
@@ -216,7 +220,7 @@ async def async_setup_entry(
class MetOfficeCurrentSensor(
CoordinatorEntity[MetOfficeUpdateCoordinator], SensorEntity
CoordinatorEntity[DataUpdateCoordinator[Forecast]], SensorEntity
):
"""Implementation of a Met Office current weather condition sensor."""
@@ -227,7 +231,7 @@ class MetOfficeCurrentSensor(
def __init__(
self,
coordinator: MetOfficeUpdateCoordinator,
coordinator: DataUpdateCoordinator[Forecast],
hass_data: dict[str, Any],
description: MetOfficeSensorEntityDescription,
) -> None:

View File

@@ -5,6 +5,8 @@ from __future__ import annotations
from datetime import datetime
from typing import Any, cast
from datapoint.Forecast import Forecast
from homeassistant.components.weather import (
ATTR_FORECAST_CONDITION,
ATTR_FORECAST_IS_DAYTIME,
@@ -33,6 +35,7 @@ from homeassistant.const import (
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import entity_registry as er
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.update_coordinator import TimestampDataUpdateCoordinator
from . import get_device_info
from .const import (
@@ -49,7 +52,6 @@ from .const import (
METOFFICE_TWICE_DAILY_COORDINATOR,
NIGHT_FORECAST_ATTRIBUTE_MAP,
)
from .coordinator import MetOfficeUpdateCoordinator
from .helpers import get_attribute
@@ -151,9 +153,9 @@ def _populate_forecast_data(
class MetOfficeWeather(
CoordinatorWeatherEntity[
MetOfficeUpdateCoordinator,
MetOfficeUpdateCoordinator,
MetOfficeUpdateCoordinator,
TimestampDataUpdateCoordinator[Forecast],
TimestampDataUpdateCoordinator[Forecast],
TimestampDataUpdateCoordinator[Forecast],
]
):
"""Implementation of a Met Office weather condition."""
@@ -175,9 +177,9 @@ class MetOfficeWeather(
def __init__(
self,
coordinator_daily: MetOfficeUpdateCoordinator,
coordinator_hourly: MetOfficeUpdateCoordinator,
coordinator_twice_daily: MetOfficeUpdateCoordinator,
coordinator_daily: TimestampDataUpdateCoordinator[Forecast],
coordinator_hourly: TimestampDataUpdateCoordinator[Forecast],
coordinator_twice_daily: TimestampDataUpdateCoordinator[Forecast],
hass_data: dict[str, Any],
) -> None:
"""Initialise the platform with a data instance."""
@@ -264,7 +266,7 @@ class MetOfficeWeather(
def _async_forecast_daily(self) -> list[WeatherForecast] | None:
"""Return the daily forecast in native units."""
coordinator = cast(
MetOfficeUpdateCoordinator,
TimestampDataUpdateCoordinator[Forecast],
self.forecast_coordinators["daily"],
)
timesteps = coordinator.data.timesteps
@@ -281,7 +283,7 @@ class MetOfficeWeather(
def _async_forecast_hourly(self) -> list[WeatherForecast] | None:
"""Return the hourly forecast in native units."""
coordinator = cast(
MetOfficeUpdateCoordinator,
TimestampDataUpdateCoordinator[Forecast],
self.forecast_coordinators["hourly"],
)
@@ -299,7 +301,7 @@ class MetOfficeWeather(
def _async_forecast_twice_daily(self) -> list[WeatherForecast] | None:
"""Return the twice daily forecast in native units."""
coordinator = cast(
MetOfficeUpdateCoordinator,
TimestampDataUpdateCoordinator[Forecast],
self.forecast_coordinators["twice_daily"],
)
timesteps = coordinator.data.timesteps

View File

@@ -13,25 +13,22 @@ from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady
from homeassistant.helpers import config_entry_oauth2_flow
from .const import PLATFORMS
from .const import DOMAIN, PLATFORMS
from .coordinator import MicroBeesUpdateCoordinator
_LOGGER = logging.getLogger(__name__)
type MicroBeesConfigEntry = ConfigEntry[HomeAssistantMicroBeesData]
@dataclass(frozen=True, kw_only=True)
class HomeAssistantMicroBeesData:
"""Microbees data stored in the config entry runtime_data."""
"""Microbees data stored in the Home Assistant data object."""
connector: MicroBees
coordinator: MicroBeesUpdateCoordinator
session: config_entry_oauth2_flow.OAuth2Session
async def async_migrate_entry(hass: HomeAssistant, entry: MicroBeesConfigEntry) -> bool:
async def async_migrate_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Migrate entry."""
_LOGGER.debug("Migrating from version %s.%s", entry.version, entry.minor_version)
@@ -48,7 +45,7 @@ async def async_migrate_entry(hass: HomeAssistant, entry: MicroBeesConfigEntry)
return True
async def async_setup_entry(hass: HomeAssistant, entry: MicroBeesConfigEntry) -> bool:
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up microBees from a config entry."""
implementation = (
await config_entry_oauth2_flow.async_get_config_entry_implementation(
@@ -70,7 +67,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: MicroBeesConfigEntry) ->
microbees = MicroBees(token=session.token[CONF_ACCESS_TOKEN])
coordinator = MicroBeesUpdateCoordinator(hass, entry, microbees)
await coordinator.async_config_entry_first_refresh()
entry.runtime_data = HomeAssistantMicroBeesData(
hass.data.setdefault(DOMAIN, {})[entry.entry_id] = HomeAssistantMicroBeesData(
connector=microbees,
coordinator=coordinator,
session=session,
@@ -79,6 +76,9 @@ async def async_setup_entry(hass: HomeAssistant, entry: MicroBeesConfigEntry) ->
return True
async def async_unload_entry(hass: HomeAssistant, entry: MicroBeesConfigEntry) -> bool:
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS):
hass.data[DOMAIN].pop(entry.entry_id)
return unload_ok

View File

@@ -7,10 +7,11 @@ from homeassistant.components.binary_sensor import (
BinarySensorEntity,
BinarySensorEntityDescription,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import MicroBeesConfigEntry
from .const import DOMAIN
from .coordinator import MicroBeesUpdateCoordinator
from .entity import MicroBeesEntity
@@ -36,11 +37,13 @@ BINARYSENSOR_TYPES = {
async def async_setup_entry(
hass: HomeAssistant,
entry: MicroBeesConfigEntry,
entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the microBees binary sensor platform."""
coordinator = entry.runtime_data.coordinator
coordinator: MicroBeesUpdateCoordinator = hass.data[DOMAIN][
entry.entry_id
].coordinator
async_add_entities(
MBBinarySensor(coordinator, entity_description, bee_id, binary_sensor.id)
for bee_id, bee in coordinator.data.bees.items()

View File

@@ -3,10 +3,11 @@
from typing import Any
from homeassistant.components.button import ButtonEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import MicroBeesConfigEntry
from .const import DOMAIN
from .coordinator import MicroBeesUpdateCoordinator
from .entity import MicroBeesActuatorEntity
@@ -15,11 +16,13 @@ BUTTON_TRANSLATIONS = {51: "button_gate", 91: "button_panic"}
async def async_setup_entry(
hass: HomeAssistant,
entry: MicroBeesConfigEntry,
entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the microBees button platform."""
coordinator = entry.runtime_data.coordinator
coordinator: MicroBeesUpdateCoordinator = hass.data[DOMAIN][
entry.entry_id
].coordinator
async_add_entities(
MBButton(coordinator, bee_id, button.id)
for bee_id, bee in coordinator.data.bees.items()

View File

@@ -7,12 +7,13 @@ from homeassistant.components.climate import (
ClimateEntityFeature,
HVACMode,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ATTR_TEMPERATURE, UnitOfTemperature
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import MicroBeesConfigEntry
from .const import DOMAIN
from .coordinator import MicroBeesUpdateCoordinator
from .entity import MicroBeesActuatorEntity
@@ -26,11 +27,13 @@ THERMOVALVE_SENSOR_ID = 782
async def async_setup_entry(
hass: HomeAssistant,
entry: MicroBeesConfigEntry,
entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the microBees climate platform."""
coordinator = entry.runtime_data.coordinator
coordinator: MicroBeesUpdateCoordinator = hass.data[DOMAIN][
entry.entry_id
].coordinator
async_add_entities(
MBClimate(
coordinator,

View File

@@ -1,24 +1,19 @@
"""The microBees Coordinator."""
from __future__ import annotations
import asyncio
from dataclasses import dataclass
from datetime import timedelta
from http import HTTPStatus
import logging
from typing import TYPE_CHECKING
import aiohttp
from microBeesPy import Actuator, Bee, MicroBees, MicroBeesException, Sensor
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryAuthFailed
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
if TYPE_CHECKING:
from . import MicroBeesConfigEntry
_LOGGER = logging.getLogger(__name__)
@@ -34,13 +29,10 @@ class MicroBeesCoordinatorData:
class MicroBeesUpdateCoordinator(DataUpdateCoordinator[MicroBeesCoordinatorData]):
"""MicroBees coordinator."""
config_entry: MicroBeesConfigEntry
config_entry: ConfigEntry
def __init__(
self,
hass: HomeAssistant,
config_entry: MicroBeesConfigEntry,
microbees: MicroBees,
self, hass: HomeAssistant, config_entry: ConfigEntry, microbees: MicroBees
) -> None:
"""Initialize microBees coordinator."""
super().__init__(

View File

@@ -9,12 +9,14 @@ from homeassistant.components.cover import (
CoverEntity,
CoverEntityFeature,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.event import async_call_later
from . import MicroBeesConfigEntry
from .const import DOMAIN
from .coordinator import MicroBeesUpdateCoordinator
from .entity import MicroBeesEntity
COVER_IDS = {47: "roller_shutter"}
@@ -22,11 +24,13 @@ COVER_IDS = {47: "roller_shutter"}
async def async_setup_entry(
hass: HomeAssistant,
entry: MicroBeesConfigEntry,
entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the microBees cover platform."""
coordinator = entry.runtime_data.coordinator
coordinator: MicroBeesUpdateCoordinator = hass.data[DOMAIN][
entry.entry_id
].coordinator
async_add_entities(
MBCover(

View File

@@ -3,22 +3,25 @@
from typing import Any
from homeassistant.components.light import ATTR_RGBW_COLOR, ColorMode, LightEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import MicroBeesConfigEntry
from .const import DOMAIN
from .coordinator import MicroBeesUpdateCoordinator
from .entity import MicroBeesActuatorEntity
async def async_setup_entry(
hass: HomeAssistant,
entry: MicroBeesConfigEntry,
entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Config entry."""
coordinator = entry.runtime_data.coordinator
coordinator: MicroBeesUpdateCoordinator = hass.data[DOMAIN][
entry.entry_id
].coordinator
async_add_entities(
MBLight(coordinator, bee_id, light.id)
for bee_id, bee in coordinator.data.bees.items()

View File

@@ -8,6 +8,7 @@ from homeassistant.components.sensor import (
SensorEntityDescription,
SensorStateClass,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
CONCENTRATION_PARTS_PER_MILLION,
LIGHT_LUX,
@@ -18,7 +19,7 @@ from homeassistant.const import (
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import MicroBeesConfigEntry
from .const import DOMAIN
from .coordinator import MicroBeesUpdateCoordinator
from .entity import MicroBeesEntity
@@ -63,11 +64,11 @@ SENSOR_TYPES = {
async def async_setup_entry(
hass: HomeAssistant,
entry: MicroBeesConfigEntry,
entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Config entry."""
coordinator = entry.runtime_data.coordinator
coordinator = hass.data[DOMAIN][entry.entry_id].coordinator
async_add_entities(
MBSensor(coordinator, desc, bee_id, sensor.id)

View File

@@ -3,11 +3,12 @@
from typing import Any
from homeassistant.components.switch import SwitchEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import MicroBeesConfigEntry
from .const import DOMAIN
from .coordinator import MicroBeesUpdateCoordinator
from .entity import MicroBeesActuatorEntity
@@ -17,11 +18,11 @@ SWITCH_PRODUCT_IDS = {25, 26, 27, 35, 38, 46, 63, 64, 65, 86}
async def async_setup_entry(
hass: HomeAssistant,
entry: MicroBeesConfigEntry,
entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Config entry."""
coordinator = entry.runtime_data.coordinator
coordinator = hass.data[DOMAIN][entry.entry_id].coordinator
async_add_entities(
MBSwitch(coordinator, bee_id, switch.id)

View File

@@ -3,20 +3,16 @@
from phone_modem import PhoneModem
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_DEVICE, EVENT_HOMEASSISTANT_STOP, Platform
from homeassistant.core import Event, HomeAssistant
from homeassistant.const import CONF_DEVICE, Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady
from .const import EXCEPTIONS
from .const import DATA_KEY_API, DOMAIN, EXCEPTIONS
PLATFORMS = [Platform.BUTTON, Platform.SENSOR]
type ModemCallerIdConfigEntry = ConfigEntry[PhoneModem]
async def async_setup_entry(
hass: HomeAssistant, entry: ModemCallerIdConfigEntry
) -> bool:
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Modem Caller ID from a config entry."""
device = entry.data[CONF_DEVICE]
api = PhoneModem(device)
@@ -25,25 +21,17 @@ async def async_setup_entry(
except EXCEPTIONS as ex:
raise ConfigEntryNotReady(f"Unable to open port: {device}") from ex
entry.async_on_unload(api.close)
async def _async_on_hass_stop(event: Event) -> None:
"""HA is shutting down, close modem port."""
api.close()
entry.async_on_unload(
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _async_on_hass_stop)
)
entry.runtime_data = api
hass.data.setdefault(DOMAIN, {})[entry.entry_id] = {DATA_KEY_API: api}
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
return True
async def async_unload_entry(
hass: HomeAssistant, entry: ModemCallerIdConfigEntry
) -> bool:
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
if unload_ok:
api = hass.data[DOMAIN].pop(entry.entry_id)[DATA_KEY_API]
await api.close()
return unload_ok

View File

@@ -5,25 +5,26 @@ from __future__ import annotations
from phone_modem import PhoneModem
from homeassistant.components.button import ButtonEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_DEVICE
from homeassistant.core import HomeAssistant
from homeassistant.helpers.device_registry import DeviceInfo
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import ModemCallerIdConfigEntry
from .const import DOMAIN
from .const import DATA_KEY_API, DOMAIN
async def async_setup_entry(
hass: HomeAssistant,
entry: ModemCallerIdConfigEntry,
entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the Modem Caller ID sensor."""
api = hass.data[DOMAIN][entry.entry_id][DATA_KEY_API]
async_add_entities(
[
PhoneModemButton(
entry.runtime_data,
api,
entry.data[CONF_DEVICE],
entry.entry_id,
)

View File

@@ -5,6 +5,7 @@ from typing import Final
from phone_modem import exceptions
from serial import SerialException
DATA_KEY_API = "api"
DEFAULT_NAME = "Phone Modem"
DOMAIN = "modem_callerid"

View File

@@ -5,30 +5,40 @@ from __future__ import annotations
from phone_modem import PhoneModem
from homeassistant.components.sensor import RestoreSensor
from homeassistant.const import STATE_IDLE
from homeassistant.core import HomeAssistant, callback
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import EVENT_HOMEASSISTANT_STOP, STATE_IDLE
from homeassistant.core import Event, HomeAssistant, callback
from homeassistant.helpers.device_registry import DeviceInfo
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import ModemCallerIdConfigEntry
from .const import CID, DOMAIN
from .const import CID, DATA_KEY_API, DOMAIN
async def async_setup_entry(
hass: HomeAssistant,
entry: ModemCallerIdConfigEntry,
entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the Modem Caller ID sensor."""
api = hass.data[DOMAIN][entry.entry_id][DATA_KEY_API]
async_add_entities(
[
ModemCalleridSensor(
entry.runtime_data,
api,
entry.entry_id,
)
]
)
async def _async_on_hass_stop(event: Event) -> None:
"""HA is shutting down, close modem port."""
if hass.data[DOMAIN][entry.entry_id][DATA_KEY_API]:
await hass.data[DOMAIN][entry.entry_id][DATA_KEY_API].close()
entry.async_on_unload(
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _async_on_hass_stop)
)
class ModemCalleridSensor(RestoreSensor):
"""Implementation of USB modem caller ID sensor."""

View File

@@ -8,10 +8,12 @@ from typing import Any, Concatenate
from aiomodernforms import ModernFormsConnectionError, ModernFormsError
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from .coordinator import ModernFormsConfigEntry, ModernFormsDataUpdateCoordinator
from .const import DOMAIN
from .coordinator import ModernFormsDataUpdateCoordinator
from .entity import ModernFormsDeviceEntity
PLATFORMS = [
@@ -24,14 +26,15 @@ PLATFORMS = [
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(hass: HomeAssistant, entry: ModernFormsConfigEntry) -> bool:
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up a Modern Forms device from a config entry."""
# Create Modern Forms instance for this entry
coordinator = ModernFormsDataUpdateCoordinator(hass, entry)
await coordinator.async_config_entry_first_refresh()
entry.runtime_data = coordinator
hass.data.setdefault(DOMAIN, {})
hass.data[DOMAIN][entry.entry_id] = coordinator
# Set up all platforms for this device/entry.
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
@@ -39,11 +42,17 @@ async def async_setup_entry(hass: HomeAssistant, entry: ModernFormsConfigEntry)
return True
async def async_unload_entry(
hass: HomeAssistant, entry: ModernFormsConfigEntry
) -> bool:
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload Modern Forms config entry."""
return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
if unload_ok:
del hass.data[DOMAIN][entry.entry_id]
if not hass.data[DOMAIN]:
del hass.data[DOMAIN]
return unload_ok
def modernforms_exception_handler[

View File

@@ -3,22 +3,23 @@
from __future__ import annotations
from homeassistant.components.binary_sensor import BinarySensorEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.util import dt as dt_util
from .const import CLEAR_TIMER
from .coordinator import ModernFormsConfigEntry, ModernFormsDataUpdateCoordinator
from .const import CLEAR_TIMER, DOMAIN
from .coordinator import ModernFormsDataUpdateCoordinator
from .entity import ModernFormsDeviceEntity
async def async_setup_entry(
hass: HomeAssistant,
entry: ModernFormsConfigEntry,
entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up Modern Forms binary sensors."""
coordinator = entry.runtime_data
coordinator: ModernFormsDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id]
binary_sensors: list[ModernFormsBinarySensor] = [
ModernFormsFanSleepTimerActive(entry.entry_id, coordinator),

View File

@@ -20,9 +20,6 @@ SCAN_INTERVAL = timedelta(seconds=5)
_LOGGER = logging.getLogger(__name__)
type ModernFormsConfigEntry = ConfigEntry[ModernFormsDataUpdateCoordinator]
class ModernFormsDataUpdateCoordinator(DataUpdateCoordinator[ModernFormsDeviceState]):
"""Class to manage fetching Modern Forms data from single endpoint."""

View File

@@ -3,23 +3,27 @@
from __future__ import annotations
from dataclasses import asdict
from typing import Any
from typing import TYPE_CHECKING, Any
from homeassistant.components.diagnostics import async_redact_data
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_MAC
from homeassistant.core import HomeAssistant
from .coordinator import ModernFormsConfigEntry
from .const import DOMAIN
from .coordinator import ModernFormsDataUpdateCoordinator
REDACT_CONFIG = {CONF_MAC}
REDACT_DEVICE_INFO = {"mac_address", "owner"}
async def async_get_config_entry_diagnostics(
hass: HomeAssistant, entry: ModernFormsConfigEntry
hass: HomeAssistant, entry: ConfigEntry
) -> dict[str, Any]:
"""Return diagnostics for a config entry."""
coordinator = entry.runtime_data
coordinator: ModernFormsDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id]
if TYPE_CHECKING:
assert coordinator is not None
return {
"config_entry": async_redact_data(entry.as_dict(), REDACT_CONFIG),

View File

@@ -8,6 +8,7 @@ from aiomodernforms.const import FAN_POWER_OFF, FAN_POWER_ON
import voluptuous as vol
from homeassistant.components.fan import FanEntity, FanEntityFeature
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_platform
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
@@ -21,23 +22,26 @@ from . import modernforms_exception_handler
from .const import (
ATTR_SLEEP_TIME,
CLEAR_TIMER,
DOMAIN,
OPT_ON,
OPT_SPEED,
SERVICE_CLEAR_FAN_SLEEP_TIMER,
SERVICE_SET_FAN_SLEEP_TIMER,
)
from .coordinator import ModernFormsConfigEntry, ModernFormsDataUpdateCoordinator
from .coordinator import ModernFormsDataUpdateCoordinator
from .entity import ModernFormsDeviceEntity
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ModernFormsConfigEntry,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up a Modern Forms platform from config entry."""
coordinator = config_entry.runtime_data
coordinator: ModernFormsDataUpdateCoordinator = hass.data[DOMAIN][
config_entry.entry_id
]
platform = entity_platform.async_get_current_platform()

View File

@@ -8,6 +8,7 @@ from aiomodernforms.const import LIGHT_POWER_OFF, LIGHT_POWER_ON
import voluptuous as vol
from homeassistant.components.light import ATTR_BRIGHTNESS, ColorMode, LightEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_platform
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
@@ -20,12 +21,13 @@ from . import modernforms_exception_handler
from .const import (
ATTR_SLEEP_TIME,
CLEAR_TIMER,
DOMAIN,
OPT_BRIGHTNESS,
OPT_ON,
SERVICE_CLEAR_LIGHT_SLEEP_TIMER,
SERVICE_SET_LIGHT_SLEEP_TIMER,
)
from .coordinator import ModernFormsConfigEntry, ModernFormsDataUpdateCoordinator
from .coordinator import ModernFormsDataUpdateCoordinator
from .entity import ModernFormsDeviceEntity
BRIGHTNESS_RANGE = (1, 255)
@@ -33,12 +35,14 @@ BRIGHTNESS_RANGE = (1, 255)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ModernFormsConfigEntry,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up a Modern Forms platform from config entry."""
coordinator = config_entry.runtime_data
coordinator: ModernFormsDataUpdateCoordinator = hass.data[DOMAIN][
config_entry.entry_id
]
# if no light unit installed no light entity
if not coordinator.data.info.light_type:

View File

@@ -5,23 +5,24 @@ from __future__ import annotations
from datetime import datetime
from homeassistant.components.sensor import SensorDeviceClass, SensorEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.typing import StateType
from homeassistant.util import dt as dt_util
from .const import CLEAR_TIMER
from .coordinator import ModernFormsConfigEntry, ModernFormsDataUpdateCoordinator
from .const import CLEAR_TIMER, DOMAIN
from .coordinator import ModernFormsDataUpdateCoordinator
from .entity import ModernFormsDeviceEntity
async def async_setup_entry(
hass: HomeAssistant,
entry: ModernFormsConfigEntry,
entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up Modern Forms sensor based on a config entry."""
coordinator = entry.runtime_data
coordinator: ModernFormsDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id]
sensors: list[ModernFormsSensor] = [
ModernFormsFanTimerRemainingTimeSensor(entry.entry_id, coordinator),

View File

@@ -5,21 +5,23 @@ from __future__ import annotations
from typing import Any
from homeassistant.components.switch import SwitchEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import modernforms_exception_handler
from .coordinator import ModernFormsConfigEntry, ModernFormsDataUpdateCoordinator
from .const import DOMAIN
from .coordinator import ModernFormsDataUpdateCoordinator
from .entity import ModernFormsDeviceEntity
async def async_setup_entry(
hass: HomeAssistant,
entry: ModernFormsConfigEntry,
entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up Modern Forms switch based on a config entry."""
coordinator = entry.runtime_data
coordinator: ModernFormsDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id]
switches = [
ModernFormsAwaySwitch(entry.entry_id, coordinator),

View File

@@ -4,33 +4,41 @@ from __future__ import annotations
from moehlenhoff_alpha2 import Alpha2Base
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_HOST, Platform
from homeassistant.core import HomeAssistant
from .coordinator import Alpha2BaseCoordinator, Alpha2ConfigEntry
from .const import DOMAIN
from .coordinator import Alpha2BaseCoordinator
PLATFORMS = [Platform.BINARY_SENSOR, Platform.BUTTON, Platform.CLIMATE, Platform.SENSOR]
async def async_setup_entry(hass: HomeAssistant, entry: Alpha2ConfigEntry) -> bool:
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up a config entry."""
base = Alpha2Base(entry.data[CONF_HOST])
coordinator = Alpha2BaseCoordinator(hass, entry, base)
await coordinator.async_config_entry_first_refresh()
entry.runtime_data = coordinator
hass.data.setdefault(DOMAIN, {})
hass.data[DOMAIN][entry.entry_id] = coordinator
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
return True
async def async_unload_entry(hass: HomeAssistant, entry: Alpha2ConfigEntry) -> bool:
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
if unload_ok and entry.entry_id in hass.data[DOMAIN]:
hass.data[DOMAIN].pop(entry.entry_id)
return unload_ok
async def update_listener(hass: HomeAssistant, entry: Alpha2ConfigEntry) -> None:
async def update_listener(hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Handle options update."""
await hass.config_entries.async_reload(entry.entry_id)

View File

@@ -4,22 +4,24 @@ from homeassistant.components.binary_sensor import (
BinarySensorDeviceClass,
BinarySensorEntity,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .coordinator import Alpha2BaseCoordinator, Alpha2ConfigEntry
from .const import DOMAIN
from .coordinator import Alpha2BaseCoordinator
async def async_setup_entry(
hass: HomeAssistant,
config_entry: Alpha2ConfigEntry,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Add Alpha2 sensor entities from a config_entry."""
coordinator = config_entry.runtime_data
coordinator: Alpha2BaseCoordinator = hass.data[DOMAIN][config_entry.entry_id]
async_add_entities(
Alpha2IODeviceBatterySensor(coordinator, io_device_id)

View File

@@ -1,23 +1,25 @@
"""Button entity to set the time of the Alpha2 base."""
from homeassistant.components.button import ButtonEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from homeassistant.util import dt as dt_util
from .coordinator import Alpha2BaseCoordinator, Alpha2ConfigEntry
from .const import DOMAIN
from .coordinator import Alpha2BaseCoordinator
async def async_setup_entry(
hass: HomeAssistant,
config_entry: Alpha2ConfigEntry,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Add Alpha2 button entities."""
coordinator = config_entry.runtime_data
coordinator: Alpha2BaseCoordinator = hass.data[DOMAIN][config_entry.entry_id]
async_add_entities([Alpha2TimeSyncButton(coordinator, config_entry.entry_id)])

View File

@@ -1,5 +1,6 @@
"""Support for Alpha2 room control unit via Alpha2 base."""
import logging
from typing import Any
from homeassistant.components.climate import (
@@ -8,23 +9,26 @@ from homeassistant.components.climate import (
HVACAction,
HVACMode,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ATTR_TEMPERATURE, UnitOfTemperature
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import PRESET_AUTO, PRESET_DAY, PRESET_NIGHT
from .coordinator import Alpha2BaseCoordinator, Alpha2ConfigEntry
from .const import DOMAIN, PRESET_AUTO, PRESET_DAY, PRESET_NIGHT
from .coordinator import Alpha2BaseCoordinator
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: Alpha2ConfigEntry,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Add Alpha2Climate entities from a config_entry."""
coordinator = config_entry.runtime_data
coordinator: Alpha2BaseCoordinator = hass.data[DOMAIN][config_entry.entry_id]
async_add_entities(
Alpha2Climate(coordinator, heat_area_id)

View File

@@ -17,16 +17,14 @@ _LOGGER = logging.getLogger(__name__)
UPDATE_INTERVAL = timedelta(seconds=60)
type Alpha2ConfigEntry = ConfigEntry[Alpha2BaseCoordinator]
class Alpha2BaseCoordinator(DataUpdateCoordinator[dict[str, dict]]):
"""Keep the base instance in one place and centralize the update."""
config_entry: Alpha2ConfigEntry
config_entry: ConfigEntry
def __init__(
self, hass: HomeAssistant, config_entry: Alpha2ConfigEntry, base: Alpha2Base
self, hass: HomeAssistant, config_entry: ConfigEntry, base: Alpha2Base
) -> None:
"""Initialize Alpha2Base data updater."""
self.base = base

View File

@@ -1,22 +1,24 @@
"""Support for Alpha2 heat control valve opening sensors."""
from homeassistant.components.sensor import SensorEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import PERCENTAGE
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .coordinator import Alpha2BaseCoordinator, Alpha2ConfigEntry
from .const import DOMAIN
from .coordinator import Alpha2BaseCoordinator
async def async_setup_entry(
hass: HomeAssistant,
config_entry: Alpha2ConfigEntry,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Add Alpha2 sensor entities from a config_entry."""
coordinator = config_entry.runtime_data
coordinator: Alpha2BaseCoordinator = hass.data[DOMAIN][config_entry.entry_id]
# HEATCTRL attribute ACTOR_PERCENT is not available in older firmware versions
async_add_entities(

View File

@@ -128,7 +128,6 @@ class MonopriceZone(MediaPlayerEntity):
)
_attr_has_entity_name = True
_attr_name = None
_attr_volume_step = 1 / MAX_VOLUME
def __init__(self, monoprice, sources, namespace, zone_id):
"""Initialize new zone."""
@@ -212,3 +211,17 @@ class MonopriceZone(MediaPlayerEntity):
def set_volume_level(self, volume: float) -> None:
"""Set volume level, range 0..1."""
self._monoprice.set_volume(self._zone_id, round(volume * MAX_VOLUME))
def volume_up(self) -> None:
"""Volume up the media player."""
if self.volume_level is None:
return
volume = round(self.volume_level * MAX_VOLUME)
self._monoprice.set_volume(self._zone_id, min(volume + 1, MAX_VOLUME))
def volume_down(self) -> None:
"""Volume down media player."""
if self.volume_level is None:
return
volume = round(self.volume_level * MAX_VOLUME)
self._monoprice.set_volume(self._zone_id, max(volume - 1, 0))

View File

@@ -56,6 +56,7 @@ from homeassistant.helpers.dispatcher import (
async_dispatcher_send,
)
from homeassistant.helpers.network import NoURLAvailableError, get_url
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import (
ATTR_EVENT_TYPE,
@@ -68,6 +69,7 @@ from .const import (
CONF_SURVEILLANCE_USERNAME,
CONF_WEBHOOK_SET,
CONF_WEBHOOK_SET_OVERWRITE,
DEFAULT_SCAN_INTERVAL,
DEFAULT_WEBHOOK_SET,
DEFAULT_WEBHOOK_SET_OVERWRITE,
DOMAIN,
@@ -82,7 +84,6 @@ from .const import (
WEB_HOOK_SENTINEL_KEY,
WEB_HOOK_SENTINEL_VALUE,
)
from .coordinator import MotionEyeUpdateCoordinator
_LOGGER = logging.getLogger(__name__)
PLATFORMS = [CAMERA_DOMAIN, SENSOR_DOMAIN, SWITCH_DOMAIN]
@@ -307,7 +308,20 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
hass, DOMAIN, "motionEye", entry.data[CONF_WEBHOOK_ID], handle_webhook
)
coordinator = MotionEyeUpdateCoordinator(hass, entry, client)
async def async_update_data() -> dict[str, Any] | None:
try:
return await client.async_get_cameras()
except MotionEyeClientError as exc:
raise UpdateFailed("Error communicating with API") from exc
coordinator = DataUpdateCoordinator(
hass,
_LOGGER,
config_entry=entry,
name=DOMAIN,
update_method=async_update_data,
update_interval=DEFAULT_SCAN_INTERVAL,
)
hass.data[DOMAIN][entry.entry_id] = {
CONF_CLIENT: client,
CONF_COORDINATOR: coordinator,

View File

@@ -43,6 +43,7 @@ from homeassistant.const import (
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv, entity_platform
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
from . import get_camera_from_cameras, is_acceptable_camera, listen_for_new_cameras
from .const import (
@@ -59,7 +60,6 @@ from .const import (
SERVICE_SNAPSHOT,
TYPE_MOTIONEYE_MJPEG_CAMERA,
)
from .coordinator import MotionEyeUpdateCoordinator
from .entity import MotionEyeEntity
PLATFORMS = [Platform.CAMERA]
@@ -153,7 +153,7 @@ class MotionEyeMjpegCamera(MotionEyeEntity, MjpegCamera):
password: str,
camera: dict[str, Any],
client: MotionEyeClient,
coordinator: MotionEyeUpdateCoordinator,
coordinator: DataUpdateCoordinator,
options: Mapping[str, str],
) -> None:
"""Initialize a MJPEG camera."""

View File

@@ -1,41 +0,0 @@
"""Coordinator for the motionEye integration."""
from __future__ import annotations
import logging
from typing import Any
from motioneye_client.client import MotionEyeClient, MotionEyeClientError
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import DEFAULT_SCAN_INTERVAL, DOMAIN
_LOGGER = logging.getLogger(__name__)
class MotionEyeUpdateCoordinator(DataUpdateCoordinator[dict[str, Any] | None]):
"""Coordinator for motionEye data."""
config_entry: ConfigEntry
def __init__(
self, hass: HomeAssistant, entry: ConfigEntry, client: MotionEyeClient
) -> None:
"""Initialize the coordinator."""
super().__init__(
hass,
_LOGGER,
name=DOMAIN,
config_entry=entry,
update_interval=DEFAULT_SCAN_INTERVAL,
)
self.client = client
async def _async_update_data(self) -> dict[str, Any] | None:
try:
return await self.client.async_get_cameras()
except MotionEyeClientError as exc:
raise UpdateFailed("Error communicating with API") from exc

View File

@@ -10,10 +10,12 @@ from motioneye_client.const import KEY_ID
from homeassistant.helpers.device_registry import DeviceInfo
from homeassistant.helpers.entity import EntityDescription
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from homeassistant.helpers.update_coordinator import (
CoordinatorEntity,
DataUpdateCoordinator,
)
from . import get_motioneye_device_identifier
from .coordinator import MotionEyeUpdateCoordinator
def get_motioneye_entity_unique_id(
@@ -23,7 +25,7 @@ def get_motioneye_entity_unique_id(
return f"{config_entry_id}_{camera_id}_{entity_type}"
class MotionEyeEntity(CoordinatorEntity[MotionEyeUpdateCoordinator]):
class MotionEyeEntity(CoordinatorEntity):
"""Base class for motionEye entities."""
_attr_has_entity_name = True
@@ -34,7 +36,7 @@ class MotionEyeEntity(CoordinatorEntity[MotionEyeUpdateCoordinator]):
type_name: str,
camera: dict[str, Any],
client: MotionEyeClient,
coordinator: MotionEyeUpdateCoordinator,
coordinator: DataUpdateCoordinator,
options: Mapping[str, Any],
entity_description: EntityDescription | None = None,
) -> None:

View File

@@ -3,6 +3,7 @@
from __future__ import annotations
from collections.abc import Mapping
import logging
from typing import Any
from motioneye_client.client import MotionEyeClient
@@ -13,12 +14,14 @@ from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.typing import StateType
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
from . import get_camera_from_cameras, listen_for_new_cameras
from .const import CONF_CLIENT, CONF_COORDINATOR, DOMAIN, TYPE_MOTIONEYE_ACTION_SENSOR
from .coordinator import MotionEyeUpdateCoordinator
from .entity import MotionEyeEntity
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(
hass: HomeAssistant,
@@ -56,7 +59,7 @@ class MotionEyeActionSensor(MotionEyeEntity, SensorEntity):
config_entry_id: str,
camera: dict[str, Any],
client: MotionEyeClient,
coordinator: MotionEyeUpdateCoordinator,
coordinator: DataUpdateCoordinator,
options: Mapping[str, str],
) -> None:
"""Initialize an action sensor."""

View File

@@ -20,10 +20,10 @@ from homeassistant.config_entries import ConfigEntry
from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
from . import get_camera_from_cameras, listen_for_new_cameras
from .const import CONF_CLIENT, CONF_COORDINATOR, DOMAIN, TYPE_MOTIONEYE_SWITCH_BASE
from .coordinator import MotionEyeUpdateCoordinator
from .entity import MotionEyeEntity
MOTIONEYE_SWITCHES = [
@@ -102,7 +102,7 @@ class MotionEyeSwitch(MotionEyeEntity, SwitchEntity):
config_entry_id: str,
camera: dict[str, Any],
client: MotionEyeClient,
coordinator: MotionEyeUpdateCoordinator,
coordinator: DataUpdateCoordinator,
options: Mapping[str, str],
entity_description: SwitchEntityDescription,
) -> None:

View File

@@ -93,7 +93,6 @@ class MpdDevice(MediaPlayerEntity):
_attr_media_content_type = MediaType.MUSIC
_attr_has_entity_name = True
_attr_name = None
_attr_volume_step = 0.05
def __init__(
self, server: str, port: int, password: str | None, unique_id: str
@@ -394,6 +393,24 @@ class MpdDevice(MediaPlayerEntity):
if "volume" in self._status:
await self._client.setvol(int(volume * 100))
async def async_volume_up(self) -> None:
"""Service to send the MPD the command for volume up."""
async with self.connection():
if "volume" in self._status:
current_volume = int(self._status["volume"])
if current_volume <= 100:
self._client.setvol(current_volume + 5)
async def async_volume_down(self) -> None:
"""Service to send the MPD the command for volume down."""
async with self.connection():
if "volume" in self._status:
current_volume = int(self._status["volume"])
if current_volume >= 0:
await self._client.setvol(current_volume - 5)
async def async_media_play(self) -> None:
"""Service to send the MPD the command for play/pause."""
async with self.connection():

View File

@@ -107,6 +107,7 @@ ABBREVIATIONS = {
"modes": "modes",
"name": "name",
"o": "origin",
"obj_id": "object_id",
"off_dly": "off_delay",
"on_cmd_type": "on_command_type",
"ops": "options",

View File

@@ -268,6 +268,7 @@ CONF_VIA_DEVICE = "via_device"
CONF_DEPRECATED_VIA_HUB = "via_hub"
CONF_SUGGESTED_AREA = "suggested_area"
CONF_CONFIGURATION_URL = "configuration_url"
CONF_OBJECT_ID = "object_id"
CONF_SUPPORT_URL = "support_url"
DEFAULT_ALARM_CONTROL_PANEL_COMMAND_TEMPLATE = "{{action}}"

View File

@@ -29,6 +29,7 @@ from homeassistant.const import (
CONF_MODEL_ID,
CONF_NAME,
CONF_UNIQUE_ID,
CONF_URL,
CONF_VALUE_TEMPLATE,
)
from homeassistant.core import Event, HassJobType, HomeAssistant, callback
@@ -83,6 +84,8 @@ from .const import (
CONF_JSON_ATTRS_TEMPLATE,
CONF_JSON_ATTRS_TOPIC,
CONF_MANUFACTURER,
CONF_OBJECT_ID,
CONF_ORIGIN,
CONF_PAYLOAD_AVAILABLE,
CONF_PAYLOAD_NOT_AVAILABLE,
CONF_QOS,
@@ -1409,12 +1412,58 @@ class MqttEntity(
"""Set entity_id from default_entity_id if defined in config."""
object_id: str
default_entity_id: str | None
if (default_entity_id := self._config.get(CONF_DEFAULT_ENTITY_ID)) is None:
# Setting the default entity_id through the CONF_OBJECT_ID is deprecated
# Support will be removed with HA Core 2026.4
if (
CONF_DEFAULT_ENTITY_ID not in self._config
and CONF_OBJECT_ID not in self._config
):
return
_, _, object_id = default_entity_id.partition(".")
if (default_entity_id := self._config.get(CONF_DEFAULT_ENTITY_ID)) is None:
object_id = self._config[CONF_OBJECT_ID]
else:
_, _, object_id = default_entity_id.partition(".")
self.entity_id = async_generate_entity_id(
self._entity_id_format, object_id, None, self.hass
)
if CONF_OBJECT_ID in self._config:
domain = self.entity_id.split(".")[0]
if not self._discovery:
async_create_issue(
self.hass,
DOMAIN,
self.entity_id,
issue_domain=DOMAIN,
is_fixable=False,
breaks_in_ha_version="2026.4",
severity=IssueSeverity.WARNING,
learn_more_url=f"{learn_more_url(domain)}#default_enity_id",
translation_placeholders={
"entity_id": self.entity_id,
"object_id": self._config[CONF_OBJECT_ID],
"domain": domain,
},
translation_key="deprecated_object_id",
)
elif CONF_DEFAULT_ENTITY_ID not in self._config:
if CONF_ORIGIN in self._config:
origin_name = self._config[CONF_ORIGIN][CONF_NAME]
url = self._config[CONF_ORIGIN].get(CONF_URL)
origin = f"[{origin_name}]({url})" if url else origin_name
else:
origin = "the integration"
_LOGGER.warning(
"The configuration for entity %s uses the deprecated option "
"`object_id` to set the default entity id. Replace the "
'`"object_id": "%s"` option with `"default_entity_id": '
'"%s"` in your published discovery configuration to fix this '
"issue, or contact the maintainer of %s that published this config "
"to fix this. This will stop working in Home Assistant Core 2026.4",
self.entity_id,
self._config[CONF_OBJECT_ID],
f"{domain}.{self._config[CONF_OBJECT_ID]}",
origin,
)
if self.unique_id is None:
return
@@ -1426,8 +1475,7 @@ class MqttEntity(
(entity_platform, DOMAIN, self.unique_id)
)
) and deleted_entry.entity_id != self.entity_id:
# Plan to update the entity_id based on `default_entity_id`
# if a deleted entity was found
# Plan to update the entity_id basis on `object_id` if a deleted entity was found
self._update_registry_entity_id = self.entity_id
@final

View File

@@ -42,6 +42,7 @@ from .const import (
CONF_JSON_ATTRS_TEMPLATE,
CONF_JSON_ATTRS_TOPIC,
CONF_MANUFACTURER,
CONF_OBJECT_ID,
CONF_ORIGIN,
CONF_PAYLOAD_AVAILABLE,
CONF_PAYLOAD_NOT_AVAILABLE,
@@ -172,6 +173,7 @@ MQTT_ENTITY_COMMON_SCHEMA = _MQTT_AVAILABILITY_SCHEMA.extend(
vol.Optional(CONF_JSON_ATTRS_TOPIC): valid_subscribe_topic,
vol.Optional(CONF_JSON_ATTRS_TEMPLATE): cv.template,
vol.Optional(CONF_DEFAULT_ENTITY_ID): cv.string,
vol.Optional(CONF_OBJECT_ID): cv.string,
vol.Optional(CONF_UNIQUE_ID): cv.string,
}
)

View File

@@ -1116,6 +1116,10 @@
}
},
"issues": {
"deprecated_object_id": {
"description": "Entity {entity_id} uses the `object_id` option which is deprecated. To fix the issue, replace the `object_id: {object_id}` option with `default_entity_id: {domain}.{object_id}` in your \"configuration.yaml\", and restart Home Assistant.",
"title": "Deprecated option object_id used"
},
"invalid_platform_config": {
"description": "Home Assistant detected an invalid config for a manually configured item.\n\nPlatform domain: **{domain}**\nConfiguration file: **{config_file}**\nNear line: **{line}**\nConfiguration found:\n```yaml\n{config}\n```\nError: **{error}**.\n\nMake sure the configuration is valid and [reload](/config/developer-tools/yaml) the manually configured MQTT items or restart Home Assistant to fix this issue.",
"title": "Invalid config found for MQTT {domain} item"

Some files were not shown because too many files have changed in this diff Show More