mirror of
https://github.com/home-assistant/core.git
synced 2026-01-22 07:26:58 +01:00
Compare commits
2 Commits
dev
...
claude/ext
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
aa6c2b4f74 | ||
|
|
e0349cae63 |
238
.claude/skills/ha-integration/BINARY-SENSOR.MD
Normal file
238
.claude/skills/ha-integration/BINARY-SENSOR.MD
Normal file
@@ -0,0 +1,238 @@
|
||||
# Binary Sensor Platform Reference
|
||||
|
||||
Binary sensors represent on/off states.
|
||||
|
||||
## Basic Binary Sensor
|
||||
|
||||
```python
|
||||
"""Binary sensor platform for My Integration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from homeassistant.components.binary_sensor import (
|
||||
BinarySensorDeviceClass,
|
||||
BinarySensorEntity,
|
||||
)
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
||||
|
||||
from . import MyIntegrationConfigEntry
|
||||
from .entity import MyEntity
|
||||
|
||||
|
||||
async def async_setup_entry(
|
||||
hass: HomeAssistant,
|
||||
entry: MyIntegrationConfigEntry,
|
||||
async_add_entities: AddEntitiesCallback,
|
||||
) -> None:
|
||||
"""Set up binary sensors from config entry."""
|
||||
coordinator = entry.runtime_data
|
||||
|
||||
async_add_entities([
|
||||
DoorSensor(coordinator),
|
||||
MotionSensor(coordinator),
|
||||
])
|
||||
|
||||
|
||||
class DoorSensor(MyEntity, BinarySensorEntity):
|
||||
"""Door open/close sensor."""
|
||||
|
||||
_attr_device_class = BinarySensorDeviceClass.DOOR
|
||||
_attr_translation_key = "door"
|
||||
|
||||
def __init__(self, coordinator: MyCoordinator) -> None:
|
||||
"""Initialize the sensor."""
|
||||
super().__init__(coordinator)
|
||||
self._attr_unique_id = f"{coordinator.client.serial_number}_door"
|
||||
|
||||
@property
|
||||
def is_on(self) -> bool | None:
|
||||
"""Return true if door is open."""
|
||||
return self.coordinator.data.door_open
|
||||
```
|
||||
|
||||
## Device Classes
|
||||
|
||||
Common binary sensor device classes:
|
||||
|
||||
| Device Class | On Means | Off Means |
|
||||
|--------------|----------|-----------|
|
||||
| `BATTERY` | Low | Normal |
|
||||
| `BATTERY_CHARGING` | Charging | Not charging |
|
||||
| `CONNECTIVITY` | Connected | Disconnected |
|
||||
| `DOOR` | Open | Closed |
|
||||
| `GARAGE_DOOR` | Open | Closed |
|
||||
| `LOCK` | Unlocked | Locked |
|
||||
| `MOISTURE` | Wet | Dry |
|
||||
| `MOTION` | Motion detected | Clear |
|
||||
| `OCCUPANCY` | Occupied | Clear |
|
||||
| `OPENING` | Open | Closed |
|
||||
| `PLUG` | Plugged in | Unplugged |
|
||||
| `POWER` | Power detected | No power |
|
||||
| `PRESENCE` | Present | Away |
|
||||
| `PROBLEM` | Problem | OK |
|
||||
| `RUNNING` | Running | Not running |
|
||||
| `SAFETY` | Unsafe | Safe |
|
||||
| `SMOKE` | Smoke detected | Clear |
|
||||
| `SOUND` | Sound detected | Clear |
|
||||
| `TAMPER` | Tampering | Clear |
|
||||
| `UPDATE` | Update available | Up-to-date |
|
||||
| `VIBRATION` | Vibration | Clear |
|
||||
| `WINDOW` | Open | Closed |
|
||||
|
||||
## Entity Description Pattern
|
||||
|
||||
```python
|
||||
from dataclasses import dataclass
|
||||
from collections.abc import Callable
|
||||
|
||||
from homeassistant.components.binary_sensor import (
|
||||
BinarySensorDeviceClass,
|
||||
BinarySensorEntityDescription,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True, kw_only=True)
|
||||
class MyBinarySensorEntityDescription(BinarySensorEntityDescription):
|
||||
"""Describe My binary sensor entity."""
|
||||
|
||||
is_on_fn: Callable[[MyData], bool | None]
|
||||
|
||||
|
||||
BINARY_SENSORS: tuple[MyBinarySensorEntityDescription, ...] = (
|
||||
MyBinarySensorEntityDescription(
|
||||
key="door",
|
||||
translation_key="door",
|
||||
device_class=BinarySensorDeviceClass.DOOR,
|
||||
is_on_fn=lambda data: data.door_open,
|
||||
),
|
||||
MyBinarySensorEntityDescription(
|
||||
key="motion",
|
||||
translation_key="motion",
|
||||
device_class=BinarySensorDeviceClass.MOTION,
|
||||
is_on_fn=lambda data: data.motion_detected,
|
||||
),
|
||||
MyBinarySensorEntityDescription(
|
||||
key="low_battery",
|
||||
translation_key="low_battery",
|
||||
device_class=BinarySensorDeviceClass.BATTERY,
|
||||
entity_category=EntityCategory.DIAGNOSTIC,
|
||||
is_on_fn=lambda data: data.battery_level < 20 if data.battery_level else None,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
async def async_setup_entry(
|
||||
hass: HomeAssistant,
|
||||
entry: MyIntegrationConfigEntry,
|
||||
async_add_entities: AddEntitiesCallback,
|
||||
) -> None:
|
||||
"""Set up binary sensors from config entry."""
|
||||
coordinator = entry.runtime_data
|
||||
async_add_entities(
|
||||
MyBinarySensor(coordinator, description)
|
||||
for description in BINARY_SENSORS
|
||||
)
|
||||
|
||||
|
||||
class MyBinarySensor(MyEntity, BinarySensorEntity):
|
||||
"""Binary sensor using entity description."""
|
||||
|
||||
entity_description: MyBinarySensorEntityDescription
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
coordinator: MyCoordinator,
|
||||
description: MyBinarySensorEntityDescription,
|
||||
) -> None:
|
||||
"""Initialize the binary sensor."""
|
||||
super().__init__(coordinator)
|
||||
self.entity_description = description
|
||||
self._attr_unique_id = f"{coordinator.client.serial_number}_{description.key}"
|
||||
|
||||
@property
|
||||
def is_on(self) -> bool | None:
|
||||
"""Return true if the binary sensor is on."""
|
||||
return self.entity_description.is_on_fn(self.coordinator.data)
|
||||
```
|
||||
|
||||
## Connectivity Sensor
|
||||
|
||||
```python
|
||||
class ConnectivitySensor(MyEntity, BinarySensorEntity):
|
||||
"""Device connectivity sensor."""
|
||||
|
||||
_attr_device_class = BinarySensorDeviceClass.CONNECTIVITY
|
||||
_attr_entity_category = EntityCategory.DIAGNOSTIC
|
||||
_attr_translation_key = "connectivity"
|
||||
|
||||
@property
|
||||
def is_on(self) -> bool:
|
||||
"""Return true if device is connected."""
|
||||
return self.coordinator.data.is_connected
|
||||
```
|
||||
|
||||
## Problem Sensor
|
||||
|
||||
```python
|
||||
class ProblemSensor(MyEntity, BinarySensorEntity):
|
||||
"""Problem indicator sensor."""
|
||||
|
||||
_attr_device_class = BinarySensorDeviceClass.PROBLEM
|
||||
_attr_entity_category = EntityCategory.DIAGNOSTIC
|
||||
_attr_translation_key = "problem"
|
||||
|
||||
@property
|
||||
def is_on(self) -> bool:
|
||||
"""Return true if there's a problem."""
|
||||
return self.coordinator.data.has_error
|
||||
|
||||
@property
|
||||
def extra_state_attributes(self) -> dict[str, Any]:
|
||||
"""Return extra state attributes."""
|
||||
return {
|
||||
"error_code": self.coordinator.data.error_code,
|
||||
"error_message": self.coordinator.data.error_message,
|
||||
}
|
||||
```
|
||||
|
||||
## Update Available Sensor
|
||||
|
||||
```python
|
||||
class UpdateAvailableSensor(MyEntity, BinarySensorEntity):
|
||||
"""Firmware update available sensor."""
|
||||
|
||||
_attr_device_class = BinarySensorDeviceClass.UPDATE
|
||||
_attr_entity_category = EntityCategory.DIAGNOSTIC
|
||||
_attr_translation_key = "update_available"
|
||||
|
||||
@property
|
||||
def is_on(self) -> bool:
|
||||
"""Return true if an update is available."""
|
||||
return self.coordinator.data.update_available
|
||||
```
|
||||
|
||||
## Translations
|
||||
|
||||
In `strings.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"entity": {
|
||||
"binary_sensor": {
|
||||
"door": {
|
||||
"name": "Door"
|
||||
},
|
||||
"motion": {
|
||||
"name": "Motion"
|
||||
},
|
||||
"low_battery": {
|
||||
"name": "Low battery"
|
||||
},
|
||||
"connectivity": {
|
||||
"name": "Connectivity"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
201
.claude/skills/ha-integration/BUTTON.MD
Normal file
201
.claude/skills/ha-integration/BUTTON.MD
Normal file
@@ -0,0 +1,201 @@
|
||||
# Button Platform Reference
|
||||
|
||||
Button entities trigger actions when pressed.
|
||||
|
||||
## Basic Button
|
||||
|
||||
```python
|
||||
"""Button platform for My Integration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from homeassistant.components.button import ButtonDeviceClass, ButtonEntity
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
||||
|
||||
from . import MyIntegrationConfigEntry
|
||||
from .entity import MyEntity
|
||||
|
||||
|
||||
async def async_setup_entry(
|
||||
hass: HomeAssistant,
|
||||
entry: MyIntegrationConfigEntry,
|
||||
async_add_entities: AddEntitiesCallback,
|
||||
) -> None:
|
||||
"""Set up buttons from config entry."""
|
||||
coordinator = entry.runtime_data
|
||||
|
||||
async_add_entities([
|
||||
RestartButton(coordinator),
|
||||
IdentifyButton(coordinator),
|
||||
])
|
||||
|
||||
|
||||
class RestartButton(MyEntity, ButtonEntity):
|
||||
"""Restart button."""
|
||||
|
||||
_attr_device_class = ButtonDeviceClass.RESTART
|
||||
_attr_translation_key = "restart"
|
||||
|
||||
def __init__(self, coordinator: MyCoordinator) -> None:
|
||||
"""Initialize the button."""
|
||||
super().__init__(coordinator)
|
||||
self._attr_unique_id = f"{coordinator.client.serial_number}_restart"
|
||||
|
||||
async def async_press(self) -> None:
|
||||
"""Handle the button press."""
|
||||
await self.coordinator.client.restart()
|
||||
```
|
||||
|
||||
## Device Classes
|
||||
|
||||
| Device Class | Icon | Use Case |
|
||||
|--------------|------|----------|
|
||||
| `IDENTIFY` | mdi:crosshairs-question | Flash light/beep to locate device |
|
||||
| `RESTART` | mdi:restart | Restart the device |
|
||||
| `UPDATE` | mdi:package-up | Trigger firmware update |
|
||||
|
||||
## Entity Description Pattern
|
||||
|
||||
```python
|
||||
from dataclasses import dataclass
|
||||
from collections.abc import Callable, Coroutine
|
||||
from typing import Any
|
||||
|
||||
from homeassistant.components.button import ButtonDeviceClass, ButtonEntityDescription
|
||||
|
||||
|
||||
@dataclass(frozen=True, kw_only=True)
|
||||
class MyButtonEntityDescription(ButtonEntityDescription):
|
||||
"""Describe My button entity."""
|
||||
|
||||
press_fn: Callable[[MyClient], Coroutine[Any, Any, None]]
|
||||
|
||||
|
||||
BUTTONS: tuple[MyButtonEntityDescription, ...] = (
|
||||
MyButtonEntityDescription(
|
||||
key="restart",
|
||||
translation_key="restart",
|
||||
device_class=ButtonDeviceClass.RESTART,
|
||||
entity_category=EntityCategory.CONFIG,
|
||||
press_fn=lambda client: client.restart(),
|
||||
),
|
||||
MyButtonEntityDescription(
|
||||
key="identify",
|
||||
translation_key="identify",
|
||||
device_class=ButtonDeviceClass.IDENTIFY,
|
||||
entity_category=EntityCategory.CONFIG,
|
||||
press_fn=lambda client: client.identify(),
|
||||
),
|
||||
MyButtonEntityDescription(
|
||||
key="factory_reset",
|
||||
translation_key="factory_reset",
|
||||
entity_category=EntityCategory.CONFIG,
|
||||
press_fn=lambda client: client.factory_reset(),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
async def async_setup_entry(
|
||||
hass: HomeAssistant,
|
||||
entry: MyIntegrationConfigEntry,
|
||||
async_add_entities: AddEntitiesCallback,
|
||||
) -> None:
|
||||
"""Set up buttons from config entry."""
|
||||
coordinator = entry.runtime_data
|
||||
async_add_entities(
|
||||
MyButton(coordinator, description)
|
||||
for description in BUTTONS
|
||||
)
|
||||
|
||||
|
||||
class MyButton(MyEntity, ButtonEntity):
|
||||
"""Button using entity description."""
|
||||
|
||||
entity_description: MyButtonEntityDescription
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
coordinator: MyCoordinator,
|
||||
description: MyButtonEntityDescription,
|
||||
) -> None:
|
||||
"""Initialize the button."""
|
||||
super().__init__(coordinator)
|
||||
self.entity_description = description
|
||||
self._attr_unique_id = f"{coordinator.client.serial_number}_{description.key}"
|
||||
|
||||
async def async_press(self) -> None:
|
||||
"""Handle the button press."""
|
||||
await self.entity_description.press_fn(self.coordinator.client)
|
||||
```
|
||||
|
||||
## Identify Button
|
||||
|
||||
```python
|
||||
class IdentifyButton(MyEntity, ButtonEntity):
|
||||
"""Identify button to locate the device."""
|
||||
|
||||
_attr_device_class = ButtonDeviceClass.IDENTIFY
|
||||
_attr_entity_category = EntityCategory.CONFIG
|
||||
_attr_translation_key = "identify"
|
||||
|
||||
async def async_press(self) -> None:
|
||||
"""Flash the device LED to identify it."""
|
||||
await self.coordinator.client.identify()
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
```python
|
||||
from homeassistant.exceptions import HomeAssistantError
|
||||
|
||||
|
||||
class SafeButton(MyEntity, ButtonEntity):
|
||||
"""Button with error handling."""
|
||||
|
||||
async def async_press(self) -> None:
|
||||
"""Handle the button press with error handling."""
|
||||
try:
|
||||
await self.coordinator.client.perform_action()
|
||||
except MyDeviceError as err:
|
||||
raise HomeAssistantError(f"Failed to perform action: {err}") from err
|
||||
```
|
||||
|
||||
## Confirmation Buttons
|
||||
|
||||
For dangerous operations, consider using a diagnostic category and clear naming:
|
||||
|
||||
```python
|
||||
class FactoryResetButton(MyEntity, ButtonEntity):
|
||||
"""Factory reset button."""
|
||||
|
||||
_attr_entity_category = EntityCategory.DIAGNOSTIC
|
||||
_attr_translation_key = "factory_reset"
|
||||
_attr_entity_registry_enabled_default = False # Disabled by default
|
||||
|
||||
async def async_press(self) -> None:
|
||||
"""Perform factory reset."""
|
||||
await self.coordinator.client.factory_reset()
|
||||
```
|
||||
|
||||
## Translations
|
||||
|
||||
In `strings.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"entity": {
|
||||
"button": {
|
||||
"restart": {
|
||||
"name": "Restart"
|
||||
},
|
||||
"identify": {
|
||||
"name": "Identify"
|
||||
},
|
||||
"factory_reset": {
|
||||
"name": "Factory reset"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
254
.claude/skills/ha-integration/CONFIG-FLOW.MD
Normal file
254
.claude/skills/ha-integration/CONFIG-FLOW.MD
Normal file
@@ -0,0 +1,254 @@
|
||||
# Config Flow Reference
|
||||
|
||||
Configuration flows allow users to set up integrations via the UI.
|
||||
|
||||
## Basic Config Flow
|
||||
|
||||
```python
|
||||
"""Config flow for My Integration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
|
||||
from homeassistant.const import CONF_HOST, CONF_API_KEY
|
||||
from homeassistant.helpers.selector import TextSelector
|
||||
|
||||
from .const import DOMAIN
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
STEP_USER_DATA_SCHEMA = vol.Schema(
|
||||
{
|
||||
vol.Required(CONF_HOST): TextSelector(),
|
||||
vol.Required(CONF_API_KEY): TextSelector(),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
class MyIntegrationConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
"""Handle a config flow for My Integration."""
|
||||
|
||||
VERSION = 1
|
||||
MINOR_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:
|
||||
try:
|
||||
# Test connection
|
||||
client = MyClient(user_input[CONF_HOST], user_input[CONF_API_KEY])
|
||||
info = await client.get_device_info()
|
||||
except CannotConnect:
|
||||
errors["base"] = "cannot_connect"
|
||||
except InvalidAuth:
|
||||
errors["base"] = "invalid_auth"
|
||||
except Exception:
|
||||
_LOGGER.exception("Unexpected exception")
|
||||
errors["base"] = "unknown"
|
||||
else:
|
||||
# Set unique ID and abort if already configured
|
||||
await self.async_set_unique_id(info.serial_number)
|
||||
self._abort_if_unique_id_configured()
|
||||
|
||||
return self.async_create_entry(
|
||||
title=info.name,
|
||||
data=user_input,
|
||||
)
|
||||
|
||||
return self.async_show_form(
|
||||
step_id="user",
|
||||
data_schema=STEP_USER_DATA_SCHEMA,
|
||||
errors=errors,
|
||||
)
|
||||
```
|
||||
|
||||
## Version Control
|
||||
|
||||
Always set version numbers:
|
||||
|
||||
```python
|
||||
VERSION = 1 # Bump for breaking changes requiring migration
|
||||
MINOR_VERSION = 1 # Bump for backward-compatible changes
|
||||
```
|
||||
|
||||
## Unique ID Management
|
||||
|
||||
```python
|
||||
# Set unique ID and abort if exists
|
||||
await self.async_set_unique_id(device_serial)
|
||||
self._abort_if_unique_id_configured()
|
||||
|
||||
# Or abort if data matches (when no unique ID available)
|
||||
self._async_abort_entries_match({CONF_HOST: user_input[CONF_HOST]})
|
||||
```
|
||||
|
||||
## Reauthentication Flow
|
||||
|
||||
```python
|
||||
async def async_step_reauth(
|
||||
self, entry_data: Mapping[str, Any]
|
||||
) -> ConfigFlowResult:
|
||||
"""Handle reauthentication."""
|
||||
return await self.async_step_reauth_confirm()
|
||||
|
||||
async def async_step_reauth_confirm(
|
||||
self, user_input: dict[str, Any] | None = None
|
||||
) -> ConfigFlowResult:
|
||||
"""Handle reauthentication confirmation."""
|
||||
errors: dict[str, str] = {}
|
||||
|
||||
if user_input is not None:
|
||||
try:
|
||||
client = MyClient(
|
||||
self._get_reauth_entry().data[CONF_HOST],
|
||||
user_input[CONF_API_KEY]
|
||||
)
|
||||
info = await client.get_device_info()
|
||||
except InvalidAuth:
|
||||
errors["base"] = "invalid_auth"
|
||||
except Exception:
|
||||
errors["base"] = "unknown"
|
||||
else:
|
||||
await self.async_set_unique_id(info.serial_number)
|
||||
self._abort_if_unique_id_mismatch(reason="wrong_account")
|
||||
return self.async_update_reload_and_abort(
|
||||
self._get_reauth_entry(),
|
||||
data_updates={CONF_API_KEY: user_input[CONF_API_KEY]},
|
||||
)
|
||||
|
||||
return self.async_show_form(
|
||||
step_id="reauth_confirm",
|
||||
data_schema=vol.Schema({vol.Required(CONF_API_KEY): str}),
|
||||
errors=errors,
|
||||
)
|
||||
```
|
||||
|
||||
## Reconfiguration Flow
|
||||
|
||||
```python
|
||||
async def async_step_reconfigure(
|
||||
self, user_input: dict[str, Any] | None = None
|
||||
) -> ConfigFlowResult:
|
||||
"""Handle reconfiguration."""
|
||||
errors: dict[str, str] = {}
|
||||
reconfigure_entry = self._get_reconfigure_entry()
|
||||
|
||||
if user_input is not None:
|
||||
try:
|
||||
client = MyClient(user_input[CONF_HOST], reconfigure_entry.data[CONF_API_KEY])
|
||||
info = await client.get_device_info()
|
||||
except CannotConnect:
|
||||
errors["base"] = "cannot_connect"
|
||||
else:
|
||||
await self.async_set_unique_id(info.serial_number)
|
||||
self._abort_if_unique_id_mismatch(reason="wrong_device")
|
||||
return self.async_update_reload_and_abort(
|
||||
reconfigure_entry,
|
||||
data_updates={CONF_HOST: user_input[CONF_HOST]},
|
||||
)
|
||||
|
||||
return self.async_show_form(
|
||||
step_id="reconfigure",
|
||||
data_schema=vol.Schema({
|
||||
vol.Required(CONF_HOST, default=reconfigure_entry.data[CONF_HOST]): str
|
||||
}),
|
||||
errors=errors,
|
||||
)
|
||||
```
|
||||
|
||||
## Discovery Flows
|
||||
|
||||
### Zeroconf Discovery
|
||||
|
||||
```python
|
||||
async def async_step_zeroconf(
|
||||
self, discovery_info: ZeroconfServiceInfo
|
||||
) -> ConfigFlowResult:
|
||||
"""Handle zeroconf discovery."""
|
||||
serial = discovery_info.properties.get("serialno")
|
||||
if not serial:
|
||||
return self.async_abort(reason="no_serial")
|
||||
|
||||
await self.async_set_unique_id(serial)
|
||||
self._abort_if_unique_id_configured(
|
||||
updates={CONF_HOST: str(discovery_info.host)}
|
||||
)
|
||||
|
||||
self._discovered_host = str(discovery_info.host)
|
||||
self._discovered_name = discovery_info.name.removesuffix("._mydevice._tcp.local.")
|
||||
|
||||
return await self.async_step_discovery_confirm()
|
||||
|
||||
async def async_step_discovery_confirm(
|
||||
self, user_input: dict[str, Any] | None = None
|
||||
) -> ConfigFlowResult:
|
||||
"""Confirm discovery."""
|
||||
if user_input is not None:
|
||||
return self.async_create_entry(
|
||||
title=self._discovered_name,
|
||||
data={CONF_HOST: self._discovered_host},
|
||||
)
|
||||
|
||||
self._set_confirm_only()
|
||||
return self.async_show_form(
|
||||
step_id="discovery_confirm",
|
||||
description_placeholders={"name": self._discovered_name},
|
||||
)
|
||||
```
|
||||
|
||||
## strings.json for Config Flow
|
||||
|
||||
```json
|
||||
{
|
||||
"config": {
|
||||
"step": {
|
||||
"user": {
|
||||
"title": "Connect to device",
|
||||
"description": "Enter your device credentials.",
|
||||
"data": {
|
||||
"host": "Host",
|
||||
"api_key": "API key"
|
||||
}
|
||||
},
|
||||
"reauth_confirm": {
|
||||
"title": "Reauthenticate",
|
||||
"description": "Please enter a new API key for {name}.",
|
||||
"data": {
|
||||
"api_key": "API key"
|
||||
}
|
||||
},
|
||||
"discovery_confirm": {
|
||||
"title": "Discovered device",
|
||||
"description": "Do you want to set up {name}?"
|
||||
}
|
||||
},
|
||||
"error": {
|
||||
"cannot_connect": "Failed to connect",
|
||||
"invalid_auth": "Invalid authentication",
|
||||
"unknown": "Unexpected error"
|
||||
},
|
||||
"abort": {
|
||||
"already_configured": "Device is already configured",
|
||||
"wrong_account": "Wrong account",
|
||||
"wrong_device": "Wrong device"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Key Rules
|
||||
|
||||
1. **Never allow user-configurable entry names** (except helper integrations)
|
||||
2. **Always test connection** before creating entry
|
||||
3. **Always set unique ID** when possible
|
||||
4. **Handle all exceptions** - bare `except Exception:` is allowed in config flows
|
||||
5. **100% test coverage required** for all flow paths
|
||||
239
.claude/skills/ha-integration/COORDINATOR.MD
Normal file
239
.claude/skills/ha-integration/COORDINATOR.MD
Normal file
@@ -0,0 +1,239 @@
|
||||
# Data Update Coordinator Reference
|
||||
|
||||
The coordinator pattern centralizes data fetching and provides efficient polling.
|
||||
|
||||
## Basic Coordinator
|
||||
|
||||
```python
|
||||
"""DataUpdateCoordinator for My Integration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import timedelta
|
||||
import logging
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from my_library import MyClient, MyData, MyError, AuthError
|
||||
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import ConfigEntryAuthFailed
|
||||
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
|
||||
|
||||
from .const import DOMAIN
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from . import MyIntegrationConfigEntry
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class MyCoordinator(DataUpdateCoordinator[MyData]):
|
||||
"""My integration data update coordinator."""
|
||||
|
||||
config_entry: MyIntegrationConfigEntry
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
hass: HomeAssistant,
|
||||
entry: MyIntegrationConfigEntry,
|
||||
client: MyClient,
|
||||
) -> None:
|
||||
"""Initialize the coordinator."""
|
||||
super().__init__(
|
||||
hass,
|
||||
logger=_LOGGER,
|
||||
name=DOMAIN,
|
||||
update_interval=timedelta(minutes=1),
|
||||
config_entry=entry,
|
||||
)
|
||||
self.client = client
|
||||
|
||||
async def _async_update_data(self) -> MyData:
|
||||
"""Fetch data from API."""
|
||||
try:
|
||||
return await self.client.get_data()
|
||||
except AuthError as err:
|
||||
raise ConfigEntryAuthFailed("Invalid credentials") from err
|
||||
except MyError as err:
|
||||
raise UpdateFailed(f"Error communicating with API: {err}") from err
|
||||
```
|
||||
|
||||
## Key Points
|
||||
|
||||
### Always Pass config_entry
|
||||
|
||||
```python
|
||||
super().__init__(
|
||||
hass,
|
||||
logger=_LOGGER,
|
||||
name=DOMAIN,
|
||||
update_interval=timedelta(minutes=1),
|
||||
config_entry=entry, # Always include this
|
||||
)
|
||||
```
|
||||
|
||||
### Generic Type Parameter
|
||||
|
||||
Specify the data type returned by `_async_update_data`:
|
||||
|
||||
```python
|
||||
class MyCoordinator(DataUpdateCoordinator[MyData]):
|
||||
...
|
||||
```
|
||||
|
||||
### Error Types
|
||||
|
||||
- **`UpdateFailed`**: API communication errors (will retry)
|
||||
- **`ConfigEntryAuthFailed`**: Authentication issues (triggers reauth flow)
|
||||
|
||||
## Polling Intervals
|
||||
|
||||
**Integration determines intervals** - never make them user-configurable.
|
||||
|
||||
```python
|
||||
# Constants (in const.py)
|
||||
SCAN_INTERVAL_LOCAL = timedelta(seconds=30)
|
||||
SCAN_INTERVAL_CLOUD = timedelta(minutes=5)
|
||||
|
||||
# In coordinator
|
||||
class MyCoordinator(DataUpdateCoordinator[MyData]):
|
||||
def __init__(self, hass: HomeAssistant, entry: MyIntegrationConfigEntry, client: MyClient) -> None:
|
||||
# Determine interval based on connection type
|
||||
interval = SCAN_INTERVAL_LOCAL if client.is_local else SCAN_INTERVAL_CLOUD
|
||||
|
||||
super().__init__(
|
||||
hass,
|
||||
logger=_LOGGER,
|
||||
name=DOMAIN,
|
||||
update_interval=interval,
|
||||
config_entry=entry,
|
||||
)
|
||||
```
|
||||
|
||||
**Minimum intervals:**
|
||||
- Local network: 5 seconds
|
||||
- Cloud services: 60 seconds
|
||||
|
||||
## Coordinator with Device Info
|
||||
|
||||
```python
|
||||
from homeassistant.helpers.device_registry import DeviceInfo
|
||||
|
||||
from .const import DOMAIN
|
||||
|
||||
|
||||
class MyCoordinator(DataUpdateCoordinator[MyData]):
|
||||
"""Coordinator with device information."""
|
||||
|
||||
config_entry: MyIntegrationConfigEntry
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
hass: HomeAssistant,
|
||||
entry: MyIntegrationConfigEntry,
|
||||
client: MyClient,
|
||||
) -> None:
|
||||
"""Initialize the coordinator."""
|
||||
super().__init__(
|
||||
hass,
|
||||
logger=_LOGGER,
|
||||
name=DOMAIN,
|
||||
update_interval=timedelta(minutes=1),
|
||||
config_entry=entry,
|
||||
)
|
||||
self.client = client
|
||||
self.device_info = DeviceInfo(
|
||||
identifiers={(DOMAIN, client.serial_number)},
|
||||
name=client.name,
|
||||
manufacturer="My Company",
|
||||
model=client.model,
|
||||
sw_version=client.firmware_version,
|
||||
)
|
||||
|
||||
async def _async_update_data(self) -> MyData:
|
||||
"""Fetch data from API."""
|
||||
try:
|
||||
return await self.client.get_data()
|
||||
except MyError as err:
|
||||
raise UpdateFailed(f"Error communicating with API: {err}") from err
|
||||
```
|
||||
|
||||
## Multiple Data Sources
|
||||
|
||||
```python
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
@dataclass
|
||||
class MyCoordinatorData:
|
||||
"""Data class for coordinator."""
|
||||
|
||||
sensors: dict[str, SensorData]
|
||||
status: DeviceStatus
|
||||
settings: DeviceSettings
|
||||
|
||||
|
||||
class MyCoordinator(DataUpdateCoordinator[MyCoordinatorData]):
|
||||
"""Coordinator for multiple data sources."""
|
||||
|
||||
async def _async_update_data(self) -> MyCoordinatorData:
|
||||
"""Fetch all data sources."""
|
||||
try:
|
||||
# Fetch all data concurrently
|
||||
sensors, status, settings = await asyncio.gather(
|
||||
self.client.get_sensors(),
|
||||
self.client.get_status(),
|
||||
self.client.get_settings(),
|
||||
)
|
||||
except MyError as err:
|
||||
raise UpdateFailed(f"Error fetching data: {err}") from err
|
||||
|
||||
return MyCoordinatorData(
|
||||
sensors=sensors,
|
||||
status=status,
|
||||
settings=settings,
|
||||
)
|
||||
```
|
||||
|
||||
## Setup in __init__.py
|
||||
|
||||
```python
|
||||
async def async_setup_entry(hass: HomeAssistant, entry: MyIntegrationConfigEntry) -> bool:
|
||||
"""Set up My Integration from a config entry."""
|
||||
client = MyClient(entry.data[CONF_HOST], entry.data[CONF_API_KEY])
|
||||
|
||||
coordinator = MyCoordinator(hass, entry, client)
|
||||
|
||||
# Perform first refresh - raises ConfigEntryNotReady on failure
|
||||
await coordinator.async_config_entry_first_refresh()
|
||||
|
||||
entry.runtime_data = coordinator
|
||||
|
||||
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
|
||||
|
||||
return True
|
||||
```
|
||||
|
||||
## Testing Coordinators
|
||||
|
||||
```python
|
||||
@pytest.fixture
|
||||
def mock_coordinator(hass: HomeAssistant, mock_config_entry: MockConfigEntry) -> MyCoordinator:
|
||||
"""Return a mocked coordinator."""
|
||||
coordinator = MyCoordinator(hass, mock_config_entry, MagicMock())
|
||||
coordinator.data = MyData(temperature=21.5, humidity=45)
|
||||
return coordinator
|
||||
|
||||
|
||||
async def test_coordinator_update_failed(
|
||||
hass: HomeAssistant,
|
||||
mock_client: MagicMock,
|
||||
) -> None:
|
||||
"""Test coordinator handles update failure."""
|
||||
mock_client.get_data.side_effect = MyError("Connection failed")
|
||||
|
||||
coordinator = MyCoordinator(hass, mock_config_entry, mock_client)
|
||||
|
||||
with pytest.raises(UpdateFailed):
|
||||
await coordinator._async_update_data()
|
||||
```
|
||||
248
.claude/skills/ha-integration/DEVICE.MD
Normal file
248
.claude/skills/ha-integration/DEVICE.MD
Normal file
@@ -0,0 +1,248 @@
|
||||
# Device Management Reference
|
||||
|
||||
Device management groups entities and provides device information.
|
||||
|
||||
## Device Info
|
||||
|
||||
```python
|
||||
from homeassistant.helpers.device_registry import DeviceInfo
|
||||
|
||||
from .const import DOMAIN
|
||||
|
||||
|
||||
class MyEntity(CoordinatorEntity[MyCoordinator]):
|
||||
"""Base entity with device info."""
|
||||
|
||||
_attr_has_entity_name = True
|
||||
|
||||
def __init__(self, coordinator: MyCoordinator) -> None:
|
||||
"""Initialize the entity."""
|
||||
super().__init__(coordinator)
|
||||
self._attr_device_info = DeviceInfo(
|
||||
identifiers={(DOMAIN, coordinator.client.serial_number)},
|
||||
name=coordinator.client.name,
|
||||
manufacturer="My Company",
|
||||
model=coordinator.client.model,
|
||||
sw_version=coordinator.client.firmware_version,
|
||||
hw_version=coordinator.client.hardware_version,
|
||||
)
|
||||
```
|
||||
|
||||
## DeviceInfo Fields
|
||||
|
||||
| Field | Description | Example |
|
||||
|-------|-------------|---------|
|
||||
| `identifiers` | Set of (domain, id) tuples | `{(DOMAIN, "ABC123")}` |
|
||||
| `connections` | Set of (type, id) tuples | `{(CONNECTION_NETWORK_MAC, mac)}` |
|
||||
| `name` | Device name | `"Living Room Thermostat"` |
|
||||
| `manufacturer` | Manufacturer name | `"My Company"` |
|
||||
| `model` | Model name | `"Smart Thermostat v2"` |
|
||||
| `model_id` | Model identifier | `"THM-2000"` |
|
||||
| `sw_version` | Software/firmware version | `"1.2.3"` |
|
||||
| `hw_version` | Hardware version | `"rev2"` |
|
||||
| `serial_number` | Serial number | `"ABC123456"` |
|
||||
| `configuration_url` | Device config URL | `"http://192.168.1.100"` |
|
||||
| `suggested_area` | Suggested room/area | `"Living Room"` |
|
||||
| `entry_type` | Device entry type | `DeviceEntryType.SERVICE` |
|
||||
| `via_device` | Parent device identifiers | `(DOMAIN, "hub_id")` |
|
||||
|
||||
## Device with Connections
|
||||
|
||||
Use connections (like MAC address) for better device merging:
|
||||
|
||||
```python
|
||||
from homeassistant.helpers.device_registry import (
|
||||
CONNECTION_NETWORK_MAC,
|
||||
DeviceInfo,
|
||||
format_mac,
|
||||
)
|
||||
|
||||
|
||||
def __init__(self, coordinator: MyCoordinator) -> None:
|
||||
"""Initialize the entity."""
|
||||
super().__init__(coordinator)
|
||||
self._attr_device_info = DeviceInfo(
|
||||
connections={(CONNECTION_NETWORK_MAC, format_mac(coordinator.client.mac))},
|
||||
identifiers={(DOMAIN, coordinator.client.serial_number)},
|
||||
name=coordinator.client.name,
|
||||
manufacturer="My Company",
|
||||
model=coordinator.client.model,
|
||||
)
|
||||
```
|
||||
|
||||
## Hub and Child Devices
|
||||
|
||||
```python
|
||||
# Hub device
|
||||
class HubEntity(CoordinatorEntity[MyCoordinator]):
|
||||
"""Hub entity."""
|
||||
|
||||
def __init__(self, coordinator: MyCoordinator) -> None:
|
||||
"""Initialize the hub entity."""
|
||||
super().__init__(coordinator)
|
||||
self._attr_device_info = DeviceInfo(
|
||||
identifiers={(DOMAIN, coordinator.hub_id)},
|
||||
name="My Hub",
|
||||
manufacturer="My Company",
|
||||
model="Hub Pro",
|
||||
)
|
||||
|
||||
|
||||
# Child device connected via hub
|
||||
class ChildEntity(CoordinatorEntity[MyCoordinator]):
|
||||
"""Child device entity."""
|
||||
|
||||
def __init__(self, coordinator: MyCoordinator, device: ChildDevice) -> None:
|
||||
"""Initialize the child entity."""
|
||||
super().__init__(coordinator)
|
||||
self._attr_device_info = DeviceInfo(
|
||||
identifiers={(DOMAIN, device.id)},
|
||||
name=device.name,
|
||||
manufacturer="My Company",
|
||||
model=device.model,
|
||||
via_device=(DOMAIN, coordinator.hub_id), # Links to parent hub
|
||||
)
|
||||
```
|
||||
|
||||
## Service Entry Type
|
||||
|
||||
For cloud services without physical devices:
|
||||
|
||||
```python
|
||||
from homeassistant.helpers.device_registry import DeviceEntryType, DeviceInfo
|
||||
|
||||
|
||||
self._attr_device_info = DeviceInfo(
|
||||
identifiers={(DOMAIN, entry.entry_id)},
|
||||
name="My Cloud Service",
|
||||
manufacturer="My Company",
|
||||
entry_type=DeviceEntryType.SERVICE,
|
||||
)
|
||||
```
|
||||
|
||||
## Dynamic Device Addition
|
||||
|
||||
Auto-detect new devices after initial setup:
|
||||
|
||||
```python
|
||||
async def async_setup_entry(
|
||||
hass: HomeAssistant,
|
||||
entry: MyIntegrationConfigEntry,
|
||||
async_add_entities: AddEntitiesCallback,
|
||||
) -> None:
|
||||
"""Set up sensors from config entry."""
|
||||
coordinator = entry.runtime_data
|
||||
known_devices: set[str] = set()
|
||||
|
||||
@callback
|
||||
def _check_devices() -> None:
|
||||
"""Check for new devices."""
|
||||
current_devices = set(coordinator.data.devices.keys())
|
||||
new_devices = current_devices - known_devices
|
||||
|
||||
if new_devices:
|
||||
known_devices.update(new_devices)
|
||||
async_add_entities(
|
||||
MySensor(coordinator, device_id)
|
||||
for device_id in new_devices
|
||||
)
|
||||
|
||||
# Initial setup
|
||||
_check_devices()
|
||||
|
||||
# Listen for updates
|
||||
entry.async_on_unload(coordinator.async_add_listener(_check_devices))
|
||||
```
|
||||
|
||||
## Stale Device Removal
|
||||
|
||||
Remove devices when they disappear:
|
||||
|
||||
```python
|
||||
async def _async_update_data(self) -> MyData:
|
||||
"""Fetch data and handle device removal."""
|
||||
data = await self.client.get_data()
|
||||
|
||||
# Check for removed devices
|
||||
device_registry = dr.async_get(self.hass)
|
||||
current_device_ids = set(data.devices.keys())
|
||||
|
||||
for device_entry in dr.async_entries_for_config_entry(
|
||||
device_registry, self.config_entry.entry_id
|
||||
):
|
||||
# Get device ID from identifiers
|
||||
device_id = next(
|
||||
(id for domain, id in device_entry.identifiers if domain == DOMAIN),
|
||||
None,
|
||||
)
|
||||
|
||||
if device_id and device_id not in current_device_ids:
|
||||
# Device no longer exists, remove it
|
||||
device_registry.async_update_device(
|
||||
device_entry.id,
|
||||
remove_config_entry_id=self.config_entry.entry_id,
|
||||
)
|
||||
|
||||
return data
|
||||
```
|
||||
|
||||
## Manual Device Removal
|
||||
|
||||
Allow users to manually remove devices:
|
||||
|
||||
```python
|
||||
# In __init__.py
|
||||
|
||||
async def async_remove_config_entry_device(
|
||||
hass: HomeAssistant, config_entry: MyIntegrationConfigEntry, device_entry: dr.DeviceEntry
|
||||
) -> bool:
|
||||
"""Remove a config entry from a device."""
|
||||
# Get device ID from identifiers
|
||||
device_id = next(
|
||||
(id for domain, id in device_entry.identifiers if domain == DOMAIN),
|
||||
None,
|
||||
)
|
||||
|
||||
if device_id is None:
|
||||
return False
|
||||
|
||||
# Check if device is still present (don't allow removal of active devices)
|
||||
coordinator = config_entry.runtime_data
|
||||
if device_id in coordinator.data.devices:
|
||||
return False # Device still exists, can't remove
|
||||
|
||||
return True # Allow removal of stale device
|
||||
```
|
||||
|
||||
## Device Registry Access
|
||||
|
||||
```python
|
||||
from homeassistant.helpers import device_registry as dr
|
||||
|
||||
|
||||
# Get device registry
|
||||
device_registry = dr.async_get(hass)
|
||||
|
||||
# Get device by identifiers
|
||||
device = device_registry.async_get_device(
|
||||
identifiers={(DOMAIN, device_id)}
|
||||
)
|
||||
|
||||
# Get all devices for config entry
|
||||
devices = dr.async_entries_for_config_entry(
|
||||
device_registry, entry.entry_id
|
||||
)
|
||||
|
||||
# Update device
|
||||
device_registry.async_update_device(
|
||||
device.id,
|
||||
sw_version="2.0.0",
|
||||
)
|
||||
```
|
||||
|
||||
## Quality Scale Requirements
|
||||
|
||||
- **Bronze**: No specific device requirements
|
||||
- **Gold**: Devices rule - group entities under devices
|
||||
- **Gold**: Stale device removal - auto-remove disconnected devices
|
||||
- **Gold**: Dynamic device addition - detect new devices at runtime
|
||||
278
.claude/skills/ha-integration/DIAGNOSTICS.MD
Normal file
278
.claude/skills/ha-integration/DIAGNOSTICS.MD
Normal file
@@ -0,0 +1,278 @@
|
||||
# Diagnostics Reference
|
||||
|
||||
Diagnostics provide debug information for troubleshooting integrations.
|
||||
|
||||
## Basic Diagnostics
|
||||
|
||||
```python
|
||||
"""Diagnostics support for My Integration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from homeassistant.components.diagnostics import async_redact_data
|
||||
from homeassistant.const import CONF_API_KEY, CONF_PASSWORD, CONF_TOKEN
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
from . import MyIntegrationConfigEntry
|
||||
|
||||
TO_REDACT = {
|
||||
CONF_API_KEY,
|
||||
CONF_PASSWORD,
|
||||
CONF_TOKEN,
|
||||
"serial_number",
|
||||
"mac_address",
|
||||
"latitude",
|
||||
"longitude",
|
||||
}
|
||||
|
||||
|
||||
async def async_get_config_entry_diagnostics(
|
||||
hass: HomeAssistant, entry: MyIntegrationConfigEntry
|
||||
) -> dict[str, Any]:
|
||||
"""Return diagnostics for a config entry."""
|
||||
coordinator = entry.runtime_data
|
||||
|
||||
return {
|
||||
"entry_data": async_redact_data(dict(entry.data), TO_REDACT),
|
||||
"entry_options": async_redact_data(dict(entry.options), TO_REDACT),
|
||||
"coordinator_data": async_redact_data(
|
||||
coordinator.data.to_dict(), TO_REDACT
|
||||
),
|
||||
}
|
||||
```
|
||||
|
||||
## What to Include
|
||||
|
||||
**Do include:**
|
||||
- Configuration data (redacted)
|
||||
- Current coordinator data
|
||||
- Device information
|
||||
- Error states and counts
|
||||
- Connection status
|
||||
- Firmware versions
|
||||
- Feature flags
|
||||
|
||||
**Never include (always redact):**
|
||||
- API keys, tokens, passwords
|
||||
- Geographic coordinates (latitude/longitude)
|
||||
- Personal identifiable information
|
||||
- Email addresses
|
||||
- MAC addresses (unless needed for debugging)
|
||||
- Serial numbers (unless needed for debugging)
|
||||
|
||||
## Comprehensive Diagnostics
|
||||
|
||||
```python
|
||||
"""Diagnostics support for My Integration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from homeassistant.components.diagnostics import async_redact_data
|
||||
from homeassistant.const import (
|
||||
CONF_API_KEY,
|
||||
CONF_LATITUDE,
|
||||
CONF_LONGITUDE,
|
||||
CONF_PASSWORD,
|
||||
CONF_TOKEN,
|
||||
CONF_USERNAME,
|
||||
)
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers import device_registry as dr, entity_registry as er
|
||||
|
||||
from . import MyIntegrationConfigEntry
|
||||
from .const import DOMAIN
|
||||
|
||||
TO_REDACT = {
|
||||
CONF_API_KEY,
|
||||
CONF_LATITUDE,
|
||||
CONF_LONGITUDE,
|
||||
CONF_PASSWORD,
|
||||
CONF_TOKEN,
|
||||
CONF_USERNAME,
|
||||
"serial",
|
||||
"serial_number",
|
||||
"mac",
|
||||
"mac_address",
|
||||
"email",
|
||||
"access_token",
|
||||
"refresh_token",
|
||||
}
|
||||
|
||||
|
||||
async def async_get_config_entry_diagnostics(
|
||||
hass: HomeAssistant, entry: MyIntegrationConfigEntry
|
||||
) -> dict[str, Any]:
|
||||
"""Return diagnostics for a config entry."""
|
||||
coordinator = entry.runtime_data
|
||||
|
||||
# Get device registry entries
|
||||
device_registry = dr.async_get(hass)
|
||||
entity_registry = er.async_get(hass)
|
||||
|
||||
devices = []
|
||||
for device in dr.async_entries_for_config_entry(device_registry, entry.entry_id):
|
||||
entities = []
|
||||
for entity in er.async_entries_for_device(
|
||||
entity_registry, device.id, include_disabled_entities=True
|
||||
):
|
||||
entities.append({
|
||||
"entity_id": entity.entity_id,
|
||||
"unique_id": entity.unique_id,
|
||||
"platform": entity.platform,
|
||||
"disabled": entity.disabled,
|
||||
"disabled_by": entity.disabled_by,
|
||||
})
|
||||
|
||||
devices.append({
|
||||
"name": device.name,
|
||||
"model": device.model,
|
||||
"manufacturer": device.manufacturer,
|
||||
"sw_version": device.sw_version,
|
||||
"hw_version": device.hw_version,
|
||||
"identifiers": list(device.identifiers),
|
||||
"connections": list(device.connections),
|
||||
"entities": entities,
|
||||
})
|
||||
|
||||
return {
|
||||
"entry": {
|
||||
"version": entry.version,
|
||||
"minor_version": entry.minor_version,
|
||||
"data": async_redact_data(dict(entry.data), TO_REDACT),
|
||||
"options": async_redact_data(dict(entry.options), TO_REDACT),
|
||||
},
|
||||
"coordinator": {
|
||||
"last_update_success": coordinator.last_update_success,
|
||||
"last_exception": str(coordinator.last_exception) if coordinator.last_exception else None,
|
||||
"data": async_redact_data(coordinator.data.to_dict(), TO_REDACT),
|
||||
},
|
||||
"devices": devices,
|
||||
}
|
||||
```
|
||||
|
||||
## Device-Level Diagnostics
|
||||
|
||||
For integrations with multiple devices, you can also provide device-level diagnostics:
|
||||
|
||||
```python
|
||||
async def async_get_device_diagnostics(
|
||||
hass: HomeAssistant, entry: MyIntegrationConfigEntry, device: dr.DeviceEntry
|
||||
) -> dict[str, Any]:
|
||||
"""Return diagnostics for a device."""
|
||||
coordinator = entry.runtime_data
|
||||
|
||||
# Find device data based on device identifiers
|
||||
device_id = next(
|
||||
(id for domain, id in device.identifiers if domain == DOMAIN), None
|
||||
)
|
||||
|
||||
if device_id is None:
|
||||
return {"error": "Device not found"}
|
||||
|
||||
device_data = coordinator.data.devices.get(device_id)
|
||||
if device_data is None:
|
||||
return {"error": "Device data not found"}
|
||||
|
||||
return {
|
||||
"device_info": {
|
||||
"name": device.name,
|
||||
"model": device.model,
|
||||
"sw_version": device.sw_version,
|
||||
},
|
||||
"device_data": async_redact_data(device_data.to_dict(), TO_REDACT),
|
||||
}
|
||||
```
|
||||
|
||||
## Redaction Patterns
|
||||
|
||||
### Simple Redaction
|
||||
|
||||
```python
|
||||
from homeassistant.components.diagnostics import async_redact_data
|
||||
|
||||
data = {"api_key": "secret123", "temperature": 21.5}
|
||||
redacted = async_redact_data(data, {"api_key"})
|
||||
# Result: {"api_key": "**REDACTED**", "temperature": 21.5}
|
||||
```
|
||||
|
||||
### Nested Redaction
|
||||
|
||||
`async_redact_data` handles nested dictionaries automatically:
|
||||
|
||||
```python
|
||||
data = {
|
||||
"config": {
|
||||
"host": "192.168.1.1",
|
||||
"api_key": "secret123",
|
||||
},
|
||||
"device": {
|
||||
"name": "My Device",
|
||||
"serial_number": "ABC123",
|
||||
}
|
||||
}
|
||||
redacted = async_redact_data(data, {"api_key", "serial_number"})
|
||||
# Result: {"config": {"host": "192.168.1.1", "api_key": "**REDACTED**"},
|
||||
# "device": {"name": "My Device", "serial_number": "**REDACTED**"}}
|
||||
```
|
||||
|
||||
### Custom Redaction
|
||||
|
||||
For complex redaction needs:
|
||||
|
||||
```python
|
||||
def _redact_data(data: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Redact sensitive data."""
|
||||
result = dict(data)
|
||||
|
||||
# Redact specific keys
|
||||
for key in ("api_key", "token", "password"):
|
||||
if key in result:
|
||||
result[key] = "**REDACTED**"
|
||||
|
||||
# Redact partial data (e.g., keep last 4 chars)
|
||||
if "serial" in result:
|
||||
result["serial"] = f"****{result['serial'][-4:]}"
|
||||
|
||||
# Redact coordinates to city level
|
||||
if "latitude" in result:
|
||||
result["latitude"] = round(result["latitude"], 1)
|
||||
if "longitude" in result:
|
||||
result["longitude"] = round(result["longitude"], 1)
|
||||
|
||||
return result
|
||||
```
|
||||
|
||||
## Testing Diagnostics
|
||||
|
||||
```python
|
||||
from homeassistant.components.diagnostics import REDACTED
|
||||
|
||||
from custom_components.my_integration.diagnostics import (
|
||||
async_get_config_entry_diagnostics,
|
||||
)
|
||||
|
||||
|
||||
async def test_diagnostics(
|
||||
hass: HomeAssistant,
|
||||
init_integration: MockConfigEntry,
|
||||
) -> None:
|
||||
"""Test diagnostics."""
|
||||
diagnostics = await async_get_config_entry_diagnostics(hass, init_integration)
|
||||
|
||||
assert diagnostics["entry"]["data"]["host"] == "192.168.1.1"
|
||||
assert diagnostics["entry"]["data"]["api_key"] == REDACTED
|
||||
assert "temperature" in diagnostics["coordinator"]["data"]
|
||||
```
|
||||
|
||||
## Quality Scale Requirement
|
||||
|
||||
Diagnostics are required for **Gold** quality scale and above. Ensure your `quality_scale.yaml` includes:
|
||||
|
||||
```yaml
|
||||
rules:
|
||||
diagnostics: done
|
||||
```
|
||||
286
.claude/skills/ha-integration/ENTITY.MD
Normal file
286
.claude/skills/ha-integration/ENTITY.MD
Normal file
@@ -0,0 +1,286 @@
|
||||
# Entity Development Reference
|
||||
|
||||
Base patterns for entity development in Home Assistant.
|
||||
|
||||
## Base Entity Class
|
||||
|
||||
Create a shared base class to reduce duplication:
|
||||
|
||||
```python
|
||||
"""Base entity for My Integration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from homeassistant.helpers.device_registry import DeviceInfo
|
||||
from homeassistant.helpers.update_coordinator import CoordinatorEntity
|
||||
|
||||
from .const import DOMAIN
|
||||
from .coordinator import MyCoordinator
|
||||
|
||||
|
||||
class MyEntity(CoordinatorEntity[MyCoordinator]):
|
||||
"""Base entity for My Integration."""
|
||||
|
||||
_attr_has_entity_name = True
|
||||
|
||||
def __init__(self, coordinator: MyCoordinator) -> None:
|
||||
"""Initialize the entity."""
|
||||
super().__init__(coordinator)
|
||||
self._attr_device_info = coordinator.device_info
|
||||
```
|
||||
|
||||
## Unique IDs
|
||||
|
||||
Every entity must have a unique ID:
|
||||
|
||||
```python
|
||||
class MySensor(MyEntity, SensorEntity):
|
||||
"""Sensor entity."""
|
||||
|
||||
def __init__(self, coordinator: MyCoordinator, sensor_type: str) -> None:
|
||||
"""Initialize the sensor."""
|
||||
super().__init__(coordinator)
|
||||
# Unique per platform, don't include domain or platform name
|
||||
self._attr_unique_id = f"{coordinator.client.serial_number}_{sensor_type}"
|
||||
```
|
||||
|
||||
**Acceptable unique ID sources:**
|
||||
- Device serial numbers
|
||||
- MAC addresses (use `format_mac` from device registry)
|
||||
- Physical identifiers
|
||||
|
||||
**Never use:**
|
||||
- IP addresses, hostnames, URLs
|
||||
- Device names
|
||||
- Email addresses, usernames
|
||||
|
||||
## Entity Naming
|
||||
|
||||
```python
|
||||
class MySensor(MyEntity, SensorEntity):
|
||||
"""Sensor with proper naming."""
|
||||
|
||||
_attr_has_entity_name = True
|
||||
_attr_translation_key = "temperature" # Translatable name
|
||||
|
||||
def __init__(self, coordinator: MyCoordinator) -> None:
|
||||
"""Initialize the sensor."""
|
||||
super().__init__(coordinator)
|
||||
# For the main/primary entity of a device, use None
|
||||
# self._attr_name = None
|
||||
|
||||
# For secondary entities, set the name
|
||||
self._attr_name = "Temperature" # Or use translation_key
|
||||
```
|
||||
|
||||
## Entity Translations
|
||||
|
||||
In `strings.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"entity": {
|
||||
"sensor": {
|
||||
"temperature": {
|
||||
"name": "Temperature"
|
||||
},
|
||||
"humidity": {
|
||||
"name": "Humidity"
|
||||
},
|
||||
"battery": {
|
||||
"name": "Battery",
|
||||
"state": {
|
||||
"charging": "Charging",
|
||||
"discharging": "Discharging"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Entity Availability
|
||||
|
||||
### Coordinator Pattern
|
||||
|
||||
```python
|
||||
@property
|
||||
def available(self) -> bool:
|
||||
"""Return if entity is available."""
|
||||
return super().available and self._sensor_key in self.coordinator.data.sensors
|
||||
```
|
||||
|
||||
### Direct Update Pattern
|
||||
|
||||
```python
|
||||
async def async_update(self) -> None:
|
||||
"""Update entity state."""
|
||||
try:
|
||||
data = await self.client.get_data()
|
||||
except MyException:
|
||||
self._attr_available = False
|
||||
return
|
||||
|
||||
self._attr_available = True
|
||||
self._attr_native_value = data.value
|
||||
```
|
||||
|
||||
## Entity Categories
|
||||
|
||||
```python
|
||||
from homeassistant.const import EntityCategory
|
||||
|
||||
|
||||
class DiagnosticSensor(MyEntity, SensorEntity):
|
||||
"""Diagnostic sensor (hidden by default in UI)."""
|
||||
|
||||
_attr_entity_category = EntityCategory.DIAGNOSTIC
|
||||
|
||||
|
||||
class ConfigSwitch(MyEntity, SwitchEntity):
|
||||
"""Configuration switch."""
|
||||
|
||||
_attr_entity_category = EntityCategory.CONFIG
|
||||
```
|
||||
|
||||
## Disabled by Default
|
||||
|
||||
For noisy or less popular entities:
|
||||
|
||||
```python
|
||||
class SignalStrengthSensor(MyEntity, SensorEntity):
|
||||
"""Signal strength sensor - disabled by default."""
|
||||
|
||||
_attr_entity_registry_enabled_default = False
|
||||
```
|
||||
|
||||
## Event Lifecycle
|
||||
|
||||
```python
|
||||
class MyEntity(CoordinatorEntity[MyCoordinator]):
|
||||
"""Entity with event subscriptions."""
|
||||
|
||||
async def async_added_to_hass(self) -> None:
|
||||
"""Subscribe to events when added."""
|
||||
await super().async_added_to_hass()
|
||||
self.async_on_remove(
|
||||
self.coordinator.client.events.subscribe(
|
||||
"state_changed",
|
||||
self._handle_state_change,
|
||||
)
|
||||
)
|
||||
|
||||
@callback
|
||||
def _handle_state_change(self, event: Event) -> None:
|
||||
"""Handle state change event."""
|
||||
self._attr_native_value = event.value
|
||||
self.async_write_ha_state()
|
||||
```
|
||||
|
||||
**Key rules:**
|
||||
- Subscribe in `async_added_to_hass`
|
||||
- Use `async_on_remove` for automatic cleanup
|
||||
- Never subscribe in `__init__`
|
||||
|
||||
## State Handling
|
||||
|
||||
```python
|
||||
@property
|
||||
def native_value(self) -> StateType:
|
||||
"""Return the state."""
|
||||
value = self.coordinator.data.get(self._key)
|
||||
# Use None for unknown values, never "unknown" or "unavailable" strings
|
||||
if value is None:
|
||||
return None
|
||||
return value
|
||||
```
|
||||
|
||||
## Extra State Attributes
|
||||
|
||||
```python
|
||||
@property
|
||||
def extra_state_attributes(self) -> dict[str, Any]:
|
||||
"""Return extra state attributes."""
|
||||
data = self.coordinator.data
|
||||
# All keys must always be present, use None for unknown
|
||||
return {
|
||||
"last_updated": data.last_updated,
|
||||
"error_count": data.error_count,
|
||||
"firmware": data.firmware or None, # Never omit keys
|
||||
}
|
||||
```
|
||||
|
||||
## Entity Descriptions Pattern
|
||||
|
||||
For multiple similar entities:
|
||||
|
||||
```python
|
||||
from dataclasses import dataclass
|
||||
from collections.abc import Callable
|
||||
|
||||
from homeassistant.components.sensor import SensorEntityDescription
|
||||
|
||||
|
||||
@dataclass(frozen=True, kw_only=True)
|
||||
class MySensorEntityDescription(SensorEntityDescription):
|
||||
"""Describe My sensor entity."""
|
||||
|
||||
value_fn: Callable[[MyData], StateType]
|
||||
|
||||
|
||||
SENSOR_DESCRIPTIONS: tuple[MySensorEntityDescription, ...] = (
|
||||
MySensorEntityDescription(
|
||||
key="temperature",
|
||||
translation_key="temperature",
|
||||
native_unit_of_measurement=UnitOfTemperature.CELSIUS,
|
||||
device_class=SensorDeviceClass.TEMPERATURE,
|
||||
state_class=SensorStateClass.MEASUREMENT,
|
||||
value_fn=lambda data: data.temperature,
|
||||
),
|
||||
MySensorEntityDescription(
|
||||
key="humidity",
|
||||
translation_key="humidity",
|
||||
native_unit_of_measurement=PERCENTAGE,
|
||||
device_class=SensorDeviceClass.HUMIDITY,
|
||||
state_class=SensorStateClass.MEASUREMENT,
|
||||
value_fn=lambda data: data.humidity,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class MySensor(MyEntity, SensorEntity):
|
||||
"""Sensor using entity description."""
|
||||
|
||||
entity_description: MySensorEntityDescription
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
coordinator: MyCoordinator,
|
||||
description: MySensorEntityDescription,
|
||||
) -> None:
|
||||
"""Initialize the sensor."""
|
||||
super().__init__(coordinator)
|
||||
self.entity_description = description
|
||||
self._attr_unique_id = f"{coordinator.client.serial_number}_{description.key}"
|
||||
|
||||
@property
|
||||
def native_value(self) -> StateType:
|
||||
"""Return the sensor value."""
|
||||
return self.entity_description.value_fn(self.coordinator.data)
|
||||
```
|
||||
|
||||
## Multiline Lambdas
|
||||
|
||||
When lambdas are too long:
|
||||
|
||||
```python
|
||||
# Good pattern - parentheses on same line as lambda
|
||||
MySensorEntityDescription(
|
||||
key="temperature",
|
||||
value_fn=lambda data: (
|
||||
round(data["temp_value"] * 1.8 + 32, 1)
|
||||
if data.get("temp_value") is not None
|
||||
else None
|
||||
),
|
||||
)
|
||||
```
|
||||
229
.claude/skills/ha-integration/NUMBER.MD
Normal file
229
.claude/skills/ha-integration/NUMBER.MD
Normal file
@@ -0,0 +1,229 @@
|
||||
# Number Platform Reference
|
||||
|
||||
Number entities represent numeric values that can be set.
|
||||
|
||||
## Basic Number
|
||||
|
||||
```python
|
||||
"""Number platform for My Integration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from homeassistant.components.number import NumberEntity, NumberMode
|
||||
from homeassistant.const import UnitOfTemperature
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
||||
|
||||
from . import MyIntegrationConfigEntry
|
||||
from .entity import MyEntity
|
||||
|
||||
|
||||
async def async_setup_entry(
|
||||
hass: HomeAssistant,
|
||||
entry: MyIntegrationConfigEntry,
|
||||
async_add_entities: AddEntitiesCallback,
|
||||
) -> None:
|
||||
"""Set up numbers from config entry."""
|
||||
coordinator = entry.runtime_data
|
||||
|
||||
async_add_entities([
|
||||
TargetTemperatureNumber(coordinator),
|
||||
])
|
||||
|
||||
|
||||
class TargetTemperatureNumber(MyEntity, NumberEntity):
|
||||
"""Target temperature number entity."""
|
||||
|
||||
_attr_native_min_value = 16
|
||||
_attr_native_max_value = 30
|
||||
_attr_native_step = 0.5
|
||||
_attr_native_unit_of_measurement = UnitOfTemperature.CELSIUS
|
||||
_attr_mode = NumberMode.SLIDER
|
||||
_attr_translation_key = "target_temperature"
|
||||
|
||||
def __init__(self, coordinator: MyCoordinator) -> None:
|
||||
"""Initialize the number entity."""
|
||||
super().__init__(coordinator)
|
||||
self._attr_unique_id = f"{coordinator.client.serial_number}_target_temp"
|
||||
|
||||
@property
|
||||
def native_value(self) -> float | None:
|
||||
"""Return the current value."""
|
||||
return self.coordinator.data.target_temperature
|
||||
|
||||
async def async_set_native_value(self, value: float) -> None:
|
||||
"""Set the target temperature."""
|
||||
await self.coordinator.client.set_target_temperature(value)
|
||||
await self.coordinator.async_request_refresh()
|
||||
```
|
||||
|
||||
## Number Modes
|
||||
|
||||
```python
|
||||
from homeassistant.components.number import NumberMode
|
||||
|
||||
# Slider display in UI
|
||||
_attr_mode = NumberMode.SLIDER
|
||||
|
||||
# Input box display in UI
|
||||
_attr_mode = NumberMode.BOX
|
||||
|
||||
# Auto (slider if range <= 256, else box)
|
||||
_attr_mode = NumberMode.AUTO
|
||||
```
|
||||
|
||||
## Device Classes
|
||||
|
||||
```python
|
||||
from homeassistant.components.number import NumberDeviceClass
|
||||
|
||||
# For temperature settings
|
||||
_attr_device_class = NumberDeviceClass.TEMPERATURE
|
||||
|
||||
# Other device classes
|
||||
NumberDeviceClass.HUMIDITY
|
||||
NumberDeviceClass.POWER
|
||||
NumberDeviceClass.VOLTAGE
|
||||
NumberDeviceClass.CURRENT
|
||||
```
|
||||
|
||||
## Entity Description Pattern
|
||||
|
||||
```python
|
||||
from dataclasses import dataclass
|
||||
from collections.abc import Callable, Coroutine
|
||||
from typing import Any
|
||||
|
||||
from homeassistant.components.number import NumberEntityDescription, NumberMode
|
||||
|
||||
|
||||
@dataclass(frozen=True, kw_only=True)
|
||||
class MyNumberEntityDescription(NumberEntityDescription):
|
||||
"""Describe My number entity."""
|
||||
|
||||
value_fn: Callable[[MyData], float | None]
|
||||
set_value_fn: Callable[[MyClient, float], Coroutine[Any, Any, None]]
|
||||
|
||||
|
||||
NUMBERS: tuple[MyNumberEntityDescription, ...] = (
|
||||
MyNumberEntityDescription(
|
||||
key="target_temperature",
|
||||
translation_key="target_temperature",
|
||||
native_min_value=16,
|
||||
native_max_value=30,
|
||||
native_step=0.5,
|
||||
native_unit_of_measurement=UnitOfTemperature.CELSIUS,
|
||||
mode=NumberMode.SLIDER,
|
||||
value_fn=lambda data: data.target_temperature,
|
||||
set_value_fn=lambda client, value: client.set_target_temperature(value),
|
||||
),
|
||||
MyNumberEntityDescription(
|
||||
key="brightness",
|
||||
translation_key="brightness",
|
||||
native_min_value=0,
|
||||
native_max_value=100,
|
||||
native_step=1,
|
||||
native_unit_of_measurement=PERCENTAGE,
|
||||
mode=NumberMode.SLIDER,
|
||||
entity_category=EntityCategory.CONFIG,
|
||||
value_fn=lambda data: data.brightness,
|
||||
set_value_fn=lambda client, value: client.set_brightness(int(value)),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class MyNumber(MyEntity, NumberEntity):
|
||||
"""Number using entity description."""
|
||||
|
||||
entity_description: MyNumberEntityDescription
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
coordinator: MyCoordinator,
|
||||
description: MyNumberEntityDescription,
|
||||
) -> None:
|
||||
"""Initialize the number entity."""
|
||||
super().__init__(coordinator)
|
||||
self.entity_description = description
|
||||
self._attr_unique_id = f"{coordinator.client.serial_number}_{description.key}"
|
||||
|
||||
@property
|
||||
def native_value(self) -> float | None:
|
||||
"""Return the current value."""
|
||||
return self.entity_description.value_fn(self.coordinator.data)
|
||||
|
||||
async def async_set_native_value(self, value: float) -> None:
|
||||
"""Set the value."""
|
||||
await self.entity_description.set_value_fn(self.coordinator.client, value)
|
||||
await self.coordinator.async_request_refresh()
|
||||
```
|
||||
|
||||
## Dynamic Min/Max Values
|
||||
|
||||
```python
|
||||
class DynamicRangeNumber(MyEntity, NumberEntity):
|
||||
"""Number with dynamic range based on device capabilities."""
|
||||
|
||||
_attr_translation_key = "fan_speed"
|
||||
|
||||
@property
|
||||
def native_min_value(self) -> float:
|
||||
"""Return minimum value."""
|
||||
return self.coordinator.data.fan_speed_min
|
||||
|
||||
@property
|
||||
def native_max_value(self) -> float:
|
||||
"""Return maximum value."""
|
||||
return self.coordinator.data.fan_speed_max
|
||||
|
||||
@property
|
||||
def native_step(self) -> float:
|
||||
"""Return step value."""
|
||||
return self.coordinator.data.fan_speed_step or 1
|
||||
```
|
||||
|
||||
## Configuration Number
|
||||
|
||||
```python
|
||||
class ConfigNumber(MyEntity, NumberEntity):
|
||||
"""Configuration number entity."""
|
||||
|
||||
_attr_entity_category = EntityCategory.CONFIG
|
||||
_attr_native_min_value = 1
|
||||
_attr_native_max_value = 60
|
||||
_attr_native_step = 1
|
||||
_attr_native_unit_of_measurement = "min"
|
||||
_attr_translation_key = "timeout"
|
||||
|
||||
@property
|
||||
def native_value(self) -> float | None:
|
||||
"""Return the timeout setting."""
|
||||
return self.coordinator.data.timeout_minutes
|
||||
|
||||
async def async_set_native_value(self, value: float) -> None:
|
||||
"""Set the timeout."""
|
||||
await self.coordinator.client.set_timeout(int(value))
|
||||
await self.coordinator.async_request_refresh()
|
||||
```
|
||||
|
||||
## Translations
|
||||
|
||||
In `strings.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"entity": {
|
||||
"number": {
|
||||
"target_temperature": {
|
||||
"name": "Target temperature"
|
||||
},
|
||||
"brightness": {
|
||||
"name": "Brightness"
|
||||
},
|
||||
"timeout": {
|
||||
"name": "Timeout"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
252
.claude/skills/ha-integration/SELECT.MD
Normal file
252
.claude/skills/ha-integration/SELECT.MD
Normal file
@@ -0,0 +1,252 @@
|
||||
# Select Platform Reference
|
||||
|
||||
Select entities allow choosing from a predefined list of options.
|
||||
|
||||
## Basic Select
|
||||
|
||||
```python
|
||||
"""Select platform for My Integration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from homeassistant.components.select import SelectEntity
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
||||
|
||||
from . import MyIntegrationConfigEntry
|
||||
from .entity import MyEntity
|
||||
|
||||
|
||||
async def async_setup_entry(
|
||||
hass: HomeAssistant,
|
||||
entry: MyIntegrationConfigEntry,
|
||||
async_add_entities: AddEntitiesCallback,
|
||||
) -> None:
|
||||
"""Set up selects from config entry."""
|
||||
coordinator = entry.runtime_data
|
||||
|
||||
async_add_entities([
|
||||
ModeSelect(coordinator),
|
||||
])
|
||||
|
||||
|
||||
class ModeSelect(MyEntity, SelectEntity):
|
||||
"""Mode select entity."""
|
||||
|
||||
_attr_options = ["auto", "cool", "heat", "fan_only", "dry"]
|
||||
_attr_translation_key = "mode"
|
||||
|
||||
def __init__(self, coordinator: MyCoordinator) -> None:
|
||||
"""Initialize the select entity."""
|
||||
super().__init__(coordinator)
|
||||
self._attr_unique_id = f"{coordinator.client.serial_number}_mode"
|
||||
|
||||
@property
|
||||
def current_option(self) -> str | None:
|
||||
"""Return the current option."""
|
||||
return self.coordinator.data.mode
|
||||
|
||||
async def async_select_option(self, option: str) -> None:
|
||||
"""Change the selected option."""
|
||||
await self.coordinator.client.set_mode(option)
|
||||
await self.coordinator.async_request_refresh()
|
||||
```
|
||||
|
||||
## Entity Description Pattern
|
||||
|
||||
```python
|
||||
from dataclasses import dataclass
|
||||
from collections.abc import Callable, Coroutine
|
||||
from typing import Any
|
||||
|
||||
from homeassistant.components.select import SelectEntityDescription
|
||||
|
||||
|
||||
@dataclass(frozen=True, kw_only=True)
|
||||
class MySelectEntityDescription(SelectEntityDescription):
|
||||
"""Describe My select entity."""
|
||||
|
||||
current_option_fn: Callable[[MyData], str | None]
|
||||
select_option_fn: Callable[[MyClient, str], Coroutine[Any, Any, None]]
|
||||
|
||||
|
||||
SELECTS: tuple[MySelectEntityDescription, ...] = (
|
||||
MySelectEntityDescription(
|
||||
key="mode",
|
||||
translation_key="mode",
|
||||
options=["auto", "cool", "heat", "fan_only", "dry"],
|
||||
current_option_fn=lambda data: data.mode,
|
||||
select_option_fn=lambda client, option: client.set_mode(option),
|
||||
),
|
||||
MySelectEntityDescription(
|
||||
key="fan_speed",
|
||||
translation_key="fan_speed",
|
||||
options=["low", "medium", "high", "auto"],
|
||||
entity_category=EntityCategory.CONFIG,
|
||||
current_option_fn=lambda data: data.fan_speed,
|
||||
select_option_fn=lambda client, option: client.set_fan_speed(option),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class MySelect(MyEntity, SelectEntity):
|
||||
"""Select using entity description."""
|
||||
|
||||
entity_description: MySelectEntityDescription
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
coordinator: MyCoordinator,
|
||||
description: MySelectEntityDescription,
|
||||
) -> None:
|
||||
"""Initialize the select entity."""
|
||||
super().__init__(coordinator)
|
||||
self.entity_description = description
|
||||
self._attr_unique_id = f"{coordinator.client.serial_number}_{description.key}"
|
||||
|
||||
@property
|
||||
def options(self) -> list[str]:
|
||||
"""Return available options."""
|
||||
return list(self.entity_description.options)
|
||||
|
||||
@property
|
||||
def current_option(self) -> str | None:
|
||||
"""Return current option."""
|
||||
return self.entity_description.current_option_fn(self.coordinator.data)
|
||||
|
||||
async def async_select_option(self, option: str) -> None:
|
||||
"""Select an option."""
|
||||
await self.entity_description.select_option_fn(self.coordinator.client, option)
|
||||
await self.coordinator.async_request_refresh()
|
||||
```
|
||||
|
||||
## Dynamic Options
|
||||
|
||||
```python
|
||||
class DynamicSelect(MyEntity, SelectEntity):
|
||||
"""Select with options from device."""
|
||||
|
||||
_attr_translation_key = "preset"
|
||||
|
||||
@property
|
||||
def options(self) -> list[str]:
|
||||
"""Return available presets from device."""
|
||||
return self.coordinator.data.available_presets
|
||||
|
||||
@property
|
||||
def current_option(self) -> str | None:
|
||||
"""Return current preset."""
|
||||
return self.coordinator.data.current_preset
|
||||
|
||||
async def async_select_option(self, option: str) -> None:
|
||||
"""Select a preset."""
|
||||
await self.coordinator.client.set_preset(option)
|
||||
await self.coordinator.async_request_refresh()
|
||||
```
|
||||
|
||||
## Configuration Select
|
||||
|
||||
```python
|
||||
class ConfigSelect(MyEntity, SelectEntity):
|
||||
"""Configuration select (settings)."""
|
||||
|
||||
_attr_entity_category = EntityCategory.CONFIG
|
||||
_attr_options = ["silent", "normal", "boost"]
|
||||
_attr_translation_key = "performance_mode"
|
||||
|
||||
@property
|
||||
def current_option(self) -> str | None:
|
||||
"""Return current performance mode."""
|
||||
return self.coordinator.data.performance_mode
|
||||
|
||||
async def async_select_option(self, option: str) -> None:
|
||||
"""Set performance mode."""
|
||||
await self.coordinator.client.set_performance_mode(option)
|
||||
await self.coordinator.async_request_refresh()
|
||||
```
|
||||
|
||||
## Translations
|
||||
|
||||
In `strings.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"entity": {
|
||||
"select": {
|
||||
"mode": {
|
||||
"name": "Mode",
|
||||
"state": {
|
||||
"auto": "Auto",
|
||||
"cool": "Cool",
|
||||
"heat": "Heat",
|
||||
"fan_only": "Fan only",
|
||||
"dry": "Dry"
|
||||
}
|
||||
},
|
||||
"fan_speed": {
|
||||
"name": "Fan speed",
|
||||
"state": {
|
||||
"low": "Low",
|
||||
"medium": "Medium",
|
||||
"high": "High",
|
||||
"auto": "Auto"
|
||||
}
|
||||
},
|
||||
"performance_mode": {
|
||||
"name": "Performance mode",
|
||||
"state": {
|
||||
"silent": "Silent",
|
||||
"normal": "Normal",
|
||||
"boost": "Boost"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Icon by State
|
||||
|
||||
In `strings.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"entity": {
|
||||
"select": {
|
||||
"mode": {
|
||||
"name": "Mode",
|
||||
"default": "mdi:thermostat",
|
||||
"state": {
|
||||
"auto": "Auto",
|
||||
"cool": "Cool",
|
||||
"heat": "Heat"
|
||||
},
|
||||
"state_icons": {
|
||||
"auto": "mdi:thermostat-auto",
|
||||
"cool": "mdi:snowflake",
|
||||
"heat": "mdi:fire"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Note: State icons are defined in `icons.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"entity": {
|
||||
"select": {
|
||||
"mode": {
|
||||
"default": "mdi:thermostat",
|
||||
"state": {
|
||||
"auto": "mdi:thermostat-auto",
|
||||
"cool": "mdi:snowflake",
|
||||
"heat": "mdi:fire"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
271
.claude/skills/ha-integration/SENSOR.MD
Normal file
271
.claude/skills/ha-integration/SENSOR.MD
Normal file
@@ -0,0 +1,271 @@
|
||||
# Sensor Platform Reference
|
||||
|
||||
Sensors represent read-only values from devices.
|
||||
|
||||
## Basic Sensor
|
||||
|
||||
```python
|
||||
"""Sensor platform for My Integration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from homeassistant.components.sensor import (
|
||||
SensorDeviceClass,
|
||||
SensorEntity,
|
||||
SensorStateClass,
|
||||
)
|
||||
from homeassistant.const import UnitOfTemperature
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
||||
|
||||
from . import MyIntegrationConfigEntry
|
||||
from .entity import MyEntity
|
||||
|
||||
|
||||
async def async_setup_entry(
|
||||
hass: HomeAssistant,
|
||||
entry: MyIntegrationConfigEntry,
|
||||
async_add_entities: AddEntitiesCallback,
|
||||
) -> None:
|
||||
"""Set up sensors from config entry."""
|
||||
coordinator = entry.runtime_data
|
||||
|
||||
async_add_entities([
|
||||
TemperatureSensor(coordinator),
|
||||
HumiditySensor(coordinator),
|
||||
])
|
||||
|
||||
|
||||
class TemperatureSensor(MyEntity, SensorEntity):
|
||||
"""Temperature sensor."""
|
||||
|
||||
_attr_device_class = SensorDeviceClass.TEMPERATURE
|
||||
_attr_native_unit_of_measurement = UnitOfTemperature.CELSIUS
|
||||
_attr_state_class = SensorStateClass.MEASUREMENT
|
||||
_attr_translation_key = "temperature"
|
||||
|
||||
def __init__(self, coordinator: MyCoordinator) -> None:
|
||||
"""Initialize the sensor."""
|
||||
super().__init__(coordinator)
|
||||
self._attr_unique_id = f"{coordinator.client.serial_number}_temperature"
|
||||
|
||||
@property
|
||||
def native_value(self) -> float | None:
|
||||
"""Return the temperature."""
|
||||
return self.coordinator.data.temperature
|
||||
```
|
||||
|
||||
## Device Classes
|
||||
|
||||
Common sensor device classes:
|
||||
|
||||
| Device Class | Unit Examples | Use Case |
|
||||
|--------------|---------------|----------|
|
||||
| `TEMPERATURE` | °C, °F | Temperature readings |
|
||||
| `HUMIDITY` | % | Humidity levels |
|
||||
| `PRESSURE` | hPa, mbar | Atmospheric pressure |
|
||||
| `BATTERY` | % | Battery level |
|
||||
| `POWER` | W, kW | Power consumption |
|
||||
| `ENERGY` | Wh, kWh | Energy usage |
|
||||
| `VOLTAGE` | V | Electrical voltage |
|
||||
| `CURRENT` | A, mA | Electrical current |
|
||||
| `CO2` | ppm | Carbon dioxide |
|
||||
| `PM25` | µg/m³ | Particulate matter |
|
||||
|
||||
## State Classes
|
||||
|
||||
```python
|
||||
from homeassistant.components.sensor import SensorStateClass
|
||||
|
||||
# For instantaneous values that can go up or down
|
||||
_attr_state_class = SensorStateClass.MEASUREMENT
|
||||
|
||||
# For ever-increasing totals (like energy consumption)
|
||||
_attr_state_class = SensorStateClass.TOTAL
|
||||
|
||||
# For totals that reset periodically
|
||||
_attr_state_class = SensorStateClass.TOTAL_INCREASING
|
||||
```
|
||||
|
||||
## Entity Description Pattern
|
||||
|
||||
For multiple sensors with similar structure:
|
||||
|
||||
```python
|
||||
from dataclasses import dataclass
|
||||
from collections.abc import Callable
|
||||
from typing import Any
|
||||
|
||||
from homeassistant.components.sensor import SensorEntityDescription
|
||||
|
||||
|
||||
@dataclass(frozen=True, kw_only=True)
|
||||
class MySensorEntityDescription(SensorEntityDescription):
|
||||
"""Describe My sensor entity."""
|
||||
|
||||
value_fn: Callable[[MyData], Any]
|
||||
|
||||
|
||||
SENSORS: tuple[MySensorEntityDescription, ...] = (
|
||||
MySensorEntityDescription(
|
||||
key="temperature",
|
||||
translation_key="temperature",
|
||||
device_class=SensorDeviceClass.TEMPERATURE,
|
||||
native_unit_of_measurement=UnitOfTemperature.CELSIUS,
|
||||
state_class=SensorStateClass.MEASUREMENT,
|
||||
value_fn=lambda data: data.temperature,
|
||||
),
|
||||
MySensorEntityDescription(
|
||||
key="humidity",
|
||||
translation_key="humidity",
|
||||
device_class=SensorDeviceClass.HUMIDITY,
|
||||
native_unit_of_measurement=PERCENTAGE,
|
||||
state_class=SensorStateClass.MEASUREMENT,
|
||||
value_fn=lambda data: data.humidity,
|
||||
),
|
||||
MySensorEntityDescription(
|
||||
key="signal_strength",
|
||||
translation_key="signal_strength",
|
||||
device_class=SensorDeviceClass.SIGNAL_STRENGTH,
|
||||
native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS_MILLIWATT,
|
||||
state_class=SensorStateClass.MEASUREMENT,
|
||||
entity_category=EntityCategory.DIAGNOSTIC,
|
||||
entity_registry_enabled_default=False, # Disabled by default
|
||||
value_fn=lambda data: data.rssi,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
async def async_setup_entry(
|
||||
hass: HomeAssistant,
|
||||
entry: MyIntegrationConfigEntry,
|
||||
async_add_entities: AddEntitiesCallback,
|
||||
) -> None:
|
||||
"""Set up sensors from config entry."""
|
||||
coordinator = entry.runtime_data
|
||||
async_add_entities(
|
||||
MySensor(coordinator, description)
|
||||
for description in SENSORS
|
||||
)
|
||||
|
||||
|
||||
class MySensor(MyEntity, SensorEntity):
|
||||
"""Sensor using entity description."""
|
||||
|
||||
entity_description: MySensorEntityDescription
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
coordinator: MyCoordinator,
|
||||
description: MySensorEntityDescription,
|
||||
) -> None:
|
||||
"""Initialize the sensor."""
|
||||
super().__init__(coordinator)
|
||||
self.entity_description = description
|
||||
self._attr_unique_id = f"{coordinator.client.serial_number}_{description.key}"
|
||||
|
||||
@property
|
||||
def native_value(self) -> StateType:
|
||||
"""Return the sensor value."""
|
||||
return self.entity_description.value_fn(self.coordinator.data)
|
||||
```
|
||||
|
||||
## Suggested Display Precision
|
||||
|
||||
```python
|
||||
# Control decimal places shown in UI
|
||||
_attr_suggested_display_precision = 1 # Show 21.5 instead of 21.456789
|
||||
```
|
||||
|
||||
## Timestamp Sensors
|
||||
|
||||
```python
|
||||
from datetime import datetime
|
||||
|
||||
from homeassistant.components.sensor import SensorDeviceClass
|
||||
|
||||
|
||||
class LastUpdatedSensor(MyEntity, SensorEntity):
|
||||
"""Last updated timestamp sensor."""
|
||||
|
||||
_attr_device_class = SensorDeviceClass.TIMESTAMP
|
||||
_attr_translation_key = "last_updated"
|
||||
|
||||
@property
|
||||
def native_value(self) -> datetime | None:
|
||||
"""Return the last update timestamp."""
|
||||
return self.coordinator.data.last_updated
|
||||
```
|
||||
|
||||
## Enum Sensors
|
||||
|
||||
```python
|
||||
from homeassistant.components.sensor import SensorDeviceClass
|
||||
|
||||
|
||||
class StatusSensor(MyEntity, SensorEntity):
|
||||
"""Status sensor with enum values."""
|
||||
|
||||
_attr_device_class = SensorDeviceClass.ENUM
|
||||
_attr_options = ["idle", "running", "error", "offline"]
|
||||
_attr_translation_key = "status"
|
||||
|
||||
@property
|
||||
def native_value(self) -> str | None:
|
||||
"""Return the current status."""
|
||||
return self.coordinator.data.status
|
||||
```
|
||||
|
||||
With translations in `strings.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"entity": {
|
||||
"sensor": {
|
||||
"status": {
|
||||
"name": "Status",
|
||||
"state": {
|
||||
"idle": "Idle",
|
||||
"running": "Running",
|
||||
"error": "Error",
|
||||
"offline": "Offline"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Dynamic Icons
|
||||
|
||||
In `strings.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"entity": {
|
||||
"sensor": {
|
||||
"battery_level": {
|
||||
"name": "Battery level",
|
||||
"default": "mdi:battery-unknown",
|
||||
"range": {
|
||||
"0": "mdi:battery-outline",
|
||||
"10": "mdi:battery-10",
|
||||
"50": "mdi:battery-50",
|
||||
"90": "mdi:battery-90",
|
||||
"100": "mdi:battery"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## PARALLEL_UPDATES
|
||||
|
||||
```python
|
||||
# At module level - limit concurrent updates
|
||||
PARALLEL_UPDATES = 1 # Serialize to prevent overwhelming device
|
||||
|
||||
# Or unlimited for coordinator-based platforms
|
||||
PARALLEL_UPDATES = 0
|
||||
```
|
||||
335
.claude/skills/ha-integration/SERVICES.MD
Normal file
335
.claude/skills/ha-integration/SERVICES.MD
Normal file
@@ -0,0 +1,335 @@
|
||||
# Services Reference
|
||||
|
||||
Services allow automations and users to trigger actions.
|
||||
|
||||
## Service Registration
|
||||
|
||||
Register services in `async_setup`, NOT in `async_setup_entry`:
|
||||
|
||||
```python
|
||||
"""My Integration setup."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.config_entries import ConfigEntry, ConfigEntryState
|
||||
from homeassistant.const import ATTR_DEVICE_ID
|
||||
from homeassistant.core import HomeAssistant, ServiceCall, ServiceResponse, SupportsResponse
|
||||
from homeassistant.exceptions import HomeAssistantError, ServiceValidationError
|
||||
from homeassistant.helpers import config_validation as cv, device_registry as dr
|
||||
|
||||
from .const import ATTR_CONFIG_ENTRY_ID, DOMAIN
|
||||
|
||||
SERVICE_REFRESH = "refresh"
|
||||
SERVICE_SET_SCHEDULE = "set_schedule"
|
||||
|
||||
|
||||
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
||||
"""Set up My Integration services."""
|
||||
|
||||
async def handle_refresh(call: ServiceCall) -> None:
|
||||
"""Handle refresh service call."""
|
||||
entry_id = call.data[ATTR_CONFIG_ENTRY_ID]
|
||||
|
||||
if not (entry := hass.config_entries.async_get_entry(entry_id)):
|
||||
raise ServiceValidationError(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="entry_not_found",
|
||||
)
|
||||
|
||||
if entry.state is not ConfigEntryState.LOADED:
|
||||
raise ServiceValidationError(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="entry_not_loaded",
|
||||
)
|
||||
|
||||
coordinator = entry.runtime_data
|
||||
await coordinator.async_request_refresh()
|
||||
|
||||
hass.services.async_register(
|
||||
DOMAIN,
|
||||
SERVICE_REFRESH,
|
||||
handle_refresh,
|
||||
schema=vol.Schema({
|
||||
vol.Required(ATTR_CONFIG_ENTRY_ID): cv.string,
|
||||
}),
|
||||
)
|
||||
|
||||
return True
|
||||
```
|
||||
|
||||
## Service with Response
|
||||
|
||||
```python
|
||||
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
||||
"""Set up services with response."""
|
||||
|
||||
async def handle_get_schedule(call: ServiceCall) -> ServiceResponse:
|
||||
"""Handle get_schedule service call."""
|
||||
entry_id = call.data[ATTR_CONFIG_ENTRY_ID]
|
||||
|
||||
if not (entry := hass.config_entries.async_get_entry(entry_id)):
|
||||
raise ServiceValidationError(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="entry_not_found",
|
||||
)
|
||||
|
||||
if entry.state is not ConfigEntryState.LOADED:
|
||||
raise ServiceValidationError(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="entry_not_loaded",
|
||||
)
|
||||
|
||||
coordinator = entry.runtime_data
|
||||
schedule = await coordinator.client.get_schedule()
|
||||
|
||||
return {
|
||||
"schedule": [
|
||||
{"day": item.day, "start": item.start, "end": item.end}
|
||||
for item in schedule
|
||||
]
|
||||
}
|
||||
|
||||
hass.services.async_register(
|
||||
DOMAIN,
|
||||
"get_schedule",
|
||||
handle_get_schedule,
|
||||
schema=vol.Schema({
|
||||
vol.Required(ATTR_CONFIG_ENTRY_ID): cv.string,
|
||||
}),
|
||||
supports_response=SupportsResponse.ONLY, # or SupportsResponse.OPTIONAL
|
||||
)
|
||||
|
||||
return True
|
||||
```
|
||||
|
||||
## Entity Services
|
||||
|
||||
Register entity-specific services in platform setup:
|
||||
|
||||
```python
|
||||
"""Switch platform with entity service."""
|
||||
|
||||
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
||||
import voluptuous as vol
|
||||
|
||||
|
||||
async def async_setup_entry(
|
||||
hass: HomeAssistant,
|
||||
entry: MyIntegrationConfigEntry,
|
||||
async_add_entities: AddEntitiesCallback,
|
||||
) -> None:
|
||||
"""Set up switches from config entry."""
|
||||
coordinator = entry.runtime_data
|
||||
|
||||
async_add_entities([PowerSwitch(coordinator)])
|
||||
|
||||
# Register entity service
|
||||
platform = entity_platform.async_get_current_platform()
|
||||
platform.async_register_entity_service(
|
||||
"set_timer",
|
||||
{
|
||||
vol.Required("minutes"): vol.All(
|
||||
vol.Coerce(int), vol.Range(min=1, max=120)
|
||||
),
|
||||
},
|
||||
"async_set_timer",
|
||||
)
|
||||
|
||||
|
||||
class PowerSwitch(MyEntity, SwitchEntity):
|
||||
"""Power switch with timer service."""
|
||||
|
||||
async def async_set_timer(self, minutes: int) -> None:
|
||||
"""Set auto-off timer."""
|
||||
await self.coordinator.client.set_timer(minutes)
|
||||
```
|
||||
|
||||
## Service Validation
|
||||
|
||||
```python
|
||||
from homeassistant.exceptions import ServiceValidationError
|
||||
|
||||
|
||||
async def handle_set_schedule(call: ServiceCall) -> None:
|
||||
"""Handle set_schedule service call."""
|
||||
start_date = call.data["start_date"]
|
||||
end_date = call.data["end_date"]
|
||||
|
||||
# Validate input
|
||||
if end_date < start_date:
|
||||
raise ServiceValidationError(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="end_date_before_start_date",
|
||||
)
|
||||
|
||||
entry_id = call.data[ATTR_CONFIG_ENTRY_ID]
|
||||
entry = hass.config_entries.async_get_entry(entry_id)
|
||||
|
||||
try:
|
||||
await entry.runtime_data.client.set_schedule(start_date, end_date)
|
||||
except MyConnectionError as err:
|
||||
raise HomeAssistantError(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="connection_failed",
|
||||
) from err
|
||||
```
|
||||
|
||||
## services.yaml
|
||||
|
||||
Define services in `services.yaml`:
|
||||
|
||||
```yaml
|
||||
refresh:
|
||||
name: Refresh
|
||||
description: Force a data refresh from the device.
|
||||
fields:
|
||||
config_entry_id:
|
||||
name: Config entry ID
|
||||
description: The config entry to refresh.
|
||||
required: true
|
||||
selector:
|
||||
config_entry:
|
||||
integration: my_integration
|
||||
|
||||
set_schedule:
|
||||
name: Set schedule
|
||||
description: Set the device schedule.
|
||||
fields:
|
||||
config_entry_id:
|
||||
name: Config entry ID
|
||||
description: The config entry to configure.
|
||||
required: true
|
||||
selector:
|
||||
config_entry:
|
||||
integration: my_integration
|
||||
start_date:
|
||||
name: Start date
|
||||
description: Schedule start date.
|
||||
required: true
|
||||
selector:
|
||||
date:
|
||||
end_date:
|
||||
name: End date
|
||||
description: Schedule end date.
|
||||
required: true
|
||||
selector:
|
||||
date:
|
||||
|
||||
get_schedule:
|
||||
name: Get schedule
|
||||
description: Get the current device schedule.
|
||||
fields:
|
||||
config_entry_id:
|
||||
name: Config entry ID
|
||||
description: The config entry to query.
|
||||
required: true
|
||||
selector:
|
||||
config_entry:
|
||||
integration: my_integration
|
||||
|
||||
set_timer:
|
||||
name: Set timer
|
||||
description: Set auto-off timer for the switch.
|
||||
target:
|
||||
entity:
|
||||
integration: my_integration
|
||||
domain: switch
|
||||
fields:
|
||||
minutes:
|
||||
name: Minutes
|
||||
description: Timer duration in minutes.
|
||||
required: true
|
||||
selector:
|
||||
number:
|
||||
min: 1
|
||||
max: 120
|
||||
unit_of_measurement: min
|
||||
```
|
||||
|
||||
## Exception Translations
|
||||
|
||||
In `strings.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"exceptions": {
|
||||
"entry_not_found": {
|
||||
"message": "Config entry not found."
|
||||
},
|
||||
"entry_not_loaded": {
|
||||
"message": "Config entry is not loaded."
|
||||
},
|
||||
"end_date_before_start_date": {
|
||||
"message": "The end date cannot be before the start date."
|
||||
},
|
||||
"connection_failed": {
|
||||
"message": "Failed to connect to the device."
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Device-Based Service Targeting
|
||||
|
||||
```python
|
||||
async def handle_device_service(call: ServiceCall) -> None:
|
||||
"""Handle service call targeting a device."""
|
||||
device_id = call.data[ATTR_DEVICE_ID]
|
||||
|
||||
device_registry = dr.async_get(hass)
|
||||
device = device_registry.async_get(device_id)
|
||||
|
||||
if device is None:
|
||||
raise ServiceValidationError(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="device_not_found",
|
||||
)
|
||||
|
||||
# Find config entry for device
|
||||
entry_id = next(
|
||||
(entry_id for entry_id in device.config_entries if entry_id),
|
||||
None,
|
||||
)
|
||||
|
||||
if entry_id is None:
|
||||
raise ServiceValidationError(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="entry_not_found",
|
||||
)
|
||||
|
||||
entry = hass.config_entries.async_get_entry(entry_id)
|
||||
# ... continue with service logic
|
||||
```
|
||||
|
||||
## Service Schema Patterns
|
||||
|
||||
```python
|
||||
import voluptuous as vol
|
||||
from homeassistant.helpers import config_validation as cv
|
||||
|
||||
# Basic schema
|
||||
SERVICE_SCHEMA = vol.Schema({
|
||||
vol.Required(ATTR_CONFIG_ENTRY_ID): cv.string,
|
||||
vol.Required("value"): vol.All(vol.Coerce(int), vol.Range(min=0, max=100)),
|
||||
vol.Optional("timeout", default=30): cv.positive_int,
|
||||
})
|
||||
|
||||
# With entity targeting
|
||||
SERVICE_SCHEMA_ENTITY = vol.Schema({
|
||||
vol.Required("entity_id"): cv.entity_ids,
|
||||
vol.Required("parameter"): cv.string,
|
||||
})
|
||||
|
||||
# With selectors (for services.yaml)
|
||||
# Use selector in services.yaml, not in Python schema
|
||||
```
|
||||
|
||||
## Quality Scale Requirements
|
||||
|
||||
- **Bronze**: `action-setup` - Register services in `async_setup` if integration has services
|
||||
- Services must validate config entry state before use
|
||||
- Use translated exceptions for error messages
|
||||
165
.claude/skills/ha-integration/SKILL.md
Normal file
165
.claude/skills/ha-integration/SKILL.md
Normal file
@@ -0,0 +1,165 @@
|
||||
---
|
||||
name: ha-integration
|
||||
description: Develop Home Assistant integrations following best practices. Use when creating, modifying, or reviewing integration code including config flows, entities, coordinators, diagnostics, services, and tests.
|
||||
---
|
||||
|
||||
# Home Assistant Integration Development
|
||||
|
||||
You are developing a Home Assistant integration. Follow these guidelines and reference the supporting documentation for specific components.
|
||||
|
||||
## Quick Reference
|
||||
|
||||
| Component | Reference File |
|
||||
|-----------|----------------|
|
||||
| Config flow | [CONFIG-FLOW.MD](CONFIG-FLOW.MD) |
|
||||
| Data coordinator | [COORDINATOR.MD](COORDINATOR.MD) |
|
||||
| Entities (base) | [ENTITY.MD](ENTITY.MD) |
|
||||
| Sensors | [SENSOR.MD](SENSOR.MD) |
|
||||
| Binary sensors | [BINARY-SENSOR.MD](BINARY-SENSOR.MD) |
|
||||
| Switches | [SWITCH.MD](SWITCH.MD) |
|
||||
| Numbers | [NUMBER.MD](NUMBER.MD) |
|
||||
| Selects | [SELECT.MD](SELECT.MD) |
|
||||
| Buttons | [BUTTON.MD](BUTTON.MD) |
|
||||
| Device management | [DEVICE.MD](DEVICE.MD) |
|
||||
| Diagnostics | [DIAGNOSTICS.MD](DIAGNOSTICS.MD) |
|
||||
| Services | [SERVICES.MD](SERVICES.MD) |
|
||||
| Testing | [TESTING.MD](TESTING.MD) |
|
||||
|
||||
## Integration Structure
|
||||
|
||||
```
|
||||
homeassistant/components/my_integration/
|
||||
├── __init__.py # Entry point with async_setup_entry
|
||||
├── manifest.json # Integration metadata and dependencies
|
||||
├── const.py # Domain and constants
|
||||
├── config_flow.py # UI configuration flow
|
||||
├── coordinator.py # Data update coordinator
|
||||
├── entity.py # Base entity class
|
||||
├── sensor.py # Sensor platform
|
||||
├── diagnostics.py # Diagnostic data collection
|
||||
├── strings.json # User-facing text and translations
|
||||
├── services.yaml # Service definitions (if applicable)
|
||||
└── quality_scale.yaml # Quality scale rule status
|
||||
```
|
||||
|
||||
## Quality Scale Levels
|
||||
|
||||
- **Bronze**: Basic requirements (ALL Bronze rules are mandatory)
|
||||
- **Silver**: Enhanced functionality (entity unavailability, parallel updates, auth flows)
|
||||
- **Gold**: Advanced features (device management, diagnostics, translations)
|
||||
- **Platinum**: Highest quality (strict typing, async dependencies, websession injection)
|
||||
|
||||
Check `manifest.json` for `"quality_scale"` key and `quality_scale.yaml` for rule status.
|
||||
|
||||
## Core Patterns
|
||||
|
||||
### Entry Point (`__init__.py`)
|
||||
|
||||
```python
|
||||
"""Integration for My Device."""
|
||||
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.const import Platform
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
from .const import DOMAIN
|
||||
from .coordinator import MyCoordinator
|
||||
|
||||
PLATFORMS = [Platform.SENSOR, Platform.BINARY_SENSOR]
|
||||
|
||||
type MyIntegrationConfigEntry = ConfigEntry[MyCoordinator]
|
||||
|
||||
|
||||
async def async_setup_entry(hass: HomeAssistant, entry: MyIntegrationConfigEntry) -> bool:
|
||||
"""Set up My Integration from a config entry."""
|
||||
coordinator = MyCoordinator(hass, entry)
|
||||
await coordinator.async_config_entry_first_refresh()
|
||||
|
||||
entry.runtime_data = coordinator
|
||||
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
|
||||
|
||||
return True
|
||||
|
||||
|
||||
async def async_unload_entry(hass: HomeAssistant, entry: MyIntegrationConfigEntry) -> bool:
|
||||
"""Unload a config entry."""
|
||||
return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
|
||||
```
|
||||
|
||||
### Constants (`const.py`)
|
||||
|
||||
```python
|
||||
"""Constants for My Integration."""
|
||||
|
||||
DOMAIN = "my_integration"
|
||||
```
|
||||
|
||||
### Manifest (`manifest.json`)
|
||||
|
||||
```json
|
||||
{
|
||||
"domain": "my_integration",
|
||||
"name": "My Integration",
|
||||
"codeowners": ["@username"],
|
||||
"config_flow": true,
|
||||
"documentation": "https://www.home-assistant.io/integrations/my_integration",
|
||||
"integration_type": "hub",
|
||||
"iot_class": "local_polling",
|
||||
"requirements": ["my-library==1.0.0"],
|
||||
"quality_scale": "bronze"
|
||||
}
|
||||
```
|
||||
|
||||
## Python Requirements
|
||||
|
||||
- **Compatibility**: Python 3.13+
|
||||
- **Type hints**: Required for all functions and methods
|
||||
- **f-strings**: Preferred over `%` or `.format()`
|
||||
- **Async**: All external I/O must be async
|
||||
|
||||
## Code Quality
|
||||
|
||||
- **Formatting**: Ruff
|
||||
- **Linting**: PyLint and Ruff
|
||||
- **Type Checking**: MyPy
|
||||
- **Testing**: pytest with >95% coverage
|
||||
|
||||
## Common Anti-Patterns to Avoid
|
||||
|
||||
```python
|
||||
# Blocking operations
|
||||
data = requests.get(url) # Use async or executor
|
||||
time.sleep(5) # Use asyncio.sleep()
|
||||
|
||||
# Hardcoded strings
|
||||
self._attr_name = "Temperature" # Use translation_key
|
||||
|
||||
# Too much in try block
|
||||
try:
|
||||
data = await client.get_data()
|
||||
processed = data["value"] * 100 # Move outside try
|
||||
except Error:
|
||||
pass
|
||||
|
||||
# User-configurable polling
|
||||
vol.Optional("scan_interval"): cv.positive_int # Not allowed
|
||||
```
|
||||
|
||||
## Development Commands
|
||||
|
||||
```bash
|
||||
# Run tests with coverage
|
||||
pytest ./tests/components/<domain> \
|
||||
--cov=homeassistant.components.<domain> \
|
||||
--cov-report term-missing \
|
||||
--numprocesses=auto
|
||||
|
||||
# Type checking
|
||||
mypy homeassistant/components/<domain>
|
||||
|
||||
# Linting
|
||||
pylint homeassistant/components/<domain>
|
||||
|
||||
# Validate integration
|
||||
python -m script.hassfest --integration-path homeassistant/components/<domain>
|
||||
```
|
||||
236
.claude/skills/ha-integration/SWITCH.MD
Normal file
236
.claude/skills/ha-integration/SWITCH.MD
Normal file
@@ -0,0 +1,236 @@
|
||||
# Switch Platform Reference
|
||||
|
||||
Switches control on/off functionality.
|
||||
|
||||
## Basic Switch
|
||||
|
||||
```python
|
||||
"""Switch platform for My Integration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from homeassistant.components.switch import SwitchEntity, SwitchDeviceClass
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
||||
|
||||
from . import MyIntegrationConfigEntry
|
||||
from .entity import MyEntity
|
||||
|
||||
|
||||
async def async_setup_entry(
|
||||
hass: HomeAssistant,
|
||||
entry: MyIntegrationConfigEntry,
|
||||
async_add_entities: AddEntitiesCallback,
|
||||
) -> None:
|
||||
"""Set up switches from config entry."""
|
||||
coordinator = entry.runtime_data
|
||||
|
||||
async_add_entities([
|
||||
PowerSwitch(coordinator),
|
||||
])
|
||||
|
||||
|
||||
class PowerSwitch(MyEntity, SwitchEntity):
|
||||
"""Power switch."""
|
||||
|
||||
_attr_device_class = SwitchDeviceClass.SWITCH
|
||||
_attr_translation_key = "power"
|
||||
|
||||
def __init__(self, coordinator: MyCoordinator) -> None:
|
||||
"""Initialize the switch."""
|
||||
super().__init__(coordinator)
|
||||
self._attr_unique_id = f"{coordinator.client.serial_number}_power"
|
||||
|
||||
@property
|
||||
def is_on(self) -> bool | None:
|
||||
"""Return true if switch is on."""
|
||||
return self.coordinator.data.is_on
|
||||
|
||||
async def async_turn_on(self, **kwargs: Any) -> None:
|
||||
"""Turn the switch on."""
|
||||
await self.coordinator.client.turn_on()
|
||||
await self.coordinator.async_request_refresh()
|
||||
|
||||
async def async_turn_off(self, **kwargs: Any) -> None:
|
||||
"""Turn the switch off."""
|
||||
await self.coordinator.client.turn_off()
|
||||
await self.coordinator.async_request_refresh()
|
||||
```
|
||||
|
||||
## Device Classes
|
||||
|
||||
| Device Class | Use Case |
|
||||
|--------------|----------|
|
||||
| `OUTLET` | Electrical outlet |
|
||||
| `SWITCH` | Generic switch |
|
||||
|
||||
## Entity Description Pattern
|
||||
|
||||
```python
|
||||
from dataclasses import dataclass
|
||||
from collections.abc import Callable, Coroutine
|
||||
from typing import Any
|
||||
|
||||
from homeassistant.components.switch import SwitchEntityDescription
|
||||
|
||||
|
||||
@dataclass(frozen=True, kw_only=True)
|
||||
class MySwitchEntityDescription(SwitchEntityDescription):
|
||||
"""Describe My switch entity."""
|
||||
|
||||
is_on_fn: Callable[[MyData], bool | None]
|
||||
turn_on_fn: Callable[[MyClient], Coroutine[Any, Any, None]]
|
||||
turn_off_fn: Callable[[MyClient], Coroutine[Any, Any, None]]
|
||||
|
||||
|
||||
SWITCHES: tuple[MySwitchEntityDescription, ...] = (
|
||||
MySwitchEntityDescription(
|
||||
key="power",
|
||||
translation_key="power",
|
||||
device_class=SwitchDeviceClass.SWITCH,
|
||||
is_on_fn=lambda data: data.is_on,
|
||||
turn_on_fn=lambda client: client.turn_on(),
|
||||
turn_off_fn=lambda client: client.turn_off(),
|
||||
),
|
||||
MySwitchEntityDescription(
|
||||
key="child_lock",
|
||||
translation_key="child_lock",
|
||||
entity_category=EntityCategory.CONFIG,
|
||||
is_on_fn=lambda data: data.child_lock_enabled,
|
||||
turn_on_fn=lambda client: client.set_child_lock(True),
|
||||
turn_off_fn=lambda client: client.set_child_lock(False),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class MySwitch(MyEntity, SwitchEntity):
|
||||
"""Switch using entity description."""
|
||||
|
||||
entity_description: MySwitchEntityDescription
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
coordinator: MyCoordinator,
|
||||
description: MySwitchEntityDescription,
|
||||
) -> None:
|
||||
"""Initialize the switch."""
|
||||
super().__init__(coordinator)
|
||||
self.entity_description = description
|
||||
self._attr_unique_id = f"{coordinator.client.serial_number}_{description.key}"
|
||||
|
||||
@property
|
||||
def is_on(self) -> bool | None:
|
||||
"""Return true if switch is on."""
|
||||
return self.entity_description.is_on_fn(self.coordinator.data)
|
||||
|
||||
async def async_turn_on(self, **kwargs: Any) -> None:
|
||||
"""Turn the switch on."""
|
||||
await self.entity_description.turn_on_fn(self.coordinator.client)
|
||||
await self.coordinator.async_request_refresh()
|
||||
|
||||
async def async_turn_off(self, **kwargs: Any) -> None:
|
||||
"""Turn the switch off."""
|
||||
await self.entity_description.turn_off_fn(self.coordinator.client)
|
||||
await self.coordinator.async_request_refresh()
|
||||
```
|
||||
|
||||
## Configuration Switch
|
||||
|
||||
```python
|
||||
class ConfigSwitch(MyEntity, SwitchEntity):
|
||||
"""Configuration switch (e.g., enable/disable a feature)."""
|
||||
|
||||
_attr_entity_category = EntityCategory.CONFIG
|
||||
_attr_translation_key = "auto_mode"
|
||||
|
||||
@property
|
||||
def is_on(self) -> bool | None:
|
||||
"""Return true if auto mode is enabled."""
|
||||
return self.coordinator.data.auto_mode_enabled
|
||||
|
||||
async def async_turn_on(self, **kwargs: Any) -> None:
|
||||
"""Enable auto mode."""
|
||||
await self.coordinator.client.set_auto_mode(True)
|
||||
await self.coordinator.async_request_refresh()
|
||||
|
||||
async def async_turn_off(self, **kwargs: Any) -> None:
|
||||
"""Disable auto mode."""
|
||||
await self.coordinator.client.set_auto_mode(False)
|
||||
await self.coordinator.async_request_refresh()
|
||||
```
|
||||
|
||||
## Optimistic Updates
|
||||
|
||||
For devices with slow response:
|
||||
|
||||
```python
|
||||
class OptimisticSwitch(MyEntity, SwitchEntity):
|
||||
"""Switch with optimistic state updates."""
|
||||
|
||||
_attr_assumed_state = True # Indicates state may not be accurate
|
||||
|
||||
def __init__(self, coordinator: MyCoordinator) -> None:
|
||||
"""Initialize the switch."""
|
||||
super().__init__(coordinator)
|
||||
self._optimistic_state: bool | None = None
|
||||
|
||||
@property
|
||||
def is_on(self) -> bool | None:
|
||||
"""Return optimistic state if set, otherwise coordinator state."""
|
||||
if self._optimistic_state is not None:
|
||||
return self._optimistic_state
|
||||
return self.coordinator.data.is_on
|
||||
|
||||
async def async_turn_on(self, **kwargs: Any) -> None:
|
||||
"""Turn on with optimistic update."""
|
||||
self._optimistic_state = True
|
||||
self.async_write_ha_state()
|
||||
try:
|
||||
await self.coordinator.client.turn_on()
|
||||
finally:
|
||||
self._optimistic_state = None
|
||||
await self.coordinator.async_request_refresh()
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
```python
|
||||
from homeassistant.exceptions import HomeAssistantError
|
||||
|
||||
|
||||
class RobustSwitch(MyEntity, SwitchEntity):
|
||||
"""Switch with proper error handling."""
|
||||
|
||||
async def async_turn_on(self, **kwargs: Any) -> None:
|
||||
"""Turn the switch on."""
|
||||
try:
|
||||
await self.coordinator.client.turn_on()
|
||||
except MyDeviceError as err:
|
||||
raise HomeAssistantError(f"Failed to turn on: {err}") from err
|
||||
|
||||
await self.coordinator.async_request_refresh()
|
||||
```
|
||||
|
||||
## Translations
|
||||
|
||||
In `strings.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"entity": {
|
||||
"switch": {
|
||||
"power": {
|
||||
"name": "Power"
|
||||
},
|
||||
"child_lock": {
|
||||
"name": "Child lock"
|
||||
},
|
||||
"auto_mode": {
|
||||
"name": "Auto mode"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
396
.claude/skills/ha-integration/TESTING.MD
Normal file
396
.claude/skills/ha-integration/TESTING.MD
Normal file
@@ -0,0 +1,396 @@
|
||||
# Testing Reference
|
||||
|
||||
Testing patterns for Home Assistant integrations.
|
||||
|
||||
## Test Structure
|
||||
|
||||
```
|
||||
tests/components/my_integration/
|
||||
├── __init__.py
|
||||
├── conftest.py # Shared fixtures
|
||||
├── test_config_flow.py # Config flow tests (100% coverage required)
|
||||
├── test_init.py # Integration setup tests
|
||||
├── test_sensor.py # Sensor platform tests
|
||||
├── test_diagnostics.py # Diagnostics tests
|
||||
├── snapshots/ # Snapshot files
|
||||
│ └── test_sensor.ambr
|
||||
└── fixtures/ # Test data fixtures
|
||||
└── device_data.json
|
||||
```
|
||||
|
||||
## conftest.py
|
||||
|
||||
```python
|
||||
"""Fixtures for My Integration tests."""
|
||||
|
||||
from collections.abc import Generator
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from homeassistant.components.my_integration.const import DOMAIN
|
||||
from homeassistant.const import CONF_API_KEY, CONF_HOST, Platform
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
from tests.common import MockConfigEntry, load_fixture
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_config_entry() -> MockConfigEntry:
|
||||
"""Return the default mocked config entry."""
|
||||
return MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
title="My Device",
|
||||
data={
|
||||
CONF_HOST: "192.168.1.100",
|
||||
CONF_API_KEY: "test_api_key",
|
||||
},
|
||||
unique_id="device_serial_123",
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_client() -> Generator[MagicMock]:
|
||||
"""Return a mocked client."""
|
||||
with patch(
|
||||
"homeassistant.components.my_integration.MyClient",
|
||||
autospec=True,
|
||||
) as client_mock:
|
||||
client = client_mock.return_value
|
||||
client.get_data = AsyncMock(
|
||||
return_value=MyData.from_json(load_fixture("device_data.json", DOMAIN))
|
||||
)
|
||||
client.serial_number = "device_serial_123"
|
||||
client.name = "My Device"
|
||||
client.model = "Model X"
|
||||
client.firmware_version = "1.2.3"
|
||||
yield client
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def platforms() -> list[Platform]:
|
||||
"""Return platforms to test."""
|
||||
return [Platform.SENSOR, Platform.BINARY_SENSOR]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def init_integration(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_client: MagicMock,
|
||||
platforms: list[Platform],
|
||||
) -> MockConfigEntry:
|
||||
"""Set up the integration for testing."""
|
||||
mock_config_entry.add_to_hass(hass)
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.my_integration.PLATFORMS",
|
||||
platforms,
|
||||
):
|
||||
await hass.config_entries.async_setup(mock_config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
return mock_config_entry
|
||||
```
|
||||
|
||||
## Config Flow Tests
|
||||
|
||||
**100% coverage required for all paths:**
|
||||
|
||||
```python
|
||||
"""Test config flow for My Integration."""
|
||||
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from homeassistant.components.my_integration.const import DOMAIN
|
||||
from homeassistant.config_entries import SOURCE_USER, SOURCE_ZEROCONF
|
||||
from homeassistant.const import CONF_API_KEY, CONF_HOST
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.data_entry_flow import FlowResultType
|
||||
|
||||
from tests.common import MockConfigEntry
|
||||
|
||||
|
||||
async def test_user_flow_success(
|
||||
hass: HomeAssistant,
|
||||
mock_client: AsyncMock,
|
||||
) -> None:
|
||||
"""Test successful user flow."""
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": SOURCE_USER}
|
||||
)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "user"
|
||||
assert result["errors"] == {}
|
||||
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
user_input={
|
||||
CONF_HOST: "192.168.1.100",
|
||||
CONF_API_KEY: "test_key",
|
||||
},
|
||||
)
|
||||
|
||||
assert result["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result["title"] == "My Device"
|
||||
assert result["data"] == {
|
||||
CONF_HOST: "192.168.1.100",
|
||||
CONF_API_KEY: "test_key",
|
||||
}
|
||||
assert result["result"].unique_id == "device_serial_123"
|
||||
|
||||
|
||||
async def test_user_flow_cannot_connect(
|
||||
hass: HomeAssistant,
|
||||
mock_client: AsyncMock,
|
||||
) -> None:
|
||||
"""Test connection error in user flow."""
|
||||
mock_client.get_data.side_effect = ConnectionError("Cannot connect")
|
||||
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": SOURCE_USER}
|
||||
)
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
user_input={
|
||||
CONF_HOST: "192.168.1.100",
|
||||
CONF_API_KEY: "test_key",
|
||||
},
|
||||
)
|
||||
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["errors"] == {"base": "cannot_connect"}
|
||||
|
||||
|
||||
async def test_user_flow_already_configured(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_client: AsyncMock,
|
||||
) -> None:
|
||||
"""Test already configured error."""
|
||||
mock_config_entry.add_to_hass(hass)
|
||||
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": SOURCE_USER}
|
||||
)
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
user_input={
|
||||
CONF_HOST: "192.168.1.100",
|
||||
CONF_API_KEY: "test_key",
|
||||
},
|
||||
)
|
||||
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "already_configured"
|
||||
|
||||
|
||||
async def test_reauth_flow(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_client: AsyncMock,
|
||||
) -> None:
|
||||
"""Test reauthentication flow."""
|
||||
mock_config_entry.add_to_hass(hass)
|
||||
|
||||
result = await mock_config_entry.start_reauth_flow(hass)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "reauth_confirm"
|
||||
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
user_input={CONF_API_KEY: "new_api_key"},
|
||||
)
|
||||
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "reauth_successful"
|
||||
assert mock_config_entry.data[CONF_API_KEY] == "new_api_key"
|
||||
```
|
||||
|
||||
## Entity Tests with Snapshots
|
||||
|
||||
```python
|
||||
"""Test sensor platform."""
|
||||
|
||||
import pytest
|
||||
from syrupy.assertion import SnapshotAssertion
|
||||
|
||||
from homeassistant.const import Platform
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers import device_registry as dr, entity_registry as er
|
||||
|
||||
from tests.common import MockConfigEntry, snapshot_platform
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def platforms() -> list[Platform]:
|
||||
"""Override platforms for sensor tests."""
|
||||
return [Platform.SENSOR]
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("entity_registry_enabled_by_default", "init_integration")
|
||||
async def test_sensors(
|
||||
hass: HomeAssistant,
|
||||
snapshot: SnapshotAssertion,
|
||||
entity_registry: er.EntityRegistry,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
) -> None:
|
||||
"""Test sensor entities."""
|
||||
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("init_integration")
|
||||
async def test_sensor_device_assignment(
|
||||
hass: HomeAssistant,
|
||||
device_registry: dr.DeviceRegistry,
|
||||
entity_registry: er.EntityRegistry,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
) -> None:
|
||||
"""Test sensors are assigned to correct device."""
|
||||
device = device_registry.async_get_device(
|
||||
identifiers={("my_integration", "device_serial_123")}
|
||||
)
|
||||
assert device is not None
|
||||
|
||||
entities = er.async_entries_for_config_entry(
|
||||
entity_registry, mock_config_entry.entry_id
|
||||
)
|
||||
for entity in entities:
|
||||
assert entity.device_id == device.id
|
||||
```
|
||||
|
||||
## Coordinator Tests
|
||||
|
||||
```python
|
||||
"""Test coordinator."""
|
||||
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
import pytest
|
||||
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import ConfigEntryAuthFailed
|
||||
from homeassistant.helpers.update_coordinator import UpdateFailed
|
||||
|
||||
|
||||
async def test_coordinator_update_success(
|
||||
hass: HomeAssistant,
|
||||
mock_client: AsyncMock,
|
||||
) -> None:
|
||||
"""Test successful coordinator update."""
|
||||
coordinator = MyCoordinator(hass, mock_config_entry, mock_client)
|
||||
await coordinator.async_refresh()
|
||||
|
||||
assert coordinator.data.temperature == 21.5
|
||||
assert coordinator.last_update_success
|
||||
|
||||
|
||||
async def test_coordinator_update_failed(
|
||||
hass: HomeAssistant,
|
||||
mock_client: AsyncMock,
|
||||
) -> None:
|
||||
"""Test coordinator handles API error."""
|
||||
mock_client.get_data.side_effect = MyError("Connection failed")
|
||||
|
||||
coordinator = MyCoordinator(hass, mock_config_entry, mock_client)
|
||||
|
||||
with pytest.raises(UpdateFailed):
|
||||
await coordinator._async_update_data()
|
||||
|
||||
|
||||
async def test_coordinator_auth_failed(
|
||||
hass: HomeAssistant,
|
||||
mock_client: AsyncMock,
|
||||
) -> None:
|
||||
"""Test coordinator handles auth error."""
|
||||
mock_client.get_data.side_effect = AuthError("Invalid token")
|
||||
|
||||
coordinator = MyCoordinator(hass, mock_config_entry, mock_client)
|
||||
|
||||
with pytest.raises(ConfigEntryAuthFailed):
|
||||
await coordinator._async_update_data()
|
||||
```
|
||||
|
||||
## Diagnostics Tests
|
||||
|
||||
```python
|
||||
"""Test diagnostics."""
|
||||
|
||||
from homeassistant.components.diagnostics import REDACTED
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
from tests.common import MockConfigEntry
|
||||
from tests.components.my_integration import snapshot_platform
|
||||
from tests.typing import ClientSessionGenerator
|
||||
|
||||
|
||||
async def test_diagnostics(
|
||||
hass: HomeAssistant,
|
||||
hass_client: ClientSessionGenerator,
|
||||
init_integration: MockConfigEntry,
|
||||
snapshot: SnapshotAssertion,
|
||||
) -> None:
|
||||
"""Test diagnostics."""
|
||||
assert await get_diagnostics_for_config_entry(
|
||||
hass, hass_client, init_integration
|
||||
) == snapshot
|
||||
```
|
||||
|
||||
## Common Fixtures
|
||||
|
||||
```python
|
||||
from tests.common import MockConfigEntry, load_fixture
|
||||
|
||||
# Load JSON fixture
|
||||
data = load_fixture("device_data.json", DOMAIN)
|
||||
|
||||
# Enable all entities (including disabled by default)
|
||||
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
|
||||
|
||||
# Freeze time
|
||||
from freezegun.api import FrozenDateTimeFactory
|
||||
|
||||
async def test_with_frozen_time(
|
||||
hass: HomeAssistant,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
) -> None:
|
||||
freezer.tick(timedelta(minutes=5))
|
||||
await hass.async_block_till_done()
|
||||
```
|
||||
|
||||
## Update Snapshots
|
||||
|
||||
```bash
|
||||
# Update snapshots
|
||||
pytest tests/components/my_integration --snapshot-update
|
||||
|
||||
# Always re-run without flag to verify
|
||||
pytest tests/components/my_integration
|
||||
```
|
||||
|
||||
## Test Commands
|
||||
|
||||
```bash
|
||||
# Run tests with coverage
|
||||
pytest tests/components/my_integration \
|
||||
--cov=homeassistant.components.my_integration \
|
||||
--cov-report term-missing \
|
||||
--numprocesses=auto
|
||||
|
||||
# Run specific test
|
||||
pytest tests/components/my_integration/test_config_flow.py::test_user_flow_success
|
||||
|
||||
# Quick test of changed files
|
||||
pytest --timeout=10 --picked
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Never access `hass.data` directly** - Use fixtures and proper setup
|
||||
2. **Mock all external APIs** - Use fixtures with realistic JSON data
|
||||
3. **Use snapshot testing** - For entity states and attributes
|
||||
4. **Test error paths** - Connection errors, auth failures, invalid data
|
||||
5. **Test edge cases** - Empty data, missing fields, None values
|
||||
6. **>95% coverage required** - All code paths must be tested
|
||||
@@ -2,35 +2,14 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from homeassistant.const import Platform
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
from .coordinator import ArveConfigEntry, ArveCoordinator
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
PLATFORMS: list[Platform] = [Platform.SENSOR]
|
||||
|
||||
|
||||
async def async_migrate_entry(hass: HomeAssistant, entry: ArveConfigEntry) -> bool:
|
||||
"""Migrate entry."""
|
||||
_LOGGER.debug("Migrating from version %s.%s", entry.version, entry.minor_version)
|
||||
|
||||
if entry.version == 1:
|
||||
# 1 -> 1.2: Unique ID from integer to string
|
||||
if entry.minor_version == 1:
|
||||
minor_version = 2
|
||||
hass.config_entries.async_update_entry(
|
||||
entry, unique_id=str(entry.unique_id), minor_version=minor_version
|
||||
)
|
||||
|
||||
_LOGGER.debug("Migration successful")
|
||||
|
||||
return True
|
||||
|
||||
|
||||
async def async_setup_entry(hass: HomeAssistant, entry: ArveConfigEntry) -> bool:
|
||||
"""Set up Arve from a config entry."""
|
||||
|
||||
|
||||
@@ -19,9 +19,6 @@ _LOGGER = logging.getLogger(__name__)
|
||||
class ArveConfigFlowHandler(ConfigFlow, domain=DOMAIN):
|
||||
"""Handle a config flow for Arve."""
|
||||
|
||||
VERSION = 1
|
||||
MINOR_VERSION = 2
|
||||
|
||||
async def async_step_user(
|
||||
self, user_input: dict[str, Any] | None = None
|
||||
) -> ConfigFlowResult:
|
||||
@@ -38,7 +35,7 @@ class ArveConfigFlowHandler(ConfigFlow, domain=DOMAIN):
|
||||
except ArveConnectionError:
|
||||
errors["base"] = "cannot_connect"
|
||||
else:
|
||||
await self.async_set_unique_id(str(customer.customerId))
|
||||
await self.async_set_unique_id(customer.customerId)
|
||||
self._abort_if_unique_id_configured()
|
||||
return self.async_create_entry(
|
||||
title="Arve",
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
from dataclasses import dataclass
|
||||
from http import HTTPStatus
|
||||
import logging
|
||||
|
||||
import aiohttp
|
||||
from microBeesPy import MicroBees
|
||||
@@ -16,8 +15,6 @@ from homeassistant.helpers import config_entry_oauth2_flow
|
||||
from .const import DOMAIN, PLATFORMS
|
||||
from .coordinator import MicroBeesUpdateCoordinator
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass(frozen=True, kw_only=True)
|
||||
class HomeAssistantMicroBeesData:
|
||||
@@ -28,23 +25,6 @@ class HomeAssistantMicroBeesData:
|
||||
session: config_entry_oauth2_flow.OAuth2Session
|
||||
|
||||
|
||||
async def async_migrate_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
||||
"""Migrate entry."""
|
||||
_LOGGER.debug("Migrating from version %s.%s", entry.version, entry.minor_version)
|
||||
|
||||
if entry.version == 1:
|
||||
# 1 -> 1.2: Unique ID from integer to string
|
||||
if entry.minor_version == 1:
|
||||
minor_version = 2
|
||||
hass.config_entries.async_update_entry(
|
||||
entry, unique_id=str(entry.unique_id), minor_version=minor_version
|
||||
)
|
||||
|
||||
_LOGGER.debug("Migration successful")
|
||||
|
||||
return True
|
||||
|
||||
|
||||
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
||||
"""Set up microBees from a config entry."""
|
||||
implementation = (
|
||||
|
||||
@@ -19,8 +19,6 @@ class OAuth2FlowHandler(
|
||||
"""Handle a config flow for microBees."""
|
||||
|
||||
DOMAIN = DOMAIN
|
||||
VERSION = 1
|
||||
MINOR_VERSION = 2
|
||||
|
||||
@property
|
||||
def logger(self) -> logging.Logger:
|
||||
@@ -49,7 +47,7 @@ class OAuth2FlowHandler(
|
||||
self.logger.exception("Unexpected error")
|
||||
return self.async_abort(reason="unknown")
|
||||
|
||||
await self.async_set_unique_id(str(current_user.id))
|
||||
await self.async_set_unique_id(current_user.id)
|
||||
if self.source != SOURCE_REAUTH:
|
||||
self._abort_if_unique_id_configured()
|
||||
return self.async_create_entry(
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.const import Platform
|
||||
from homeassistant.core import HomeAssistant
|
||||
@@ -17,28 +15,9 @@ from .api import AuthenticatedMonzoAPI
|
||||
from .const import DOMAIN
|
||||
from .coordinator import MonzoCoordinator
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
PLATFORMS: list[Platform] = [Platform.SENSOR]
|
||||
|
||||
|
||||
async def async_migrate_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
||||
"""Migrate entry."""
|
||||
_LOGGER.debug("Migrating from version %s.%s", entry.version, entry.minor_version)
|
||||
|
||||
if entry.version == 1:
|
||||
# 1 -> 1.2: Unique ID from integer to string
|
||||
if entry.minor_version == 1:
|
||||
minor_version = 2
|
||||
hass.config_entries.async_update_entry(
|
||||
entry, unique_id=str(entry.unique_id), minor_version=minor_version
|
||||
)
|
||||
|
||||
_LOGGER.debug("Migration successful")
|
||||
|
||||
return True
|
||||
|
||||
|
||||
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
||||
"""Set up Monzo from a config entry."""
|
||||
implementation = await async_get_config_entry_implementation(hass, entry)
|
||||
|
||||
@@ -21,8 +21,6 @@ class MonzoFlowHandler(
|
||||
"""Handle a config flow."""
|
||||
|
||||
DOMAIN = DOMAIN
|
||||
VERSION = 1
|
||||
MINOR_VERSION = 2
|
||||
|
||||
oauth_data: dict[str, Any]
|
||||
|
||||
@@ -53,7 +51,7 @@ class MonzoFlowHandler(
|
||||
"""Create an entry for the flow."""
|
||||
self.oauth_data = data
|
||||
user_id = data[CONF_TOKEN]["user_id"]
|
||||
await self.async_set_unique_id(str(user_id))
|
||||
await self.async_set_unique_id(user_id)
|
||||
if self.source != SOURCE_REAUTH:
|
||||
self._abort_if_unique_id_configured()
|
||||
else:
|
||||
|
||||
@@ -83,14 +83,6 @@ async def async_migrate_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
||||
)
|
||||
return False
|
||||
|
||||
if entry.version == 2:
|
||||
# 2 -> 2.2: Unique ID from integer to string
|
||||
if entry.minor_version == 1:
|
||||
minor_version = 2
|
||||
hass.config_entries.async_update_entry(
|
||||
entry, unique_id=str(entry.unique_id), minor_version=minor_version
|
||||
)
|
||||
|
||||
return True
|
||||
|
||||
|
||||
|
||||
@@ -20,7 +20,6 @@ class ToonFlowHandler(AbstractOAuth2FlowHandler, domain=DOMAIN):
|
||||
|
||||
DOMAIN = DOMAIN
|
||||
VERSION = 2
|
||||
MINOR_VERSION = 2
|
||||
|
||||
agreements: list[Agreement]
|
||||
data: dict[str, Any]
|
||||
@@ -93,7 +92,7 @@ class ToonFlowHandler(AbstractOAuth2FlowHandler, domain=DOMAIN):
|
||||
if self.migrate_entry:
|
||||
await self.hass.config_entries.async_remove(self.migrate_entry)
|
||||
|
||||
await self.async_set_unique_id(str(agreement.agreement_id))
|
||||
await self.async_set_unique_id(agreement.agreement_id)
|
||||
self._abort_if_unique_id_configured()
|
||||
|
||||
self.data[CONF_AGREEMENT_ID] = agreement.agreement_id
|
||||
|
||||
@@ -27,10 +27,7 @@ def mock_setup_entry() -> Generator[AsyncMock]:
|
||||
def mock_config_entry(hass: HomeAssistant, mock_arve: MagicMock) -> MockConfigEntry:
|
||||
"""Return the default mocked config entry."""
|
||||
return MockConfigEntry(
|
||||
title="Arve",
|
||||
domain=DOMAIN,
|
||||
data=USER_INPUT,
|
||||
unique_id=str(mock_arve.customer_id),
|
||||
title="Arve", domain=DOMAIN, data=USER_INPUT, unique_id=mock_arve.customer_id
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -34,7 +34,7 @@ async def test_correct_flow(
|
||||
assert result2["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result2["data"] == USER_INPUT
|
||||
assert len(mock_setup_entry.mock_calls) == 1
|
||||
assert result2["result"].unique_id == "12345"
|
||||
assert result2["result"].unique_id == 12345
|
||||
|
||||
|
||||
async def test_form_cannot_connect(
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
"""Tests for the Arve component."""
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
from homeassistant.components.arve.const import DOMAIN
|
||||
from homeassistant.const import CONF_ACCESS_TOKEN, CONF_CLIENT_SECRET
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
from tests.common import MockConfigEntry
|
||||
|
||||
|
||||
async def test_migrate_entry_minor_version_1_2(hass: HomeAssistant) -> None:
|
||||
"""Test migrating a 1.1 config entry to 1.2."""
|
||||
with patch("homeassistant.components.arve.async_setup_entry", return_value=True):
|
||||
entry = MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
data={CONF_ACCESS_TOKEN: "mock", CONF_CLIENT_SECRET: "mock"},
|
||||
version=1,
|
||||
minor_version=1,
|
||||
unique_id=12345,
|
||||
)
|
||||
entry.add_to_hass(hass)
|
||||
assert await hass.config_entries.async_setup(entry.entry_id)
|
||||
assert entry.version == 1
|
||||
assert entry.minor_version == 2
|
||||
assert entry.unique_id == "12345"
|
||||
@@ -59,7 +59,7 @@ def mock_config_entry(expires_at: int, scopes: list[str]) -> MockConfigEntry:
|
||||
return MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
title=TITLE,
|
||||
unique_id="54321",
|
||||
unique_id=54321,
|
||||
data={
|
||||
"auth_implementation": DOMAIN,
|
||||
"token": {
|
||||
|
||||
@@ -74,7 +74,7 @@ async def test_full_flow(
|
||||
assert result["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result["title"] == "test@microbees.com"
|
||||
assert "result" in result
|
||||
assert result["result"].unique_id == "54321"
|
||||
assert result["result"].unique_id == 54321
|
||||
assert "token" in result["result"].data
|
||||
assert result["result"].data["token"]["access_token"] == "mock-access-token"
|
||||
assert result["result"].data["token"]["refresh_token"] == "mock-refresh-token"
|
||||
@@ -197,7 +197,7 @@ async def test_config_reauth_wrong_account(
|
||||
) -> None:
|
||||
"""Test reauth with wrong account."""
|
||||
await setup_integration(hass, config_entry)
|
||||
microbees.return_value.getMyProfile.return_value.id = "12345"
|
||||
microbees.return_value.getMyProfile.return_value.id = 12345
|
||||
result = await config_entry.start_reauth_flow(hass)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "reauth_confirm"
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
"""Tests for the microBees component."""
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
from homeassistant.components.microbees.const import DOMAIN
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
from tests.common import MockConfigEntry
|
||||
|
||||
|
||||
async def test_migrate_entry_minor_version_1_2(hass: HomeAssistant) -> None:
|
||||
"""Test migrating a 1.1 config entry to 1.2."""
|
||||
with patch(
|
||||
"homeassistant.components.microbees.async_setup_entry", return_value=True
|
||||
):
|
||||
entry = MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
data={
|
||||
"auth_implementation": DOMAIN,
|
||||
"token": {
|
||||
"refresh_token": "mock-refresh-token",
|
||||
"access_token": "mock-access-token",
|
||||
"type": "Bearer",
|
||||
"expires_in": 60,
|
||||
},
|
||||
},
|
||||
version=1,
|
||||
minor_version=1,
|
||||
unique_id=54321,
|
||||
)
|
||||
entry.add_to_hass(hass)
|
||||
assert await hass.config_entries.async_setup(entry.entry_id)
|
||||
assert entry.version == 1
|
||||
assert entry.minor_version == 2
|
||||
assert entry.unique_id == "54321"
|
||||
@@ -244,7 +244,7 @@ async def test_config_reauth_wrong_account(
|
||||
"access_token": "mock-access-token",
|
||||
"type": "Bearer",
|
||||
"expires_in": 60,
|
||||
"user_id": "12346",
|
||||
"user_id": 12346,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""Tests for component initialisation."""
|
||||
|
||||
from datetime import timedelta
|
||||
from unittest.mock import AsyncMock, patch
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
from freezegun.api import FrozenDateTimeFactory
|
||||
from monzopy import AuthorisationExpiredError
|
||||
@@ -35,29 +35,3 @@ async def test_api_can_trigger_reauth(
|
||||
assert flow["step_id"] == "reauth_confirm"
|
||||
assert flow["handler"] == DOMAIN
|
||||
assert flow["context"]["source"] == SOURCE_REAUTH
|
||||
|
||||
|
||||
async def test_migrate_entry_minor_version_1_2(hass: HomeAssistant) -> None:
|
||||
"""Test migrating a 1.1 config entry to 1.2."""
|
||||
with patch("homeassistant.components.monzo.async_setup_entry", return_value=True):
|
||||
entry = MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
data={
|
||||
"auth_implementation": DOMAIN,
|
||||
"token": {
|
||||
"refresh_token": "mock-refresh-token",
|
||||
"access_token": "mock-access-token",
|
||||
"type": "Bearer",
|
||||
"expires_in": 60,
|
||||
"user_id": "600",
|
||||
},
|
||||
},
|
||||
version=1,
|
||||
minor_version=1,
|
||||
unique_id=600,
|
||||
)
|
||||
entry.add_to_hass(hass)
|
||||
assert await hass.config_entries.async_setup(entry.entry_id)
|
||||
assert entry.version == 1
|
||||
assert entry.minor_version == 2
|
||||
assert entry.unique_id == "600"
|
||||
|
||||
@@ -213,7 +213,7 @@ async def test_agreement_already_set_up(
|
||||
) -> None:
|
||||
"""Test showing display form again if display already exists."""
|
||||
await setup_component(hass)
|
||||
MockConfigEntry(domain=DOMAIN, unique_id="123").add_to_hass(hass)
|
||||
MockConfigEntry(domain=DOMAIN, unique_id=123).add_to_hass(hass)
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": SOURCE_USER}
|
||||
)
|
||||
@@ -312,7 +312,7 @@ async def test_import_migration(
|
||||
aioclient_mock: AiohttpClientMocker,
|
||||
) -> None:
|
||||
"""Test if importing step with migration works."""
|
||||
old_entry = MockConfigEntry(domain=DOMAIN, unique_id="123", version=1)
|
||||
old_entry = MockConfigEntry(domain=DOMAIN, unique_id=123, version=1)
|
||||
old_entry.add_to_hass(hass)
|
||||
|
||||
await setup_component(hass)
|
||||
|
||||
@@ -40,29 +40,3 @@ async def test_oauth_implementation_not_available(
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert config_entry.state is ConfigEntryState.SETUP_RETRY
|
||||
|
||||
|
||||
async def test_migrate_entry_minor_version_2_2(hass: HomeAssistant) -> None:
|
||||
"""Test migrating a 2.1 config entry to 2.2."""
|
||||
with patch("homeassistant.components.toon.async_setup_entry", return_value=True):
|
||||
entry = MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
data={
|
||||
"auth_implementation": DOMAIN,
|
||||
"token": {
|
||||
"refresh_token": "mock-refresh-token",
|
||||
"access_token": "mock-access-token",
|
||||
"type": "Bearer",
|
||||
"expires_in": 60,
|
||||
},
|
||||
"agreement_id": 123,
|
||||
},
|
||||
version=2,
|
||||
minor_version=1,
|
||||
unique_id=123,
|
||||
)
|
||||
entry.add_to_hass(hass)
|
||||
assert await hass.config_entries.async_setup(entry.entry_id)
|
||||
assert entry.version == 2
|
||||
assert entry.minor_version == 2
|
||||
assert entry.unique_id == "123"
|
||||
|
||||
Reference in New Issue
Block a user