Compare commits

..

2 Commits

Author SHA1 Message Date
Claude
6bcbcbc6a1 Convert agent files to proper Claude Skills
Restructured from agent markdown files to proper Claude Skills format:

Changed:
- Moved from .claude/agents/*.md to .claude/skills/*/SKILL.md
- Updated YAML frontmatter to Skills format (name + description only)
- Removed agent-specific fields (model, color, tools)
- Condensed descriptions to focus on triggering conditions
- Updated README to reflect proper Skills structure

New Skills:
- testing: Write, run, and fix tests for HA integrations
- code-review: Review code for quality and standards
- quality-scale-architect: Architecture and quality tier guidance

Skills use progressive disclosure for efficient context management:
- Level 1: Metadata (always loaded, ~100 tokens)
- Level 2: Instructions (loaded when triggered, <5k tokens)
- Level 3: Resources (loaded as needed, unlimited)

Reference files in .claude/references/ remain unchanged and are
loaded on-demand by Skills.

See: https://platform.claude.com/docs/en/agents-and-tools/agent-skills/
2026-01-12 19:08:45 +00:00
Claude
5c8f494ac6 Add Claude Code skills and reference documentation
Created structured skill system for Home Assistant development:

Agents (specialized AI assistants):
- testing.md: Test writing, running, and fixing specialist
- code-review.md: Code quality and standards reviewer
- quality-scale-architect.md: Architecture and tier guidance

Reference documentation:
- diagnostics.md: Integration diagnostics implementation
- sensor.md: Sensor platform implementation guide
- binary_sensor.md: Binary sensor platform guide
- switch.md: Switch platform guide
- button.md: Button platform guide
- number.md: Number platform guide
- select.md: Select platform guide

Each file provides comprehensive implementation guidance, patterns,
best practices, and quality scale considerations extracted from
CLAUDE.md and organized for focused, specialized assistance.
2026-01-11 20:33:36 +00:00
2676 changed files with 45085 additions and 111527 deletions

168
.claude/README.md Normal file
View File

@@ -0,0 +1,168 @@
# Claude Code Skills and Reference Files
This directory contains Claude Skills and reference documentation for working with Home Assistant integrations.
## Directory Structure
```
.claude/
├── skills/ # Claude Skills (auto-loaded)
│ ├── testing/
│ │ └── SKILL.md # Testing specialist skill
│ ├── code-review/
│ │ └── SKILL.md # Code review specialist skill
│ └── quality-scale-architect/
│ └── SKILL.md # Architecture guidance skill
├── agents/ # Legacy agent definitions
│ └── quality-scale-rule-verifier.md
└── references/ # Deep-dive reference docs
├── diagnostics.md # Diagnostics implementation
├── sensor.md # Sensor platform
├── binary_sensor.md # Binary sensor platform
├── switch.md # Switch platform
├── button.md # Button platform
├── number.md # Number platform
└── select.md # Select platform
```
## Claude Skills
Claude Skills are modular capabilities that extend Claude's functionality. Each Skill packages instructions and metadata that Claude uses automatically when relevant.
### How Skills Work
Skills use **progressive disclosure** - they load content in stages:
1. **Level 1 - Metadata (always loaded)**: Skill name and description
2. **Level 2 - Instructions (loaded when triggered)**: Main SKILL.md content
3. **Level 3+ - Resources (loaded as needed)**: Reference files and additional docs
This means you can have many Skills installed with minimal context penalty. Claude only knows each Skill exists and when to use it until triggered.
### Available Skills
#### Testing (`testing`)
**Use when**: Writing, running, or fixing tests for Home Assistant integrations
Specializes in:
- Writing comprehensive test coverage (>95%)
- Running pytest with appropriate flags
- Fixing failing tests and updating snapshots
- Following Home Assistant testing patterns
- Modern fixture patterns and snapshot testing
**Triggers on**: Requests about writing tests, running tests, fixing test failures, test coverage, pytest, snapshots
#### Code Review (`code-review`)
**Use when**: Reviewing code for quality, best practices, and standards compliance
Specializes in:
- Reviewing pull requests and code changes
- Identifying anti-patterns and security vulnerabilities
- Verifying async patterns and error handling
- Ensuring quality scale compliance
- Performance optimization
**Triggers on**: Requests to review code, check for issues, analyze code quality, security review
#### Quality Scale Architect (`quality-scale-architect`)
**Use when**: Needing architectural guidance and quality scale planning
Specializes in:
- High-level architecture guidance
- Quality scale tier selection (Bronze/Silver/Gold/Platinum)
- Integration structure planning
- Pattern recommendations (coordinator, push, hub)
- Progression strategies between quality tiers
**Triggers on**: Requests about architecture, integration design, quality tiers, structural planning, choosing patterns
## Reference Files
Reference files provide deep-dive documentation for specific implementation areas. Skills can reference these for detailed guidance, and they're loaded on-demand to avoid consuming context.
### Available References
- **diagnostics.md**: Complete guide to implementing integration and device diagnostics, data redaction, testing
- **sensor.md**: Sensor platform implementation, device classes, state classes, entity descriptions
- **binary_sensor.md**: Binary sensor implementation, device classes, push-updated patterns
- **switch.md**: Switch control implementation, state updates, configuration switches
- **button.md**: Button action implementation, device classes, one-time actions
- **number.md**: Numeric value control, ranges, display modes, units
- **select.md**: Option selection implementation, enums, translations, dynamic options
## How to Use
### As a Developer
Skills work automatically - just ask Claude to help with tasks:
- **Testing**: "Write tests for my sensor platform" or "Fix the failing config flow tests"
- **Review**: "Review this integration for security issues" or "Check my async patterns"
- **Architecture**: "Help me design a hub integration" or "What quality tier should I target?"
### As Claude
Skills are triggered automatically when requests match the skill descriptions. Skills can reference the documentation files in `.claude/references/` for detailed implementation guidance.
Example:
```python
# When a testing request comes in, Claude triggers the testing skill
# The skill can then reference .claude/references/sensor.md for sensor-specific patterns
```
## Quality Scale Overview
Home Assistant uses a Quality Scale system:
- **Bronze**: Basic requirements (mandatory baseline) - Config flow, unique IDs, auth flows
- **Silver**: Enhanced functionality - Unavailability tracking, runtime data, parallel updates
- **Gold**: Advanced features - Diagnostics, translations, device registry
- **Platinum**: Highest quality - Strict typing, async-only dependencies, WebSession injection
All Bronze rules are mandatory. Higher tiers are additive.
## Skill Structure
Each Skill is a directory containing a `SKILL.md` file with YAML frontmatter:
```yaml
---
name: skill-name
description: Brief description of what this Skill does and when to use it (max 1024 chars)
---
# Skill Content in Markdown
Instructions, examples, and guidance...
```
**Progressive Loading**: Only the name/description are loaded initially. The full content loads when the Skill is triggered.
## Creating Custom Skills
To add a new Skill:
1. Create a directory: `.claude/skills/my-skill/`
2. Add a `SKILL.md` file with proper frontmatter
3. Include clear instructions and examples
4. Reference existing documentation when appropriate
See [Claude Skills Documentation](https://platform.claude.com/docs/en/agents-and-tools/agent-skills/overview) for complete guidance.
## Additional Resources
- Main instructions: `/home/user/core/CLAUDE.md`
- Home Assistant Docs: https://developers.home-assistant.io
- Integration Quality Scale: https://developers.home-assistant.io/docs/core/integration-quality-scale/
- Claude Skills Cookbook: https://platform.claude.com/cookbook/skills-notebooks-01-skills-introduction
## Contributing
When adding new Skills or references:
1. Follow the proper Skill structure (SKILL.md with frontmatter)
2. Keep descriptions concise and trigger-focused (max 1024 chars)
3. Include practical examples in Skill content
4. Link to reference documentation for deep dives
5. Consider quality scale implications
6. Test that Skills trigger appropriately

View File

@@ -0,0 +1,470 @@
# Binary Sensor Platform Reference
## Overview
Binary sensors are read-only entities that represent an on/off, true/false, or open/closed state. They are simpler than regular sensors and don't have units or numeric values.
## Basic Binary Sensor Implementation
```python
"""Binary sensor platform for my_integration."""
from homeassistant.components.binary_sensor import (
BinarySensorDeviceClass,
BinarySensorEntity,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from . import MyConfigEntry
from .coordinator import MyCoordinator
from .entity import MyEntity
async def async_setup_entry(
hass: HomeAssistant,
entry: MyConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up binary sensors."""
coordinator = entry.runtime_data
async_add_entities(
MyBinarySensor(coordinator, device_id)
for device_id in coordinator.data.devices
)
class MyBinarySensor(MyEntity, BinarySensorEntity):
"""Representation of a binary sensor."""
_attr_has_entity_name = True
_attr_translation_key = "motion"
_attr_device_class = BinarySensorDeviceClass.MOTION
def __init__(self, coordinator: MyCoordinator, device_id: str) -> None:
"""Initialize the binary sensor."""
super().__init__(coordinator, device_id)
self._attr_unique_id = f"{device_id}_motion"
@property
def is_on(self) -> bool | None:
"""Return true if motion is detected."""
if device := self.coordinator.data.devices.get(self.device_id):
return device.motion_detected
return None
```
## Binary Sensor State
The core property for binary sensors is `is_on`:
```python
@property
def is_on(self) -> bool | None:
"""Return true if the binary sensor is on."""
return self.device.is_active
# Alternatively, use attribute
_attr_is_on = True # or False, or None
```
**State Meaning**:
- `True` / `"on"` - Active/detected/open
- `False` / `"off"` - Inactive/not detected/closed
- `None` - Unknown (displays as "unavailable")
## Device Classes
Binary sensors should use device classes for proper representation:
```python
from homeassistant.components.binary_sensor import BinarySensorDeviceClass
# Common device classes
_attr_device_class = BinarySensorDeviceClass.MOTION
_attr_device_class = BinarySensorDeviceClass.OCCUPANCY
_attr_device_class = BinarySensorDeviceClass.DOOR
_attr_device_class = BinarySensorDeviceClass.WINDOW
_attr_device_class = BinarySensorDeviceClass.OPENING
_attr_device_class = BinarySensorDeviceClass.CONNECTIVITY
_attr_device_class = BinarySensorDeviceClass.BATTERY
_attr_device_class = BinarySensorDeviceClass.BATTERY_CHARGING
_attr_device_class = BinarySensorDeviceClass.PROBLEM
_attr_device_class = BinarySensorDeviceClass.RUNNING
_attr_device_class = BinarySensorDeviceClass.SMOKE
_attr_device_class = BinarySensorDeviceClass.MOISTURE
_attr_device_class = BinarySensorDeviceClass.LOCK
_attr_device_class = BinarySensorDeviceClass.TAMPER
_attr_device_class = BinarySensorDeviceClass.PLUG
_attr_device_class = BinarySensorDeviceClass.POWER
```
### Device Class Selection Guide
**Detection Sensors**:
- Motion detector → `MOTION`
- Presence detector → `OCCUPANCY`
- Smoke detector → `SMOKE`
- Water leak detector → `MOISTURE`
**Contact Sensors**:
- Door sensor → `DOOR`
- Window sensor → `WINDOW`
- Generic contact → `OPENING`
**Status Sensors**:
- Network connection → `CONNECTIVITY`
- Device running → `RUNNING`
- Low battery → `BATTERY`
- Charging state → `BATTERY_CHARGING`
- Problem/fault → `PROBLEM`
- Tamper detection → `TAMPER`
**Power Sensors**:
- Outlet state → `PLUG`
- Power state → `POWER`
- Lock state → `LOCK`
## Entity Descriptions Pattern
For multiple similar binary sensors:
```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 MyBinarySensorDescription(BinarySensorEntityDescription):
"""Describes a binary sensor."""
is_on_fn: Callable[[MyData], bool | None]
BINARY_SENSORS: tuple[MyBinarySensorDescription, ...] = (
MyBinarySensorDescription(
key="motion",
translation_key="motion",
device_class=BinarySensorDeviceClass.MOTION,
is_on_fn=lambda data: data.motion_detected,
),
MyBinarySensorDescription(
key="door",
translation_key="door",
device_class=BinarySensorDeviceClass.DOOR,
is_on_fn=lambda data: data.door_open,
),
MyBinarySensorDescription(
key="battery_low",
translation_key="battery_low",
device_class=BinarySensorDeviceClass.BATTERY,
entity_category=EntityCategory.DIAGNOSTIC,
is_on_fn=lambda data: data.battery_level < 20,
),
)
async def async_setup_entry(
hass: HomeAssistant,
entry: MyConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up binary sensors."""
coordinator = entry.runtime_data
async_add_entities(
MyBinarySensor(coordinator, device_id, description)
for device_id in coordinator.data.devices
for description in BINARY_SENSORS
)
class MyBinarySensor(MyEntity, BinarySensorEntity):
"""Binary sensor using entity description."""
entity_description: MyBinarySensorDescription
def __init__(
self,
coordinator: MyCoordinator,
device_id: str,
description: MyBinarySensorDescription,
) -> None:
"""Initialize the binary sensor."""
super().__init__(coordinator, device_id)
self.entity_description = description
self._attr_unique_id = f"{device_id}_{description.key}"
@property
def is_on(self) -> bool | None:
"""Return true if the binary sensor is on."""
if device := self.coordinator.data.devices.get(self.device_id):
return self.entity_description.is_on_fn(device)
return None
```
## Entity Category
Mark diagnostic or configuration binary sensors:
```python
from homeassistant.helpers.entity import EntityCategory
# Diagnostic sensors
_attr_entity_category = EntityCategory.DIAGNOSTIC
# Examples: connectivity, update available, battery low
# Config sensors
_attr_entity_category = EntityCategory.CONFIG
# Examples: configuration status
```
## State Inversion
For some sensors, you may need to invert the logic:
```python
class MyBinarySensor(BinarySensorEntity):
"""Binary sensor with inverted state."""
@property
def is_on(self) -> bool | None:
"""Return true if sensor is on."""
if self.device.is_closed:
return False # Closed = off for door sensor
if self.device.is_open:
return True # Open = on for door sensor
return None
```
## Push-Updated Binary Sensor
For event-driven sensors:
```python
class MyPushBinarySensor(BinarySensorEntity):
"""Push-updated binary sensor."""
_attr_should_poll = False
async def async_added_to_hass(self) -> None:
"""Subscribe to updates when added."""
self.async_on_remove(
self.device.subscribe_state(self._handle_state_update)
)
@callback
def _handle_state_update(self, state: bool) -> None:
"""Handle state update from device."""
self._attr_is_on = state
self.async_write_ha_state()
```
## Testing Binary Sensors
### Snapshot Testing
```python
"""Test binary sensors."""
import pytest
from syrupy import SnapshotAssertion
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_binary_sensors(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
mock_config_entry: MockConfigEntry,
init_integration,
) -> None:
"""Test binary sensor entities."""
await snapshot_platform(
hass,
entity_registry,
snapshot,
mock_config_entry.entry_id,
)
```
### State Testing
```python
async def test_binary_sensor_states(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test binary sensor states."""
await init_integration(hass, mock_config_entry)
# Test on state
state = hass.states.get("binary_sensor.my_device_motion")
assert state
assert state.state == "on"
assert state.attributes["device_class"] == "motion"
# Test off state
state = hass.states.get("binary_sensor.my_device_door")
assert state
assert state.state == "off"
assert state.attributes["device_class"] == "door"
```
## Common Patterns
### Pattern 1: Coordinator-Based
```python
class MyBinarySensor(CoordinatorEntity[MyCoordinator], BinarySensorEntity):
"""Coordinator-based binary sensor."""
_attr_should_poll = False
@property
def is_on(self) -> bool | None:
"""Get state from coordinator data."""
if device := self.coordinator.data.devices.get(self.device_id):
return device.is_active
return None
@property
def available(self) -> bool:
"""Return if entity is available."""
return super().available and self.device_id in self.coordinator.data
```
### Pattern 2: Event-Driven
```python
class MyEventBinarySensor(BinarySensorEntity):
"""Event-driven binary sensor."""
_attr_should_poll = False
async def async_added_to_hass(self) -> None:
"""Subscribe to events."""
self.async_on_remove(
async_dispatcher_connect(
self.hass,
f"{DOMAIN}_event",
self._handle_event,
)
)
@callback
def _handle_event(self, event_type: str, active: bool) -> None:
"""Handle incoming event."""
if event_type == self.event_type:
self._attr_is_on = active
self.async_write_ha_state()
```
### Pattern 3: Calculated/Derived
```python
class MyCalculatedBinarySensor(BinarySensorEntity):
"""Binary sensor calculated from other sensors."""
_attr_should_poll = False
async def async_added_to_hass(self) -> None:
"""Subscribe to source sensors."""
self.async_on_remove(
async_track_state_change_event(
self.hass,
["sensor.temperature", "sensor.humidity"],
self._handle_source_update,
)
)
@callback
def _handle_source_update(self, event: Event) -> None:
"""Recalculate when sources change."""
temp = self.hass.states.get("sensor.temperature")
humidity = self.hass.states.get("sensor.humidity")
if temp and humidity:
# Example: high comfort if temp 20-25 and humidity 30-60
temp_ok = 20 <= float(temp.state) <= 25
humidity_ok = 30 <= float(humidity.state) <= 60
self._attr_is_on = temp_ok and humidity_ok
self.async_write_ha_state()
```
## Best Practices
### ✅ DO
- Use appropriate device classes
- Return `None` for unknown state
- Use `is_on` property (not state)
- Implement unique IDs
- Use entity descriptions for similar sensors
- Mark diagnostic sensors with entity_category
- Use translation keys for entity names
- Handle availability properly
### ❌ DON'T
- Return strings like "on"/"off" from is_on
- Use regular Sensor for binary states
- Hardcode entity names
- Create binary sensors without device classes (when available)
- Use unavailable/unknown as state values
- Block the event loop
- Poll unnecessarily (use coordinator or events)
## Disabled by Default
For less important binary sensors:
```python
class MyConnectivitySensor(BinarySensorEntity):
"""Connectivity sensor - diagnostic."""
_attr_entity_registry_enabled_default = False
_attr_entity_category = EntityCategory.DIAGNOSTIC
_attr_device_class = BinarySensorDeviceClass.CONNECTIVITY
```
## Troubleshooting
### Binary Sensor Not Appearing
Check:
- [ ] Unique ID is set
- [ ] Platform is in PLATFORMS list
- [ ] Entity is added with async_add_entities
- [ ] is_on returns bool or None (not string)
### State Not Updating
Check:
- [ ] Coordinator is updating (if used)
- [ ] Event subscriptions are working
- [ ] is_on returns correct value
- [ ] async_write_ha_state() is called (push updates)
### Wrong Icon
Check:
- [ ] Device class is set correctly
- [ ] Device class matches sensor purpose
- [ ] Icon translations if using Gold tier
## Quality Scale Considerations
- **Bronze**: Unique ID required
- **Gold**: Entity translations, device class, entity category
- **Platinum**: Full type hints
## References
- [Binary Sensor Documentation](https://developers.home-assistant.io/docs/core/entity/binary-sensor)
- [Device Classes](https://www.home-assistant.io/integrations/binary_sensor/#device-class)

View File

@@ -0,0 +1,459 @@
# Button Platform Reference
## Overview
Buttons are entities that trigger an action when pressed. They don't have a state (on/off) and are used for one-time actions like rebooting a device, triggering an update, or running a routine.
## Basic Button Implementation
```python
"""Button platform for my_integration."""
from homeassistant.components.button import ButtonEntity
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from . import MyConfigEntry
from .coordinator import MyCoordinator
from .entity import MyEntity
async def async_setup_entry(
hass: HomeAssistant,
entry: MyConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up buttons."""
coordinator = entry.runtime_data
async_add_entities(
MyButton(coordinator, device_id)
for device_id in coordinator.data.devices
)
class MyButton(MyEntity, ButtonEntity):
"""Representation of a button."""
_attr_has_entity_name = True
_attr_translation_key = "reboot"
def __init__(self, coordinator: MyCoordinator, device_id: str) -> None:
"""Initialize the button."""
super().__init__(coordinator, device_id)
self._attr_unique_id = f"{device_id}_reboot"
async def async_press(self) -> None:
"""Handle the button press."""
await self.coordinator.client.reboot(self.device_id)
```
## Button Method
The only required method for buttons:
```python
async def async_press(self) -> None:
"""Handle the button press."""
await self.device.trigger_action()
```
**Note**: Buttons don't have state. They only perform an action when pressed.
## Device Class
Buttons can have device classes to indicate their purpose:
```python
from homeassistant.components.button import ButtonDeviceClass
_attr_device_class = ButtonDeviceClass.RESTART
_attr_device_class = ButtonDeviceClass.UPDATE
_attr_device_class = ButtonDeviceClass.IDENTIFY
```
Device classes:
- `RESTART` - Reboot/restart device
- `UPDATE` - Trigger update check or installation
- `IDENTIFY` - Make device identify itself (blink LED, beep, etc.)
## Entity Category
Most buttons are configuration actions:
```python
from homeassistant.helpers.entity import EntityCategory
# Config buttons (device settings/actions)
_attr_entity_category = EntityCategory.CONFIG
# Examples: reboot, reset, identify
# Diagnostic buttons (troubleshooting)
_attr_entity_category = EntityCategory.DIAGNOSTIC
# Examples: test connection, refresh diagnostics
```
## Entity Descriptions Pattern
For multiple buttons:
```python
from dataclasses import dataclass
from collections.abc import Awaitable, Callable
from homeassistant.components.button import ButtonEntityDescription, ButtonDeviceClass
@dataclass(frozen=True, kw_only=True)
class MyButtonDescription(ButtonEntityDescription):
"""Describes a button."""
press_fn: Callable[[MyClient, str], Awaitable[None]]
BUTTONS: tuple[MyButtonDescription, ...] = (
MyButtonDescription(
key="reboot",
translation_key="reboot",
device_class=ButtonDeviceClass.RESTART,
entity_category=EntityCategory.CONFIG,
press_fn=lambda client, device_id: client.reboot(device_id),
),
MyButtonDescription(
key="identify",
translation_key="identify",
device_class=ButtonDeviceClass.IDENTIFY,
entity_category=EntityCategory.CONFIG,
press_fn=lambda client, device_id: client.identify(device_id),
),
MyButtonDescription(
key="check_update",
translation_key="check_update",
device_class=ButtonDeviceClass.UPDATE,
entity_category=EntityCategory.CONFIG,
press_fn=lambda client, device_id: client.check_updates(device_id),
),
)
async def async_setup_entry(
hass: HomeAssistant,
entry: MyConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up buttons."""
coordinator = entry.runtime_data
async_add_entities(
MyButton(coordinator, device_id, description)
for device_id in coordinator.data.devices
for description in BUTTONS
)
class MyButton(MyEntity, ButtonEntity):
"""Button using entity description."""
entity_description: MyButtonDescription
def __init__(
self,
coordinator: MyCoordinator,
device_id: str,
description: MyButtonDescription,
) -> None:
"""Initialize the button."""
super().__init__(coordinator, device_id)
self.entity_description = description
self._attr_unique_id = f"{device_id}_{description.key}"
async def async_press(self) -> None:
"""Handle the button press."""
await self.entity_description.press_fn(
self.coordinator.client,
self.device_id,
)
```
## Common Button Types
### Restart Button
```python
class RestartButton(ButtonEntity):
"""Restart device button."""
_attr_device_class = ButtonDeviceClass.RESTART
_attr_entity_category = EntityCategory.CONFIG
_attr_translation_key = "restart"
async def async_press(self) -> None:
"""Restart the device."""
await self.device.restart()
```
### Update Button
```python
class UpdateButton(ButtonEntity):
"""Trigger update check button."""
_attr_device_class = ButtonDeviceClass.UPDATE
_attr_entity_category = EntityCategory.CONFIG
_attr_translation_key = "check_update"
async def async_press(self) -> None:
"""Check for updates."""
await self.device.check_for_updates()
```
### Identify Button
```python
class IdentifyButton(ButtonEntity):
"""Make device identify itself."""
_attr_device_class = ButtonDeviceClass.IDENTIFY
_attr_entity_category = EntityCategory.CONFIG
_attr_translation_key = "identify"
async def async_press(self) -> None:
"""Trigger device identification."""
await self.device.identify()
```
### Custom Action Button
```python
class CustomButton(ButtonEntity):
"""Custom action button."""
_attr_entity_category = EntityCategory.CONFIG
_attr_translation_key = "run_cycle"
async def async_press(self) -> None:
"""Run cleaning cycle."""
await self.device.start_cleaning_cycle()
```
## State Updates After Press
Buttons trigger coordinator refresh if needed:
```python
async def async_press(self) -> None:
"""Handle press with refresh."""
await self.coordinator.client.reboot(self.device_id)
# Refresh coordinator to update related entities
await self.coordinator.async_request_refresh()
```
## Error Handling
Handle errors appropriately:
```python
from homeassistant.exceptions import HomeAssistantError
async def async_press(self) -> None:
"""Handle press with error handling."""
try:
await self.device.reboot()
except DeviceOfflineError as err:
raise HomeAssistantError(f"Device is offline: {err}") from err
except DeviceError as err:
raise HomeAssistantError(f"Failed to reboot: {err}") from err
```
## Testing Buttons
### Snapshot Testing
```python
"""Test buttons."""
import pytest
from syrupy import SnapshotAssertion
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_buttons(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
mock_config_entry: MockConfigEntry,
init_integration,
) -> None:
"""Test button entities."""
await snapshot_platform(
hass,
entity_registry,
snapshot,
mock_config_entry.entry_id,
)
```
### Press Testing
```python
from homeassistant.const import ATTR_ENTITY_ID
from homeassistant.components.button import DOMAIN as BUTTON_DOMAIN, SERVICE_PRESS
async def test_button_press(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_device,
) -> None:
"""Test button press."""
await init_integration(hass, mock_config_entry)
# Press button
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,
{ATTR_ENTITY_ID: "button.my_device_reboot"},
blocking=True,
)
# Verify action was called
mock_device.reboot.assert_called_once()
```
### Error Testing
```python
async def test_button_press_error(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_device,
) -> None:
"""Test button press with error."""
await init_integration(hass, mock_config_entry)
mock_device.reboot.side_effect = DeviceError("Connection failed")
# Press button should raise error
with pytest.raises(HomeAssistantError):
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,
{ATTR_ENTITY_ID: "button.my_device_reboot"},
blocking=True,
)
```
## Common Patterns
### Pattern 1: Simple Action Button
```python
class SimpleButton(ButtonEntity):
"""Simple button that triggers action."""
async def async_press(self) -> None:
"""Trigger action."""
await self.device.do_something()
```
### Pattern 2: Button with Coordinator Refresh
```python
class RefreshingButton(CoordinatorEntity[MyCoordinator], ButtonEntity):
"""Button that refreshes coordinator."""
async def async_press(self) -> None:
"""Trigger action and refresh."""
await self.coordinator.client.action(self.device_id)
await self.coordinator.async_request_refresh()
```
### Pattern 3: Button with Validation
```python
class ValidatingButton(ButtonEntity):
"""Button with pre-action validation."""
async def async_press(self) -> None:
"""Validate then trigger action."""
if not self.device.is_ready:
raise HomeAssistantError("Device not ready")
await self.device.trigger_action()
```
## Best Practices
### ✅ DO
- Use appropriate device class
- Set entity category (usually CONFIG)
- Handle errors with HomeAssistantError
- Implement unique IDs
- Use translation keys
- Refresh coordinator if state changes
- Provide clear button names/translations
### ❌ DON'T
- Create buttons that track state (use switch instead)
- Poll buttons (they have no state)
- Block the event loop
- Ignore errors silently
- Create buttons without entity category
- Hardcode entity names
- Use buttons for binary controls (use switch)
## Button vs. Switch vs. Service
**Use Button when**:
- One-time action with no state
- Trigger command (reboot, identify)
- User initiates action
**Use Switch when**:
- Binary control (on/off)
- State matters
- Can be turned on and off
**Use Service when**:
- Complex parameters needed
- Multiple related actions
- Integration-wide operations
## Troubleshooting
### Button Not Appearing
Check:
- [ ] Unique ID is set
- [ ] Platform is in PLATFORMS list
- [ ] Entity is added with async_add_entities
- [ ] async_press is implemented
### Button Press Not Working
Check:
- [ ] async_press is async def
- [ ] Not blocking the event loop
- [ ] API client is working
- [ ] Errors are being raised properly
### Button Not in Expected Category
Check:
- [ ] entity_category is set
- [ ] Using correct EntityCategory value
- [ ] Device class is appropriate
## Quality Scale Considerations
- **Bronze**: Unique ID required
- **Gold**: Entity translations, device class, entity category
- **Platinum**: Full type hints
## References
- [Button Documentation](https://developers.home-assistant.io/docs/core/entity/button)
- [Button Integration](https://www.home-assistant.io/integrations/button/)

View File

@@ -0,0 +1,420 @@
# Diagnostics Reference
## Overview
Diagnostics provide a way to collect and export integration data for troubleshooting purposes. This is a **Gold tier** quality scale requirement that helps users and developers debug issues.
## When to Implement Diagnostics
Diagnostics are required for:
- ✅ Gold tier and above integrations
- ✅ Any integration where users might need support
- ✅ Integrations with complex configuration or state
## Diagnostics Types
Home Assistant supports two types of diagnostics:
### 1. Config Entry Diagnostics
Provides data about a specific configuration entry.
**File**: `diagnostics.py` in your integration folder
```python
"""Diagnostics support for My Integration."""
from typing import Any
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from .const import DOMAIN
TO_REDACT = {
"api_key",
"access_token",
"refresh_token",
"password",
"username",
"email",
"latitude",
"longitude",
}
async def async_get_config_entry_diagnostics(
hass: HomeAssistant,
entry: ConfigEntry,
) -> dict[str, Any]:
"""Return diagnostics for a config entry."""
coordinator = entry.runtime_data
return {
"entry": {
"title": entry.title,
"data": async_redact_data(entry.data, TO_REDACT),
"options": async_redact_data(entry.options, TO_REDACT),
},
"coordinator_data": coordinator.data.to_dict(),
"last_update_success": coordinator.last_update_success,
"last_update": coordinator.last_update_success_time.isoformat()
if coordinator.last_update_success_time
else None,
}
```
### 2. Device Diagnostics
Provides data about a specific device.
```python
async def async_get_device_diagnostics(
hass: HomeAssistant,
entry: ConfigEntry,
device: dr.DeviceEntry,
) -> dict[str, Any]:
"""Return diagnostics for a device."""
coordinator = entry.runtime_data
# Find device identifier
device_id = None
for identifier in device.identifiers:
if identifier[0] == DOMAIN:
device_id = identifier[1]
break
if device_id is None:
return {}
device_data = coordinator.data.devices.get(device_id)
if device_data is None:
return {}
return {
"device_info": {
"id": device_id,
"name": device_data.name,
"model": device_data.model,
"firmware": device_data.firmware_version,
},
"device_data": device_data.to_dict(),
"entities": [
{
"entity_id": entity.entity_id,
"name": entity.name,
"state": hass.states.get(entity.entity_id).state
if (state := hass.states.get(entity.entity_id))
else None,
}
for entity in er.async_entries_for_device(
er.async_get(hass), device.id, include_disabled_entities=True
)
],
}
```
## Data Redaction
**CRITICAL**: Always redact sensitive information!
### What to Redact
Always redact:
- API keys, tokens, secrets
- Passwords, credentials
- Email addresses, usernames
- Precise GPS coordinates (latitude, longitude)
- MAC addresses (sometimes)
- Serial numbers (if sensitive)
- Personal information
### Using async_redact_data
```python
from homeassistant.helpers import async_redact_data
# Basic redaction
data = async_redact_data(entry.data, TO_REDACT)
# With nested redaction
TO_REDACT = {
"api_key",
"auth.password", # Nested key
"user.email", # Nested key
}
# Redacting from multiple sources
diagnostics = {
"config": async_redact_data(entry.data, TO_REDACT),
"options": async_redact_data(entry.options, TO_REDACT),
"coordinator": async_redact_data(coordinator.data, TO_REDACT),
}
```
### Custom Redaction
For complex data structures:
```python
def redact_device_data(data: dict[str, Any]) -> dict[str, Any]:
"""Redact sensitive device data."""
redacted = data.copy()
# Redact specific fields
if "serial_number" in redacted:
redacted["serial_number"] = "**REDACTED**"
# Redact nested structures
if "location" in redacted:
redacted["location"] = {
"city": redacted["location"].get("city"),
# Don't include exact coordinates
}
return redacted
```
## What to Include
### Good Diagnostic Data
Include information helpful for troubleshooting:
- ✅ Integration version/state
- ✅ Configuration (redacted)
- ✅ Coordinator/connection status
- ✅ Device information (model, firmware)
- ✅ API response examples (redacted)
- ✅ Error states
- ✅ Entity states
- ✅ Feature flags/capabilities
### Example Comprehensive Diagnostics
```python
async def async_get_config_entry_diagnostics(
hass: HomeAssistant,
entry: ConfigEntry,
) -> dict[str, Any]:
"""Return diagnostics for a config entry."""
coordinator = entry.runtime_data
return {
# Integration state
"integration": {
"version": coordinator.version,
"entry_id": entry.entry_id,
"title": entry.title,
"state": entry.state,
},
# Configuration (redacted)
"configuration": {
"data": async_redact_data(entry.data, TO_REDACT),
"options": async_redact_data(entry.options, TO_REDACT),
},
# Connection/Coordinator status
"coordinator": {
"last_update_success": coordinator.last_update_success,
"last_update": coordinator.last_update_success_time.isoformat()
if coordinator.last_update_success_time
else None,
"update_interval": coordinator.update_interval.total_seconds(),
"last_exception": str(coordinator.last_exception)
if coordinator.last_exception
else None,
},
# Device/System information
"devices": {
device_id: {
"name": device.name,
"model": device.model,
"firmware": device.firmware,
"features": device.supported_features,
"state": device.state,
}
for device_id, device in coordinator.data.devices.items()
},
# API information (redacted)
"api": {
"endpoint": coordinator.client.endpoint,
"authenticated": coordinator.client.is_authenticated,
"rate_limit_remaining": coordinator.client.rate_limit_remaining,
},
}
```
## Testing Diagnostics
### Test File Structure
```python
"""Test diagnostics."""
from homeassistant.core import HomeAssistant
from pytest_homeassistant_custom_component.common import MockConfigEntry
from tests.components.my_integration import setup_integration
async def test_entry_diagnostics(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_api,
) -> None:
"""Test config entry diagnostics."""
await setup_integration(hass, mock_config_entry)
diagnostics = await get_diagnostics_for_config_entry(
hass, hass_client, mock_config_entry
)
# Verify structure
assert "entry" in diagnostics
assert "coordinator_data" in diagnostics
# Verify redaction
assert "api_key" not in str(diagnostics)
assert "password" not in str(diagnostics)
# Verify useful data is present
assert diagnostics["entry"]["title"] == "My Device"
assert diagnostics["coordinator_data"]["devices"]
async def test_device_diagnostics(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
device_registry: dr.DeviceRegistry,
) -> None:
"""Test device diagnostics."""
await setup_integration(hass, mock_config_entry)
device = device_registry.async_get_device(
identifiers={(DOMAIN, "device_id")}
)
assert device
diagnostics = await get_diagnostics_for_device(
hass, hass_client, mock_config_entry, device
)
# Verify device-specific data
assert diagnostics["device_info"]["id"] == "device_id"
assert "entities" in diagnostics
```
## Common Patterns
### Pattern 1: Coordinator-Based Integration
```python
async def async_get_config_entry_diagnostics(
hass: HomeAssistant,
entry: ConfigEntry,
) -> dict[str, Any]:
"""Return diagnostics for a config entry."""
coordinator = entry.runtime_data
return {
"coordinator": {
"last_update_success": coordinator.last_update_success,
"data": coordinator.data.to_dict(),
}
}
```
### Pattern 2: Multiple Coordinators
```python
async def async_get_config_entry_diagnostics(
hass: HomeAssistant,
entry: ConfigEntry,
) -> dict[str, Any]:
"""Return diagnostics for a config entry."""
data = entry.runtime_data
return {
"device_coordinator": data.device_coordinator.data.to_dict(),
"status_coordinator": data.status_coordinator.data.to_dict(),
}
```
### Pattern 3: Hub with Multiple Devices
```python
async def async_get_config_entry_diagnostics(
hass: HomeAssistant,
entry: ConfigEntry,
) -> dict[str, Any]:
"""Return diagnostics for a config entry."""
hub = entry.runtime_data
return {
"hub": {
"connected": hub.connected,
"version": hub.version,
},
"devices": {
device_id: device.to_dict()
for device_id, device in hub.devices.items()
},
}
```
## Best Practices
### ✅ DO
- Redact all sensitive information
- Include coordinator state and update times
- Provide device/system information
- Include error messages (if present)
- Make data easily readable
- Test that redaction works
- Include API/connection status
### ❌ DON'T
- Include raw passwords, tokens, or API keys
- Include precise GPS coordinates
- Include personal information (emails, names)
- Make diagnostics too large (>1MB)
- Include binary data
- Assume all fields are present (use .get())
- Include sensitive serial numbers
## Troubleshooting
### Diagnostics Not Appearing
Check:
1. File named `diagnostics.py` in integration folder
2. Function named exactly `async_get_config_entry_diagnostics`
3. Proper import of `ConfigEntry` and `HomeAssistant`
4. Integration is loaded successfully
### Redaction Not Working
Check:
1. Using `async_redact_data` from `homeassistant.helpers`
2. Field names match exactly (case-sensitive)
3. Nested fields use dot notation: `"auth.password"`
4. TO_REDACT is a set, not a list
### Device Diagnostics Not Working
Check:
1. Device has proper identifiers
2. Function named exactly `async_get_device_diagnostics`
3. Device parameter is `dr.DeviceEntry`
4. Proper device lookup logic
## Quality Scale Considerations
Diagnostics are required for **Gold tier** integrations:
- Must implement config entry diagnostics
- Should implement device diagnostics (if applicable)
- Must redact all sensitive information
- Should provide comprehensive troubleshooting data
## References
- Quality Scale Rule: `diagnostics`
- Home Assistant Docs: [Integration Diagnostics](https://developers.home-assistant.io/docs/integration_fetching_data)
- Helper Functions: `homeassistant.helpers.redact`

View File

@@ -0,0 +1,508 @@
# Number Platform Reference
## Overview
Number entities allow users to control numeric values within a defined range. They're used for settings like volume, brightness, temperature setpoints, or any numeric configuration parameter.
## Basic Number Implementation
```python
"""Number platform for my_integration."""
from homeassistant.components.number import NumberEntity, NumberMode
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from . import MyConfigEntry
from .coordinator import MyCoordinator
from .entity import MyEntity
async def async_setup_entry(
hass: HomeAssistant,
entry: MyConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up numbers."""
coordinator = entry.runtime_data
async_add_entities(
MyNumber(coordinator, device_id)
for device_id in coordinator.data.devices
)
class MyNumber(MyEntity, NumberEntity):
"""Representation of a number."""
_attr_has_entity_name = True
_attr_translation_key = "volume"
_attr_native_min_value = 0
_attr_native_max_value = 100
_attr_native_step = 1
def __init__(self, coordinator: MyCoordinator, device_id: str) -> None:
"""Initialize the number."""
super().__init__(coordinator, device_id)
self._attr_unique_id = f"{device_id}_volume"
@property
def native_value(self) -> float | None:
"""Return the current value."""
if device := self.coordinator.data.devices.get(self.device_id):
return device.volume
return None
async def async_set_native_value(self, value: float) -> None:
"""Set new value."""
await self.coordinator.client.set_volume(self.device_id, int(value))
await self.coordinator.async_request_refresh()
```
## Number Properties
### Core Properties
```python
class MyNumber(NumberEntity):
"""Number with all common properties."""
# Basic identification
_attr_has_entity_name = True
_attr_translation_key = "brightness"
_attr_unique_id = "device_123_brightness"
# Value range and step
_attr_native_min_value = 0
_attr_native_max_value = 255
_attr_native_step = 1 # or 0.1 for decimals
# Unit of measurement
_attr_native_unit_of_measurement = PERCENTAGE # or other units
# Display mode
_attr_mode = NumberMode.SLIDER # or NumberMode.BOX, NumberMode.AUTO
# Entity category
_attr_entity_category = EntityCategory.CONFIG
@property
def native_value(self) -> float | None:
"""Return current value."""
return self.device.brightness
async def async_set_native_value(self, value: float) -> None:
"""Set new value."""
await self.device.set_brightness(int(value))
```
### Required Properties
```python
# Minimum value
_attr_native_min_value = 0
# Maximum value
_attr_native_max_value = 100
# Step size (precision)
_attr_native_step = 1 # Integers
_attr_native_step = 0.1 # One decimal place
_attr_native_step = 0.01 # Two decimal places
```
### Current Value
```python
@property
def native_value(self) -> float | None:
"""Return the current value."""
return self.device.current_value
# Or use attribute
_attr_native_value = 50.0
```
### Set Value Method
```python
async def async_set_native_value(self, value: float) -> None:
"""Update to new value."""
await self.device.set_value(value)
# Update state
self._attr_native_value = value
self.async_write_ha_state()
```
## Display Mode
Control how the number is displayed in the UI:
```python
from homeassistant.components.number import NumberMode
# Slider (default for ranges)
_attr_mode = NumberMode.SLIDER
# Input box (better for precise values or large ranges)
_attr_mode = NumberMode.BOX
# Auto (let HA decide based on range)
_attr_mode = NumberMode.AUTO
```
**When to use each**:
- `SLIDER`: Small ranges (0-100), settings like volume/brightness
- `BOX`: Large ranges, precise values, IDs or codes
- `AUTO`: Let Home Assistant decide (default)
## Device Class
Use device classes for proper representation:
```python
from homeassistant.components.number import NumberDeviceClass
# Common device classes
_attr_device_class = NumberDeviceClass.TEMPERATURE
_attr_device_class = NumberDeviceClass.HUMIDITY
_attr_device_class = NumberDeviceClass.VOLTAGE
_attr_device_class = NumberDeviceClass.CURRENT
_attr_device_class = NumberDeviceClass.POWER
_attr_device_class = NumberDeviceClass.BATTERY
_attr_device_class = NumberDeviceClass.DISTANCE
_attr_device_class = NumberDeviceClass.DURATION
```
## Units of Measurement
```python
from homeassistant.const import (
PERCENTAGE,
UnitOfTemperature,
UnitOfTime,
)
# Percentage (0-100)
_attr_native_unit_of_measurement = PERCENTAGE
# Temperature
_attr_native_unit_of_measurement = UnitOfTemperature.CELSIUS
# Time
_attr_native_unit_of_measurement = UnitOfTime.SECONDS
# Custom units
_attr_native_unit_of_measurement = "dB" # Decibels
```
## Entity Descriptions Pattern
For multiple number entities:
```python
from dataclasses import dataclass
from collections.abc import Awaitable, Callable
from homeassistant.components.number import NumberEntityDescription, NumberMode
@dataclass(frozen=True, kw_only=True)
class MyNumberDescription(NumberEntityDescription):
"""Describes a number."""
value_fn: Callable[[MyData], float | None]
set_fn: Callable[[MyClient, str, float], Awaitable[None]]
NUMBERS: tuple[MyNumberDescription, ...] = (
MyNumberDescription(
key="volume",
translation_key="volume",
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.volume,
set_fn=lambda client, device_id, value: client.set_volume(device_id, int(value)),
),
MyNumberDescription(
key="temperature_setpoint",
translation_key="temperature_setpoint",
device_class=NumberDeviceClass.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_fn=lambda client, device_id, value: client.set_temperature(device_id, value),
),
)
class MyNumber(MyEntity, NumberEntity):
"""Number using entity description."""
entity_description: MyNumberDescription
def __init__(
self,
coordinator: MyCoordinator,
device_id: str,
description: MyNumberDescription,
) -> None:
"""Initialize the number."""
super().__init__(coordinator, device_id)
self.entity_description = description
self._attr_unique_id = f"{device_id}_{description.key}"
@property
def native_value(self) -> float | None:
"""Return current value."""
if device := self.coordinator.data.devices.get(self.device_id):
return self.entity_description.value_fn(device)
return None
async def async_set_native_value(self, value: float) -> None:
"""Set new value."""
await self.entity_description.set_fn(
self.coordinator.client,
self.device_id,
value,
)
await self.coordinator.async_request_refresh()
```
## Value Validation
Home Assistant validates against min/max/step, but you can add custom validation:
```python
async def async_set_native_value(self, value: float) -> None:
"""Set value with custom validation."""
# Custom validation
if value % 5 != 0:
raise ValueError("Value must be multiple of 5")
await self.device.set_value(value)
await self.coordinator.async_request_refresh()
```
## State Update Patterns
### Pattern 1: Optimistic Update
```python
async def async_set_native_value(self, value: float) -> None:
"""Set value with optimistic update."""
# Update immediately
self._attr_native_value = value
self.async_write_ha_state()
try:
await self.device.set_value(value)
except DeviceError:
# Revert on error
await self.coordinator.async_request_refresh()
raise
```
### Pattern 2: Coordinator Refresh
```python
async def async_set_native_value(self, value: float) -> None:
"""Set value and refresh."""
await self.device.set_value(value)
# Get actual value from device
await self.coordinator.async_request_refresh()
```
### Pattern 3: Direct State Update
```python
async def async_set_native_value(self, value: float) -> None:
"""Set value with direct state update."""
new_value = await self.device.set_value(value)
# Device returns actual value
self._attr_native_value = new_value
self.async_write_ha_state()
```
## Testing Numbers
### Snapshot Testing
```python
"""Test numbers."""
import pytest
from syrupy import SnapshotAssertion
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_numbers(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
mock_config_entry: MockConfigEntry,
init_integration,
) -> None:
"""Test number entities."""
await snapshot_platform(
hass,
entity_registry,
snapshot,
mock_config_entry.entry_id,
)
```
### Value Testing
```python
from homeassistant.const import ATTR_ENTITY_ID
from homeassistant.components.number import (
ATTR_VALUE,
DOMAIN as NUMBER_DOMAIN,
SERVICE_SET_VALUE,
)
async def test_set_value(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_device,
) -> None:
"""Test setting number value."""
await init_integration(hass, mock_config_entry)
# Check initial value
state = hass.states.get("number.my_device_volume")
assert state
assert state.state == "50"
assert state.attributes["min"] == 0
assert state.attributes["max"] == 100
assert state.attributes["step"] == 1
# Set new value
await hass.services.async_call(
NUMBER_DOMAIN,
SERVICE_SET_VALUE,
{
ATTR_ENTITY_ID: "number.my_device_volume",
ATTR_VALUE: 75,
},
blocking=True,
)
mock_device.set_volume.assert_called_once_with(75)
# Verify state updated
state = hass.states.get("number.my_device_volume")
assert state.state == "75"
```
## Common Number Types
### Volume Control
```python
class VolumeNumber(NumberEntity):
"""Volume control."""
_attr_native_min_value = 0
_attr_native_max_value = 100
_attr_native_step = 1
_attr_native_unit_of_measurement = PERCENTAGE
_attr_mode = NumberMode.SLIDER
```
### Temperature Setpoint
```python
class TemperatureNumber(NumberEntity):
"""Temperature setpoint."""
_attr_device_class = NumberDeviceClass.TEMPERATURE
_attr_native_min_value = 16.0
_attr_native_max_value = 30.0
_attr_native_step = 0.5
_attr_native_unit_of_measurement = UnitOfTemperature.CELSIUS
_attr_mode = NumberMode.SLIDER
```
### Duration Setting
```python
class DurationNumber(NumberEntity):
"""Duration setting."""
_attr_device_class = NumberDeviceClass.DURATION
_attr_native_min_value = 0
_attr_native_max_value = 3600
_attr_native_step = 60 # 1 minute steps
_attr_native_unit_of_measurement = UnitOfTime.SECONDS
_attr_mode = NumberMode.BOX
```
## Best Practices
### ✅ DO
- Set appropriate min/max/step values
- Use device class when available
- Use standard units
- Set display mode appropriately
- Implement unique IDs
- Use translation keys
- Mark config numbers with entity_category
- Handle value updates properly
### ❌ DON'T
- Allow invalid ranges (min > max)
- Use zero or negative step
- Block the event loop
- Ignore validation errors
- Create numbers without min/max/step
- Hardcode entity names
- Use for binary values (use switch)
- Use for selection from list (use select)
## Troubleshooting
### Number Not Appearing
Check:
- [ ] Unique ID is set
- [ ] Platform is in PLATFORMS list
- [ ] min/max/step are all set
- [ ] Entity is added with async_add_entities
### Value Not Updating
Check:
- [ ] async_set_native_value is called
- [ ] Coordinator refresh is working
- [ ] native_value returns correct value
- [ ] Value is within min/max range
### UI Shows Wrong Control Type
Check:
- [ ] mode is set correctly
- [ ] Range is appropriate for mode
- [ ] Step size is reasonable
## Quality Scale Considerations
- **Bronze**: Unique ID required
- **Gold**: Entity translations, device class, entity category
- **Platinum**: Full type hints
## References
- [Number Documentation](https://developers.home-assistant.io/docs/core/entity/number)
- [Number Integration](https://www.home-assistant.io/integrations/number/)

View File

@@ -0,0 +1,520 @@
# Select Platform Reference
## Overview
Select entities allow users to choose from a predefined list of options. They're used for settings like operation modes, presets, input sources, or any configuration with a fixed set of choices.
## Basic Select Implementation
```python
"""Select platform for my_integration."""
from homeassistant.components.select import SelectEntity
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from . import MyConfigEntry
from .coordinator import MyCoordinator
from .entity import MyEntity
async def async_setup_entry(
hass: HomeAssistant,
entry: MyConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up selects."""
coordinator = entry.runtime_data
async_add_entities(
MySelect(coordinator, device_id)
for device_id in coordinator.data.devices
)
class MySelect(MyEntity, SelectEntity):
"""Representation of a select."""
_attr_has_entity_name = True
_attr_translation_key = "operation_mode"
_attr_options = ["auto", "cool", "heat", "fan"]
def __init__(self, coordinator: MyCoordinator, device_id: str) -> None:
"""Initialize the select."""
super().__init__(coordinator, device_id)
self._attr_unique_id = f"{device_id}_mode"
@property
def current_option(self) -> str | None:
"""Return the current selected option."""
if device := self.coordinator.data.devices.get(self.device_id):
return device.mode
return None
async def async_select_option(self, option: str) -> None:
"""Change the selected option."""
await self.coordinator.client.set_mode(self.device_id, option)
await self.coordinator.async_request_refresh()
```
## Select Properties
### Core Properties
```python
class MySelect(SelectEntity):
"""Select with all common properties."""
# Basic identification
_attr_has_entity_name = True
_attr_translation_key = "preset"
_attr_unique_id = "device_123_preset"
# Available options (required)
_attr_options = ["comfort", "eco", "away", "sleep"]
# Entity category
_attr_entity_category = EntityCategory.CONFIG
@property
def current_option(self) -> str | None:
"""Return current selected option."""
return self.device.preset
async def async_select_option(self, option: str) -> None:
"""Set the selected option."""
await self.device.set_preset(option)
```
### Required Properties and Methods
```python
# List of available options
_attr_options = ["option1", "option2", "option3"]
# Current selected option
@property
def current_option(self) -> str | None:
"""Return the selected option."""
return self.device.current_mode
# Or use attribute
_attr_current_option = "option1"
# Method to change option
async def async_select_option(self, option: str) -> None:
"""Change the selected option."""
await self.device.set_option(option)
```
## Using Enums for Options
Recommended pattern for type safety:
```python
from enum import StrEnum
class OperationMode(StrEnum):
"""Operation modes."""
AUTO = "auto"
COOL = "cool"
HEAT = "heat"
FAN = "fan"
class MySelect(SelectEntity):
"""Select using enum."""
_attr_options = [mode.value for mode in OperationMode]
@property
def current_option(self) -> str | None:
"""Return current mode."""
if device := self.coordinator.data.devices.get(self.device_id):
return device.mode
return None
async def async_select_option(self, option: str) -> None:
"""Set mode."""
# Validate option is in enum
mode = OperationMode(option)
await self.coordinator.client.set_mode(self.device_id, mode)
await self.coordinator.async_request_refresh()
```
## Entity Descriptions Pattern
For multiple select entities:
```python
from dataclasses import dataclass
from collections.abc import Awaitable, Callable
from homeassistant.components.select import SelectEntityDescription
@dataclass(frozen=True, kw_only=True)
class MySelectDescription(SelectEntityDescription):
"""Describes a select."""
current_fn: Callable[[MyData], str | None]
select_fn: Callable[[MyClient, str, str], Awaitable[None]]
SELECTS: tuple[MySelectDescription, ...] = (
MySelectDescription(
key="mode",
translation_key="operation_mode",
options=["auto", "cool", "heat", "fan"],
entity_category=EntityCategory.CONFIG,
current_fn=lambda data: data.mode,
select_fn=lambda client, device_id, option: client.set_mode(device_id, option),
),
MySelectDescription(
key="preset",
translation_key="preset",
options=["comfort", "eco", "away", "sleep"],
entity_category=EntityCategory.CONFIG,
current_fn=lambda data: data.preset,
select_fn=lambda client, device_id, option: client.set_preset(device_id, option),
),
)
async def async_setup_entry(
hass: HomeAssistant,
entry: MyConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up selects."""
coordinator = entry.runtime_data
async_add_entities(
MySelect(coordinator, device_id, description)
for device_id in coordinator.data.devices
for description in SELECTS
)
class MySelect(MyEntity, SelectEntity):
"""Select using entity description."""
entity_description: MySelectDescription
def __init__(
self,
coordinator: MyCoordinator,
device_id: str,
description: MySelectDescription,
) -> None:
"""Initialize the select."""
super().__init__(coordinator, device_id)
self.entity_description = description
self._attr_unique_id = f"{device_id}_{description.key}"
@property
def current_option(self) -> str | None:
"""Return current option."""
if device := self.coordinator.data.devices.get(self.device_id):
return self.entity_description.current_fn(device)
return None
async def async_select_option(self, option: str) -> None:
"""Select option."""
await self.entity_description.select_fn(
self.coordinator.client,
self.device_id,
option,
)
await self.coordinator.async_request_refresh()
```
## Dynamic Options
If options change based on device state:
```python
class MyDynamicSelect(SelectEntity):
"""Select with dynamic options."""
@property
def options(self) -> list[str]:
"""Return available options based on device state."""
if device := self.coordinator.data.devices.get(self.device_id):
return device.available_modes
return []
@property
def current_option(self) -> str | None:
"""Return current option."""
if device := self.coordinator.data.devices.get(self.device_id):
return device.current_mode
return None
async def async_select_option(self, option: str) -> None:
"""Select option."""
await self.device.set_mode(option)
await self.coordinator.async_request_refresh()
```
## Option Translation
Use translation keys for user-friendly option labels:
```json
// strings.json
{
"entity": {
"select": {
"operation_mode": {
"name": "Operation mode",
"state": {
"auto": "Automatic",
"cool": "Cooling",
"heat": "Heating",
"fan": "Fan only"
}
}
}
}
}
```
```python
class MySelect(SelectEntity):
"""Select with translated options."""
_attr_translation_key = "operation_mode"
_attr_options = ["auto", "cool", "heat", "fan"]
```
## State Update Patterns
### Pattern 1: Optimistic Update
```python
async def async_select_option(self, option: str) -> None:
"""Select option with optimistic update."""
# Update immediately
self._attr_current_option = option
self.async_write_ha_state()
try:
await self.device.set_option(option)
except DeviceError:
# Revert on error
await self.coordinator.async_request_refresh()
raise
```
### Pattern 2: Coordinator Refresh
```python
async def async_select_option(self, option: str) -> None:
"""Select option and refresh."""
await self.device.set_option(option)
# Get actual option from device
await self.coordinator.async_request_refresh()
```
### Pattern 3: Direct State Update
```python
async def async_select_option(self, option: str) -> None:
"""Select option with direct state update."""
actual_option = await self.device.set_option(option)
# Device returns actual option
self._attr_current_option = actual_option
self.async_write_ha_state()
```
## Testing Selects
### Snapshot Testing
```python
"""Test selects."""
import pytest
from syrupy import SnapshotAssertion
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_selects(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
mock_config_entry: MockConfigEntry,
init_integration,
) -> None:
"""Test select entities."""
await snapshot_platform(
hass,
entity_registry,
snapshot,
mock_config_entry.entry_id,
)
```
### Option Selection Testing
```python
from homeassistant.const import ATTR_ENTITY_ID, ATTR_OPTION
from homeassistant.components.select import DOMAIN as SELECT_DOMAIN, SERVICE_SELECT_OPTION
async def test_select_option(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_device,
) -> None:
"""Test selecting an option."""
await init_integration(hass, mock_config_entry)
# Check initial state
state = hass.states.get("select.my_device_mode")
assert state
assert state.state == "auto"
assert state.attributes["options"] == ["auto", "cool", "heat", "fan"]
# Select new option
await hass.services.async_call(
SELECT_DOMAIN,
SERVICE_SELECT_OPTION,
{
ATTR_ENTITY_ID: "select.my_device_mode",
ATTR_OPTION: "cool",
},
blocking=True,
)
mock_device.set_mode.assert_called_once_with("cool")
# Verify state updated
state = hass.states.get("select.my_device_mode")
assert state.state == "cool"
```
## Common Select Types
### Operation Mode
```python
class ModeSelect(SelectEntity):
"""Operation mode select."""
_attr_translation_key = "operation_mode"
_attr_options = ["auto", "cool", "heat", "fan", "dry"]
_attr_entity_category = EntityCategory.CONFIG
```
### Preset
```python
class PresetSelect(SelectEntity):
"""Preset select."""
_attr_translation_key = "preset"
_attr_options = ["comfort", "eco", "away", "sleep", "boost"]
_attr_entity_category = EntityCategory.CONFIG
```
### Input Source
```python
class InputSourceSelect(SelectEntity):
"""Input source select."""
_attr_translation_key = "source"
_attr_options = ["hdmi1", "hdmi2", "usb", "bluetooth", "optical"]
```
### Effect/Scene
```python
class EffectSelect(SelectEntity):
"""Light effect select."""
_attr_translation_key = "effect"
_attr_options = ["none", "rainbow", "pulse", "strobe", "breathe"]
```
## Best Practices
### ✅ DO
- Use enums for type safety
- Provide translation keys for options
- Validate selected options
- Implement unique IDs
- Use entity_category for config selects
- Keep option lists reasonable (<20 items)
- Use consistent option naming (lowercase, underscores)
- Provide clear option translations
### ❌ DON'T
- Accept options not in the list
- Have too many options (use input_select helper instead)
- Block the event loop
- Hardcode entity names
- Change options list arbitrarily
- Use for numeric values (use number entity)
- Use for binary choices (use switch)
- Have empty options list
## Select vs. Other Entities
**Use Select when**:
- Fixed list of text options
- Modes, presets, or settings
- 2-20 options
**Use Switch when**:
- Binary on/off control
- Only 2 states
**Use Number when**:
- Numeric range
- Continuous values
**Use Input Select when**:
- User-defined options
- Need dynamic option list
- Helper/template integration
## Troubleshooting
### Select Not Appearing
Check:
- [ ] Unique ID is set
- [ ] Platform is in PLATFORMS list
- [ ] options list is not empty
- [ ] Entity is added with async_add_entities
### Option Not Accepted
Check:
- [ ] Option is in options list (case-sensitive)
- [ ] Options list is properly formatted
- [ ] async_select_option handles the option
### Options Not Translating
Check:
- [ ] translation_key is set
- [ ] strings.json has state translations
- [ ] Option keys match exactly
## Quality Scale Considerations
- **Bronze**: Unique ID required
- **Gold**: Entity translations, entity category
- **Platinum**: Full type hints, use StrEnum for options
## References
- [Select Documentation](https://developers.home-assistant.io/docs/core/entity/select)
- [Select Integration](https://www.home-assistant.io/integrations/select/)

View File

@@ -0,0 +1,560 @@
# Sensor Platform Reference
## Overview
Sensors are read-only entities that represent measurements, states, or information from devices and services. They display numeric values, strings, timestamps, or other data types.
## Basic Sensor Implementation
### Minimal Sensor
```python
"""Sensor platform for my_integration."""
from homeassistant.components.sensor import SensorEntity
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from . import MyConfigEntry
from .const import DOMAIN
from .coordinator import MyCoordinator
from .entity import MyEntity
async def async_setup_entry(
hass: HomeAssistant,
entry: MyConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up sensors."""
coordinator = entry.runtime_data
async_add_entities(
MySensor(coordinator, device_id)
for device_id in coordinator.data.devices
)
class MySensor(MyEntity, SensorEntity):
"""Representation of a sensor."""
def __init__(self, coordinator: MyCoordinator, device_id: str) -> None:
"""Initialize the sensor."""
super().__init__(coordinator, device_id)
self._attr_unique_id = f"{device_id}_temperature"
self._attr_translation_key = "temperature"
@property
def native_value(self) -> float | None:
"""Return the sensor value."""
if device := self.coordinator.data.devices.get(self.device_id):
return device.temperature
return None
```
## Sensor Properties
### Core Properties
```python
class MySensor(SensorEntity):
"""Sensor with all common properties."""
# Basic identification
_attr_has_entity_name = True # Required
_attr_translation_key = "temperature" # For translations
_attr_unique_id = "device_123_temp" # Required
# Device class and units
_attr_device_class = SensorDeviceClass.TEMPERATURE
_attr_native_unit_of_measurement = UnitOfTemperature.CELSIUS
_attr_suggested_display_precision = 1 # Decimal places
# State class for statistics
_attr_state_class = SensorStateClass.MEASUREMENT
# Entity category
_attr_entity_category = EntityCategory.DIAGNOSTIC # If diagnostic
# Availability
_attr_entity_registry_enabled_default = False # If noisy/less important
@property
def native_value(self) -> float | None:
"""Return sensor value."""
return self.device.temperature
@property
def available(self) -> bool:
"""Return if entity is available."""
return super().available and self.device_id in self.coordinator.data
```
## Device Classes
Use device classes for proper representation:
```python
from homeassistant.components.sensor import SensorDeviceClass
# Common device classes
_attr_device_class = SensorDeviceClass.TEMPERATURE
_attr_device_class = SensorDeviceClass.HUMIDITY
_attr_device_class = SensorDeviceClass.PRESSURE
_attr_device_class = SensorDeviceClass.BATTERY
_attr_device_class = SensorDeviceClass.ENERGY
_attr_device_class = SensorDeviceClass.POWER
_attr_device_class = SensorDeviceClass.VOLTAGE
_attr_device_class = SensorDeviceClass.CURRENT
_attr_device_class = SensorDeviceClass.TIMESTAMP
_attr_device_class = SensorDeviceClass.MONETARY
```
Benefits:
- Automatic unit conversion
- Proper UI representation
- Voice assistant integration
- Historical statistics
## State Classes
For long-term statistics support:
```python
from homeassistant.components.sensor import SensorStateClass
# Measurement - value at a point in time
_attr_state_class = SensorStateClass.MEASUREMENT
# Examples: temperature, humidity, power
# Total - cumulative value that can increase/decrease
_attr_state_class = SensorStateClass.TOTAL
# Examples: energy consumed, data transferred
# Use with last_reset for resettable totals
# Total increasing - cumulative value that only increases
_attr_state_class = SensorStateClass.TOTAL_INCREASING
# Examples: lifetime energy, odometer
```
### When to Use State Classes
**Use MEASUREMENT for**:
- Temperature, humidity, pressure
- Current power usage
- Instantaneous values
**Use TOTAL for**:
- Daily/monthly energy consumption (resets)
- Periodic counters
**Use TOTAL_INCREASING for**:
- Lifetime energy consumption
- Monotonically increasing counters
**Don't use state class for**:
- Text/string sensors
- Status sensors (enum values)
- Non-numeric sensors
## Unit of Measurement
### Using Standard Units
```python
from homeassistant.const import (
UnitOfTemperature,
UnitOfPower,
UnitOfEnergy,
PERCENTAGE,
)
# Temperature
_attr_native_unit_of_measurement = UnitOfTemperature.CELSIUS
# Auto-converts to user's preference (°F/°C/K)
# Power
_attr_native_unit_of_measurement = UnitOfPower.WATT
# Energy
_attr_native_unit_of_measurement = UnitOfEnergy.KILO_WATT_HOUR
# Percentage
_attr_native_unit_of_measurement = PERCENTAGE
```
### Custom Units
```python
# For non-standard units
_attr_native_unit_of_measurement = "AQI" # Air Quality Index
_attr_native_unit_of_measurement = "ppm" # Parts per million
```
## Entity Descriptions Pattern
For multiple similar sensors, use SensorEntityDescription:
```python
from dataclasses import dataclass
from homeassistant.components.sensor import SensorEntityDescription
from homeassistant.helpers.typing import StateType
@dataclass(frozen=True, kw_only=True)
class MySensorDescription(SensorEntityDescription):
"""Describes a sensor."""
value_fn: Callable[[MyData], StateType]
SENSORS: tuple[MySensorDescription, ...] = (
MySensorDescription(
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,
),
MySensorDescription(
key="humidity",
translation_key="humidity",
device_class=SensorDeviceClass.HUMIDITY,
native_unit_of_measurement=PERCENTAGE,
state_class=SensorStateClass.MEASUREMENT,
value_fn=lambda data: data.humidity,
),
)
class MySensor(MyEntity, SensorEntity):
"""Sensor using entity description."""
entity_description: MySensorDescription
def __init__(
self,
coordinator: MyCoordinator,
description: MySensorDescription,
device_id: str,
) -> None:
"""Initialize the sensor."""
super().__init__(coordinator, device_id)
self.entity_description = description
self._attr_unique_id = f"{device_id}_{description.key}"
@property
def native_value(self) -> StateType:
"""Return the sensor value."""
if device := self.coordinator.data.devices.get(self.device_id):
return self.entity_description.value_fn(device)
return None
```
### Lambda Functions in EntityDescription
When lambdas get long, use proper formatting:
```python
# ❌ Bad - too long
SensorEntityDescription(
key="temperature",
value_fn=lambda data: round(data["temp_value"] * 1.8 + 32, 1) if data.get("temp_value") is not None else None,
)
# ✅ Good - wrapped properly
SensorEntityDescription(
key="temperature",
value_fn=lambda data: (
round(data["temp_value"] * 1.8 + 32, 1)
if data.get("temp_value") is not None
else None
),
)
```
## Timestamp Sensors
For datetime values:
```python
from datetime import datetime
from homeassistant.components.sensor import SensorDeviceClass
class MyTimestampSensor(SensorEntity):
"""Timestamp sensor."""
_attr_device_class = SensorDeviceClass.TIMESTAMP
@property
def native_value(self) -> datetime | None:
"""Return timestamp."""
return self.device.last_update
```
## Enum Sensors
For sensors with fixed set of possible values:
```python
from enum import StrEnum
from homeassistant.components.sensor import SensorEntity
class OperationMode(StrEnum):
"""Operation modes."""
AUTO = "auto"
MANUAL = "manual"
ECO = "eco"
class MyModeSensor(SensorEntity):
"""Mode sensor."""
_attr_device_class = SensorDeviceClass.ENUM
_attr_options = [mode.value for mode in OperationMode]
@property
def native_value(self) -> str | None:
"""Return current mode."""
return self.device.mode
```
## Entity Category
Mark diagnostic or configuration sensors:
```python
from homeassistant.helpers.entity import EntityCategory
# Diagnostic sensors (technical info)
_attr_entity_category = EntityCategory.DIAGNOSTIC
# Examples: signal strength, uptime, IP address
# Config sensors (device settings)
_attr_entity_category = EntityCategory.CONFIG
# Examples: current mode setting, configuration values
```
## Disabled by Default
For noisy or less important sensors:
```python
class MySignalStrengthSensor(SensorEntity):
"""Signal strength sensor - noisy."""
_attr_entity_registry_enabled_default = False
```
## Dynamic Sensor Addition
For devices that appear after setup:
```python
async def async_setup_entry(
hass: HomeAssistant,
entry: MyConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up sensors with dynamic addition."""
coordinator = entry.runtime_data
known_devices: set[str] = set()
@callback
def _add_new_devices() -> None:
"""Add newly discovered 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
_add_new_devices()
# Listen for new devices
entry.async_on_unload(coordinator.async_add_listener(_add_new_devices))
```
## Testing Sensors
### Test with Snapshots
```python
"""Test sensors."""
import pytest
from syrupy import SnapshotAssertion
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from tests.common import MockConfigEntry
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_sensors(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
mock_config_entry: MockConfigEntry,
init_integration,
) -> None:
"""Test sensor entities."""
await snapshot_platform(
hass,
entity_registry,
snapshot,
mock_config_entry.entry_id,
)
```
### Test Sensor Values
```python
async def test_sensor_values(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test sensor values are correct."""
await init_integration(hass, mock_config_entry)
state = hass.states.get("sensor.my_device_temperature")
assert state
assert state.state == "22.5"
assert state.attributes["unit_of_measurement"] == "°C"
assert state.attributes["device_class"] == "temperature"
```
## Best Practices
### ✅ DO
- Use device classes when available
- Set state classes for statistics
- Use standard units of measurement
- Implement unique IDs
- Use entity descriptions for similar sensors
- Mark diagnostic sensors with entity_category
- Disable noisy sensors by default
- Return None for unknown values
- Use translation keys for entity names
### ❌ DON'T
- Hardcode entity names
- Use string "unavailable" or "unknown" as state
- Mix units (always use native_unit_of_measurement)
- Create sensors without unique IDs
- Poll in sensor update if using coordinator
- Block the event loop
- Use state class for non-numeric sensors
## Common Patterns
### Pattern 1: Coordinator-Based Sensor
```python
class MySensor(CoordinatorEntity[MyCoordinator], SensorEntity):
"""Coordinator-based sensor."""
_attr_should_poll = False # Coordinator handles updates
@property
def native_value(self) -> StateType:
"""Get value from coordinator data."""
return self.coordinator.data.get(self.key)
```
### Pattern 2: Push-Updated Sensor
```python
class MyPushSensor(SensorEntity):
"""Push-updated sensor."""
_attr_should_poll = False
async def async_added_to_hass(self) -> None:
"""Subscribe to updates."""
self.async_on_remove(
self.device.subscribe(self._handle_update)
)
@callback
def _handle_update(self, value: float) -> None:
"""Handle push update."""
self._attr_native_value = value
self.async_write_ha_state()
```
### Pattern 3: Calculated Sensor
```python
class MyCalculatedSensor(SensorEntity):
"""Calculated from other sensors."""
_attr_should_poll = False
async def async_added_to_hass(self) -> None:
"""Subscribe to source sensors."""
self.async_on_remove(
async_track_state_change_event(
self.hass,
["sensor.source1", "sensor.source2"],
self._handle_update,
)
)
@callback
def _handle_update(self, event: Event) -> None:
"""Recalculate when sources change."""
# Calculate new value
self._attr_native_value = self._calculate()
self.async_write_ha_state()
```
## Troubleshooting
### Sensor Not Appearing
Check:
- [ ] Unique ID is set
- [ ] Platform is in PLATFORMS list
- [ ] async_setup_entry is called
- [ ] Entity is added with async_add_entities
### Values Not Updating
Check:
- [ ] Coordinator is updating
- [ ] Entity is available
- [ ] native_value returns correct data
- [ ] should_poll is False for coordinator
### Units Not Converting
Check:
- [ ] Using standard unit constants
- [ ] Device class is set correctly
- [ ] Unit matches device class
### Statistics Not Working
Check:
- [ ] State class is set
- [ ] Values are numeric
- [ ] Device class is appropriate
- [ ] Units are consistent
## Quality Scale Considerations
- **Bronze**: Unique ID required
- **Gold**: Entity translations, device class, entity category
- **Platinum**: Full type hints
## References
- [Sensor Documentation](https://developers.home-assistant.io/docs/core/entity/sensor)
- [Device Classes](https://www.home-assistant.io/integrations/sensor/#device-class)
- [State Classes](https://developers.home-assistant.io/docs/core/entity/sensor/#available-state-classes)

View File

@@ -0,0 +1,505 @@
# Switch Platform Reference
## Overview
Switches are entities that can be turned on or off. They represent controllable devices like smart plugs, relays, or any binary control. Unlike binary sensors, switches can be controlled by the user.
## Basic Switch Implementation
```python
"""Switch platform for my_integration."""
from typing import Any
from homeassistant.components.switch import SwitchEntity
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from . import MyConfigEntry
from .coordinator import MyCoordinator
from .entity import MyEntity
async def async_setup_entry(
hass: HomeAssistant,
entry: MyConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up switches."""
coordinator = entry.runtime_data
async_add_entities(
MySwitch(coordinator, device_id)
for device_id in coordinator.data.devices
)
class MySwitch(MyEntity, SwitchEntity):
"""Representation of a switch."""
_attr_has_entity_name = True
_attr_translation_key = "outlet"
def __init__(self, coordinator: MyCoordinator, device_id: str) -> None:
"""Initialize the switch."""
super().__init__(coordinator, device_id)
self._attr_unique_id = f"{device_id}_switch"
@property
def is_on(self) -> bool | None:
"""Return true if switch is on."""
if device := self.coordinator.data.devices.get(self.device_id):
return device.is_on
return None
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn the switch on."""
await self.coordinator.client.turn_on(self.device_id)
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(self.device_id)
await self.coordinator.async_request_refresh()
```
## Switch Properties and Methods
### Core Properties
```python
@property
def is_on(self) -> bool | None:
"""Return true if entity is on."""
return self.device.state
# Or use attribute
_attr_is_on = True # or False, or None
```
### Required Methods
```python
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn the entity on."""
await self.device.turn_on()
# Update state
self._attr_is_on = True
self.async_write_ha_state()
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn the entity off."""
await self.device.turn_off()
# Update state
self._attr_is_on = False
self.async_write_ha_state()
```
### Optional Toggle Method
```python
async def async_toggle(self, **kwargs: Any) -> None:
"""Toggle the entity."""
# Only implement if device has native toggle
await self.device.toggle()
await self.coordinator.async_request_refresh()
```
**Note**: If `async_toggle` is not implemented, Home Assistant will use `async_turn_on`/`async_turn_off` based on current state.
## Device Class
Switches can have device classes to indicate their type:
```python
from homeassistant.components.switch import SwitchDeviceClass
_attr_device_class = SwitchDeviceClass.OUTLET
_attr_device_class = SwitchDeviceClass.SWITCH
```
Device classes:
- `OUTLET` - Smart plug/outlet
- `SWITCH` - Generic switch (default)
## State Update Patterns
### Pattern 1: Optimistic Update
For fast UI response:
```python
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn on."""
# Update state immediately (optimistic)
self._attr_is_on = True
self.async_write_ha_state()
try:
await self.coordinator.client.turn_on(self.device_id)
except DeviceError:
# Revert on error
self._attr_is_on = False
self.async_write_ha_state()
raise
```
### Pattern 2: Coordinator Refresh
Wait for actual state:
```python
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn on."""
await self.coordinator.client.turn_on(self.device_id)
# Refresh coordinator to get actual state
await self.coordinator.async_request_refresh()
```
### Pattern 3: Push Update
For push-based systems:
```python
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn on."""
# Command device
await self.device.turn_on()
# State will be updated via push event
# No need to call async_write_ha_state()
```
## Entity Descriptions Pattern
For multiple similar switches:
```python
from dataclasses import dataclass
from collections.abc import Awaitable, Callable
from homeassistant.components.switch import SwitchEntityDescription
@dataclass(frozen=True, kw_only=True)
class MySwitchDescription(SwitchEntityDescription):
"""Describes a switch."""
is_on_fn: Callable[[MyData], bool | None]
turn_on_fn: Callable[[MyClient, str], Awaitable[None]]
turn_off_fn: Callable[[MyClient, str], Awaitable[None]]
SWITCHES: tuple[MySwitchDescription, ...] = (
MySwitchDescription(
key="outlet",
translation_key="outlet",
device_class=SwitchDeviceClass.OUTLET,
is_on_fn=lambda data: data.outlet_state,
turn_on_fn=lambda client, device_id: client.turn_on_outlet(device_id),
turn_off_fn=lambda client, device_id: client.turn_off_outlet(device_id),
),
MySwitchDescription(
key="led",
translation_key="led",
entity_category=EntityCategory.CONFIG,
is_on_fn=lambda data: data.led_enabled,
turn_on_fn=lambda client, device_id: client.enable_led(device_id),
turn_off_fn=lambda client, device_id: client.disable_led(device_id),
),
)
class MySwitch(MyEntity, SwitchEntity):
"""Switch using entity description."""
entity_description: MySwitchDescription
def __init__(
self,
coordinator: MyCoordinator,
device_id: str,
description: MySwitchDescription,
) -> None:
"""Initialize the switch."""
super().__init__(coordinator, device_id)
self.entity_description = description
self._attr_unique_id = f"{device_id}_{description.key}"
@property
def is_on(self) -> bool | None:
"""Return if switch is on."""
if device := self.coordinator.data.devices.get(self.device_id):
return self.entity_description.is_on_fn(device)
return None
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn on."""
await self.entity_description.turn_on_fn(
self.coordinator.client,
self.device_id,
)
await self.coordinator.async_request_refresh()
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn off."""
await self.entity_description.turn_off_fn(
self.coordinator.client,
self.device_id,
)
await self.coordinator.async_request_refresh()
```
## Configuration Switches
Switches that control device settings (not physical devices):
```python
from homeassistant.helpers.entity import EntityCategory
class MyConfigSwitch(SwitchEntity):
"""Configuration switch."""
_attr_entity_category = EntityCategory.CONFIG
_attr_translation_key = "led_indicator"
@property
def is_on(self) -> bool:
"""Return if LED is enabled."""
return self.device.led_enabled
async def async_turn_on(self, **kwargs: Any) -> None:
"""Enable LED indicator."""
await self.device.set_led(True)
self._attr_is_on = True
self.async_write_ha_state()
async def async_turn_off(self, **kwargs: Any) -> None:
"""Disable LED indicator."""
await self.device.set_led(False)
self._attr_is_on = False
self.async_write_ha_state()
```
## Error Handling
Handle errors gracefully:
```python
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn on with error handling."""
try:
await self.device.turn_on()
except DeviceOfflineError as err:
# Let entity become unavailable
raise HomeAssistantError(f"Device is offline: {err}") from err
except DeviceError as err:
# Specific error
raise HomeAssistantError(f"Failed to turn on: {err}") from err
else:
self._attr_is_on = True
self.async_write_ha_state()
```
## Testing Switches
### Snapshot Testing
```python
"""Test switches."""
import pytest
from syrupy import SnapshotAssertion
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_switches(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
mock_config_entry: MockConfigEntry,
init_integration,
) -> None:
"""Test switch entities."""
await snapshot_platform(
hass,
entity_registry,
snapshot,
mock_config_entry.entry_id,
)
```
### Control Testing
```python
from homeassistant.const import (
ATTR_ENTITY_ID,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
)
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN
async def test_switch_on_off(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_device,
) -> None:
"""Test turning switch on and off."""
await init_integration(hass, mock_config_entry)
# Test initial state
state = hass.states.get("switch.my_device_outlet")
assert state
assert state.state == "off"
# Turn on
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: "switch.my_device_outlet"},
blocking=True,
)
mock_device.turn_on.assert_called_once()
# Check state updated
state = hass.states.get("switch.my_device_outlet")
assert state.state == "on"
# Turn off
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: "switch.my_device_outlet"},
blocking=True,
)
mock_device.turn_off.assert_called_once()
state = hass.states.get("switch.my_device_outlet")
assert state.state == "off"
```
## Common Patterns
### Pattern 1: Coordinator-Based Switch
```python
class MySwitch(CoordinatorEntity[MyCoordinator], SwitchEntity):
"""Coordinator-based switch."""
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn on."""
await self.coordinator.client.turn_on(self.device_id)
await self.coordinator.async_request_refresh()
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn off."""
await self.coordinator.client.turn_off(self.device_id)
await self.coordinator.async_request_refresh()
@property
def is_on(self) -> bool | None:
"""Return if switch is on."""
if device := self.coordinator.data.devices.get(self.device_id):
return device.is_on
return None
```
### Pattern 2: Local State Management
```python
class MyLocalSwitch(SwitchEntity):
"""Switch with local state."""
_attr_should_poll = False
_attr_is_on = False
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn on."""
await self.device.turn_on()
self._attr_is_on = True
self.async_write_ha_state()
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn off."""
await self.device.turn_off()
self._attr_is_on = False
self.async_write_ha_state()
```
### Pattern 3: With Additional Control
```python
class MyAdvancedSwitch(SwitchEntity):
"""Switch with timer support."""
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn on with optional duration."""
duration = kwargs.get("duration") # Custom kwarg
if duration:
await self.device.turn_on_for(duration)
else:
await self.device.turn_on()
await self.coordinator.async_request_refresh()
```
## Best Practices
### ✅ DO
- Implement both turn_on and turn_off
- Update state after commands
- Handle errors properly
- Use coordinator for state management
- Implement unique IDs
- Use translation keys
- Mark config switches with entity_category
- Refresh coordinator after commands
### ❌ DON'T
- Block the event loop
- Ignore errors silently
- Create switches without unique IDs
- Mix control and sensing (use separate entities)
- Poll unnecessarily
- Hardcode entity names
- Forget to update state after commands
## Troubleshooting
### Switch Not Responding
Check:
- [ ] turn_on/turn_off methods are async
- [ ] Not blocking the event loop
- [ ] API client is working
- [ ] Errors are being raised properly
### State Not Updating
Check:
- [ ] async_write_ha_state() is called
- [ ] Coordinator refresh is working
- [ ] is_on returns correct value
- [ ] Push updates are subscribed
### Switch Appearing as Unavailable
Check:
- [ ] Device connection is working
- [ ] Coordinator update is successful
- [ ] available property returns True
- [ ] Entity is in coordinator.data
## Quality Scale Considerations
- **Bronze**: Unique ID required
- **Gold**: Entity translations, device class (if applicable)
- **Platinum**: Full type hints
## References
- [Switch Documentation](https://developers.home-assistant.io/docs/core/entity/switch)
- [Switch Integration](https://www.home-assistant.io/integrations/switch/)

View File

@@ -0,0 +1,285 @@
---
name: code-review
description: Review Home Assistant integration code for quality, best practices, and standards compliance. Use when reviewing pull requests, identifying anti-patterns, checking security vulnerabilities (OWASP), verifying async patterns, ensuring quality scale compliance, or providing comprehensive code feedback.
---
# Code Review Skill for Home Assistant Integrations
You are an expert Home Assistant code reviewer with deep knowledge of Python, async programming, Home Assistant architecture, and integration best practices.
## Review Guidelines
### What to Review
**DO review and comment on:**
- Architecture and design patterns
- Async programming correctness
- Error handling and edge cases
- Security vulnerabilities (XSS, SQL injection, command injection, etc.)
- Performance issues (blocking operations, inefficient loops)
- Code organization and clarity
- Compliance with Home Assistant patterns
- Quality scale requirements
- Missing functionality or incomplete implementations
**DO NOT comment on:**
- Missing imports (static analysis catches this)
- Code formatting (Ruff handles this)
- Minor style issues that linters catch
### Git Practices During Review
⚠️ **CRITICAL**: After review has started:
- **DO NOT amend commits**
- **DO NOT squash commits**
- **DO NOT rebase commits**
- Reviewers need to see what changed since their last review
## Key Review Areas
### 1. Async Programming Patterns
#### ✅ Good Async Patterns
```python
# Proper async I/O
data = await client.get_data()
# Using asyncio.sleep instead of time.sleep
await asyncio.sleep(5)
# Executor for blocking operations
result = await hass.async_add_executor_job(blocking_function, args)
# Gathering async operations
results = await asyncio.gather(
client.get_temp(),
client.get_humidity(),
)
# @callback for event loop safe functions
@callback
def async_update_callback(self, event):
self.async_write_ha_state()
```
#### ❌ Bad Async Patterns
```python
# Blocking operations in event loop
data = requests.get(url) # ❌ Blocks event loop
time.sleep(5) # ❌ Blocks event loop
# Awaiting in loops (use gather instead)
for device in devices:
data = await device.get_data() # ❌ Sequential, slow
# Reusing BleakClient instances
await self.client.connect() # ❌ Don't reuse BleakClient
```
### 2. Error Handling
#### ✅ Good Error Handling
```python
# Minimal try blocks, process outside
try:
data = await device.get_data()
except DeviceError as err:
_LOGGER.error("Failed to get data: %s", err)
return
# Process data outside try block
processed = data.get("value", 0) * 100
self._attr_native_value = processed
# Proper exception types
try:
await client.connect()
except asyncio.TimeoutError as ex:
raise ConfigEntryNotReady(f"Timeout connecting to {host}") from ex
except AuthError as ex:
raise ConfigEntryAuthFailed("Invalid credentials") from ex
```
#### ❌ Bad Error Handling
```python
# Too much code in try block
try:
data = await device.get_data()
processed = data.get("value", 0) * 100 # ❌ Should be outside
self._attr_native_value = processed
except DeviceError:
_LOGGER.error("Failed")
# Bare exceptions in regular code
try:
data = await device.get_data()
except Exception: # ❌ Too broad (unless in config flow/background task)
_LOGGER.error("Failed")
# Wrong exception type
if end_date < start_date:
raise ValueError("Invalid dates") # ❌ Should be ServiceValidationError
```
### 3. Security Vulnerabilities
Check for OWASP Top 10 vulnerabilities:
```python
# ❌ Command Injection
os.system(f"ping {user_input}") # DANGEROUS
# ✅ Safe alternative
await hass.async_add_executor_job(
subprocess.run,
["ping", user_input],
check=True
)
# ❌ Exposing secrets in diagnostics
return {"api_key": entry.data[CONF_API_KEY]} # DANGEROUS
# ✅ Safe alternative
return async_redact_data(entry.data, {CONF_API_KEY, CONF_PASSWORD})
```
### 4. Configuration Flow Patterns
#### ✅ Good Config Flow
```python
class MyConfigFlow(ConfigFlow, domain=DOMAIN):
VERSION = 1
MINOR_VERSION = 1
async def async_step_user(self, user_input=None):
errors = {}
if user_input is not None:
try:
await self._test_connection(user_input)
except ConnectionError:
errors["base"] = "cannot_connect"
except AuthError:
errors["base"] = "invalid_auth"
except Exception: # ✅ Allowed in config flow
errors["base"] = "unknown"
else:
await self.async_set_unique_id(device_id)
self._abort_if_unique_id_configured()
return self.async_create_entry(
title=device_name,
data=user_input,
)
return self.async_show_form(
step_id="user",
data_schema=vol.Schema({
vol.Required(CONF_HOST): str,
vol.Required(CONF_API_KEY): str,
}),
errors=errors,
)
```
### 5. Entity Patterns
#### ✅ Good Entity Patterns
```python
class MySensor(CoordinatorEntity[MyCoordinator], SensorEntity):
_attr_has_entity_name = True
_attr_translation_key = "temperature"
def __init__(self, coordinator: MyCoordinator, device_id: str) -> None:
super().__init__(coordinator)
self._attr_unique_id = f"{device_id}_temperature"
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, device_id)},
name=coordinator.data[device_id].name,
)
@property
def native_value(self) -> float | None:
if device_data := self.coordinator.data.get(self.device_id):
return device_data.temperature
return None
@property
def available(self) -> bool:
return super().available and self.device_id in self.coordinator.data
```
### 6. Quality Scale Compliance
Review manifest.json and quality_scale.yaml:
```json
{
"domain": "my_integration",
"name": "My Integration",
"codeowners": ["@me"],
"config_flow": true,
"integration_type": "device",
"iot_class": "cloud_polling",
"quality_scale": "silver"
}
```
Check:
- [ ] All required Bronze rules implemented or exempted
- [ ] Rules match declared quality scale tier
- [ ] Valid exemption reasons provided
- [ ] manifest.json has all required fields
## Performance Patterns
### ✅ Good Performance
```python
# Parallel API calls
temp, humidity = await asyncio.gather(
api.get_temperature(),
api.get_humidity(),
)
# Efficient coordinator usage
PARALLEL_UPDATES = 0 # Unlimited for coordinator-based
```
### ❌ Bad Performance
```python
# Sequential API calls
temp = await api.get_temperature()
humidity = await api.get_humidity() # ❌ Should use gather
# User-configurable scan intervals
vol.Optional("scan_interval"): cv.positive_int # ❌ Not allowed
```
## Review Process
When reviewing code:
1. **Architecture Review**: Does it follow HA patterns?
2. **Code Quality**: Are async patterns correct? Is error handling comprehensive?
3. **Standards Compliance**: Quality scale requirements met?
4. **Performance & Efficiency**: No blocking operations? Efficient API usage?
5. **User Experience**: Clear error messages? Proper translations?
## Providing Feedback
Structure feedback as:
1. **Summary**: Overall assessment
2. **Critical Issues**: Must fix before merge
3. **Suggestions**: Nice-to-have improvements
4. **Positive Notes**: What's done well
Be specific with file:line references and provide code examples.
## Reference Files
For detailed patterns and best practices, see:
- `.claude/references/diagnostics.md` - Diagnostics implementation
- `.claude/references/sensor.md` - Sensor platform
- `.claude/references/binary_sensor.md` - Binary sensor platform
- `.claude/references/switch.md` - Switch platform
- `.claude/references/button.md` - Button platform
- `.claude/references/number.md` - Number platform
- `.claude/references/select.md` - Select platform

View File

@@ -1,784 +0,0 @@
---
name: Home Assistant Integration knowledge
description: Everything you need to know to build, test and review Home Assistant Integrations. If you're looking at an integration, you must use this as your primary reference.
---
### File Locations
- **Integration code**: `./homeassistant/components/<integration_domain>/`
- **Integration tests**: `./tests/components/<integration_domain>/`
## Integration Templates
### Standard 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 (if needed)
├── entity.py # Base entity class (if shared patterns)
├── sensor.py # Sensor platform
├── strings.json # User-facing text and translations
├── services.yaml # Service definitions (if applicable)
└── quality_scale.yaml # Quality scale rule status
```
An integration can have platforms as needed (e.g., `sensor.py`, `switch.py`, etc.). The following platforms have extra guidelines:
- **Diagnostics**: [`platform-diagnostics.md`](platform-diagnostics.md) for diagnostic data collection
- **Repairs**: [`platform-repairs.md`](platform-repairs.md) for user-actionable repair issues
### Minimal Integration Checklist
- [ ] `manifest.json` with required fields (domain, name, codeowners, etc.)
- [ ] `__init__.py` with `async_setup_entry` and `async_unload_entry`
- [ ] `config_flow.py` with UI configuration support
- [ ] `const.py` with `DOMAIN` constant
- [ ] `strings.json` with at least config flow text
- [ ] Platform files (`sensor.py`, etc.) as needed
- [ ] `quality_scale.yaml` with rule status tracking
## Integration Quality Scale
Home Assistant uses an Integration Quality Scale to ensure code quality and consistency. The quality level determines which rules apply:
### Quality Scale Levels
- **Bronze**: Basic requirements (ALL Bronze rules are mandatory)
- **Silver**: Enhanced functionality
- **Gold**: Advanced features
- **Platinum**: Highest quality standards
### Quality Scale Progression
- **Bronze → Silver**: Add entity unavailability, parallel updates, auth flows
- **Silver → Gold**: Add device management, diagnostics, translations
- **Gold → Platinum**: Add strict typing, async dependencies, websession injection
### How Rules Apply
1. **Check `manifest.json`**: Look for `"quality_scale"` key to determine integration level
2. **Bronze Rules**: Always required for any integration with quality scale
3. **Higher Tier Rules**: Only apply if integration targets that tier or higher
4. **Rule Status**: Check `quality_scale.yaml` in integration folder for:
- `done`: Rule implemented
- `exempt`: Rule doesn't apply (with reason in comment)
- `todo`: Rule needs implementation
### Example `quality_scale.yaml` Structure
```yaml
rules:
# Bronze (mandatory)
config-flow: done
entity-unique-id: done
action-setup:
status: exempt
comment: Integration does not register custom actions.
# Silver (if targeting Silver+)
entity-unavailable: done
parallel-updates: done
# Gold (if targeting Gold+)
devices: done
diagnostics: done
# Platinum (if targeting Platinum)
strict-typing: done
```
**When Reviewing/Creating Code**: Always check the integration's quality scale level and exemption status before applying rules.
## Code Organization
### Core Locations
- Shared constants: `homeassistant/const.py` (use these instead of hardcoding)
- Integration structure:
- `homeassistant/components/{domain}/const.py` - Constants
- `homeassistant/components/{domain}/models.py` - Data models
- `homeassistant/components/{domain}/coordinator.py` - Update coordinator
- `homeassistant/components/{domain}/config_flow.py` - Configuration flow
- `homeassistant/components/{domain}/{platform}.py` - Platform implementations
### Common Modules
- **coordinator.py**: Centralize data fetching logic
```python
class MyCoordinator(DataUpdateCoordinator[MyData]):
def __init__(self, hass: HomeAssistant, client: MyClient, config_entry: ConfigEntry) -> None:
super().__init__(
hass,
logger=LOGGER,
name=DOMAIN,
update_interval=timedelta(minutes=1),
config_entry=config_entry, # ✅ Pass config_entry - it's accepted and recommended
)
```
- **entity.py**: Base entity definitions to reduce duplication
```python
class MyEntity(CoordinatorEntity[MyCoordinator]):
_attr_has_entity_name = True
```
### Runtime Data Storage
- **Use ConfigEntry.runtime_data**: Store non-persistent runtime data
```python
type MyIntegrationConfigEntry = ConfigEntry[MyClient]
async def async_setup_entry(hass: HomeAssistant, entry: MyIntegrationConfigEntry) -> bool:
client = MyClient(entry.data[CONF_HOST])
entry.runtime_data = client
```
### Manifest Requirements
- **Required Fields**: `domain`, `name`, `codeowners`, `integration_type`, `documentation`, `requirements`
- **Integration Types**: `device`, `hub`, `service`, `system`, `helper`
- **IoT Class**: Always specify connectivity method (e.g., `cloud_polling`, `local_polling`, `local_push`)
- **Discovery Methods**: Add when applicable: `zeroconf`, `dhcp`, `bluetooth`, `ssdp`, `usb`
- **Dependencies**: Include platform dependencies (e.g., `application_credentials`, `bluetooth_adapters`)
### Config Flow Patterns
- **Version Control**: Always set `VERSION = 1` and `MINOR_VERSION = 1`
- **Unique ID Management**:
```python
await self.async_set_unique_id(device_unique_id)
self._abort_if_unique_id_configured()
```
- **Error Handling**: Define errors in `strings.json` under `config.error`
- **Step Methods**: Use standard naming (`async_step_user`, `async_step_discovery`, etc.)
### Integration Ownership
- **manifest.json**: Add GitHub usernames to `codeowners`:
```json
{
"domain": "my_integration",
"name": "My Integration",
"codeowners": ["@me"]
}
```
### Async Dependencies (Platinum)
- **Requirement**: All dependencies must use asyncio
- Ensures efficient task handling without thread context switching
### WebSession Injection (Platinum)
- **Pass WebSession**: Support passing web sessions to dependencies
```python
async def async_setup_entry(hass: HomeAssistant, entry: MyConfigEntry) -> bool:
"""Set up integration from config entry."""
client = MyClient(entry.data[CONF_HOST], async_get_clientsession(hass))
```
- For cookies: Use `async_create_clientsession` (aiohttp) or `create_async_httpx_client` (httpx)
### Data Update Coordinator
- **Standard Pattern**: Use for efficient data management
```python
class MyCoordinator(DataUpdateCoordinator):
def __init__(self, hass: HomeAssistant, client: MyClient, config_entry: ConfigEntry) -> None:
super().__init__(
hass,
logger=LOGGER,
name=DOMAIN,
update_interval=timedelta(minutes=5),
config_entry=config_entry, # ✅ Pass config_entry - it's accepted and recommended
)
self.client = client
async def _async_update_data(self):
try:
return await self.client.fetch_data()
except ApiError as err:
raise UpdateFailed(f"API communication error: {err}")
```
- **Error Types**: Use `UpdateFailed` for API errors, `ConfigEntryAuthFailed` for auth issues
- **Config Entry**: Always pass `config_entry` parameter to coordinator - it's accepted and recommended
## Integration Guidelines
### Configuration Flow
- **UI Setup Required**: All integrations must support configuration via UI
- **Manifest**: Set `"config_flow": true` in `manifest.json`
- **Data Storage**:
- Connection-critical config: Store in `ConfigEntry.data`
- Non-critical settings: Store in `ConfigEntry.options`
- **Validation**: Always validate user input before creating entries
- **Config Entry Naming**:
- ❌ Do NOT allow users to set config entry names in config flows
- Names are automatically generated or can be customized later in UI
- ✅ Exception: Helper integrations MAY allow custom names in config flow
- **Connection Testing**: Test device/service connection during config flow:
```python
try:
await client.get_data()
except MyException:
errors["base"] = "cannot_connect"
```
- **Duplicate Prevention**: Prevent duplicate configurations:
```python
# Using unique ID
await self.async_set_unique_id(identifier)
self._abort_if_unique_id_configured()
# Using unique data
self._async_abort_entries_match({CONF_HOST: user_input[CONF_HOST]})
```
### Reauthentication Support
- **Required Method**: Implement `async_step_reauth` in config flow
- **Credential Updates**: Allow users to update credentials without re-adding
- **Validation**: Verify account matches existing unique ID:
```python
await self.async_set_unique_id(user_id)
self._abort_if_unique_id_mismatch(reason="wrong_account")
return self.async_update_reload_and_abort(
self._get_reauth_entry(),
data_updates={CONF_API_TOKEN: user_input[CONF_API_TOKEN]}
)
```
### Reconfiguration Flow
- **Purpose**: Allow configuration updates without removing device
- **Implementation**: Add `async_step_reconfigure` method
- **Validation**: Prevent changing underlying account with `_abort_if_unique_id_mismatch`
### Device Discovery
- **Manifest Configuration**: Add discovery method (zeroconf, dhcp, etc.)
```json
{
"zeroconf": ["_mydevice._tcp.local."]
}
```
- **Discovery Handler**: Implement appropriate `async_step_*` method:
```python
async def async_step_zeroconf(self, discovery_info):
"""Handle zeroconf discovery."""
await self.async_set_unique_id(discovery_info.properties["serialno"])
self._abort_if_unique_id_configured(updates={CONF_HOST: discovery_info.host})
```
- **Network Updates**: Use discovery to update dynamic IP addresses
### Network Discovery Implementation
- **Zeroconf/mDNS**: Use async instances
```python
aiozc = await zeroconf.async_get_async_instance(hass)
```
- **SSDP Discovery**: Register callbacks with cleanup
```python
entry.async_on_unload(
ssdp.async_register_callback(
hass, _async_discovered_device,
{"st": "urn:schemas-upnp-org:device:ZonePlayer:1"}
)
)
```
### Bluetooth Integration
- **Manifest Dependencies**: Add `bluetooth_adapters` to dependencies
- **Connectable**: Set `"connectable": true` for connection-required devices
- **Scanner Usage**: Always use shared scanner instance
```python
scanner = bluetooth.async_get_scanner()
entry.async_on_unload(
bluetooth.async_register_callback(
hass, _async_discovered_device,
{"service_uuid": "example_uuid"},
bluetooth.BluetoothScanningMode.ACTIVE
)
)
```
- **Connection Handling**: Never reuse `BleakClient` instances, use 10+ second timeouts
### Setup Validation
- **Test Before Setup**: Verify integration can be set up in `async_setup_entry`
- **Exception Handling**:
- `ConfigEntryNotReady`: Device offline or temporary failure
- `ConfigEntryAuthFailed`: Authentication issues
- `ConfigEntryError`: Unresolvable setup problems
### Config Entry Unloading
- **Required**: Implement `async_unload_entry` for runtime removal/reload
- **Platform Unloading**: Use `hass.config_entries.async_unload_platforms`
- **Cleanup**: Register callbacks with `entry.async_on_unload`:
```python
async def async_unload_entry(hass: HomeAssistant, entry: MyConfigEntry) -> bool:
"""Unload a config entry."""
if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS):
entry.runtime_data.listener() # Clean up resources
return unload_ok
```
### Service Actions
- **Registration**: Register all service actions in `async_setup`, NOT in `async_setup_entry`
- **Validation**: Check config entry existence and loaded state:
```python
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
async def service_action(call: ServiceCall) -> ServiceResponse:
if not (entry := hass.config_entries.async_get_entry(call.data[ATTR_CONFIG_ENTRY_ID])):
raise ServiceValidationError("Entry not found")
if entry.state is not ConfigEntryState.LOADED:
raise ServiceValidationError("Entry not loaded")
```
- **Exception Handling**: Raise appropriate exceptions:
```python
# For invalid input
if end_date < start_date:
raise ServiceValidationError("End date must be after start date")
# For service errors
try:
await client.set_schedule(start_date, end_date)
except MyConnectionError as err:
raise HomeAssistantError("Could not connect to the schedule") from err
```
### Service Registration Patterns
- **Entity Services**: Register on platform setup
```python
platform.async_register_entity_service(
"my_entity_service",
{vol.Required("parameter"): cv.string},
"handle_service_method"
)
```
- **Service Schema**: Always validate input
```python
SERVICE_SCHEMA = vol.Schema({
vol.Required("entity_id"): cv.entity_ids,
vol.Required("parameter"): cv.string,
vol.Optional("timeout", default=30): cv.positive_int,
})
```
- **Services File**: Create `services.yaml` with descriptions and field definitions
### Polling
- Use update coordinator pattern when possible
- **Polling intervals are NOT user-configurable**: Never add scan_interval, update_interval, or polling frequency options to config flows or config entries
- **Integration determines intervals**: Set `update_interval` programmatically based on integration logic, not user input
- **Minimum Intervals**:
- Local network: 5 seconds
- Cloud services: 60 seconds
- **Parallel Updates**: Specify number of concurrent updates:
```python
PARALLEL_UPDATES = 1 # Serialize updates to prevent overwhelming device
# OR
PARALLEL_UPDATES = 0 # Unlimited (for coordinator-based or read-only)
```
## Entity Development
### Unique IDs
- **Required**: Every entity must have a unique ID for registry tracking
- Must be unique per platform (not per integration)
- Don't include integration domain or platform in ID
- **Implementation**:
```python
class MySensor(SensorEntity):
def __init__(self, device_id: str) -> None:
self._attr_unique_id = f"{device_id}_temperature"
```
**Acceptable ID Sources**:
- Device serial numbers
- MAC addresses (formatted using `format_mac` from device registry)
- Physical identifiers (printed/EEPROM)
- Config entry ID as last resort: `f"{entry.entry_id}-battery"`
**Never Use**:
- IP addresses, hostnames, URLs
- Device names
- Email addresses, usernames
### Entity Descriptions
- **Lambda/Anonymous Functions**: Often used in EntityDescription for value transformation
- **Multiline Lambdas**: When lambdas exceed line length, wrap in parentheses for readability
- **Bad pattern**:
```python
SensorEntityDescription(
key="temperature",
name="Temperature",
value_fn=lambda data: round(data["temp_value"] * 1.8 + 32, 1) if data.get("temp_value") is not None else None, # ❌ Too long
)
```
- **Good pattern**:
```python
SensorEntityDescription(
key="temperature",
name="Temperature",
value_fn=lambda data: ( # ✅ Parenthesis on same line as lambda
round(data["temp_value"] * 1.8 + 32, 1)
if data.get("temp_value") is not None
else None
),
)
```
### Entity Naming
- **Use has_entity_name**: Set `_attr_has_entity_name = True`
- **For specific fields**:
```python
class MySensor(SensorEntity):
_attr_has_entity_name = True
def __init__(self, device: Device, field: str) -> None:
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, device.id)},
name=device.name,
)
self._attr_name = field # e.g., "temperature", "humidity"
```
- **For device itself**: Set `_attr_name = None`
### Event Lifecycle Management
- **Subscribe in `async_added_to_hass`**:
```python
async def async_added_to_hass(self) -> None:
"""Subscribe to events."""
self.async_on_remove(
self.client.events.subscribe("my_event", self._handle_event)
)
```
- **Unsubscribe in `async_will_remove_from_hass`** if not using `async_on_remove`
- Never subscribe in `__init__` or other methods
### State Handling
- Unknown values: Use `None` (not "unknown" or "unavailable")
- Availability: Implement `available()` property instead of using "unavailable" state
### Entity Availability
- **Mark Unavailable**: When data cannot be fetched from device/service
- **Coordinator Pattern**:
```python
@property
def available(self) -> bool:
"""Return if entity is available."""
return super().available and self.identifier in self.coordinator.data
```
- **Direct Update Pattern**:
```python
async def async_update(self) -> None:
"""Update entity."""
try:
data = await self.client.get_data()
except MyException:
self._attr_available = False
else:
self._attr_available = True
self._attr_native_value = data.value
```
### Extra State Attributes
- All attribute keys must always be present
- Unknown values: Use `None`
- Provide descriptive attributes
## Device Management
### Device Registry
- **Create Devices**: Group related entities under devices
- **Device Info**: Provide comprehensive metadata:
```python
_attr_device_info = DeviceInfo(
connections={(CONNECTION_NETWORK_MAC, device.mac)},
identifiers={(DOMAIN, device.id)},
name=device.name,
manufacturer="My Company",
model="My Sensor",
sw_version=device.version,
)
```
- For services: Add `entry_type=DeviceEntryType.SERVICE`
### Dynamic Device Addition
- **Auto-detect New Devices**: After initial setup
- **Implementation Pattern**:
```python
def _check_device() -> None:
current_devices = set(coordinator.data)
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])
entry.async_on_unload(coordinator.async_add_listener(_check_device))
```
### Stale Device Removal
- **Auto-remove**: When devices disappear from hub/account
- **Device Registry Update**:
```python
device_registry.async_update_device(
device_id=device.id,
remove_config_entry_id=self.config_entry.entry_id,
)
```
- **Manual Deletion**: Implement `async_remove_config_entry_device` when needed
### Entity Categories
- **Required**: Assign appropriate category to entities
- **Implementation**: Set `_attr_entity_category`
```python
class MySensor(SensorEntity):
_attr_entity_category = EntityCategory.DIAGNOSTIC
```
- Categories include: `DIAGNOSTIC` for system/technical information
### Device Classes
- **Use When Available**: Set appropriate device class for entity type
```python
class MyTemperatureSensor(SensorEntity):
_attr_device_class = SensorDeviceClass.TEMPERATURE
```
- Provides context for: unit conversion, voice control, UI representation
### Disabled by Default
- **Disable Noisy/Less Popular Entities**: Reduce resource usage
```python
class MySignalStrengthSensor(SensorEntity):
_attr_entity_registry_enabled_default = False
```
- Target: frequently changing states, technical diagnostics
### Entity Translations
- **Required with has_entity_name**: Support international users
- **Implementation**:
```python
class MySensor(SensorEntity):
_attr_has_entity_name = True
_attr_translation_key = "phase_voltage"
```
- Create `strings.json` with translations:
```json
{
"entity": {
"sensor": {
"phase_voltage": {
"name": "Phase voltage"
}
}
}
}
```
### Exception Translations (Gold)
- **Translatable Errors**: Use translation keys for user-facing exceptions
- **Implementation**:
```python
raise ServiceValidationError(
translation_domain=DOMAIN,
translation_key="end_date_before_start_date",
)
```
- Add to `strings.json`:
```json
{
"exceptions": {
"end_date_before_start_date": {
"message": "The end date cannot be before the start date."
}
}
}
```
### Icon Translations (Gold)
- **Dynamic Icons**: Support state and range-based icon selection
- **State-based Icons**:
```json
{
"entity": {
"sensor": {
"tree_pollen": {
"default": "mdi:tree",
"state": {
"high": "mdi:tree-outline"
}
}
}
}
}
```
- **Range-based Icons** (for numeric values):
```json
{
"entity": {
"sensor": {
"battery_level": {
"default": "mdi:battery-unknown",
"range": {
"0": "mdi:battery-outline",
"90": "mdi:battery-90",
"100": "mdi:battery"
}
}
}
}
}
```
## Testing Requirements
- **Location**: `tests/components/{domain}/`
- **Coverage Requirement**: Above 95% test coverage for all modules
- **Best Practices**:
- Use pytest fixtures from `tests.common`
- Mock all external dependencies
- Use snapshots for complex data structures
- Follow existing test patterns
### Config Flow Testing
- **100% Coverage Required**: All config flow paths must be tested
- **Test Scenarios**:
- All flow initiation methods (user, discovery, import)
- Successful configuration paths
- Error recovery scenarios
- Prevention of duplicate entries
- Flow completion after errors
### Testing
- **Integration-specific tests** (recommended):
```bash
pytest ./tests/components/<integration_domain> \
--cov=homeassistant.components.<integration_domain> \
--cov-report term-missing \
--durations-min=1 \
--durations=0 \
--numprocesses=auto
```
### Testing Best Practices
- **Never access `hass.data` directly** - Use fixtures and proper integration setup instead
- **Use snapshot testing** - For verifying entity states and attributes
- **Test through integration setup** - Don't test entities in isolation
- **Mock external APIs** - Use fixtures with realistic JSON data
- **Verify registries** - Ensure entities are properly registered with devices
### Config Flow Testing Template
```python
async def test_user_flow_success(hass, mock_api):
"""Test successful user flow."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "user"
# Test form submission
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input=TEST_USER_INPUT
)
assert result["type"] == FlowResultType.CREATE_ENTRY
assert result["title"] == "My Device"
assert result["data"] == TEST_USER_INPUT
async def test_flow_connection_error(hass, mock_api_error):
"""Test connection error handling."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input=TEST_USER_INPUT
)
assert result["type"] == FlowResultType.FORM
assert result["errors"] == {"base": "cannot_connect"}
```
### Entity Testing Patterns
```python
@pytest.fixture
def platforms() -> list[Platform]:
"""Overridden fixture to specify platforms to test."""
return [Platform.SENSOR] # Or another specific platform as needed.
@pytest.mark.usefixtures("entity_registry_enabled_by_default", "init_integration")
async def test_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
device_registry: dr.DeviceRegistry,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the sensor entities."""
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
# Ensure entities are correctly assigned to device
device_entry = device_registry.async_get_device(
identifiers={(DOMAIN, "device_unique_id")}
)
assert device_entry
entity_entries = er.async_entries_for_config_entry(
entity_registry, mock_config_entry.entry_id
)
for entity_entry in entity_entries:
assert entity_entry.device_id == device_entry.id
```
### Mock Patterns
```python
# Modern integration fixture setup
@pytest.fixture
def mock_config_entry() -> MockConfigEntry:
"""Return the default mocked config entry."""
return MockConfigEntry(
title="My Integration",
domain=DOMAIN,
data={CONF_HOST: "127.0.0.1", CONF_API_KEY: "test_key"},
unique_id="device_unique_id",
)
@pytest.fixture
def mock_device_api() -> Generator[MagicMock]:
"""Return a mocked device API."""
with patch("homeassistant.components.my_integration.MyDeviceAPI", autospec=True) as api_mock:
api = api_mock.return_value
api.get_data.return_value = MyDeviceData.from_json(
load_fixture("device_data.json", DOMAIN)
)
yield api
@pytest.fixture
def platforms() -> list[Platform]:
"""Fixture to specify platforms to test."""
return PLATFORMS
@pytest.fixture
async def init_integration(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_device_api: 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
```
## Debugging & Troubleshooting
### Common Issues & Solutions
- **Integration won't load**: Check `manifest.json` syntax and required fields
- **Entities not appearing**: Verify `unique_id` and `has_entity_name` implementation
- **Config flow errors**: Check `strings.json` entries and error handling
- **Discovery not working**: Verify manifest discovery configuration and callbacks
- **Tests failing**: Check mock setup and async context
### Debug Logging Setup
```python
# Enable debug logging in tests
caplog.set_level(logging.DEBUG, logger="my_integration")
# In integration code - use proper logging
_LOGGER = logging.getLogger(__name__)
_LOGGER.debug("Processing data: %s", data) # Use lazy logging
```
### Validation Commands
```bash
# Check specific integration
python -m script.hassfest --integration-path homeassistant/components/my_integration
# Validate quality scale
# Check quality_scale.yaml against current rules
# Run integration tests with coverage
pytest ./tests/components/my_integration \
--cov=homeassistant.components.my_integration \
--cov-report term-missing
```

View File

@@ -1,19 +0,0 @@
# Integration Diagnostics
Platform exists as `homeassistant/components/<domain>/diagnostics.py`.
- **Required**: Implement diagnostic data collection
- **Implementation**:
```python
TO_REDACT = [CONF_API_KEY, CONF_LATITUDE, CONF_LONGITUDE]
async def async_get_config_entry_diagnostics(
hass: HomeAssistant, entry: MyConfigEntry
) -> dict[str, Any]:
"""Return diagnostics for a config entry."""
return {
"entry_data": async_redact_data(entry.data, TO_REDACT),
"data": entry.runtime_data.data,
}
```
- **Security**: Never expose passwords, tokens, or sensitive coordinates

View File

@@ -1,55 +0,0 @@
# Repairs platform
Platform exists as `homeassistant/components/<domain>/repairs.py`.
- **Actionable Issues Required**: All repair issues must be actionable for end users
- **Issue Content Requirements**:
- Clearly explain what is happening
- Provide specific steps users need to take to resolve the issue
- Use friendly, helpful language
- Include relevant context (device names, error details, etc.)
- **Implementation**:
```python
ir.async_create_issue(
hass,
DOMAIN,
"outdated_version",
is_fixable=False,
issue_domain=DOMAIN,
severity=ir.IssueSeverity.ERROR,
translation_key="outdated_version",
)
```
- **Translation Strings Requirements**: Must contain user-actionable text in `strings.json`:
```json
{
"issues": {
"outdated_version": {
"title": "Device firmware is outdated",
"description": "Your device firmware version {current_version} is below the minimum required version {min_version}. To fix this issue: 1) Open the manufacturer's mobile app, 2) Navigate to device settings, 3) Select 'Update Firmware', 4) Wait for the update to complete, then 5) Restart Home Assistant."
}
}
}
```
- **String Content Must Include**:
- What the problem is
- Why it matters
- Exact steps to resolve (numbered list when multiple steps)
- What to expect after following the steps
- **Avoid Vague Instructions**: Don't just say "update firmware" - provide specific steps
- **Severity Guidelines**:
- `CRITICAL`: Reserved for extreme scenarios only
- `ERROR`: Requires immediate user attention
- `WARNING`: Indicates future potential breakage
- **Additional Attributes**:
```python
ir.async_create_issue(
hass, DOMAIN, "issue_id",
breaks_in_ha_version="2024.1.0",
is_fixable=True,
is_persistent=True,
severity=ir.IssueSeverity.ERROR,
translation_key="issue_description",
)
```
- Only create issues for problems users can potentially resolve

View File

@@ -0,0 +1,297 @@
---
name: quality-scale-architect
description: Provide architectural guidance and quality scale oversight for Home Assistant integrations. Use when designing integration structure, selecting quality tiers (Bronze/Silver/Gold/Platinum), recommending architectural patterns (coordinator/push/hub), planning quality progression, or advising on integration organization.
---
# Quality Scale Architect for Home Assistant Integrations
You are an expert Home Assistant integration architect specializing in quality scale systems, best practices, and architectural patterns.
## Quality Scale System
### Quality Scale Tiers
**Bronze** - Basic Requirements (Mandatory for all integrations with quality scale)
- ✅ Config flow (UI configuration)
- ✅ Entity unique IDs
- ✅ Action setup (or exempt)
- ✅ Appropriate setup retries
- ✅ Reauthentication flow
- ✅ Reconfigure flow
- ✅ Test coverage
**Silver** - Enhanced Functionality
- All Bronze requirements +
- ✅ Entity unavailable tracking
- ✅ Parallel updates configuration
- ✅ Runtime data storage
- ✅ Unique config entry titles
**Gold** - Advanced Features
- All Silver requirements +
- ✅ Device registry usage
- ✅ Integration diagnostics
- ✅ Device diagnostics
- ✅ Entity category
- ✅ Device class
- ✅ Disabled by default (for noisy entities)
- ✅ Entity translations
- ✅ Exception translations
- ✅ Icon translations
**Platinum** - Highest Quality Standards
- All Gold requirements +
- ✅ Strict typing (full type hints)
- ✅ Async dependencies (no sync-blocking libs)
- ✅ WebSession injection
- ✅ config_entry parameter in coordinator
## Architectural Patterns
### Pattern 1: Coordinator-Based Architecture
**Use when**: Polling multiple entities from the same API
```python
class MyCoordinator(DataUpdateCoordinator[MyData]):
def __init__(
self,
hass: HomeAssistant,
client: MyClient,
config_entry: ConfigEntry,
) -> None:
super().__init__(
hass,
logger=LOGGER,
name=DOMAIN,
update_interval=timedelta(minutes=5),
config_entry=config_entry, # ✅ Pass for Platinum
)
self.client = client
async def _async_update_data(self) -> MyData:
try:
return await self.client.fetch_data()
except ApiError as err:
raise UpdateFailed(f"Error: {err}") from err
```
### Pattern 2: Push-Based Architecture
**Use when**: Device pushes updates (webhooks, MQTT, WebSocket)
```python
class MyEntity(SensorEntity):
async def async_added_to_hass(self) -> None:
self.async_on_remove(
self.hub.subscribe_updates(self._handle_update)
)
@callback
def _handle_update(self, data: dict) -> None:
self._attr_native_value = data["value"]
self.async_write_ha_state()
```
### Pattern 3: Hub with Discovery
**Use when**: Hub device with multiple discoverable endpoints
```python
@callback
def _check_new_devices() -> None:
"""Check for new devices."""
current = set(coordinator.data.devices.keys())
new = current - known_devices
if new:
known_devices.update(new)
async_dispatcher_send(hass, f"{DOMAIN}_new_device", new)
entry.async_on_unload(coordinator.async_add_listener(_check_new_devices))
```
## Architectural Decision Guide
### Choosing Integration Type
**Device Integration** (`"integration_type": "device"`)
- Physical or virtual devices
- Example: Smart plugs, thermostats, cameras
**Hub Integration** (`"integration_type": "hub"`)
- Central hub controlling multiple devices
- Example: Philips Hue bridge, Z-Wave controller
**Service Integration** (`"integration_type": "service"`)
- Cloud services, APIs
- Example: Weather services, notification platforms
**Helper Integration** (`"integration_type": "helper"`)
- Utility integrations
- Example: Template, group, automation helpers
### Choosing IoT Class
```json
{
"iot_class": "cloud_polling", // API polling
"iot_class": "cloud_push", // Cloud webhooks/MQTT
"iot_class": "local_polling", // Local device polling
"iot_class": "local_push", // Local device push
"iot_class": "calculated" // No external data
}
```
## Quality Scale Progression Strategy
### Starting Bronze (Minimum Viable Integration)
**Essential Components**:
```
homeassistant/components/my_integration/
├── __init__.py # async_setup_entry, async_unload_entry
├── manifest.json # Required fields, quality_scale: "bronze"
├── const.py # DOMAIN constant
├── config_flow.py # UI configuration with reauth/reconfigure
├── sensor.py # Platform with unique IDs
├── strings.json # Translations
└── quality_scale.yaml # Rule tracking
tests/components/my_integration/
├── conftest.py # Test fixtures
├── test_config_flow.py # 100% coverage
└── test_sensor.py # Entity tests
```
**Bronze Checklist**:
- [ ] Config flow with UI setup
- [ ] Reauthentication flow
- [ ] Reconfigure flow
- [ ] All entities have unique IDs
- [ ] Proper setup error handling
- [ ] >95% test coverage
- [ ] 100% config flow coverage
### Progressing to Silver
**Add**:
- Entity unavailability tracking
- Runtime data storage (not hass.data)
- Parallel updates configuration
- Unique entry titles
```python
# Store in runtime_data (Silver requirement)
entry.runtime_data = coordinator
# Entity availability (Silver requirement)
@property
def available(self) -> bool:
return super().available and self.device_id in self.coordinator.data
# Parallel updates (Silver requirement)
PARALLEL_UPDATES = 0 # For coordinator-based
```
### Progressing to Gold
**Add**:
- Device registry entries
- Integration & device diagnostics
- Entity categories, device classes
- Entity translations
- Exception translations
- Icon translations
```python
# Device info (Gold requirement)
_attr_device_info = DeviceInfo(
identifiers={(DOMAIN, device.id)},
name=device.name,
manufacturer="Manufacturer",
model="Model",
)
# Diagnostics (Gold requirement)
async def async_get_config_entry_diagnostics(
hass: HomeAssistant,
entry: MyConfigEntry,
) -> dict[str, Any]:
return {
"data": async_redact_data(entry.data, TO_REDACT),
"runtime": entry.runtime_data.to_dict(),
}
```
### Progressing to Platinum
**Add**:
- Comprehensive type hints (py.typed)
- Async-only dependencies
- WebSession injection support
```python
# Type hints (Platinum requirement)
type MyIntegrationConfigEntry = ConfigEntry[MyClient]
# WebSession injection (Platinum requirement)
client = MyClient(
host=entry.data[CONF_HOST],
session=async_get_clientsession(hass),
)
# Pass config_entry to coordinator (Platinum requirement)
coordinator = MyCoordinator(hass, client, entry)
```
## Common Architectural Questions
### Q: Should I use a coordinator?
**Use coordinator when**:
- Polling API for multiple entities
- Want efficient data sharing
- Need coordinated updates
**Don't use coordinator when**:
- Push-based updates (use callbacks)
- Single entity integration
- Each entity has independent data source
### Q: Where should I store runtime data?
```python
# ✅ GOOD - Use runtime_data (Silver+)
entry.runtime_data = coordinator
# ❌ BAD - Don't use hass.data
hass.data.setdefault(DOMAIN, {})[entry.entry_id] = coordinator
```
### Q: When should I create devices vs. just entities?
**Create devices when**:
- Representing physical/virtual devices
- Multiple entities belong to same device
- Want grouped device management
**Just entities when**:
- Service integration (no physical device)
- Single entity integration
- Calculated/helper entities
## Reference Files
For detailed implementation guidance, see:
- `.claude/references/diagnostics.md` - Diagnostics implementation
- `.claude/references/sensor.md` - Sensor platform
- `.claude/references/binary_sensor.md` - Binary sensor platform
- `.claude/references/switch.md` - Switch platform
- `.claude/references/button.md` - Button platform
- `.claude/references/number.md` - Number platform
- `.claude/references/select.md` - Select platform
## Your Task
When providing architectural guidance:
1. **Understand Requirements**: What is the integration type? What data needs exposure? Polling or push? What quality tier?
2. **Recommend Architecture**: Suggest appropriate patterns, identify required components, explain decisions
3. **Quality Scale Guidance**: Recommend starting tier, identify applicable rules, suggest progression path
4. **Implementation Plan**: Outline file structure, identify key components, suggest implementation order
5. **Best Practices**: Performance considerations, maintainability tips, common pitfalls to avoid

View File

@@ -0,0 +1,205 @@
---
name: testing
description: Write, run, and fix tests for Home Assistant integrations. Use when writing comprehensive test coverage (>95%), running pytest, fixing failing tests, updating snapshots, or following HA testing patterns. Specializes in modern fixture patterns, config flow testing (100% coverage), entity snapshot testing, and mocking external APIs.
---
# Testing Skill for Home Assistant Integrations
You are an expert Home Assistant integration test engineer specializing in writing comprehensive, maintainable tests that follow Home Assistant conventions and best practices.
## Testing Standards
### Coverage Requirements
- **Minimum Coverage**: 95% for all modules
- **Config Flow**: 100% coverage required for all paths
- **Location**: Tests go in `tests/components/{domain}/`
### Test File Organization
```
tests/components/my_integration/
├── __init__.py
├── conftest.py # Fixtures and test setup
├── test_config_flow.py # Config flow tests (100% coverage)
├── test_sensor.py # Sensor platform tests
├── test_init.py # Integration setup tests
└── snapshots/ # Generated snapshot files
```
## Modern Fixture Setup Pattern
Always use this pattern for integration tests:
```python
from homeassistant.core import HomeAssistant
from homeassistant.const import Platform
from pytest_homeassistant_custom_component.common import MockConfigEntry
@pytest.fixture
def mock_config_entry() -> MockConfigEntry:
"""Return the default mocked config entry."""
return MockConfigEntry(
title="My Integration",
domain=DOMAIN,
data={CONF_HOST: "127.0.0.1", CONF_API_KEY: "test_key"},
unique_id="device_unique_id",
)
@pytest.fixture
def mock_device_api() -> Generator[MagicMock]:
"""Return a mocked device API."""
with patch("homeassistant.components.my_integration.MyDeviceAPI", autospec=True) as api_mock:
api = api_mock.return_value
api.get_data.return_value = MyDeviceData.from_json(
load_fixture("device_data.json", DOMAIN)
)
yield api
@pytest.fixture
def platforms() -> list[Platform]:
"""Fixture to specify platforms to test."""
return [Platform.SENSOR]
@pytest.fixture
async def init_integration(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_device_api: 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
```
## Entity Testing with Snapshots
Use snapshot testing for entity verification:
```python
from syrupy import SnapshotAssertion
from homeassistant.helpers import entity_registry as er, device_registry as dr
@pytest.mark.usefixtures("entity_registry_enabled_by_default", "init_integration")
async def test_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
device_registry: dr.DeviceRegistry,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the sensor entities."""
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
# Verify entities are assigned to device
device_entry = device_registry.async_get_device(
identifiers={(DOMAIN, "device_unique_id")}
)
assert device_entry
entity_entries = er.async_entries_for_config_entry(
entity_registry, mock_config_entry.entry_id
)
for entity_entry in entity_entries:
assert entity_entry.device_id == device_entry.id
```
## Config Flow Testing (100% Coverage Required)
Test ALL paths in config flow:
```python
async def test_user_flow_success(hass, mock_api):
"""Test successful user flow."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input=TEST_USER_INPUT
)
assert result["type"] == FlowResultType.CREATE_ENTRY
assert result["title"] == "My Device"
assert result["data"] == TEST_USER_INPUT
async def test_flow_connection_error(hass, mock_api_error):
"""Test connection error handling."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input=TEST_USER_INPUT
)
assert result["type"] == FlowResultType.FORM
assert result["errors"] == {"base": "cannot_connect"}
async def test_flow_duplicate_entry(hass, mock_config_entry, mock_api):
"""Test duplicate entry prevention."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input=TEST_USER_INPUT
)
assert result["type"] == FlowResultType.ABORT
assert result["reason"] == "already_configured"
```
## Running Tests
### Integration-Specific Tests (Recommended)
```bash
pytest ./tests/components/<integration_domain> \
--cov=homeassistant.components.<integration_domain> \
--cov-report term-missing \
--durations-min=1 \
--durations=0 \
--numprocesses=auto
```
### Quick Test of Changed Files
```bash
pytest --timeout=10 --picked
```
### Update Test Snapshots
```bash
pytest ./tests/components/<integration_domain> --snapshot-update
```
**⚠️ IMPORTANT**: After using `--snapshot-update`:
1. Run tests again WITHOUT the flag to verify snapshots
2. Review the snapshot changes carefully
3. Don't commit snapshot updates without verification
## Critical Testing Rules
### NEVER Do These Things
- ❌ Don't access `hass.data` directly in tests
- ❌ Don't test entities in isolation without integration setup
- ❌ Don't forget to mock external dependencies
### ALWAYS Do These Things
- ✅ Use proper integration setup through fixtures
- ✅ Mock all external APIs
- ✅ Test through the integration's public interface
- ✅ Use snapshot testing for entities
- ✅ Achieve 100% config flow coverage
- ✅ Achieve >95% overall coverage
## Reference Files
For detailed implementation guidance, see:
- `.claude/references/sensor.md` - Sensor platform patterns
- `.claude/references/binary_sensor.md` - Binary sensor patterns
- `.claude/references/switch.md` - Switch platform patterns
- `.claude/references/button.md` - Button platform patterns
- `.claude/references/number.md` - Number platform patterns
- `.claude/references/select.md` - Select platform patterns

View File

@@ -91,7 +91,6 @@ components: &components
- homeassistant/components/input_number/**
- homeassistant/components/input_select/**
- homeassistant/components/input_text/**
- homeassistant/components/labs/**
- homeassistant/components/logbook/**
- homeassistant/components/logger/**
- homeassistant/components/lovelace/**

View File

@@ -8,6 +8,9 @@
"PYTHONASYNCIODEBUG": "1"
},
"features": {
// Node feature required for Claude Code until fixed https://github.com/anthropics/devcontainer-features/issues/28
"ghcr.io/devcontainers/features/node:1": {},
"ghcr.io/anthropics/devcontainer-features/claude-code:1.0": {},
"ghcr.io/devcontainers/features/github-cli:1": {}
},
// Port 5683 udp is used by Shelly integration
@@ -37,8 +40,7 @@
"python.terminal.activateEnvInCurrentTerminal": true,
"python.testing.pytestArgs": ["--no-cov"],
"pylint.importStrategy": "fromEnvironment",
// Pyright type checking is not compatible with mypy which Home Assistant uses for type checking
"python.analysis.typeCheckingMode": "off",
"python.analysis.typeCheckingMode": "basic",
"editor.formatOnPaste": false,
"editor.formatOnSave": true,
"editor.formatOnType": true,

View File

@@ -80,7 +80,7 @@ If the code communicates with devices, web services, or third-party tools:
Updated and included derived files by running: `python3 -m script.hassfest`.
- [ ] New or updated dependencies have been added to `requirements_all.txt`.
Updated by running `python3 -m script.gen_requirements_all`.
- [ ] For the updated dependencies a diff between library versions and ideally a link to the changelog/release notes is added to the PR description.
- [ ] For the updated dependencies - a link to the changelog, or at minimum a diff between library versions is added to the PR description.
<!--
This project is very active and we have a high turnover of pull requests.

File diff suppressed because it is too large Load Diff

View File

@@ -10,12 +10,12 @@ on:
env:
BUILD_TYPE: core
DEFAULT_PYTHON: "3.14.2"
DEFAULT_PYTHON: "3.13"
PIP_TIMEOUT: 60
UV_HTTP_TIMEOUT: 60
UV_SYSTEM_PYTHON: "true"
# Base image version from https://github.com/home-assistant/docker
BASE_IMAGE_VERSION: "2026.01.0"
BASE_IMAGE_VERSION: "2025.12.0"
ARCHITECTURES: '["amd64", "aarch64"]'
jobs:
@@ -30,10 +30,10 @@ jobs:
architectures: ${{ env.ARCHITECTURES }}
steps:
- name: Checkout the repository
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1
- name: Set up Python ${{ env.DEFAULT_PYTHON }}
uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
uses: actions/setup-python@83679a892e2d95755f2dac6acb0bfd1e9ac5d548 # v6.1.0
with:
python-version: ${{ env.DEFAULT_PYTHON }}
@@ -96,11 +96,11 @@ jobs:
os: ubuntu-24.04-arm
steps:
- name: Checkout the repository
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1
- name: Download nightly wheels of frontend
if: needs.init.outputs.channel == 'dev'
uses: dawidd6/action-download-artifact@5c98f0b039f36ef966fdb7dfa9779262785ecb05 # v14
uses: dawidd6/action-download-artifact@0bd50d53a6d7fb5cb921e607957e9cc12b4ce392 # v12
with:
github_token: ${{secrets.GITHUB_TOKEN}}
repo: home-assistant/frontend
@@ -111,7 +111,7 @@ jobs:
- name: Download nightly wheels of intents
if: needs.init.outputs.channel == 'dev'
uses: dawidd6/action-download-artifact@5c98f0b039f36ef966fdb7dfa9779262785ecb05 # v14
uses: dawidd6/action-download-artifact@0bd50d53a6d7fb5cb921e607957e9cc12b4ce392 # v12
with:
github_token: ${{secrets.GITHUB_TOKEN}}
repo: OHF-Voice/intents-package
@@ -122,7 +122,7 @@ jobs:
- name: Set up Python ${{ env.DEFAULT_PYTHON }}
if: needs.init.outputs.channel == 'dev'
uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
uses: actions/setup-python@83679a892e2d95755f2dac6acb0bfd1e9ac5d548 # v6.1.0
with:
python-version: ${{ env.DEFAULT_PYTHON }}
@@ -184,7 +184,7 @@ jobs:
echo "${{ github.sha }};${{ github.ref }};${{ github.event_name }};${{ github.actor }}" > rootfs/OFFICIAL_IMAGE
- name: Login to GitHub Container Registry
uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3.7.0
uses: docker/login-action@5e57cd118135c172c3672efd75eb46360885c0ef # v3.6.0
with:
registry: ghcr.io
username: ${{ github.repository_owner }}
@@ -273,7 +273,7 @@ jobs:
- green
steps:
- name: Checkout the repository
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1
- name: Set build additional args
run: |
@@ -287,7 +287,7 @@ jobs:
fi
- name: Login to GitHub Container Registry
uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3.7.0
uses: docker/login-action@5e57cd118135c172c3672efd75eb46360885c0ef # v3.6.0
with:
registry: ghcr.io
username: ${{ github.repository_owner }}
@@ -311,7 +311,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout the repository
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1
- name: Initialize git
uses: home-assistant/actions/helpers/git-init@master
@@ -358,13 +358,13 @@ jobs:
- name: Login to DockerHub
if: matrix.registry == 'docker.io/homeassistant'
uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3.7.0
uses: docker/login-action@5e57cd118135c172c3672efd75eb46360885c0ef # v3.6.0
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Login to GitHub Container Registry
uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3.7.0
uses: docker/login-action@5e57cd118135c172c3672efd75eb46360885c0ef # v3.6.0
with:
registry: ghcr.io
username: ${{ github.repository_owner }}
@@ -474,10 +474,10 @@ jobs:
if: github.repository_owner == 'home-assistant' && needs.init.outputs.publish == 'true'
steps:
- name: Checkout the repository
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1
- name: Set up Python ${{ env.DEFAULT_PYTHON }}
uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
uses: actions/setup-python@83679a892e2d95755f2dac6acb0bfd1e9ac5d548 # v6.1.0
with:
python-version: ${{ env.DEFAULT_PYTHON }}
@@ -519,10 +519,10 @@ jobs:
HASSFEST_IMAGE_TAG: ghcr.io/home-assistant/hassfest:${{ needs.init.outputs.version }}
steps:
- name: Checkout repository
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1
- name: Login to GitHub Container Registry
uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3.7.0
uses: docker/login-action@5e57cd118135c172c3672efd75eb46360885c0ef # v3.6.0
with:
registry: ghcr.io
username: ${{ github.repository_owner }}
@@ -551,7 +551,7 @@ jobs:
- name: Generate artifact attestation
if: needs.init.outputs.channel != 'dev' && needs.init.outputs.publish == 'true'
uses: actions/attest-build-provenance@96278af6caaf10aea03fd8d33a09a777ca52d62f # v3.2.0
uses: actions/attest-build-provenance@00014ed6ed5efc5b1ab7f7f34a39eb55d41aa4f8 # v3.1.0
with:
subject-name: ${{ env.HASSFEST_IMAGE_NAME }}
subject-digest: ${{ steps.push.outputs.digest }}

View File

@@ -40,9 +40,9 @@ env:
CACHE_VERSION: 2
UV_CACHE_VERSION: 1
MYPY_CACHE_VERSION: 1
HA_SHORT_VERSION: "2026.3"
DEFAULT_PYTHON: "3.14.2"
ALL_PYTHON_VERSIONS: "['3.14.2']"
HA_SHORT_VERSION: "2026.2"
DEFAULT_PYTHON: "3.13.11"
ALL_PYTHON_VERSIONS: "['3.13.11', '3.14.2']"
# 10.3 is the oldest supported version
# - 10.3.32 is the version currently shipped with Synology (as of 17 Feb 2022)
# 10.6 is the current long-term-support
@@ -59,6 +59,7 @@ env:
# 15 is the latest version
# - 15.2 is the latest (as of 9 Feb 2023)
POSTGRESQL_VERSIONS: "['postgres:12.14','postgres:15.2']"
PRE_COMMIT_CACHE: ~/.cache/pre-commit
UV_CACHE_DIR: /tmp/uv-cache
APT_CACHE_BASE: /home/runner/work/apt
APT_CACHE_DIR: /home/runner/work/apt/cache
@@ -82,6 +83,7 @@ jobs:
integrations_glob: ${{ steps.info.outputs.integrations_glob }}
integrations: ${{ steps.integrations.outputs.changes }}
apt_cache_key: ${{ steps.generate_apt_cache_key.outputs.key }}
pre-commit_cache_key: ${{ steps.generate_pre-commit_cache_key.outputs.key }}
python_cache_key: ${{ steps.generate_python_cache_key.outputs.key }}
requirements: ${{ steps.core.outputs.requirements }}
mariadb_groups: ${{ steps.info.outputs.mariadb_groups }}
@@ -97,7 +99,7 @@ jobs:
steps:
- &checkout
name: Check out code from GitHub
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1
- name: Generate partial Python venv restore key
id: generate_python_cache_key
run: |
@@ -109,6 +111,11 @@ jobs:
hashFiles('requirements_all.txt') }}-${{
hashFiles('homeassistant/package_constraints.txt') }}-${{
hashFiles('script/gen_requirements_all.py') }}" >> $GITHUB_OUTPUT
- name: Generate partial pre-commit restore key
id: generate_pre-commit_cache_key
run: >-
echo "key=pre-commit-${{ env.CACHE_VERSION }}-${{
hashFiles('.pre-commit-config.yaml') }}" >> $GITHUB_OUTPUT
- name: Generate partial apt restore key
id: generate_apt_cache_key
run: |
@@ -237,8 +244,8 @@ jobs:
echo "skip_coverage: ${skip_coverage}"
echo "skip_coverage=${skip_coverage}" >> $GITHUB_OUTPUT
prek:
name: Run prek checks
pre-commit:
name: Prepare pre-commit base
runs-on: *runs-on-ubuntu
needs: [info]
if: |
@@ -247,17 +254,147 @@ jobs:
&& github.event.inputs.audit-licenses-only != 'true'
steps:
- *checkout
- name: Register problem matchers
- &setup-python-default
name: Set up Python ${{ env.DEFAULT_PYTHON }}
id: python
uses: &actions-setup-python actions/setup-python@83679a892e2d95755f2dac6acb0bfd1e9ac5d548 # v6.1.0
with:
python-version: ${{ env.DEFAULT_PYTHON }}
check-latest: true
- name: Restore base Python virtual environment
id: cache-venv
uses: &actions-cache actions/cache@9255dc7a253b0ccc959486e2bca901246202afeb # v5.0.1
with:
path: venv
key: &key-pre-commit-venv >-
${{ runner.os }}-${{ runner.arch }}-${{ steps.python.outputs.python-version }}-venv-${{
needs.info.outputs.pre-commit_cache_key }}
- name: Create Python virtual environment
if: steps.cache-venv.outputs.cache-hit != 'true'
run: |
python -m venv venv
. venv/bin/activate
python --version
pip install "$(grep '^uv' < requirements.txt)"
uv pip install "$(cat requirements_test.txt | grep pre-commit)"
- name: Restore pre-commit environment from cache
id: cache-precommit
uses: *actions-cache
with:
path: ${{ env.PRE_COMMIT_CACHE }}
lookup-only: true
key: &key-pre-commit-env >-
${{ runner.os }}-${{ runner.arch }}-${{ steps.python.outputs.python-version }}-${{
needs.info.outputs.pre-commit_cache_key }}
- name: Install pre-commit dependencies
if: steps.cache-precommit.outputs.cache-hit != 'true'
run: |
. venv/bin/activate
pre-commit install-hooks
lint-ruff-format:
name: Check ruff-format
runs-on: *runs-on-ubuntu
needs: &needs-pre-commit
- info
- pre-commit
steps:
- *checkout
- *setup-python-default
- &cache-restore-pre-commit-venv
name: Restore base Python virtual environment
id: cache-venv
uses: &actions-cache-restore actions/cache/restore@9255dc7a253b0ccc959486e2bca901246202afeb # v5.0.1
with:
path: venv
fail-on-cache-miss: true
key: *key-pre-commit-venv
- &cache-restore-pre-commit-env
name: Restore pre-commit environment from cache
id: cache-precommit
uses: *actions-cache-restore
with:
path: ${{ env.PRE_COMMIT_CACHE }}
fail-on-cache-miss: true
key: *key-pre-commit-env
- name: Run ruff-format
run: |
. venv/bin/activate
pre-commit run --hook-stage manual ruff-format --all-files --show-diff-on-failure
env:
RUFF_OUTPUT_FORMAT: github
lint-ruff:
name: Check ruff
runs-on: *runs-on-ubuntu
needs: *needs-pre-commit
steps:
- *checkout
- *setup-python-default
- *cache-restore-pre-commit-venv
- *cache-restore-pre-commit-env
- name: Run ruff
run: |
. venv/bin/activate
pre-commit run --hook-stage manual ruff-check --all-files --show-diff-on-failure
env:
RUFF_OUTPUT_FORMAT: github
lint-other:
name: Check other linters
runs-on: *runs-on-ubuntu
needs: *needs-pre-commit
steps:
- *checkout
- *setup-python-default
- *cache-restore-pre-commit-venv
- *cache-restore-pre-commit-env
- name: Register yamllint problem matcher
run: |
echo "::add-matcher::.github/workflows/matchers/yamllint.json"
- name: Run yamllint
run: |
. venv/bin/activate
pre-commit run --hook-stage manual yamllint --all-files --show-diff-on-failure
- name: Register check-json problem matcher
run: |
echo "::add-matcher::.github/workflows/matchers/check-json.json"
- name: Run check-json
run: |
. venv/bin/activate
pre-commit run --hook-stage manual check-json --all-files --show-diff-on-failure
- name: Run prettier (fully)
if: needs.info.outputs.test_full_suite == 'true'
run: |
. venv/bin/activate
pre-commit run --hook-stage manual prettier --all-files --show-diff-on-failure
- name: Run prettier (partially)
if: needs.info.outputs.test_full_suite == 'false'
shell: bash
run: |
. venv/bin/activate
shopt -s globstar
pre-commit run --hook-stage manual prettier --show-diff-on-failure --files {homeassistant,tests}/components/${{ needs.info.outputs.integrations_glob }}/{*,**/*}
- name: Register check executables problem matcher
run: |
echo "::add-matcher::.github/workflows/matchers/check-executables-have-shebangs.json"
- name: Run executables check
run: |
. venv/bin/activate
pre-commit run --hook-stage manual check-executables-have-shebangs --all-files --show-diff-on-failure
- name: Register codespell problem matcher
run: |
echo "::add-matcher::.github/workflows/matchers/codespell.json"
- name: Run prek
uses: j178/prek-action@564dda4cfa5e96aafdc4a5696c4bf7b46baae5ac # v1.1.0
env:
PREK_SKIP: no-commit-to-branch,mypy,pylint,gen_requirements_all,hassfest,hassfest-metadata,hassfest-mypy-config
RUFF_OUTPUT_FORMAT: github
- name: Run codespell
run: |
. venv/bin/activate
pre-commit run --show-diff-on-failure --hook-stage manual codespell --all-files
lint-hadolint:
name: Check ${{ matrix.file }}
@@ -297,7 +434,7 @@ jobs:
- &setup-python-matrix
name: Set up Python ${{ matrix.python-version }}
id: python
uses: &actions-setup-python actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
uses: *actions-setup-python
with:
python-version: ${{ matrix.python-version }}
check-latest: true
@@ -310,7 +447,7 @@ jobs:
env.HA_SHORT_VERSION }}-$(date -u '+%Y-%m-%dT%H:%M:%s')" >> $GITHUB_OUTPUT
- name: Restore base Python virtual environment
id: cache-venv
uses: &actions-cache actions/cache@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3
uses: *actions-cache
with:
path: venv
key: &key-python-venv >-
@@ -374,7 +511,7 @@ jobs:
fi
- name: Save apt cache
if: steps.cache-apt-check.outputs.cache-hit != 'true'
uses: &actions-cache-save actions/cache/save@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3
uses: &actions-cache-save actions/cache/save@9255dc7a253b0ccc959486e2bca901246202afeb # v5.0.1
with:
path: *path-apt-cache
key: *key-apt-cache
@@ -425,7 +562,7 @@ jobs:
steps:
- &cache-restore-apt
name: Restore apt cache
uses: &actions-cache-restore actions/cache/restore@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3
uses: *actions-cache-restore
with:
path: *path-apt-cache
fail-on-cache-miss: true
@@ -442,13 +579,7 @@ jobs:
-o Dir::State::Lists=${{ env.APT_LIST_CACHE_DIR }} \
libturbojpeg
- *checkout
- &setup-python-default
name: Set up Python ${{ env.DEFAULT_PYTHON }}
id: python
uses: *actions-setup-python
with:
python-version: ${{ env.DEFAULT_PYTHON }}
check-latest: true
- *setup-python-default
- &cache-restore-python-default
name: Restore full Python ${{ env.DEFAULT_PYTHON }} virtual environment
id: cache-venv
@@ -479,22 +610,6 @@ jobs:
. venv/bin/activate
python -m script.gen_requirements_all validate
gen-copilot-instructions:
name: Check copilot instructions
runs-on: *runs-on-ubuntu
needs:
- info
if: |
github.event.inputs.pylint-only != 'true'
&& github.event.inputs.mypy-only != 'true'
&& github.event.inputs.audit-licenses-only != 'true'
steps:
- *checkout
- *setup-python-default
- name: Run gen_copilot_instructions.py
run: |
python -m script.gen_copilot_instructions validate
dependency-review:
name: Dependency review
runs-on: *runs-on-ubuntu
@@ -667,7 +782,9 @@ jobs:
- base
- gen-requirements-all
- hassfest
- prek
- lint-other
- lint-ruff
- lint-ruff-format
- mypy
steps:
- *cache-restore-apt
@@ -706,7 +823,9 @@ jobs:
- base
- gen-requirements-all
- hassfest
- prek
- lint-other
- lint-ruff
- lint-ruff-format
- mypy
- prepare-pytest-full
if: |
@@ -830,7 +949,9 @@ jobs:
- base
- gen-requirements-all
- hassfest
- prek
- lint-other
- lint-ruff
- lint-ruff-format
- mypy
if: |
needs.info.outputs.lint_only != 'true'
@@ -945,7 +1066,9 @@ jobs:
- base
- gen-requirements-all
- hassfest
- prek
- lint-other
- lint-ruff
- lint-ruff-format
- mypy
if: |
needs.info.outputs.lint_only != 'true'
@@ -1079,7 +1202,9 @@ jobs:
- base
- gen-requirements-all
- hassfest
- prek
- lint-other
- lint-ruff
- lint-ruff-format
- mypy
if: |
needs.info.outputs.lint_only != 'true'
@@ -1203,8 +1328,6 @@ jobs:
- pytest-postgres
- pytest-mariadb
timeout-minutes: 10
permissions:
id-token: write
# codecov/test-results-action currently doesn't support tokenless uploads
# therefore we can't run it on forks
if: |
@@ -1216,9 +1339,8 @@ jobs:
with:
pattern: test-results-*
- name: Upload test results to Codecov
uses: codecov/codecov-action@671740ac38dd9b0130fbe1cec585b89eea48d3de # v5.5.2
uses: codecov/test-results-action@47f89e9acb64b76debcd5ea40642d25a4adced9f # v1.1.1
with:
report_type: test_results
fail_ci_if_error: true
verbose: true
use_oidc: true
token: ${{ secrets.CODECOV_TOKEN }}

View File

@@ -21,14 +21,14 @@ jobs:
steps:
- name: Check out code from GitHub
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1
- name: Initialize CodeQL
uses: github/codeql-action/init@6bc82e05fd0ea64601dd4b465378bbcf57de0314 # v4.32.1
uses: github/codeql-action/init@5d4e8d1aca955e8d8589aabd499c5cae939e33c7 # v4.31.9
with:
languages: python
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@6bc82e05fd0ea64601dd4b465378bbcf57de0314 # v4.32.1
uses: github/codeql-action/analyze@5d4e8d1aca955e8d8589aabd499c5cae939e33c7 # v4.31.9
with:
category: "/language:python"

View File

@@ -231,7 +231,7 @@ jobs:
- name: Detect duplicates using AI
id: ai_detection
if: steps.extract.outputs.should_continue == 'true' && steps.fetch_similar.outputs.has_similar == 'true'
uses: actions/ai-inference@a6101c89c6feaecc585efdd8d461f18bb7896f20 # v2.0.5
uses: actions/ai-inference@334892bb203895caaed82ec52d23c1ed9385151e # v2.0.4
with:
model: openai/gpt-4o
system-prompt: |

View File

@@ -57,7 +57,7 @@ jobs:
- name: Detect language using AI
id: ai_language_detection
if: steps.detect_language.outputs.should_continue == 'true'
uses: actions/ai-inference@a6101c89c6feaecc585efdd8d461f18bb7896f20 # v2.0.5
uses: actions/ai-inference@334892bb203895caaed82ec52d23c1ed9385151e # v2.0.4
with:
model: openai/gpt-4o-mini
system-prompt: |

View File

@@ -4,7 +4,7 @@
"owner": "check-executables-have-shebangs",
"pattern": [
{
"regexp": "^(.+):\\s(marked executable but has no \\(or invalid\\) shebang!.*)$",
"regexp": "^(.+):\\s(.+)$",
"file": 1,
"message": 2
}

View File

@@ -10,7 +10,7 @@ on:
- "**strings.json"
env:
DEFAULT_PYTHON: "3.14.2"
DEFAULT_PYTHON: "3.13"
jobs:
upload:
@@ -19,10 +19,10 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout the repository
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1
- name: Set up Python ${{ env.DEFAULT_PYTHON }}
uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
uses: actions/setup-python@83679a892e2d95755f2dac6acb0bfd1e9ac5d548 # v6.1.0
with:
python-version: ${{ env.DEFAULT_PYTHON }}

View File

@@ -17,7 +17,7 @@ on:
- "script/gen_requirements_all.py"
env:
DEFAULT_PYTHON: "3.14.2"
DEFAULT_PYTHON: "3.13"
concurrency:
group: ${{ github.workflow }}-${{ github.ref_name}}
@@ -31,11 +31,11 @@ jobs:
steps:
- &checkout
name: Checkout the repository
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1
- name: Set up Python ${{ env.DEFAULT_PYTHON }}
id: python
uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
uses: actions/setup-python@83679a892e2d95755f2dac6acb0bfd1e9ac5d548 # v6.1.0
with:
python-version: ${{ env.DEFAULT_PYTHON }}
check-latest: true

View File

@@ -1,6 +1,6 @@
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.14.13
rev: v0.13.0
hooks:
- id: ruff-check
args:
@@ -39,14 +39,14 @@ repos:
- id: prettier
additional_dependencies:
- prettier@3.6.2
- prettier-plugin-sort-json@4.2.0
- prettier-plugin-sort-json@4.1.1
- repo: https://github.com/cdce8p/python-typing-update
rev: v0.6.0
hooks:
# Run `python-typing-update` hook manually from time to time
# to update python typing syntax.
# Will require manual work, before submitting changes!
# prek run --hook-stage manual python-typing-update --all-files
# pre-commit run --hook-stage manual python-typing-update --all-files
- id: python-typing-update
stages: [manual]
args:

View File

@@ -1 +1 @@
3.14
3.13

View File

@@ -53,7 +53,6 @@ homeassistant.components.air_quality.*
homeassistant.components.airgradient.*
homeassistant.components.airly.*
homeassistant.components.airnow.*
homeassistant.components.airobot.*
homeassistant.components.airos.*
homeassistant.components.airq.*
homeassistant.components.airthings.*
@@ -376,7 +375,6 @@ homeassistant.components.no_ip.*
homeassistant.components.nordpool.*
homeassistant.components.notify.*
homeassistant.components.notion.*
homeassistant.components.nrgkick.*
homeassistant.components.ntfy.*
homeassistant.components.number.*
homeassistant.components.nut.*
@@ -389,7 +387,6 @@ homeassistant.components.onkyo.*
homeassistant.components.open_meteo.*
homeassistant.components.open_router.*
homeassistant.components.openai_conversation.*
homeassistant.components.openevse.*
homeassistant.components.openexchangerates.*
homeassistant.components.opensky.*
homeassistant.components.openuv.*
@@ -410,7 +407,6 @@ homeassistant.components.person.*
homeassistant.components.pi_hole.*
homeassistant.components.ping.*
homeassistant.components.plugwise.*
homeassistant.components.pooldose.*
homeassistant.components.portainer.*
homeassistant.components.powerfox.*
homeassistant.components.powerwall.*
@@ -458,7 +454,6 @@ homeassistant.components.russound_rio.*
homeassistant.components.ruuvi_gateway.*
homeassistant.components.ruuvitag_ble.*
homeassistant.components.samsungtv.*
homeassistant.components.saunum.*
homeassistant.components.scene.*
homeassistant.components.schedule.*
homeassistant.components.schlage.*

View File

@@ -7,8 +7,8 @@
"python.testing.pytestEnabled": false,
// https://code.visualstudio.com/docs/python/linting#_general-settings
"pylint.importStrategy": "fromEnvironment",
// Pyright type checking is not compatible with mypy which Home Assistant uses for type checking
"python.analysis.typeCheckingMode": "off",
// Pyright is too pedantic for Home Assistant
"python.analysis.typeCheckingMode": "basic",
"[python]": {
"editor.defaultFormatter": "charliermarsh.ruff",
},

8
.vscode/tasks.json vendored
View File

@@ -45,7 +45,7 @@
{
"label": "Ruff",
"type": "shell",
"command": "prek run ruff-check --all-files",
"command": "pre-commit run ruff-check --all-files",
"group": {
"kind": "test",
"isDefault": true
@@ -57,9 +57,9 @@
"problemMatcher": []
},
{
"label": "Prek",
"label": "Pre-commit",
"type": "shell",
"command": "prek run --show-diff-on-failure",
"command": "pre-commit run --show-diff-on-failure",
"group": {
"kind": "test",
"isDefault": true
@@ -120,7 +120,7 @@
{
"label": "Generate Requirements",
"type": "shell",
"command": "${command:python.interpreterPath} -m script.gen_requirements_all",
"command": "./script/gen_requirements_all.py",
"group": {
"kind": "build",
"isDefault": true

328
AGENTS.md
View File

@@ -1,328 +0,0 @@
# GitHub Copilot & Claude Code Instructions
This repository contains the core of Home Assistant, a Python 3 based home automation application.
## Code Review Guidelines
**When reviewing code, do NOT comment on:**
- **Missing imports** - We use static analysis tooling to catch that
- **Code formatting** - We have ruff as a formatting tool that will catch those if needed (unless specifically instructed otherwise in these instructions)
**Git commit practices during review:**
- **Do NOT amend, squash, or rebase commits after review has started** - Reviewers need to see what changed since their last review
## Python Requirements
- **Compatibility**: Python 3.13+
- **Language Features**: Use the newest features when possible:
- Pattern matching
- Type hints
- f-strings (preferred over `%` or `.format()`)
- Dataclasses
- Walrus operator
### Strict Typing (Platinum)
- **Comprehensive Type Hints**: Add type hints to all functions, methods, and variables
- **Custom Config Entry Types**: When using runtime_data:
```python
type MyIntegrationConfigEntry = ConfigEntry[MyClient]
```
- **Library Requirements**: Include `py.typed` file for PEP-561 compliance
## Code Quality Standards
- **Formatting**: Ruff
- **Linting**: PyLint and Ruff
- **Type Checking**: MyPy
- **Lint/Type/Format Fixes**: Always prefer addressing the underlying issue (e.g., import the typed source, update shared stubs, align with Ruff expectations, or correct formatting at the source) before disabling a rule, adding `# type: ignore`, or skipping a formatter. Treat suppressions and `noqa` comments as a last resort once no compliant fix exists
- **Testing**: pytest with plain functions and fixtures
- **Language**: American English for all code, comments, and documentation (use sentence case, including titles)
### Writing Style Guidelines
- **Tone**: Friendly and informative
- **Perspective**: Use second-person ("you" and "your") for user-facing messages
- **Inclusivity**: Use objective, non-discriminatory language
- **Clarity**: Write for non-native English speakers
- **Formatting in Messages**:
- Use backticks for: file paths, filenames, variable names, field entries
- Use sentence case for titles and messages (capitalize only the first word and proper nouns)
- Avoid abbreviations when possible
### Documentation Standards
- **File Headers**: Short and concise
```python
"""Integration for Peblar EV chargers."""
```
- **Method/Function Docstrings**: Required for all
```python
async def async_setup_entry(hass: HomeAssistant, entry: PeblarConfigEntry) -> bool:
"""Set up Peblar from a config entry."""
```
- **Comment Style**:
- Use clear, descriptive comments
- Explain the "why" not just the "what"
- Keep code block lines under 80 characters when possible
- Use progressive disclosure (simple explanation first, complex details later)
## Async Programming
- All external I/O operations must be async
- **Best Practices**:
- Avoid sleeping in loops
- Avoid awaiting in loops - use `gather` instead
- No blocking calls
- Group executor jobs when possible - switching between event loop and executor is expensive
### Blocking Operations
- **Use Executor**: For blocking I/O operations
```python
result = await hass.async_add_executor_job(blocking_function, args)
```
- **Never Block Event Loop**: Avoid file operations, `time.sleep()`, blocking HTTP calls
- **Replace with Async**: Use `asyncio.sleep()` instead of `time.sleep()`
### Thread Safety
- **@callback Decorator**: For event loop safe functions
```python
@callback
def async_update_callback(self, event):
"""Safe to run in event loop."""
self.async_write_ha_state()
```
- **Sync APIs from Threads**: Use sync versions when calling from non-event loop threads
- **Registry Changes**: Must be done in event loop thread
### Error Handling
- **Exception Types**: Choose most specific exception available
- `ServiceValidationError`: User input errors (preferred over `ValueError`)
- `HomeAssistantError`: Device communication failures
- `ConfigEntryNotReady`: Temporary setup issues (device offline)
- `ConfigEntryAuthFailed`: Authentication problems
- `ConfigEntryError`: Permanent setup issues
- **Try/Catch Best Practices**:
- Only wrap code that can throw exceptions
- Keep try blocks minimal - process data after the try/catch
- **Avoid bare exceptions** except in specific cases:
- ❌ Generally not allowed: `except:` or `except Exception:`
- ✅ Allowed in config flows to ensure robustness
- ✅ Allowed in functions/methods that run in background tasks
- Bad pattern:
```python
try:
data = await device.get_data() # Can throw
# ❌ Don't process data inside try block
processed = data.get("value", 0) * 100
self._attr_native_value = processed
except DeviceError:
_LOGGER.error("Failed to get data")
```
- Good pattern:
```python
try:
data = await device.get_data() # Can throw
except DeviceError:
_LOGGER.error("Failed to get data")
return
# ✅ Process data outside try block
processed = data.get("value", 0) * 100
self._attr_native_value = processed
```
- **Bare Exception Usage**:
```python
# ❌ Not allowed in regular code
try:
data = await device.get_data()
except Exception: # Too broad
_LOGGER.error("Failed")
# ✅ Allowed in config flow for robustness
async def async_step_user(self, user_input=None):
try:
await self._test_connection(user_input)
except Exception: # Allowed here
errors["base"] = "unknown"
# ✅ Allowed in background tasks
async def _background_refresh():
try:
await coordinator.async_refresh()
except Exception: # Allowed in task
_LOGGER.exception("Unexpected error in background task")
```
- **Setup Failure Patterns**:
```python
try:
await device.async_setup()
except (asyncio.TimeoutError, TimeoutException) as ex:
raise ConfigEntryNotReady(f"Timeout connecting to {device.host}") from ex
except AuthFailed as ex:
raise ConfigEntryAuthFailed(f"Credentials expired for {device.name}") from ex
```
### Logging
- **Format Guidelines**:
- No periods at end of messages
- No integration names/domains (added automatically)
- No sensitive data (keys, tokens, passwords)
- Use debug level for non-user-facing messages
- **Use Lazy Logging**:
```python
_LOGGER.debug("This is a log message with %s", variable)
```
### Unavailability Logging
- **Log Once**: When device/service becomes unavailable (info level)
- **Log Recovery**: When device/service comes back online
- **Implementation Pattern**:
```python
_unavailable_logged: bool = False
if not self._unavailable_logged:
_LOGGER.info("The sensor is unavailable: %s", ex)
self._unavailable_logged = True
# On recovery:
if self._unavailable_logged:
_LOGGER.info("The sensor is back online")
self._unavailable_logged = False
```
## Development Commands
### Environment
- **Local development (non-container)**: Activate the project venv before running commands: `source .venv/bin/activate`
- **Dev container**: No activation needed, the environment is pre-configured
### Code Quality & Linting
- **Run all linters on all files**: `prek run --all-files`
- **Run linters on staged files only**: `prek run`
- **PyLint on everything** (slow): `pylint homeassistant`
- **PyLint on specific folder**: `pylint homeassistant/components/my_integration`
- **MyPy type checking (whole project)**: `mypy homeassistant/`
- **MyPy on specific integration**: `mypy homeassistant/components/my_integration`
### Testing
- **Quick test of changed files**: `pytest --timeout=10 --picked`
- **Update test snapshots**: Add `--snapshot-update` to pytest command
- ⚠️ Omit test results after using `--snapshot-update`
- Always run tests again without the flag to verify snapshots
- **Full test suite** (AVOID - very slow): `pytest ./tests`
### Dependencies & Requirements
- **Update generated files after dependency changes**: `python -m script.gen_requirements_all`
- **Install all Python requirements**:
```bash
uv pip install -r requirements_all.txt -r requirements.txt -r requirements_test.txt
```
- **Install test requirements only**:
```bash
uv pip install -r requirements_test_all.txt -r requirements.txt
```
### Translations
- **Update translations after strings.json changes**:
```bash
python -m script.translations develop --all
```
### Project Validation
- **Run hassfest** (checks project structure and updates generated files):
```bash
python -m script.hassfest
```
## Common Anti-Patterns & Best Practices
### ❌ **Avoid These Patterns**
```python
# Blocking operations in event loop
data = requests.get(url) # ❌ Blocks event loop
time.sleep(5) # ❌ Blocks event loop
# Reusing BleakClient instances
self.client = BleakClient(address)
await self.client.connect()
# Later...
await self.client.connect() # ❌ Don't reuse
# Hardcoded strings in code
self._attr_name = "Temperature Sensor" # ❌ Not translatable
# Missing error handling
data = await self.api.get_data() # ❌ No exception handling
# Storing sensitive data in diagnostics
return {"api_key": entry.data[CONF_API_KEY]} # ❌ Exposes secrets
# Accessing hass.data directly in tests
coordinator = hass.data[DOMAIN][entry.entry_id] # ❌ Don't access hass.data
# User-configurable polling intervals
# In config flow
vol.Optional("scan_interval", default=60): cv.positive_int # ❌ Not allowed
# In coordinator
update_interval = timedelta(minutes=entry.data.get("scan_interval", 1)) # ❌ Not allowed
# User-configurable config entry names (non-helper integrations)
vol.Optional("name", default="My Device"): cv.string # ❌ Not allowed in regular integrations
# Too much code in try block
try:
response = await client.get_data() # Can throw
# ❌ Data processing should be outside try block
temperature = response["temperature"] / 10
humidity = response["humidity"]
self._attr_native_value = temperature
except ClientError:
_LOGGER.error("Failed to fetch data")
# Bare exceptions in regular code
try:
value = await sensor.read_value()
except Exception: # ❌ Too broad - catch specific exceptions
_LOGGER.error("Failed to read sensor")
```
### ✅ **Use These Patterns Instead**
```python
# Async operations with executor
data = await hass.async_add_executor_job(requests.get, url)
await asyncio.sleep(5) # ✅ Non-blocking
# Fresh BleakClient instances
client = BleakClient(address) # ✅ New instance each time
await client.connect()
# Translatable entity names
_attr_translation_key = "temperature_sensor" # ✅ Translatable
# Proper error handling
try:
data = await self.api.get_data()
except ApiException as err:
raise UpdateFailed(f"API error: {err}") from err
# Redacted diagnostics data
return async_redact_data(data, {"api_key", "password"}) # ✅ Safe
# Test through proper integration setup and fixtures
@pytest.fixture
async def init_integration(hass, mock_config_entry, mock_api):
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id) # ✅ Proper setup
# Integration-determined polling intervals (not user-configurable)
SCAN_INTERVAL = timedelta(minutes=5) # ✅ Common pattern: constant in const.py
class MyCoordinator(DataUpdateCoordinator[MyData]):
def __init__(self, hass: HomeAssistant, client: MyClient, config_entry: ConfigEntry) -> None:
# ✅ Integration determines interval based on device capabilities, connection type, etc.
interval = timedelta(minutes=1) if client.is_local else SCAN_INTERVAL
super().__init__(
hass,
logger=LOGGER,
name=DOMAIN,
update_interval=interval,
config_entry=config_entry, # ✅ Pass config_entry - it's accepted and recommended
)
```

1
AGENTS.md Symbolic link
View File

@@ -0,0 +1 @@
.github/copilot-instructions.md

View File

@@ -1 +1 @@
AGENTS.md
.github/copilot-instructions.md

24
CODEOWNERS generated
View File

@@ -288,8 +288,6 @@ build.json @home-assistant/supervisor
/tests/components/cloud/ @home-assistant/cloud
/homeassistant/components/cloudflare/ @ludeeus @ctalkington
/tests/components/cloudflare/ @ludeeus @ctalkington
/homeassistant/components/cloudflare_r2/ @corrreia
/tests/components/cloudflare_r2/ @corrreia
/homeassistant/components/co2signal/ @jpbede @VIKTORVAV99
/tests/components/co2signal/ @jpbede @VIKTORVAV99
/homeassistant/components/coinbase/ @tombrien
@@ -643,8 +641,6 @@ build.json @home-assistant/supervisor
/tests/components/gpsd/ @fabaff @jrieger
/homeassistant/components/gree/ @cmroche
/tests/components/gree/ @cmroche
/homeassistant/components/green_planet_energy/ @petschni
/tests/components/green_planet_energy/ @petschni
/homeassistant/components/greeneye_monitor/ @jkeljo
/tests/components/greeneye_monitor/ @jkeljo
/homeassistant/components/group/ @home-assistant/core
@@ -921,8 +917,6 @@ build.json @home-assistant/supervisor
/tests/components/libre_hardware_monitor/ @Sab44
/homeassistant/components/lidarr/ @tkdrob
/tests/components/lidarr/ @tkdrob
/homeassistant/components/liebherr/ @mettolen
/tests/components/liebherr/ @mettolen
/homeassistant/components/lifx/ @Djelibeybi
/tests/components/lifx/ @Djelibeybi
/homeassistant/components/light/ @home-assistant/core
@@ -1023,8 +1017,8 @@ build.json @home-assistant/supervisor
/tests/components/mill/ @danielhiversen
/homeassistant/components/min_max/ @gjohansson-ST
/tests/components/min_max/ @gjohansson-ST
/homeassistant/components/minecraft_server/ @elmurato @zachdeibert
/tests/components/minecraft_server/ @elmurato @zachdeibert
/homeassistant/components/minecraft_server/ @elmurato
/tests/components/minecraft_server/ @elmurato
/homeassistant/components/minio/ @tkislan
/tests/components/minio/ @tkislan
/homeassistant/components/moat/ @bdraco
@@ -1074,8 +1068,6 @@ build.json @home-assistant/supervisor
/tests/components/myuplink/ @pajzo @astrandb
/homeassistant/components/nam/ @bieniu
/tests/components/nam/ @bieniu
/homeassistant/components/namecheapdns/ @tr4nt0r
/tests/components/namecheapdns/ @tr4nt0r
/homeassistant/components/nanoleaf/ @milanmeu @joostlek
/tests/components/nanoleaf/ @milanmeu @joostlek
/homeassistant/components/nasweb/ @nasWebio
@@ -1130,8 +1122,6 @@ build.json @home-assistant/supervisor
/tests/components/notify_events/ @matrozov @papajojo
/homeassistant/components/notion/ @bachya
/tests/components/notion/ @bachya
/homeassistant/components/nrgkick/ @andijakl
/tests/components/nrgkick/ @andijakl
/homeassistant/components/nsw_fuel_station/ @nickw444
/tests/components/nsw_fuel_station/ @nickw444
/homeassistant/components/nsw_rural_fire_service_feed/ @exxamalte
@@ -1267,8 +1257,6 @@ build.json @home-assistant/supervisor
/tests/components/powerfox/ @klaasnicolaas
/homeassistant/components/powerwall/ @bdraco @jrester @daniel-simpson
/tests/components/powerwall/ @bdraco @jrester @daniel-simpson
/homeassistant/components/prana/ @prana-dev-official
/tests/components/prana/ @prana-dev-official
/homeassistant/components/private_ble_device/ @Jc2k
/tests/components/private_ble_device/ @Jc2k
/homeassistant/components/probe_plus/ @pantherale0
@@ -1283,8 +1271,7 @@ build.json @home-assistant/supervisor
/tests/components/prosegur/ @dgomes
/homeassistant/components/proximity/ @mib1185
/tests/components/proximity/ @mib1185
/homeassistant/components/proxmoxve/ @jhollowe @Corbeno @erwindouna
/tests/components/proxmoxve/ @jhollowe @Corbeno @erwindouna
/homeassistant/components/proxmoxve/ @jhollowe @Corbeno
/homeassistant/components/ps4/ @ktnrg45
/tests/components/ps4/ @ktnrg45
/homeassistant/components/pterodactyl/ @elmurato
@@ -1732,8 +1719,6 @@ build.json @home-assistant/supervisor
/tests/components/twinkly/ @dr1rrb @Robbie1221 @Olen
/homeassistant/components/twitch/ @joostlek
/tests/components/twitch/ @joostlek
/homeassistant/components/uhoo/ @getuhoo @joshsmonta
/tests/components/uhoo/ @getuhoo @joshsmonta
/homeassistant/components/ukraine_alarm/ @PaulAnnekov
/tests/components/ukraine_alarm/ @PaulAnnekov
/homeassistant/components/unifi/ @Kane610
@@ -1821,7 +1806,6 @@ build.json @home-assistant/supervisor
/homeassistant/components/water_heater/ @home-assistant/core
/tests/components/water_heater/ @home-assistant/core
/homeassistant/components/waterfurnace/ @sdague @masterkoppa
/tests/components/waterfurnace/ @sdague @masterkoppa
/homeassistant/components/watergate/ @adam-the-hero
/tests/components/watergate/ @adam-the-hero
/homeassistant/components/watson_tts/ @rutkai
@@ -1880,8 +1864,6 @@ build.json @home-assistant/supervisor
/tests/components/worldclock/ @fabaff
/homeassistant/components/ws66i/ @ssaenger
/tests/components/ws66i/ @ssaenger
/homeassistant/components/wsdot/ @ucodery
/tests/components/wsdot/ @ucodery
/homeassistant/components/wyoming/ @synesthesiam
/tests/components/wyoming/ @synesthesiam
/homeassistant/components/xbox/ @hunterjm @tr4nt0r

4
Dockerfile generated
View File

@@ -24,13 +24,13 @@ ENV \
COPY rootfs /
# Add go2rtc binary
COPY --from=ghcr.io/alexxit/go2rtc@sha256:675c318b23c06fd862a61d262240c9a63436b4050d177ffc68a32710d9e05bae /usr/local/bin/go2rtc /bin/go2rtc
COPY --from=ghcr.io/alexxit/go2rtc@sha256:f394f6329f5389a4c9a7fc54b09fdec9621bbb78bf7a672b973440bbdfb02241 /usr/local/bin/go2rtc /bin/go2rtc
RUN \
# Verify go2rtc can be executed
go2rtc --version \
# Install uv
&& pip3 install uv==0.9.26
&& pip3 install uv==0.9.17
WORKDIR /usr/src

View File

@@ -52,9 +52,6 @@ RUN --mount=type=bind,source=requirements.txt,target=requirements.txt \
--mount=type=bind,source=requirements_test_pre_commit.txt,target=requirements_test_pre_commit.txt \
uv pip install -r requirements.txt -r requirements_test.txt
# Claude Code native install
RUN curl -fsSL https://claude.ai/install.sh | bash
WORKDIR /workspaces
# Set the default shell to bash instead of sh

View File

@@ -67,6 +67,8 @@ from .const import (
BASE_PLATFORMS,
FORMAT_DATETIME,
KEY_DATA_LOGGING as DATA_LOGGING,
REQUIRED_NEXT_PYTHON_HA_RELEASE,
REQUIRED_NEXT_PYTHON_VER,
SIGNAL_BOOTSTRAP_INTEGRATIONS,
)
from .core_config import async_process_ha_core_config
@@ -514,6 +516,38 @@ async def async_from_config_dict(
stop = monotonic()
_LOGGER.info("Home Assistant initialized in %.2fs", stop - start)
if (
REQUIRED_NEXT_PYTHON_HA_RELEASE
and sys.version_info[:3] < REQUIRED_NEXT_PYTHON_VER
):
current_python_version = ".".join(str(x) for x in sys.version_info[:3])
required_python_version = ".".join(str(x) for x in REQUIRED_NEXT_PYTHON_VER[:2])
_LOGGER.warning(
(
"Support for the running Python version %s is deprecated and "
"will be removed in Home Assistant %s; "
"Please upgrade Python to %s"
),
current_python_version,
REQUIRED_NEXT_PYTHON_HA_RELEASE,
required_python_version,
)
issue_registry.async_create_issue(
hass,
core.DOMAIN,
f"python_version_{required_python_version}",
is_fixable=False,
severity=issue_registry.IssueSeverity.WARNING,
breaks_in_ha_version=REQUIRED_NEXT_PYTHON_HA_RELEASE,
translation_key="python_version",
translation_placeholders={
"current_python_version": current_python_version,
"required_python_version": required_python_version,
"breaks_in_ha_version": REQUIRED_NEXT_PYTHON_HA_RELEASE,
},
)
return hass

View File

@@ -1,5 +0,0 @@
{
"domain": "cloudflare",
"name": "Cloudflare",
"integrations": ["cloudflare", "cloudflare_r2"]
}

View File

@@ -1,6 +1,5 @@
{
"domain": "leviton",
"name": "Leviton",
"integrations": ["decora_wifi"],
"iot_standards": ["zwave"]
}

View File

@@ -30,7 +30,7 @@ from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.typing import ConfigType
from .const import CONF_POLLING, DOMAIN, DOMAIN_DATA, LOGGER
from .const import CONF_POLLING, DOMAIN, LOGGER
from .services import async_setup_services
ATTR_DEVICE_NAME = "device_name"
@@ -99,7 +99,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
except (AbodeException, ConnectTimeout, HTTPError) as ex:
raise ConfigEntryNotReady(f"Unable to connect to Abode: {ex}") from ex
hass.data[DOMAIN_DATA] = AbodeSystem(abode, polling)
hass.data[DOMAIN] = AbodeSystem(abode, polling)
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
@@ -113,12 +113,11 @@ async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
await hass.async_add_executor_job(hass.data[DOMAIN_DATA].abode.events.stop)
await hass.async_add_executor_job(hass.data[DOMAIN_DATA].abode.logout)
await hass.async_add_executor_job(hass.data[DOMAIN].abode.events.stop)
await hass.async_add_executor_job(hass.data[DOMAIN].abode.logout)
if logout_listener := hass.data[DOMAIN_DATA].logout_listener:
logout_listener()
hass.data.pop(DOMAIN_DATA)
hass.data[DOMAIN].logout_listener()
hass.data.pop(DOMAIN)
return unload_ok
@@ -128,16 +127,16 @@ async def setup_hass_events(hass: HomeAssistant) -> None:
def logout(event: Event) -> None:
"""Logout of Abode."""
if not hass.data[DOMAIN_DATA].polling:
hass.data[DOMAIN_DATA].abode.events.stop()
if not hass.data[DOMAIN].polling:
hass.data[DOMAIN].abode.events.stop()
hass.data[DOMAIN_DATA].abode.logout()
hass.data[DOMAIN].abode.logout()
LOGGER.info("Logged out of Abode")
if not hass.data[DOMAIN_DATA].polling:
await hass.async_add_executor_job(hass.data[DOMAIN_DATA].abode.events.start)
if not hass.data[DOMAIN].polling:
await hass.async_add_executor_job(hass.data[DOMAIN].abode.events.start)
hass.data[DOMAIN_DATA].logout_listener = hass.bus.async_listen_once(
hass.data[DOMAIN].logout_listener = hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP, logout
)
@@ -179,6 +178,6 @@ def setup_abode_events(hass: HomeAssistant) -> None:
]
for event in events:
hass.data[DOMAIN_DATA].abode.events.add_event_callback(
hass.data[DOMAIN].abode.events.add_event_callback(
event, partial(event_callback, event)
)

View File

@@ -13,7 +13,8 @@ from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .const import DOMAIN_DATA
from . import AbodeSystem
from .const import DOMAIN
from .entity import AbodeDevice
@@ -23,7 +24,7 @@ async def async_setup_entry(
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up Abode alarm control panel device."""
data = hass.data[DOMAIN_DATA]
data: AbodeSystem = hass.data[DOMAIN]
async_add_entities(
[AbodeAlarm(data, await hass.async_add_executor_job(data.abode.get_alarm))]
)

View File

@@ -15,7 +15,8 @@ from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.util.enum import try_parse_enum
from .const import DOMAIN_DATA
from . import AbodeSystem
from .const import DOMAIN
from .entity import AbodeDevice
@@ -25,7 +26,7 @@ async def async_setup_entry(
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up Abode binary sensor devices."""
data = hass.data[DOMAIN_DATA]
data: AbodeSystem = hass.data[DOMAIN]
device_types = [
"connectivity",

View File

@@ -19,7 +19,7 @@ from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.util import Throttle
from . import AbodeSystem
from .const import DOMAIN_DATA, LOGGER
from .const import DOMAIN, LOGGER
from .entity import AbodeDevice
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=90)
@@ -31,7 +31,7 @@ async def async_setup_entry(
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up Abode camera devices."""
data = hass.data[DOMAIN_DATA]
data: AbodeSystem = hass.data[DOMAIN]
async_add_entities(
AbodeCamera(data, device, timeline.CAPTURE_IMAGE)

View File

@@ -1,19 +1,10 @@
"""Constants for the Abode Security System component."""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING
from homeassistant.util.hass_dict import HassKey
if TYPE_CHECKING:
from . import AbodeSystem
LOGGER = logging.getLogger(__package__)
DOMAIN = "abode"
DOMAIN_DATA: HassKey[AbodeSystem] = HassKey(DOMAIN)
ATTRIBUTION = "Data provided by goabode.com"
CONF_POLLING = "polling"

View File

@@ -9,7 +9,8 @@ from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .const import DOMAIN_DATA
from . import AbodeSystem
from .const import DOMAIN
from .entity import AbodeDevice
@@ -19,7 +20,7 @@ async def async_setup_entry(
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up Abode cover devices."""
data = hass.data[DOMAIN_DATA]
data: AbodeSystem = hass.data[DOMAIN]
async_add_entities(
AbodeCover(data, device)

View File

@@ -7,7 +7,7 @@ from homeassistant.helpers.device_registry import DeviceInfo
from homeassistant.helpers.entity import Entity
from . import AbodeSystem
from .const import ATTRIBUTION, DOMAIN, DOMAIN_DATA
from .const import ATTRIBUTION, DOMAIN
class AbodeEntity(Entity):
@@ -29,7 +29,7 @@ class AbodeEntity(Entity):
self._update_connection_status,
)
self.hass.data[DOMAIN_DATA].entity_ids.add(self.entity_id)
self.hass.data[DOMAIN].entity_ids.add(self.entity_id)
async def async_will_remove_from_hass(self) -> None:
"""Unsubscribe from Abode connection status updates."""

View File

@@ -20,7 +20,8 @@ from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .const import DOMAIN_DATA
from . import AbodeSystem
from .const import DOMAIN
from .entity import AbodeDevice
@@ -30,7 +31,7 @@ async def async_setup_entry(
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up Abode light devices."""
data = hass.data[DOMAIN_DATA]
data: AbodeSystem = hass.data[DOMAIN]
async_add_entities(
AbodeLight(data, device)
@@ -99,7 +100,7 @@ class AbodeLight(AbodeDevice, LightEntity):
return _hs
@property
def color_mode(self) -> ColorMode | None:
def color_mode(self) -> str | None:
"""Return the color mode of the light."""
if self._device.is_dimmable and self._device.is_color_capable:
if self.hs_color is not None:
@@ -110,7 +111,7 @@ class AbodeLight(AbodeDevice, LightEntity):
return ColorMode.ONOFF
@property
def supported_color_modes(self) -> set[ColorMode] | None:
def supported_color_modes(self) -> set[str] | None:
"""Flag supported color modes."""
if self._device.is_dimmable and self._device.is_color_capable:
return {ColorMode.COLOR_TEMP, ColorMode.HS}

View File

@@ -9,7 +9,8 @@ from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .const import DOMAIN_DATA
from . import AbodeSystem
from .const import DOMAIN
from .entity import AbodeDevice
@@ -19,7 +20,7 @@ async def async_setup_entry(
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up Abode lock devices."""
data = hass.data[DOMAIN_DATA]
data: AbodeSystem = hass.data[DOMAIN]
async_add_entities(
AbodeLock(data, device)

View File

@@ -19,7 +19,7 @@ from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import AbodeSystem
from .const import DOMAIN_DATA
from .const import DOMAIN
from .entity import AbodeDevice
ABODE_TEMPERATURE_UNIT_HA_UNIT = {
@@ -66,7 +66,7 @@ async def async_setup_entry(
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up Abode sensor devices."""
data = hass.data[DOMAIN_DATA]
data: AbodeSystem = hass.data[DOMAIN]
async_add_entities(
AbodeSensor(data, device, description)

View File

@@ -10,7 +10,7 @@ from homeassistant.core import HomeAssistant, ServiceCall, callback
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.dispatcher import dispatcher_send
from .const import DOMAIN, DOMAIN_DATA, LOGGER
from .const import DOMAIN, LOGGER
SERVICE_SETTINGS = "change_setting"
SERVICE_CAPTURE_IMAGE = "capture_image"
@@ -35,7 +35,7 @@ def _change_setting(call: ServiceCall) -> None:
value = call.data[ATTR_VALUE]
try:
call.hass.data[DOMAIN_DATA].abode.set_setting(setting, value)
call.hass.data[DOMAIN].abode.set_setting(setting, value)
except AbodeException as ex:
LOGGER.warning(ex)
@@ -46,7 +46,7 @@ def _capture_image(call: ServiceCall) -> None:
target_entities = [
entity_id
for entity_id in call.hass.data[DOMAIN_DATA].entity_ids
for entity_id in call.hass.data[DOMAIN].entity_ids
if entity_id in entity_ids
]
@@ -61,7 +61,7 @@ def _trigger_automation(call: ServiceCall) -> None:
target_entities = [
entity_id
for entity_id in call.hass.data[DOMAIN_DATA].entity_ids
for entity_id in call.hass.data[DOMAIN].entity_ids
if entity_id in entity_ids
]

View File

@@ -12,7 +12,8 @@ from homeassistant.core import HomeAssistant
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .const import DOMAIN_DATA
from . import AbodeSystem
from .const import DOMAIN
from .entity import AbodeAutomation, AbodeDevice
DEVICE_TYPES = ["switch", "valve"]
@@ -24,7 +25,7 @@ async def async_setup_entry(
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up Abode switch devices."""
data = hass.data[DOMAIN_DATA]
data: AbodeSystem = hass.data[DOMAIN]
entities: list[SwitchEntity] = [
AbodeSwitch(data, device)

View File

@@ -87,7 +87,7 @@ class AdaxConfigFlow(ConfigFlow, domain=DOMAIN):
data_schema=data_schema,
)
wifi_ssid = user_input[WIFI_SSID]
wifi_ssid = user_input[WIFI_SSID].replace(" ", "")
wifi_pswd = user_input[WIFI_PSWD].replace(" ", "")
configurator = adax_local.AdaxConfig(wifi_ssid, wifi_pswd)

View File

@@ -107,7 +107,7 @@ class AdGuardHomeFlowHandler(ConfigFlow, domain=DOMAIN):
async def async_step_hassio(
self, discovery_info: HassioServiceInfo
) -> ConfigFlowResult:
"""Prepare configuration for a Hass.io AdGuard Home app.
"""Prepare configuration for a Hass.io AdGuard Home add-on.
This flow is triggered by the discovery component.
"""

View File

@@ -52,7 +52,7 @@ class AdGuardHomeEntity(Entity):
def device_info(self) -> DeviceInfo:
"""Return device information about this AdGuard Home instance."""
if self._entry.source == SOURCE_HASSIO:
config_url = "homeassistant://app/a0d7b954_adguard"
config_url = "homeassistant://hassio/ingress/a0d7b954_adguard"
elif self.adguard.tls:
config_url = f"https://{self.adguard.host}:{self.adguard.port}"
else:

View File

@@ -9,8 +9,8 @@
},
"step": {
"hassio_confirm": {
"description": "Do you want to configure Home Assistant to connect to the AdGuard Home provided by the app: {addon}?",
"title": "AdGuard Home via Home Assistant app"
"description": "Do you want to configure Home Assistant to connect to the AdGuard Home provided by the add-on: {addon}?",
"title": "AdGuard Home via Home Assistant add-on"
},
"user": {
"data": {

View File

@@ -8,15 +8,12 @@ from advantage_air import ApiError, advantage_air
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_IP_ADDRESS, CONF_PORT, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.debounce import Debouncer
from homeassistant.helpers.typing import ConfigType
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import ADVANTAGE_AIR_RETRY, DOMAIN
from .const import ADVANTAGE_AIR_RETRY
from .models import AdvantageAirData
from .services import async_setup_services
type AdvantageAirDataConfigEntry = ConfigEntry[AdvantageAirData]
@@ -35,14 +32,6 @@ PLATFORMS = [
_LOGGER = logging.getLogger(__name__)
REQUEST_REFRESH_DELAY = 0.5
CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN)
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up the component."""
async_setup_services(hass)
return True
async def async_setup_entry(
hass: HomeAssistant, entry: AdvantageAirDataConfigEntry

View File

@@ -5,6 +5,8 @@ from __future__ import annotations
from decimal import Decimal
from typing import Any
import voluptuous as vol
from homeassistant.components.sensor import (
SensorDeviceClass,
SensorEntity,
@@ -12,6 +14,7 @@ from homeassistant.components.sensor import (
)
from homeassistant.const import PERCENTAGE, EntityCategory, UnitOfTemperature
from homeassistant.core import HomeAssistant
from homeassistant.helpers import config_validation as cv, entity_platform
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import AdvantageAirDataConfigEntry
@@ -21,6 +24,7 @@ from .models import AdvantageAirData
ADVANTAGE_AIR_SET_COUNTDOWN_VALUE = "minutes"
ADVANTAGE_AIR_SET_COUNTDOWN_UNIT = "min"
ADVANTAGE_AIR_SERVICE_SET_TIME_TO = "set_time_to"
PARALLEL_UPDATES = 0
@@ -49,6 +53,13 @@ async def async_setup_entry(
entities.append(AdvantageAirZoneSignal(instance, ac_key, zone_key))
async_add_entities(entities)
platform = entity_platform.async_get_current_platform()
platform.async_register_entity_service(
ADVANTAGE_AIR_SERVICE_SET_TIME_TO,
{vol.Required("minutes"): cv.positive_int},
"set_time_to",
)
class AdvantageAirTimeTo(AdvantageAirAcEntity, SensorEntity):
"""Representation of Advantage Air timer control."""

View File

@@ -1,27 +0,0 @@
"""Services for Advantage Air integration."""
from __future__ import annotations
import voluptuous as vol
from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv, service
from .const import DOMAIN
ADVANTAGE_AIR_SERVICE_SET_TIME_TO = "set_time_to"
@callback
def async_setup_services(hass: HomeAssistant) -> None:
"""Home Assistant services."""
service.async_register_platform_entity_service(
hass,
DOMAIN,
ADVANTAGE_AIR_SERVICE_SET_TIME_TO,
entity_domain=SENSOR_DOMAIN,
schema={vol.Required("minutes"): cv.positive_int},
func="set_time_to",
)

View File

@@ -7,12 +7,10 @@ from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers import config_validation as cv, device_registry as dr
from homeassistant.helpers import device_registry as dr
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.typing import ConfigType
from .const import DOMAIN, SERVER_URL
from .services import async_setup_services
ATTRIBUTION = "ispyconnect.com"
DEFAULT_BRAND = "Agent DVR by ispyconnect.com"
@@ -21,14 +19,6 @@ PLATFORMS = [Platform.ALARM_CONTROL_PANEL, Platform.CAMERA]
AgentDVRConfigEntry = ConfigEntry[Agent]
CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN)
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up the component."""
async_setup_services(hass)
return True
async def async_setup_entry(
hass: HomeAssistant, config_entry: AgentDVRConfigEntry

View File

@@ -9,7 +9,10 @@ from homeassistant.components.camera import CameraEntityFeature
from homeassistant.components.mjpeg import MjpegCamera, filter_urllib3_logging
from homeassistant.core import HomeAssistant
from homeassistant.helpers.device_registry import DeviceInfo
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.entity_platform import (
AddConfigEntryEntitiesCallback,
async_get_current_platform,
)
from . import AgentDVRConfigEntry
from .const import ATTRIBUTION, CAMERA_SCAN_INTERVAL_SECS, DOMAIN
@@ -18,6 +21,20 @@ SCAN_INTERVAL = timedelta(seconds=CAMERA_SCAN_INTERVAL_SECS)
_LOGGER = logging.getLogger(__name__)
_DEV_EN_ALT = "enable_alerts"
_DEV_DS_ALT = "disable_alerts"
_DEV_EN_REC = "start_recording"
_DEV_DS_REC = "stop_recording"
_DEV_SNAP = "snapshot"
CAMERA_SERVICES = {
_DEV_EN_ALT: "async_enable_alerts",
_DEV_DS_ALT: "async_disable_alerts",
_DEV_EN_REC: "async_start_recording",
_DEV_DS_REC: "async_stop_recording",
_DEV_SNAP: "async_snapshot",
}
async def async_setup_entry(
hass: HomeAssistant,
@@ -40,6 +57,10 @@ async def async_setup_entry(
async_add_entities(cameras)
platform = async_get_current_platform()
for service, method in CAMERA_SERVICES.items():
platform.async_register_entity_service(service, None, method)
class AgentCamera(MjpegCamera):
"""Representation of an Agent Device Stream."""

View File

@@ -1,38 +0,0 @@
"""Services for Agent DVR."""
from __future__ import annotations
from homeassistant.components.camera import DOMAIN as CAMERA_DOMAIN
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import service
from .const import DOMAIN
_DEV_EN_ALT = "enable_alerts"
_DEV_DS_ALT = "disable_alerts"
_DEV_EN_REC = "start_recording"
_DEV_DS_REC = "stop_recording"
_DEV_SNAP = "snapshot"
CAMERA_SERVICES = {
_DEV_EN_ALT: "async_enable_alerts",
_DEV_DS_ALT: "async_disable_alerts",
_DEV_EN_REC: "async_start_recording",
_DEV_DS_REC: "async_stop_recording",
_DEV_SNAP: "async_snapshot",
}
@callback
def async_setup_services(hass: HomeAssistant) -> None:
"""Home Assistant services."""
for service_name, method in CAMERA_SERVICES.items():
service.async_register_platform_entity_service(
hass,
DOMAIN,
service_name,
entity_domain=CAMERA_DOMAIN,
schema=None,
func=method,
)

View File

@@ -12,7 +12,6 @@ PLATFORMS: list[Platform] = [
Platform.CLIMATE,
Platform.NUMBER,
Platform.SENSOR,
Platform.SWITCH,
]

View File

@@ -29,7 +29,6 @@ from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import AirobotConfigEntry
from .const import DOMAIN
from .coordinator import AirobotDataUpdateCoordinator
from .entity import AirobotEntity
PARALLEL_UPDATES = 1
@@ -64,11 +63,6 @@ class AirobotClimate(AirobotEntity, ClimateEntity):
_attr_min_temp = SETPOINT_TEMP_MIN
_attr_max_temp = SETPOINT_TEMP_MAX
def __init__(self, coordinator: AirobotDataUpdateCoordinator) -> None:
"""Initialize the climate entity."""
super().__init__(coordinator)
self._attr_unique_id = coordinator.data.status.device_id
@property
def _status(self) -> ThermostatStatus:
"""Get status from coordinator data."""

View File

@@ -2,7 +2,6 @@
from __future__ import annotations
import asyncio
from collections.abc import Mapping
from dataclasses import dataclass
import logging
@@ -61,17 +60,11 @@ async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> DeviceInf
try:
# Try to fetch data to validate connection and authentication
status, settings = await asyncio.gather(
client.get_statuses(), client.get_settings()
)
status = await client.get_statuses()
settings = await client.get_settings()
except AirobotAuthError as err:
raise InvalidAuth from err
except (
AirobotConnectionError,
AirobotTimeoutError,
AirobotError,
TimeoutError,
) as err:
except (AirobotConnectionError, AirobotTimeoutError, AirobotError) as err:
raise CannotConnect from err
# Use device name or device ID as title

View File

@@ -2,7 +2,6 @@
from __future__ import annotations
import asyncio
from datetime import timedelta
import logging
@@ -53,10 +52,8 @@ class AirobotDataUpdateCoordinator(DataUpdateCoordinator[AirobotData]):
async def _async_update_data(self) -> AirobotData:
"""Fetch data from API endpoint."""
try:
status, settings = await asyncio.gather(
self.client.get_statuses(),
self.client.get_settings(),
)
status = await self.client.get_statuses()
settings = await self.client.get_settings()
except AirobotAuthError as err:
raise ConfigEntryAuthFailed(
translation_domain=DOMAIN,

View File

@@ -24,6 +24,8 @@ class AirobotEntity(CoordinatorEntity[AirobotDataUpdateCoordinator]):
status = coordinator.data.status
settings = coordinator.data.settings
self._attr_unique_id = status.device_id
connections = set()
if (mac := coordinator.config_entry.data.get(CONF_MAC)) is not None:
connections.add((CONNECTION_NETWORK_MAC, mac))
@@ -35,6 +37,6 @@ class AirobotEntity(CoordinatorEntity[AirobotDataUpdateCoordinator]):
manufacturer="Airobot",
model="Thermostat",
model_id="TE1",
sw_version=status.fw_version_string,
hw_version=status.hw_version_string,
sw_version=str(status.fw_version),
hw_version=str(status.hw_version),
)

View File

@@ -9,14 +9,6 @@
"hysteresis_band": {
"default": "mdi:delta"
}
},
"switch": {
"actuator_exercise_disabled": {
"default": "mdi:valve"
},
"child_lock": {
"default": "mdi:lock"
}
}
}
}

View File

@@ -12,6 +12,6 @@
"integration_type": "device",
"iot_class": "local_polling",
"loggers": ["pyairobotrest"],
"quality_scale": "platinum",
"requirements": ["pyairobotrest==0.3.0"]
"quality_scale": "gold",
"requirements": ["pyairobotrest==0.2.0"]
}

View File

@@ -69,4 +69,4 @@ rules:
# Platinum
async-dependency: done
inject-websession: done
strict-typing: done
strict-typing: todo

View File

@@ -28,7 +28,6 @@ from homeassistant.util.dt import utcnow
from homeassistant.util.variance import ignore_variance
from . import AirobotConfigEntry
from .coordinator import AirobotDataUpdateCoordinator
from .entity import AirobotEntity
PARALLEL_UPDATES = 0
@@ -54,7 +53,6 @@ SENSOR_TYPES: tuple[AirobotSensorEntityDescription, ...] = (
device_class=SensorDeviceClass.TEMPERATURE,
native_unit_of_measurement=UnitOfTemperature.CELSIUS,
state_class=SensorStateClass.MEASUREMENT,
suggested_display_precision=1,
value_fn=lambda status: status.temp_air,
),
AirobotSensorEntityDescription(
@@ -138,7 +136,7 @@ class AirobotSensor(AirobotEntity, SensorEntity):
def __init__(
self,
coordinator: AirobotDataUpdateCoordinator,
coordinator,
description: AirobotSensorEntityDescription,
) -> None:
"""Initialize the sensor."""

View File

@@ -85,14 +85,6 @@
"heating_uptime": {
"name": "Heating uptime"
}
},
"switch": {
"actuator_exercise_disabled": {
"name": "Actuator exercise disabled"
},
"child_lock": {
"name": "Child lock"
}
}
},
"exceptions": {
@@ -113,12 +105,6 @@
},
"set_value_failed": {
"message": "Failed to set value: {error}"
},
"switch_turn_off_failed": {
"message": "Failed to turn off {switch}."
},
"switch_turn_on_failed": {
"message": "Failed to turn on {switch}."
}
}
}

View File

@@ -1,118 +0,0 @@
"""Switch platform for Airobot thermostat."""
from __future__ import annotations
from collections.abc import Callable, Coroutine
from dataclasses import dataclass
from typing import Any
from pyairobotrest.exceptions import AirobotError
from homeassistant.components.switch import SwitchEntity, SwitchEntityDescription
from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import AirobotConfigEntry
from .const import DOMAIN
from .coordinator import AirobotDataUpdateCoordinator
from .entity import AirobotEntity
PARALLEL_UPDATES = 0
@dataclass(frozen=True, kw_only=True)
class AirobotSwitchEntityDescription(SwitchEntityDescription):
"""Describes Airobot switch entity."""
is_on_fn: Callable[[AirobotDataUpdateCoordinator], bool]
turn_on_fn: Callable[[AirobotDataUpdateCoordinator], Coroutine[Any, Any, None]]
turn_off_fn: Callable[[AirobotDataUpdateCoordinator], Coroutine[Any, Any, None]]
SWITCH_TYPES: tuple[AirobotSwitchEntityDescription, ...] = (
AirobotSwitchEntityDescription(
key="child_lock",
translation_key="child_lock",
entity_category=EntityCategory.CONFIG,
is_on_fn=lambda coordinator: (
coordinator.data.settings.setting_flags.childlock_enabled
),
turn_on_fn=lambda coordinator: coordinator.client.set_child_lock(True),
turn_off_fn=lambda coordinator: coordinator.client.set_child_lock(False),
),
AirobotSwitchEntityDescription(
key="actuator_exercise_disabled",
translation_key="actuator_exercise_disabled",
entity_category=EntityCategory.CONFIG,
entity_registry_enabled_default=False,
is_on_fn=lambda coordinator: (
coordinator.data.settings.setting_flags.actuator_exercise_disabled
),
turn_on_fn=lambda coordinator: coordinator.client.toggle_actuator_exercise(
True
),
turn_off_fn=lambda coordinator: coordinator.client.toggle_actuator_exercise(
False
),
),
)
async def async_setup_entry(
hass: HomeAssistant,
entry: AirobotConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up Airobot switch entities."""
coordinator = entry.runtime_data
async_add_entities(
AirobotSwitch(coordinator, description) for description in SWITCH_TYPES
)
class AirobotSwitch(AirobotEntity, SwitchEntity):
"""Representation of an Airobot switch."""
entity_description: AirobotSwitchEntityDescription
def __init__(
self,
coordinator: AirobotDataUpdateCoordinator,
description: AirobotSwitchEntityDescription,
) -> None:
"""Initialize the switch."""
super().__init__(coordinator)
self.entity_description = description
self._attr_unique_id = f"{coordinator.data.status.device_id}_{description.key}"
@property
def is_on(self) -> bool:
"""Return true if the switch is on."""
return self.entity_description.is_on_fn(self.coordinator)
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn the switch on."""
try:
await self.entity_description.turn_on_fn(self.coordinator)
except AirobotError as err:
raise HomeAssistantError(
translation_domain=DOMAIN,
translation_key="switch_turn_on_failed",
translation_placeholders={"switch": self.entity_description.key},
) from err
await self.coordinator.async_request_refresh()
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn the switch off."""
try:
await self.entity_description.turn_off_fn(self.coordinator)
except AirobotError as err:
raise HomeAssistantError(
translation_domain=DOMAIN,
translation_key="switch_turn_off_failed",
translation_placeholders={"switch": self.entity_description.key},
) from err
await self.coordinator.async_request_refresh()

View File

@@ -7,5 +7,5 @@
"integration_type": "device",
"iot_class": "local_polling",
"quality_scale": "silver",
"requirements": ["airos==0.6.3"]
"requirements": ["airos==0.6.1"]
}

View File

@@ -4,24 +4,12 @@
"health_index": {
"default": "mdi:heart-pulse"
},
"mold": {
"default": "mdi:water-check"
},
"oxygen": {
"default": "mdi:leaf"
},
"performance_index": {
"default": "mdi:head-check"
},
"r32": {
"default": "mdi:hvac"
},
"r454b": {
"default": "mdi:hvac"
},
"r454c": {
"default": "mdi:hvac"
},
"radon": {
"default": "mdi:radioactive"
},

View File

@@ -219,13 +219,6 @@ SENSOR_TYPES: list[AirQEntityDescription] = [
state_class=SensorStateClass.MEASUREMENT,
value=lambda data: data.get("ch4_MIPEX"),
),
AirQEntityDescription(
key="mold",
translation_key="mold",
native_unit_of_measurement=PERCENTAGE,
state_class=SensorStateClass.MEASUREMENT,
value=lambda data: data.get("mold"),
),
AirQEntityDescription(
key="n2o",
device_class=SensorDeviceClass.NITROUS_OXIDE,
@@ -326,25 +319,11 @@ SENSOR_TYPES: list[AirQEntityDescription] = [
value=lambda data: data.get("c3h8_MIPEX"),
),
AirQEntityDescription(
key="r32",
translation_key="r32",
native_unit_of_measurement=PERCENTAGE,
key="refigerant",
translation_key="refigerant",
native_unit_of_measurement=CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
state_class=SensorStateClass.MEASUREMENT,
value=lambda data: data.get("r32"),
),
AirQEntityDescription(
key="r454b",
translation_key="r454b",
native_unit_of_measurement=PERCENTAGE,
state_class=SensorStateClass.MEASUREMENT,
value=lambda data: data.get("r454b"),
),
AirQEntityDescription(
key="r454c",
translation_key="r454c",
native_unit_of_measurement=PERCENTAGE,
state_class=SensorStateClass.MEASUREMENT,
value=lambda data: data.get("r454c"),
value=lambda data: data.get("refigerant"),
),
AirQEntityDescription(
key="sih4",

View File

@@ -101,9 +101,6 @@
"methanethiol": {
"name": "Methanethiol"
},
"mold": {
"name": "Mold index"
},
"noise": {
"name": "Noise"
},
@@ -119,18 +116,12 @@
"propane": {
"name": "Propane"
},
"r32": {
"name": "Refrigerant R-32"
},
"r454b": {
"name": "Refrigerant R-454B"
},
"r454c": {
"name": "Refrigerant R-454C"
},
"radon": {
"name": "Radon"
},
"refigerant": {
"name": "Refrigerant"
},
"relative_pressure": {
"name": "Relative pressure"
},

View File

@@ -1,14 +1,6 @@
{
"entity": {
"sensor": {
"connectivity_mode": {
"default": "mdi:bluetooth-off",
"state": {
"bluetooth": "mdi:bluetooth",
"not_configured": "mdi:alert-circle",
"smartlink": "mdi:hub"
}
},
"radon_1day_avg": {
"default": "mdi:radioactive"
},

View File

@@ -5,7 +5,7 @@ from __future__ import annotations
import dataclasses
import logging
from airthings_ble import AirthingsConnectivityMode, AirthingsDevice
from airthings_ble import AirthingsDevice
from homeassistant.components.sensor import (
SensorDeviceClass,
@@ -41,12 +41,6 @@ from .coordinator import AirthingsBLEConfigEntry, AirthingsBLEDataUpdateCoordina
_LOGGER = logging.getLogger(__name__)
CONNECTIVITY_MODE_MAP = {
AirthingsConnectivityMode.BLE.value: "bluetooth",
AirthingsConnectivityMode.SMARTLINK.value: "smartlink",
AirthingsConnectivityMode.NOT_CONFIGURED.value: "not_configured",
}
SENSORS_MAPPING_TEMPLATE: dict[str, SensorEntityDescription] = {
"radon_1day_avg": SensorEntityDescription(
key="radon_1day_avg",
@@ -135,14 +129,6 @@ SENSORS_MAPPING_TEMPLATE: dict[str, SensorEntityDescription] = {
state_class=SensorStateClass.MEASUREMENT,
suggested_display_precision=0,
),
"connectivity_mode": SensorEntityDescription(
key="connectivity_mode",
translation_key="connectivity_mode",
device_class=SensorDeviceClass.ENUM,
options=list(CONNECTIVITY_MODE_MAP.values()),
entity_category=EntityCategory.DIAGNOSTIC,
entity_registry_enabled_default=False,
),
}
PARALLEL_UPDATES = 0
@@ -270,12 +256,4 @@ class AirthingsSensor(
@property
def native_value(self) -> StateType:
"""Return the value reported by the sensor."""
value = self.coordinator.data.sensors[self.entity_description.key]
# Map connectivity mode to enum values
if self.entity_description.key == "connectivity_mode":
if not isinstance(value, str):
return None
return CONNECTIVITY_MODE_MAP.get(value)
return value
return self.coordinator.data.sensors[self.entity_description.key]

View File

@@ -30,14 +30,6 @@
"ambient_noise": {
"name": "Ambient noise"
},
"connectivity_mode": {
"name": "Connectivity mode",
"state": {
"bluetooth": "Bluetooth",
"not_configured": "Not configured",
"smartlink": "SmartLink"
}
},
"illuminance": {
"name": "[%key:component::sensor::entity_component::illuminance::name%]"
},

View File

@@ -85,22 +85,6 @@ class AirzoneSystemEntity(AirzoneEntity):
value = system[key]
return value
async def _async_update_sys_params(self, params: dict[str, Any]) -> None:
"""Send system parameters to API."""
_params = {
API_SYSTEM_ID: self.system_id,
**params,
}
_LOGGER.debug("update_sys_params=%s", _params)
try:
await self.coordinator.airzone.set_sys_parameters(_params)
except AirzoneError as error:
raise HomeAssistantError(
f"Failed to set system {self.entity_id}: {error}"
) from error
self.coordinator.async_set_updated_data(self.coordinator.airzone.data())
class AirzoneHotWaterEntity(AirzoneEntity):
"""Define an Airzone Hot Water entity."""

View File

@@ -20,7 +20,6 @@ from aioairzone.const import (
AZD_MODES,
AZD_Q_ADAPT,
AZD_SLEEP,
AZD_SYSTEMS,
AZD_ZONES,
)
@@ -31,7 +30,7 @@ from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .coordinator import AirzoneConfigEntry, AirzoneUpdateCoordinator
from .entity import AirzoneEntity, AirzoneSystemEntity, AirzoneZoneEntity
from .entity import AirzoneEntity, AirzoneZoneEntity
@dataclass(frozen=True, kw_only=True)
@@ -86,18 +85,6 @@ def main_zone_options(
return [k for k, v in options.items() if v in modes]
SYSTEM_SELECT_TYPES: Final[tuple[AirzoneSelectDescription, ...]] = (
AirzoneSelectDescription(
api_param=API_Q_ADAPT,
entity_category=EntityCategory.CONFIG,
key=AZD_Q_ADAPT,
options=list(Q_ADAPT_DICT),
options_dict=Q_ADAPT_DICT,
translation_key="q_adapt",
),
)
MAIN_ZONE_SELECT_TYPES: Final[tuple[AirzoneSelectDescription, ...]] = (
AirzoneSelectDescription(
api_param=API_MODE,
@@ -106,6 +93,14 @@ MAIN_ZONE_SELECT_TYPES: Final[tuple[AirzoneSelectDescription, ...]] = (
options_fn=main_zone_options,
translation_key="modes",
),
AirzoneSelectDescription(
api_param=API_Q_ADAPT,
entity_category=EntityCategory.CONFIG,
key=AZD_Q_ADAPT,
options=list(Q_ADAPT_DICT),
options_dict=Q_ADAPT_DICT,
translation_key="q_adapt",
),
)
@@ -145,37 +140,16 @@ async def async_setup_entry(
"""Add Airzone select from a config_entry."""
coordinator = entry.runtime_data
added_systems: set[str] = set()
added_zones: set[str] = set()
def _async_entity_listener() -> None:
"""Handle additions of select."""
entities: list[AirzoneBaseSelect] = []
systems_data = coordinator.data.get(AZD_SYSTEMS, {})
received_systems = set(systems_data)
new_systems = received_systems - added_systems
if new_systems:
entities.extend(
AirzoneSystemSelect(
coordinator,
description,
entry,
system_id,
systems_data.get(system_id),
)
for system_id in new_systems
for description in SYSTEM_SELECT_TYPES
if description.key in systems_data.get(system_id)
)
added_systems.update(new_systems)
zones_data = coordinator.data.get(AZD_ZONES, {})
received_zones = set(zones_data)
new_zones = received_zones - added_zones
if new_zones:
entities.extend(
entities: list[AirzoneZoneSelect] = [
AirzoneZoneSelect(
coordinator,
description,
@@ -187,8 +161,8 @@ async def async_setup_entry(
for description in MAIN_ZONE_SELECT_TYPES
if description.key in zones_data.get(system_zone_id)
and zones_data.get(system_zone_id).get(AZD_MASTER) is True
)
entities.extend(
]
entities += [
AirzoneZoneSelect(
coordinator,
description,
@@ -199,11 +173,10 @@ async def async_setup_entry(
for system_zone_id in new_zones
for description in ZONE_SELECT_TYPES
if description.key in zones_data.get(system_zone_id)
)
]
async_add_entities(entities)
added_zones.update(new_zones)
async_add_entities(entities)
entry.async_on_unload(coordinator.async_add_listener(_async_entity_listener))
_async_entity_listener()
@@ -230,38 +203,6 @@ class AirzoneBaseSelect(AirzoneEntity, SelectEntity):
self._attr_current_option = self._get_current_option()
class AirzoneSystemSelect(AirzoneSystemEntity, AirzoneBaseSelect):
"""Define an Airzone System select."""
def __init__(
self,
coordinator: AirzoneUpdateCoordinator,
description: AirzoneSelectDescription,
entry: ConfigEntry,
system_id: str,
system_data: dict[str, Any],
) -> None:
"""Initialize."""
super().__init__(coordinator, entry, system_data)
self._attr_unique_id = f"{self._attr_unique_id}_{system_id}_{description.key}"
self.entity_description = description
self._attr_options = self.entity_description.options_fn(
system_data, description.options_dict
)
self.values_dict = {v: k for k, v in description.options_dict.items()}
self._async_update_attrs()
async def async_select_option(self, option: str) -> None:
"""Change the selected option."""
param = self.entity_description.api_param
value = self.entity_description.options_dict[option]
await self._async_update_sys_params({param: value})
class AirzoneZoneSelect(AirzoneZoneEntity, AirzoneBaseSelect):
"""Define an Airzone Zone select."""

View File

@@ -9,7 +9,6 @@
"no_url_available": "[%key:common::config_flow::abort::oauth2_no_url_available%]",
"oauth_error": "[%key:common::config_flow::abort::oauth2_error%]",
"oauth_failed": "[%key:common::config_flow::abort::oauth2_failed%]",
"oauth_implementation_unavailable": "[%key:common::config_flow::abort::oauth2_implementation_unavailable%]",
"oauth_timeout": "[%key:common::config_flow::abort::oauth2_timeout%]",
"oauth_unauthorized": "[%key:common::config_flow::abort::oauth2_unauthorized%]",
"reauth_successful": "[%key:common::config_flow::abort::reauth_successful%]",

View File

@@ -1,93 +0,0 @@
"""Provides conditions for alarm control panels."""
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.condition import (
Condition,
EntityStateConditionBase,
make_entity_state_condition,
)
from homeassistant.helpers.entity import get_supported_features
from .const import DOMAIN, AlarmControlPanelEntityFeature, AlarmControlPanelState
def supports_feature(hass: HomeAssistant, entity_id: str, features: int) -> bool:
"""Test if an entity supports the specified features."""
try:
return bool(get_supported_features(hass, entity_id) & features)
except HomeAssistantError:
return False
class EntityStateRequiredFeaturesCondition(EntityStateConditionBase):
"""State condition."""
_required_features: int
def entity_filter(self, entities: set[str]) -> set[str]:
"""Filter entities of this domain with the required features."""
entities = super().entity_filter(entities)
return {
entity_id
for entity_id in entities
if supports_feature(self._hass, entity_id, self._required_features)
}
def make_entity_state_required_features_condition(
domain: str, to_state: str, required_features: int
) -> type[EntityStateRequiredFeaturesCondition]:
"""Create an entity state condition class with required feature filtering."""
class CustomCondition(EntityStateRequiredFeaturesCondition):
"""Condition for entity state changes."""
_domain = domain
_states = {to_state}
_required_features = required_features
return CustomCondition
CONDITIONS: dict[str, type[Condition]] = {
"is_armed": make_entity_state_condition(
DOMAIN,
{
AlarmControlPanelState.ARMED_AWAY,
AlarmControlPanelState.ARMED_CUSTOM_BYPASS,
AlarmControlPanelState.ARMED_HOME,
AlarmControlPanelState.ARMED_NIGHT,
AlarmControlPanelState.ARMED_VACATION,
},
),
"is_armed_away": make_entity_state_required_features_condition(
DOMAIN,
AlarmControlPanelState.ARMED_AWAY,
AlarmControlPanelEntityFeature.ARM_AWAY,
),
"is_armed_home": make_entity_state_required_features_condition(
DOMAIN,
AlarmControlPanelState.ARMED_HOME,
AlarmControlPanelEntityFeature.ARM_HOME,
),
"is_armed_night": make_entity_state_required_features_condition(
DOMAIN,
AlarmControlPanelState.ARMED_NIGHT,
AlarmControlPanelEntityFeature.ARM_NIGHT,
),
"is_armed_vacation": make_entity_state_required_features_condition(
DOMAIN,
AlarmControlPanelState.ARMED_VACATION,
AlarmControlPanelEntityFeature.ARM_VACATION,
),
"is_disarmed": make_entity_state_condition(DOMAIN, AlarmControlPanelState.DISARMED),
"is_triggered": make_entity_state_condition(
DOMAIN, AlarmControlPanelState.TRIGGERED
),
}
async def async_get_conditions(hass: HomeAssistant) -> dict[str, type[Condition]]:
"""Return the alarm control panel conditions."""
return CONDITIONS

View File

@@ -1,52 +0,0 @@
.condition_common: &condition_common
target:
entity:
domain: alarm_control_panel
fields: &condition_common_fields
behavior:
required: true
default: any
selector:
select:
translation_key: condition_behavior
options:
- all
- any
is_armed: *condition_common
is_armed_away:
fields: *condition_common_fields
target:
entity:
domain: alarm_control_panel
supported_features:
- alarm_control_panel.AlarmControlPanelEntityFeature.ARM_AWAY
is_armed_home:
fields: *condition_common_fields
target:
entity:
domain: alarm_control_panel
supported_features:
- alarm_control_panel.AlarmControlPanelEntityFeature.ARM_HOME
is_armed_night:
fields: *condition_common_fields
target:
entity:
domain: alarm_control_panel
supported_features:
- alarm_control_panel.AlarmControlPanelEntityFeature.ARM_NIGHT
is_armed_vacation:
fields: *condition_common_fields
target:
entity:
domain: alarm_control_panel
supported_features:
- alarm_control_panel.AlarmControlPanelEntityFeature.ARM_VACATION
is_disarmed: *condition_common
is_triggered: *condition_common

View File

@@ -1,27 +1,4 @@
{
"conditions": {
"is_armed": {
"condition": "mdi:shield"
},
"is_armed_away": {
"condition": "mdi:shield-lock"
},
"is_armed_home": {
"condition": "mdi:shield-home"
},
"is_armed_night": {
"condition": "mdi:shield-moon"
},
"is_armed_vacation": {
"condition": "mdi:shield-airplane"
},
"is_disarmed": {
"condition": "mdi:shield-off"
},
"is_triggered": {
"condition": "mdi:bell-ring"
}
},
"entity_component": {
"_": {
"default": "mdi:shield",

View File

@@ -1,82 +1,8 @@
{
"common": {
"condition_behavior_description": "How the state should match on the targeted alarms.",
"condition_behavior_name": "Behavior",
"trigger_behavior_description": "The behavior of the targeted alarms to trigger on.",
"trigger_behavior_name": "Behavior"
},
"conditions": {
"is_armed": {
"description": "Tests if one or more alarms are armed.",
"fields": {
"behavior": {
"description": "[%key:component::alarm_control_panel::common::condition_behavior_description%]",
"name": "[%key:component::alarm_control_panel::common::condition_behavior_name%]"
}
},
"name": "Alarm is armed"
},
"is_armed_away": {
"description": "Tests if one or more alarms are armed in away mode.",
"fields": {
"behavior": {
"description": "[%key:component::alarm_control_panel::common::condition_behavior_description%]",
"name": "[%key:component::alarm_control_panel::common::condition_behavior_name%]"
}
},
"name": "Alarm is armed away"
},
"is_armed_home": {
"description": "Tests if one or more alarms are armed in home mode.",
"fields": {
"behavior": {
"description": "[%key:component::alarm_control_panel::common::condition_behavior_description%]",
"name": "[%key:component::alarm_control_panel::common::condition_behavior_name%]"
}
},
"name": "Alarm is armed home"
},
"is_armed_night": {
"description": "Tests if one or more alarms are armed in night mode.",
"fields": {
"behavior": {
"description": "[%key:component::alarm_control_panel::common::condition_behavior_description%]",
"name": "[%key:component::alarm_control_panel::common::condition_behavior_name%]"
}
},
"name": "Alarm is armed night"
},
"is_armed_vacation": {
"description": "Tests if one or more alarms are armed in vacation mode.",
"fields": {
"behavior": {
"description": "[%key:component::alarm_control_panel::common::condition_behavior_description%]",
"name": "[%key:component::alarm_control_panel::common::condition_behavior_name%]"
}
},
"name": "Alarm is armed vacation"
},
"is_disarmed": {
"description": "Tests if one or more alarms are disarmed.",
"fields": {
"behavior": {
"description": "[%key:component::alarm_control_panel::common::condition_behavior_description%]",
"name": "[%key:component::alarm_control_panel::common::condition_behavior_name%]"
}
},
"name": "Alarm is disarmed"
},
"is_triggered": {
"description": "Tests if one or more alarms are triggered.",
"fields": {
"behavior": {
"description": "[%key:component::alarm_control_panel::common::condition_behavior_description%]",
"name": "[%key:component::alarm_control_panel::common::condition_behavior_name%]"
}
},
"name": "Alarm is triggered"
}
},
"device_automation": {
"action_type": {
"arm_away": "Arm {entity_name} away",
@@ -150,12 +76,6 @@
}
},
"selector": {
"condition_behavior": {
"options": {
"all": "All",
"any": "Any"
}
},
"trigger_behavior": {
"options": {
"any": "Any",
@@ -166,7 +86,7 @@
},
"services": {
"alarm_arm_away": {
"description": "Arms an alarm in the away mode.",
"description": "Arms the alarm in the away mode.",
"fields": {
"code": {
"description": "[%key:component::alarm_control_panel::services::alarm_arm_custom_bypass::fields::code::description%]",
@@ -176,7 +96,7 @@
"name": "Arm away"
},
"alarm_arm_custom_bypass": {
"description": "Arms an alarm while allowing to bypass a custom area.",
"description": "Arms the alarm while allowing to bypass a custom area.",
"fields": {
"code": {
"description": "Code to arm the alarm.",
@@ -186,7 +106,7 @@
"name": "Arm with custom bypass"
},
"alarm_arm_home": {
"description": "Arms an alarm in the home mode.",
"description": "Arms the alarm in the home mode.",
"fields": {
"code": {
"description": "[%key:component::alarm_control_panel::services::alarm_arm_custom_bypass::fields::code::description%]",
@@ -196,7 +116,7 @@
"name": "Arm home"
},
"alarm_arm_night": {
"description": "Arms an alarm in the night mode.",
"description": "Arms the alarm in the night mode.",
"fields": {
"code": {
"description": "[%key:component::alarm_control_panel::services::alarm_arm_custom_bypass::fields::code::description%]",
@@ -206,7 +126,7 @@
"name": "Arm night"
},
"alarm_arm_vacation": {
"description": "Arms an alarm in the vacation mode.",
"description": "Arms the alarm in the vacation mode.",
"fields": {
"code": {
"description": "[%key:component::alarm_control_panel::services::alarm_arm_custom_bypass::fields::code::description%]",
@@ -216,7 +136,7 @@
"name": "Arm vacation"
},
"alarm_disarm": {
"description": "Disarms an alarm.",
"description": "Disarms the alarm.",
"fields": {
"code": {
"description": "Code to disarm the alarm.",
@@ -226,7 +146,7 @@
"name": "Disarm"
},
"alarm_trigger": {
"description": "Triggers an alarm manually.",
"description": "Triggers the alarm manually.",
"fields": {
"code": {
"description": "[%key:component::alarm_control_panel::services::alarm_arm_custom_bypass::fields::code::description%]",

View File

@@ -14,7 +14,7 @@ from .const import DOMAIN, AlarmControlPanelEntityFeature, AlarmControlPanelStat
def supports_feature(hass: HomeAssistant, entity_id: str, features: int) -> bool:
"""Test if an entity supports the specified features."""
"""Get the device class of an entity or UNDEFINED if not found."""
try:
return bool(get_supported_features(hass, entity_id) & features)
except HomeAssistantError:
@@ -39,7 +39,7 @@ class EntityStateTriggerRequiredFeatures(EntityTargetStateTriggerBase):
def make_entity_state_trigger_required_features(
domain: str, to_state: str, required_features: int
) -> type[EntityTargetStateTriggerBase]:
"""Create an entity state trigger class with required feature filtering."""
"""Create an entity state trigger class."""
class CustomTrigger(EntityStateTriggerRequiredFeatures):
"""Trigger for entity state changes."""

View File

@@ -18,15 +18,12 @@ from homeassistant.const import (
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.dispatcher import dispatcher_send
from homeassistant.helpers.event import async_call_later
from homeassistant.helpers.typing import ConfigType
from .const import (
CONF_DEVICE_BAUD,
CONF_DEVICE_PATH,
DOMAIN,
PROTOCOL_SERIAL,
PROTOCOL_SOCKET,
SIGNAL_PANEL_MESSAGE,
@@ -35,11 +32,9 @@ from .const import (
SIGNAL_ZONE_FAULT,
SIGNAL_ZONE_RESTORE,
)
from .services import async_setup_services
_LOGGER = logging.getLogger(__name__)
CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN)
PLATFORMS = [
Platform.ALARM_CONTROL_PANEL,
Platform.BINARY_SENSOR,
@@ -59,12 +54,6 @@ class AlarmDecoderData:
restart: bool
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up the component."""
async_setup_services(hass)
return True
async def async_setup_entry(
hass: HomeAssistant, entry: AlarmDecoderConfigEntry
) -> bool:

View File

@@ -2,13 +2,17 @@
from __future__ import annotations
import voluptuous as vol
from homeassistant.components.alarm_control_panel import (
AlarmControlPanelEntity,
AlarmControlPanelEntityFeature,
AlarmControlPanelState,
CodeFormat,
)
from homeassistant.const import ATTR_CODE
from homeassistant.core import HomeAssistant
from homeassistant.helpers import config_validation as cv, entity_platform
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
@@ -23,6 +27,11 @@ from .const import (
)
from .entity import AlarmDecoderEntity
SERVICE_ALARM_TOGGLE_CHIME = "alarm_toggle_chime"
SERVICE_ALARM_KEYPRESS = "alarm_keypress"
ATTR_KEYPRESS = "keypress"
async def async_setup_entry(
hass: HomeAssistant,
@@ -41,6 +50,23 @@ async def async_setup_entry(
)
async_add_entities([entity])
platform = entity_platform.async_get_current_platform()
platform.async_register_entity_service(
SERVICE_ALARM_TOGGLE_CHIME,
{
vol.Required(ATTR_CODE): cv.string,
},
"alarm_toggle_chime",
)
platform.async_register_entity_service(
SERVICE_ALARM_KEYPRESS,
{
vol.Required(ATTR_KEYPRESS): cv.string,
},
"alarm_keypress",
)
class AlarmDecoderAlarmPanel(AlarmDecoderEntity, AlarmControlPanelEntity):
"""Representation of an AlarmDecoder-based alarm panel."""

View File

@@ -1,46 +0,0 @@
"""Support for AlarmDecoder-based alarm control panels (Honeywell/DSC)."""
from __future__ import annotations
import voluptuous as vol
from homeassistant.components.alarm_control_panel import (
DOMAIN as ALARM_CONTROL_PANEL_DOMAIN,
)
from homeassistant.const import ATTR_CODE
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv, service
from .const import DOMAIN
SERVICE_ALARM_TOGGLE_CHIME = "alarm_toggle_chime"
SERVICE_ALARM_KEYPRESS = "alarm_keypress"
ATTR_KEYPRESS = "keypress"
@callback
def async_setup_services(hass: HomeAssistant) -> None:
"""Home Assistant services."""
service.async_register_platform_entity_service(
hass,
DOMAIN,
SERVICE_ALARM_TOGGLE_CHIME,
entity_domain=ALARM_CONTROL_PANEL_DOMAIN,
schema={
vol.Required(ATTR_CODE): cv.string,
},
func="alarm_toggle_chime",
)
service.async_register_platform_entity_service(
hass,
DOMAIN,
SERVICE_ALARM_KEYPRESS,
entity_domain=ALARM_CONTROL_PANEL_DOMAIN,
schema={
vol.Required(ATTR_KEYPRESS): cv.string,
},
func="alarm_keypress",
)

View File

@@ -4,7 +4,7 @@ from typing import Any
import voluptuous as vol
from homeassistant.components import labs, websocket_api
from homeassistant.components import websocket_api
from homeassistant.const import EVENT_HOMEASSISTANT_STARTED
from homeassistant.core import Event, HomeAssistant, callback
from homeassistant.helpers.typing import ConfigType
@@ -18,13 +18,7 @@ from .analytics import (
EntityAnalyticsModifications,
async_devices_payload,
)
from .const import (
ATTR_ONBOARDED,
ATTR_PREFERENCES,
ATTR_SNAPSHOTS,
DOMAIN,
PREFERENCE_SCHEMA,
)
from .const import ATTR_ONBOARDED, ATTR_PREFERENCES, DOMAIN, PREFERENCE_SCHEMA
from .http import AnalyticsDevicesView
__all__ = [
@@ -50,55 +44,29 @@ CONFIG_SCHEMA = vol.Schema(
DATA_COMPONENT: HassKey[Analytics] = HassKey(DOMAIN)
LABS_SNAPSHOT_FEATURE = "snapshots"
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up the analytics integration."""
analytics_config = config.get(DOMAIN, {})
# For now we want to enable device analytics only if the url option
# is explicitly listed in YAML.
if CONF_SNAPSHOTS_URL in analytics_config:
await labs.async_update_preview_feature(
hass, DOMAIN, LABS_SNAPSHOT_FEATURE, enabled=True
)
disable_snapshots = False
snapshots_url = analytics_config[CONF_SNAPSHOTS_URL]
else:
disable_snapshots = True
snapshots_url = None
analytics = Analytics(hass, snapshots_url)
analytics = Analytics(hass, snapshots_url, disable_snapshots)
# Load stored data
await analytics.load()
started = False
async def _async_handle_labs_update(
event: Event[labs.EventLabsUpdatedData],
) -> None:
"""Handle labs feature toggle."""
await analytics.save_preferences({ATTR_SNAPSHOTS: event.data["enabled"]})
if started:
await analytics.async_schedule()
@callback
def _async_labs_event_filter(event_data: labs.EventLabsUpdatedData) -> bool:
"""Filter labs events for this integration's snapshot feature."""
return (
event_data["domain"] == DOMAIN
and event_data["preview_feature"] == LABS_SNAPSHOT_FEATURE
)
async def start_schedule(_event: Event) -> None:
"""Start the send schedule after the started event."""
nonlocal started
started = True
await analytics.async_schedule()
hass.bus.async_listen(
labs.EVENT_LABS_UPDATED,
_async_handle_labs_update,
event_filter=_async_labs_event_filter,
)
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STARTED, start_schedule)
websocket_api.async_register_command(hass, websocket_analytics)

View File

@@ -22,7 +22,6 @@ from homeassistant.components.energy import (
DOMAIN as ENERGY_DOMAIN,
is_configured as energy_is_configured,
)
from homeassistant.components.labs import async_is_preview_feature_enabled
from homeassistant.components.recorder import (
DOMAIN as RECORDER_DOMAIN,
get_instance as get_recorder_instance,
@@ -242,10 +241,12 @@ class Analytics:
self,
hass: HomeAssistant,
snapshots_url: str | None = None,
disable_snapshots: bool = False,
) -> None:
"""Initialize the Analytics class."""
self._hass: HomeAssistant = hass
self._snapshots_url = snapshots_url
self._disable_snapshots = disable_snapshots
self._session = async_get_clientsession(hass)
self._data = AnalyticsData(False, {})
@@ -257,13 +258,15 @@ class Analytics:
def preferences(self) -> dict:
"""Return the current active preferences."""
preferences = self._data.preferences
return {
result = {
ATTR_BASE: preferences.get(ATTR_BASE, False),
ATTR_DIAGNOSTICS: preferences.get(ATTR_DIAGNOSTICS, False),
ATTR_USAGE: preferences.get(ATTR_USAGE, False),
ATTR_STATISTICS: preferences.get(ATTR_STATISTICS, False),
ATTR_SNAPSHOTS: preferences.get(ATTR_SNAPSHOTS, False),
}
if not self._disable_snapshots:
result[ATTR_SNAPSHOTS] = preferences.get(ATTR_SNAPSHOTS, False)
return result
@property
def onboarded(self) -> bool:
@@ -288,11 +291,6 @@ class Analytics:
"""Return bool if a supervisor is present."""
return is_hassio(self._hass)
@property
def _snapshots_enabled(self) -> bool:
"""Check if snapshots feature is enabled via labs."""
return async_is_preview_feature_enabled(self._hass, DOMAIN, "snapshots")
async def load(self) -> None:
"""Load preferences."""
stored = await self._store.async_load()
@@ -647,10 +645,7 @@ class Analytics:
),
)
if (
not self.preferences.get(ATTR_SNAPSHOTS, False)
or not self._snapshots_enabled
):
if not self.preferences.get(ATTR_SNAPSHOTS, False) or self._disable_snapshots:
LOGGER.debug("Snapshot analytics not scheduled")
if self._snapshot_scheduled:
self._snapshot_scheduled()

View File

@@ -7,12 +7,5 @@
"documentation": "https://www.home-assistant.io/integrations/analytics",
"integration_type": "system",
"iot_class": "cloud_push",
"preview_features": {
"snapshots": {
"feedback_url": "https://forms.gle/GqvRmgmghSDco8M46",
"learn_more_url": "https://www.home-assistant.io/blog/2026/02/02/about-device-database/",
"report_issue_url": "https://github.com/OHF-Device-Database/device-database/issues/new"
}
},
"quality_scale": "internal"
}

View File

@@ -1,10 +0,0 @@
{
"preview_features": {
"snapshots": {
"description": "This free, open source device database of the Open Home Foundation helps users find useful information about smart home devices used in real installations.\n\nYou can help build it by anonymously sharing data about your devices. Only device-specific details (like model or manufacturer) are shared — never personally identifying information (like the names you assign).\n\nLearn more about the device database and how we process your data in our [Data Use Statement](https://www.openhomefoundation.org/device-database-data-use-statement), which you accept by opting in.",
"disable_confirmation": "Your data will no longer be shared with the Open Home Foundation's device database.",
"enable_confirmation": "This feature is still in development and may change. The device database is being refined based on user feedback and is not yet complete.",
"name": "Device database"
}
}
}

View File

@@ -13,10 +13,9 @@ from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers import entity_registry as er
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from .const import CONF_TRACKED_APPS, CONF_TRACKED_INTEGRATIONS
from .const import CONF_TRACKED_INTEGRATIONS
from .coordinator import HomeassistantAnalyticsDataUpdateCoordinator
PLATFORMS: list[Platform] = [Platform.SENSOR]
@@ -60,30 +59,6 @@ async def async_setup_entry(
return True
async def async_migrate_entry(
hass: HomeAssistant, entry: AnalyticsInsightsConfigEntry
) -> bool:
"""Migrate to a new version."""
# Migration for switching add-ons to apps
if entry.version < 2:
ent_reg = er.async_get(hass)
for entity_entry in er.async_entries_for_config_entry(ent_reg, entry.entry_id):
if not entity_entry.unique_id.startswith("addon_"):
continue
ent_reg.async_update_entity(
entity_entry.entity_id,
new_unique_id=entity_entry.unique_id.replace("addon_", "app_"),
)
options = dict(entry.options)
options[CONF_TRACKED_APPS] = options.pop("tracked_addons", [])
hass.config_entries.async_update_entry(entry, version=2, options=options)
return True
async def async_unload_entry(
hass: HomeAssistant, entry: AnalyticsInsightsConfigEntry
) -> bool:

View File

@@ -26,7 +26,7 @@ from homeassistant.helpers.selector import (
from . import AnalyticsInsightsConfigEntry
from .const import (
CONF_TRACKED_APPS,
CONF_TRACKED_ADDONS,
CONF_TRACKED_CUSTOM_INTEGRATIONS,
CONF_TRACKED_INTEGRATIONS,
DOMAIN,
@@ -43,8 +43,6 @@ INTEGRATION_TYPES_WITHOUT_ANALYTICS = (
class HomeassistantAnalyticsConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a config flow for Homeassistant Analytics."""
VERSION = 2
@staticmethod
@callback
def async_get_options_flow(
@@ -61,7 +59,7 @@ class HomeassistantAnalyticsConfigFlow(ConfigFlow, domain=DOMAIN):
if user_input is not None:
if all(
[
not user_input.get(CONF_TRACKED_APPS),
not user_input.get(CONF_TRACKED_ADDONS),
not user_input.get(CONF_TRACKED_INTEGRATIONS),
not user_input.get(CONF_TRACKED_CUSTOM_INTEGRATIONS),
]
@@ -72,7 +70,7 @@ class HomeassistantAnalyticsConfigFlow(ConfigFlow, domain=DOMAIN):
title="Home Assistant Analytics Insights",
data={},
options={
CONF_TRACKED_APPS: user_input.get(CONF_TRACKED_APPS, []),
CONF_TRACKED_ADDONS: user_input.get(CONF_TRACKED_ADDONS, []),
CONF_TRACKED_INTEGRATIONS: user_input.get(
CONF_TRACKED_INTEGRATIONS, []
),
@@ -86,7 +84,7 @@ class HomeassistantAnalyticsConfigFlow(ConfigFlow, domain=DOMAIN):
session=async_get_clientsession(self.hass)
)
try:
apps = await client.get_addons()
addons = await client.get_addons()
integrations = await client.get_integrations(Environment.NEXT)
custom_integrations = await client.get_custom_integrations()
except HomeassistantAnalyticsConnectionError:
@@ -109,9 +107,9 @@ class HomeassistantAnalyticsConfigFlow(ConfigFlow, domain=DOMAIN):
errors=errors,
data_schema=vol.Schema(
{
vol.Optional(CONF_TRACKED_APPS): SelectSelector(
vol.Optional(CONF_TRACKED_ADDONS): SelectSelector(
SelectSelectorConfig(
options=list(apps),
options=list(addons),
multiple=True,
sort=True,
)
@@ -146,7 +144,7 @@ class HomeassistantAnalyticsOptionsFlowHandler(OptionsFlowWithReload):
if user_input is not None:
if all(
[
not user_input.get(CONF_TRACKED_APPS),
not user_input.get(CONF_TRACKED_ADDONS),
not user_input.get(CONF_TRACKED_INTEGRATIONS),
not user_input.get(CONF_TRACKED_CUSTOM_INTEGRATIONS),
]
@@ -156,7 +154,7 @@ class HomeassistantAnalyticsOptionsFlowHandler(OptionsFlowWithReload):
return self.async_create_entry(
title="",
data={
CONF_TRACKED_APPS: user_input.get(CONF_TRACKED_APPS, []),
CONF_TRACKED_ADDONS: user_input.get(CONF_TRACKED_ADDONS, []),
CONF_TRACKED_INTEGRATIONS: user_input.get(
CONF_TRACKED_INTEGRATIONS, []
),
@@ -170,7 +168,7 @@ class HomeassistantAnalyticsOptionsFlowHandler(OptionsFlowWithReload):
session=async_get_clientsession(self.hass)
)
try:
apps = await client.get_addons()
addons = await client.get_addons()
integrations = await client.get_integrations(Environment.NEXT)
custom_integrations = await client.get_custom_integrations()
except HomeassistantAnalyticsConnectionError:
@@ -191,9 +189,9 @@ class HomeassistantAnalyticsOptionsFlowHandler(OptionsFlowWithReload):
data_schema=self.add_suggested_values_to_schema(
vol.Schema(
{
vol.Optional(CONF_TRACKED_APPS): SelectSelector(
vol.Optional(CONF_TRACKED_ADDONS): SelectSelector(
SelectSelectorConfig(
options=list(apps),
options=list(addons),
multiple=True,
sort=True,
)

View File

@@ -4,7 +4,7 @@ import logging
DOMAIN = "analytics_insights"
CONF_TRACKED_APPS = "tracked_apps"
CONF_TRACKED_ADDONS = "tracked_addons"
CONF_TRACKED_INTEGRATIONS = "tracked_integrations"
CONF_TRACKED_CUSTOM_INTEGRATIONS = "tracked_custom_integrations"

View File

@@ -18,7 +18,7 @@ from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import (
CONF_TRACKED_APPS,
CONF_TRACKED_ADDONS,
CONF_TRACKED_CUSTOM_INTEGRATIONS,
CONF_TRACKED_INTEGRATIONS,
DOMAIN,
@@ -35,7 +35,7 @@ class AnalyticsData:
active_installations: int
reports_integrations: int
apps: dict[str, int]
addons: dict[str, int]
core_integrations: dict[str, int]
custom_integrations: dict[str, int]
@@ -60,7 +60,7 @@ class HomeassistantAnalyticsDataUpdateCoordinator(DataUpdateCoordinator[Analytic
update_interval=timedelta(hours=12),
)
self._client = client
self._tracked_apps = self.config_entry.options.get(CONF_TRACKED_APPS, [])
self._tracked_addons = self.config_entry.options.get(CONF_TRACKED_ADDONS, [])
self._tracked_integrations = self.config_entry.options[
CONF_TRACKED_INTEGRATIONS
]
@@ -70,9 +70,7 @@ class HomeassistantAnalyticsDataUpdateCoordinator(DataUpdateCoordinator[Analytic
async def _async_update_data(self) -> AnalyticsData:
try:
apps_data = (
await self._client.get_addons()
) # Still add method name. Needs library update
addons_data = await self._client.get_addons()
data = await self._client.get_current_analytics()
custom_data = await self._client.get_custom_integrations()
except HomeassistantAnalyticsConnectionError as err:
@@ -81,7 +79,9 @@ class HomeassistantAnalyticsDataUpdateCoordinator(DataUpdateCoordinator[Analytic
) from err
except HomeassistantAnalyticsNotModifiedError:
return self.data
apps = {app: get_app_value(apps_data, app) for app in self._tracked_apps}
addons = {
addon: get_addon_value(addons_data, addon) for addon in self._tracked_addons
}
core_integrations = {
integration: data.integrations.get(integration, 0)
for integration in self._tracked_integrations
@@ -93,14 +93,14 @@ class HomeassistantAnalyticsDataUpdateCoordinator(DataUpdateCoordinator[Analytic
return AnalyticsData(
data.active_installations,
data.reports_integrations,
apps,
addons,
core_integrations,
custom_integrations,
)
def get_app_value(data: dict[str, Addon], name_slug: str) -> int:
"""Get app value."""
def get_addon_value(data: dict[str, Addon], name_slug: str) -> int:
"""Get addon value."""
if name_slug in data:
return data[name_slug].total
return 0

View File

@@ -29,17 +29,17 @@ class AnalyticsSensorEntityDescription(SensorEntityDescription):
value_fn: Callable[[AnalyticsData], StateType]
def get_app_entity_description(
def get_addon_entity_description(
name_slug: str,
) -> AnalyticsSensorEntityDescription:
"""Get app entity description."""
"""Get addon entity description."""
return AnalyticsSensorEntityDescription(
key=f"app_{name_slug}_active_installations",
translation_key="apps",
key=f"addon_{name_slug}_active_installations",
translation_key="addons",
name=name_slug,
state_class=SensorStateClass.TOTAL,
native_unit_of_measurement="active installations",
value_fn=lambda data: data.apps.get(name_slug),
value_fn=lambda data: data.addons.get(name_slug),
)
@@ -106,9 +106,9 @@ async def async_setup_entry(
entities.extend(
HomeassistantAnalyticsSensor(
coordinator,
get_app_entity_description(app_name_slug),
get_addon_entity_description(addon_name_slug),
)
for app_name_slug in coordinator.data.apps
for addon_name_slug in coordinator.data.addons
)
entities.extend(
HomeassistantAnalyticsSensor(

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