Merge branch 'master' into patch-1

This commit is contained in:
Jack Gaino 2024-07-31 23:03:30 -04:00 committed by GitHub
commit 058c2c7e3a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
179 changed files with 7715 additions and 3653 deletions

2
.gitignore vendored
View File

@ -21,3 +21,5 @@
npm-debug.log* npm-debug.log*
yarn-debug.log* yarn-debug.log*
yarn-error.log* yarn-error.log*
.idea

2
.nvmrc
View File

@ -1 +1 @@
18 20

View File

@ -37,7 +37,8 @@ This strategy allows us to not waste any of our workers time on running a full t
Below is a screenshot of our CI pipeline for Home Assistant. Because all work is distributed over multiple workers, the total runtime is the longest task in the first column, plus the longest task in the second column. Below is a screenshot of our CI pipeline for Home Assistant. Because all work is distributed over multiple workers, the total runtime is the longest task in the first column, plus the longest task in the second column.
<center> <center>
![Screenshot of the Home Assistant CI pipeline.](/img/en/blog/2019-07-building-all-the-things/test-stages.png)</center> ![Screenshot of the Home Assistant CI pipeline.](/img/en/blog/2019-07-building-all-the-things/test-stages.png)
</center>
To improve the time of our CI on Azure, were using a preview version of [pipeline artifact caching](https://marketplace.visualstudio.com/items?itemName=1ESLighthouseEng.PipelineArtifactCaching). This allows us to build the dependencies once, store it as a package close to the test runners and re-use it across jobs and pipeline runs. To improve the time of our CI on Azure, were using a preview version of [pipeline artifact caching](https://marketplace.visualstudio.com/items?itemName=1ESLighthouseEng.PipelineArtifactCaching). This allows us to build the dependencies once, store it as a package close to the test runners and re-use it across jobs and pipeline runs.

View File

@ -26,7 +26,8 @@ In simple mode, we will structure the configuration to how the user thinks about
- Outputs: scenes, scripts, automations - Outputs: scenes, scripts, automations
<center> <center>
![Configuration concepts. Inputs are users, integrations, zones, persons, devices. Outputs are scenes, scripts and automations.](/img/en/blog/2019-10-simple-mode/config-concepts.png)</center> ![Configuration concepts. Inputs are users, integrations, zones, persons, devices. Outputs are scenes, scripts and automations.](/img/en/blog/2019-10-simple-mode/config-concepts.png)
</center>
<!-- https://docs.google.com/drawings/d/1021ATCQ_Q3eBQQ1Ei5Bq7rSBfn6YtLh9113HimpsYWs/edit?usp=sharing --> <!-- https://docs.google.com/drawings/d/1021ATCQ_Q3eBQQ1Ei5Bq7rSBfn6YtLh9113HimpsYWs/edit?usp=sharing -->

View File

@ -40,14 +40,20 @@ If you are using the `hassfest` GitHub action, you will now start to see warning
## Serving files ## Serving files
Making resources available to the user is a common use case for custom integrations, whether that is images, panels, or enhancements the user can use in Lovelace. The only way one should serve static files from a path is to use `hass.http.register_static_path`. Use this method and avoid using your own, as this can lead to serious bugs or security issues. Making resources available to the user is a common use case for custom integrations, whether that is images, panels, or enhancements the user can use in Lovelace. The only way one should serve static files from a path is to use `hass.http.async_register_static_paths`. Use this method and avoid using your own, as this can lead to serious bugs or security issues.
```python ```python
from pathlib import Path from pathlib import Path
from homeassisant.components.http import StaticPathConfig
should_cache = False should_cache = False
files_path = Path(__file__).parent / "static" files_path = Path(__file__).parent / "static"
hass.http.register_static_path("/api/my_integration/static", str(files_path), should_cache) files2_path = Path(__file__).parent / "static2"
await hass.http.async_register_static_paths([
StaticPathConfig("/api/my_integration/static", str(files_path), should_cache),
StaticPathConfig("/api/my_integration/static2", str(files2_path), should_cache)
])
``` ```
That's it for this update about custom integrations. Keep doing awesome stuff! Until next time 👋 That's it for this update about custom integrations. Keep doing awesome stuff! Until next time 👋

View File

@ -6,6 +6,6 @@ title: "Waiting for config entry platforms"
Before 2022.8, it was impossible to `await` config entry platforms forwards without a deadlock if one of the platforms loaded by the config entry was not already loaded. Before 2022.8, it was impossible to `await` config entry platforms forwards without a deadlock if one of the platforms loaded by the config entry was not already loaded.
Integrations need to be refactored to replace calls to `hass.config_entries.async_setup_platforms` with `hass.config_entries.async_forward_entry_setups` and/or await all `hass.config_entries.async_forward_entry_setup` to ensure that Home Assistant does not inadvertently reload the integration while entities and platforms are still being set up. Integrations need to be refactored to replace calls to `hass.config_entries.async_setup_platforms` with awaiting `hass.config_entries.async_forward_entry_setups` to ensure that Home Assistant does not inadvertently reload the integration while entities and platforms are still being set up.
`hass.config_entries.async_setup_platforms` is scheduled to be removed in 2022.12. `hass.config_entries.async_setup_platforms` is scheduled to be removed in 2022.12.

View File

@ -0,0 +1,9 @@
---
author: J. Nick Koston
authorURL: https://github.com/bdraco
title: Avoid unnecessary callbacks with DataUpdateCoordinator
---
The `DataUpdateCoordinator` can now reduce unnecessary updates when API data can be compared.
When using the `DataUpdateCoordinator`, the data being polled is often expected to stay mostly the same. For example, if you are polling a light that is only turned on once a week, that data may be the same nearly all the time. The default behavior is always calling back listeners when the data is updated, even if it does not change. If the data returned from the API can be compared for changes with the Python `__eq__` method, set `always_update=False` when creating the `DataUpdateCoordinator` to avoid unnecessary callbacks and writes to the state machine.

View File

@ -0,0 +1,9 @@
---
author: J. Nick Koston
authorURL: https://github.com/bdraco
title: "Deprecating `async_add_hass_job`"
---
As part of an effort to improve performance and simplify the core job API, `async_add_hass_job` is deprecated and will be removed from Home Assistant in 2025.5.
Calls should be replaced with `async_run_hass_job` instead.

View File

@ -0,0 +1,21 @@
---
author: Marc Mueller
authorURL: https://github.com/cdce8p
title: "Deprecate old backports and typing alias"
---
In the past, we've backported features from upstream CPython to use them early and improve user and developers' experience. Home Assistant only supports Python 3.12, so these can be used directly from Python. These backports are now deprecated and will be removed in the future.
| Deprecated | Replacement | Python version |
| ---------- | ----------- | -------------- |
| `homeassistant.backports.enum.StrEnum` | `enum.StrEnum` | >= 3.11 |
| `homeassistant.backports.functools.cached_property` | `functools.cached_property` | >= 3.8, >= 3.12 (performance improvement) |
In addition, some typing aliases are also deprecated now.
| Deprecated | Replacement |
| ---------- | ----------- |
| `homeassistant.helpers.typing.ContextType` | `homeassistant.core.Context` |
| `homeassistant.helpers.typing.EventType` | `homeassistant.core.Event` |
| `homeassistant.helpers.typing.HomeAssistantType` | `homeassistant.core.HomeAssistant` |
| `homeassistant.helpers.typing.ServiceCallType` | `homeassistant.core.ServiceCall` |

View File

@ -0,0 +1,32 @@
---
author: Jan Bouwhuis
authorURL: https://github.com/jbouwh
authorImageURL: https://avatars.githubusercontent.com/u/7188918?s=96&v=4
title: New notify entity platform
---
### New notify entity platform
The notify platform is now available as an [entity platform](https://developers.home-assistant.io/docs/core/entity/notify/). The MVP for the new `notify` platform [implements](https://github.com/home-assistant/core/pull/110950) the method and service `send_message`. It accepts `message` as a required attribute.
Unlike the legacy `notify.notify` service we have no targets as argument, as it is an entity we can target multiple `notify` entities when calling `send_message`.
The [architecture discussion](https://github.com/home-assistant/architecture/discussions/1041) is ongoing, and is about the device classes to implement and the implementation of recipient support in the form of [contacts via a contact registry](https://github.com/home-assistant/architecture/discussions/1041#discussioncomment-8947842).
Existing integrations that implement the legacy `notify` services will be migrated in phases. The first step is to migrate the integrations than only use `message` as a parameter to notify.
The integrations identified for migration are:
- circuit
- clickatell
- clicksend
- command_line
- demo
- ecobee
- flock
- free_mobile
- knx
- mastodon
As soon as we have `title` and/or `recipient` support we can migrate more integrations to use the new platform.
When integrations are migrated, users will need to use the new `notify.send_message` service, so the migration changes will cause automations to break after the deprecation period is over.

View File

@ -0,0 +1,40 @@
---
author: J. Nick Koston
authorURL: https://github.com/bdraco
title: "Replacing `async_track_state_change` with `async_track_state_change_event`"
---
`async_track_state_change` is deprecated and will be removed in Home Assistant 2025.5. `async_track_state_change_event` should be used instead.
`async_track_state_change` always creates a top-level listener for `EVENT_STATE_CHANGED`, which would have to reject all state changes that did not match the desired entities. This design presented a performance problem when there were many integrations using `async_track_state_change`. `async_track_state_change` has been phased out in `core` since the introduction of `async_track_state_change_event`, with the last instance being removed in 2024.5.
Example with `async_track_state_change`:
```python
from homeassistant.core import State, callback
from homeassistant.helper.event import async_track_state_change
@callback
def _async_on_change(entity_id: str, old_state: State | None, new_state: State | None) -> None:
...
unsub = async_track_state_change(hass, "sensor.one", _async_on_change)
unsub()
```
Example replacement with `async_track_state_change_event`:
```python
from homeassistant.core import Event, EventStateChangedData, callback
from homeassistant.helper.event import async_track_state_change_event
@callback
def _async_on_change(event: Event[EventStateChangedData]) -> None:
entity_id = event.data["entity_id"]
old_state = event.data["old_state"]
new_state = event.data["new_state"]
...
unsub = async_track_state_change_event(hass, "sensor.one", _async_on_change)
unsub()
```

View File

@ -0,0 +1,52 @@
---
author: Jan Bouwhuis
authorURL: https://github.com/jbouwh
authorImageURL: https://avatars.githubusercontent.com/u/7188918?s=96&v=4
title: Always reload after a successful re-auth flow
---
## Always reload after successful reauthentication
To update and reload the entry after a successful reauthentication flow, the helper `async_update_reload_and_abort` can be used. The default behavior of the helper has been changed. By default the entry will always reload if the helper is called. If an entry needs reauthentication, it is not always needed to update the entry if an account was temporary disabled or an API-key was temporary disallowed.
For cases where reloading is not wanted in case the entry is not changed, the `reload_even_if_entry_is_unchanged=False` parameter can be passed to the helper.
More about this helper can be found here [here](/docs/config_entries_config_flow_handler/#reauthentication).
### Example
```python
class OAuth2FlowHandler(
config_entry_oauth2_flow.AbstractOAuth2FlowHandler, domain=DOMAIN
):
"""Config flow to handle OAuth2 authentication."""
reauth_entry: ConfigEntry | None = None
async def async_step_reauth(self, user_input=None):
"""Perform reauth upon an API authentication error."""
self.reauth_entry = self.hass.config_entries.async_get_entry(
self.context["entry_id"]
)
return await self.async_step_reauth_confirm()
async def async_step_reauth_confirm(self, user_input=None):
"""Dialog that informs the user that reauth is required."""
if user_input is None:
return self.async_show_form(
step_id="reauth_confirm",
data_schema=vol.Schema({}),
)
return await self.async_step_user()
async def async_oauth_create_entry(self, data: dict) -> dict:
"""Create an oauth config entry or update existing entry for reauth."""
if self.reauth_entry:
# Only reload if the entry was updated
return self.async_update_reload_and_abort(
self.reauth_entry,
data=data,
reload_even_if_entry_is_unchanged=False,
)
return await super().async_oauth_create_entry(data)
```

View File

@ -0,0 +1,49 @@
---
author: Marc Mueller
authorURL: https://github.com/cdce8p
title: "Store runtime data inside the config entry"
---
Integrations often need to set up and track custom data, such as coordinators, API connections, or code objects. Previously, those were all stored inside `hass.data`, which made tracking them difficult.
With recent changes, it's now possible to use `entry.runtime_data` for that. The config entry is already available when setting up platforms and gets cleaned up automatically. No more deleting the key from `hass.data` after unloading.
It also better supports type-checking. `ConfigEntry` is generic now, so passing the data type along is possible. Use a typed data structure like `dataclass` for that. To simplify the annotation, it's recommended to define a type alias for it.
An example could look like this:
```py
# <integration>/__init__.py
# The type alias needs to be suffixed with 'ConfigEntry'
type MyConfigEntry = ConfigEntry[MyData]
@dataclass
class MyData:
client: MyClient
other_data: dict[str, Any]
async def async_setup_entry(
hass: HomeAssistant,
entry: MyConfigEntry, # use type alias instead of ConfigEntry
) -> bool:
client = MyClient(...)
# Assign the runtime_data
entry.runtime_data = MyData(client, {...})
```
```py
# <integration>/switch.py
from . import MyConfigEntry
async def async_setup_entry(
hass: HomeAssistant,
entry: MyConfigEntry, # use type alias instead of ConfigEntry
async_add_entities: AddEntitiesCallback,
) -> None:
# Access the runtime data form the config entry
data = entry.runtime_data
async_add_entities([MySwitch(data.client)])
```

View File

@ -0,0 +1,68 @@
---
author: Marc Mueller
authorURL: https://github.com/cdce8p
title: "Improved typing for hass.data"
---
In the past, one of the challenges with `hass.data` was to correctly assign type information. Since it was typed as `dict[str, Any]`, the only options were annotation assignments or `cast` like:
```py
data: MyData = hass.data[SOME_KEY]
```
This had several disadvantages. Not only was it necessary to annotate every assignment, but type checkers also basically pretended that the annotation would always be correct. Especially during refactoring, it could easily happen that one instance was missed, and while type-checking still succeeded, the actual code would be broken.
To fix that, it's now possible to use two new key types `HassKey` and `HassEntryKey`. With a little bit of magic, type checkers are now able to infer the type and make sure it's correct. Even when storing data.
An example could look like this:
```py
# <integration>/__init__.py
from homeassistant.util.hass_dict import HassKey
MY_KEY: HassKey["MyData"] = HassKey(DOMAIN)
@dataclass
class MyData:
client: MyClient
other_data: dict[str, Any]
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
client = MyClient(...)
hass.data[MY_KEY] = MyData(client, {...})
hass.data[MY_KEY] = 1 # mypy error
```
```py
# <integration>/switch.py
from . import MY_KEY
async def async_setup_platform(
hass: HomeAssistant,
config: ConfigType,
async_add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
data = hass.data[MY_KEY]
reveal_type(data) # MyData
async_add_entities([MySwitch(data.client)])
```
Storing data in a dict by `entry.entry_id`? It's often better to just store it inside the `ConfigEntry` directly. See the recent [blog post](/blog/2024/04/30/store-runtime-data-inside-config-entry) about it. If that isn't an option, use `HassEntryKey`.
```py
# <integration>/__init__.py
from homeassistant.util.hass_dict import HassEntryKey
MY_KEY: HassEntryKey["MyData"] = HassEntryKey(DOMAIN)
async def async_setup_entry(
hass: HomeAssistant,
entry: ConfigEntry,
) -> bool:
client = MyClient(...)
hass.data.setdefault(MY_KEY, {})[entry.entry_id] = MyData(client, {...})
```

View File

@ -0,0 +1,20 @@
---
author: Jan Bouwhuis
authorURL: https://github.com/jbouwh
authorImageURL: https://avatars.githubusercontent.com/u/7188918?s=96&v=4
title: Second phase of notify entity platform implementation
---
### Title option for send_message service notify entity platform
Recently we added the notify [entity platform](https://developers.home-assistant.io/docs/core/entity/notify/). The new `notify` platform method implements service `send_message`. This service now also accepts an optional `title` as an argument. This allows some new integrations that can be migrated now to use the new entity platform:
- cisco_webex_teams
- file
- sendgrid
- syslog
- tibber
The [architecture discussion](https://github.com/home-assistant/architecture/discussions/1041) is still ongoing.
When integrations are migrated, users will need to use the new `notify.send_message` service, so the migration changes will cause automations to break after the deprecation period is over.

View File

@ -0,0 +1,53 @@
---
author: Robert Resch
authorURL: https://github.com/edenhaus
authorImageURL: https://avatars.githubusercontent.com/u/26537646?s=96&v=4
title: "How we managed to speed up our CI to save 168+ days of execution time per month"
---
We got a taste for speed after [UV gave us back 215 compute hours a month](2024-04-03-build-images-with-uv.md).
Our CI workflow gets triggered on each commit, and due to the high volume of contributions, it was triggered 6647 times in March 2024.
The full runs, where the whole test suite is being executed, take a long time.
It turned out that the plugin, we used to split the tests into 10 groups, was inefficient. Each pytest job needed to discover all tests, even when the job intended to only execute a subset of them.
Now we have a separate job to discover all tests and split them into 10 groups. The 10 pytest jobs only need to execute a subset of all tests. Not doing full-discovery in each test runner saves us 3 hours on each full run!
```mermaid
flowchart LR
A[Full run] --> R{Distribute work}
R -->|One| D[Discover tests to run]
R -->|Two| E[Discover tests to run]
R -->|Three| F[Discover tests to run]
D --> D2[Run tests]
E --> E2[Run tests]
F --> F2[Run tests]
AN[Full run] --> RW[Discover tests to run]
RW --> RN{Distribute work}
RN -->|One| D2N[Run tests]
RN -->|Two| E2N[Run tests]
RN -->|Three| F2N[Run tests]
```
A short analysis of the 6647 CI workflows in March 2024 revealed the following stats:
- 2406 were canceled before termination
- 1771 should be full runs
- 1085 failed
- 732 where failed full runs
- 3007 terminated successfully
- 1629 partial runs (only tests for a given integration where executed)
- 1378 full runs
Considering the 1378 successful full runs, we would have saved around **4042 hours ~ 168 days** of execution time in March 2024 with [#114381](https://github.com/home-assistant/core/pull/114381). Even more, if I had also analyzed the failed/canceled ones.
The more than 168 monthly saved execution days can be used by other jobs and make the CI experience for all developers and our community better.
We improved our sustainability by using fewer resources to run our test suite.
**A big thank you to GitHub for providing Home Assistant with additional CI runners.**

View File

@ -0,0 +1,94 @@
---
author: Jan Bouwhuis
authorURL: https://github.com/jbouwh
authorImageURL: https://avatars.githubusercontent.com/u/7188918?s=96&v=4
title: Changes in setup entity platforms with group integration
---
## Changes in setup entity platforms with group integration
By default, the `group` integration allows entities to be grouped. If the default `ON`/`OFF` states for an entity default to `on` and `off`, then `grouping` is supported by default. The setup changes, though, for Entity platforms that can be grouped but have alternative states, e.g., `cover` (`open`/`closed`) or `person` (`home`/`not_home`), or platforms that are meant to be excluded, such as `sensor`. These entity platforms must implement `async_describe_on_off_states` in the `group.py` module.
In `async_describe_on_off_states`, the `domain` needs to be the first argument passed to the `registry` methods `on_off_states` and `exclude_domain`. When registering alternative `ON`/`OFF` states with `registry.on_off_state`, in addition to the `ON` states, the default `ON` state needs to be passed.
### Example registering alternative states
New signature for `registry.on_off_states`:
```python
@callback
def on_off_states(
self, domain: str, on_states: set[str], default_on_state:str, off_state: str
) -> None:
"""Register on and off states for the current domain."""
...
```
Example `group.py` for the `vacuum` entity platform registering alternative `ON`/`OFF` states. Note the the first `ON` state now is considered to be the default `ON` state.
```python
"""Describe group states."""
from typing import TYPE_CHECKING
from homeassistant.const import STATE_OFF, STATE_ON
from homeassistant.core import HomeAssistant, callback
if TYPE_CHECKING:
from homeassistant.components.group import GroupIntegrationRegistry
from .const import DOMAIN, STATE_CLEANING, STATE_ERROR, STATE_RETURNING
@callback
def async_describe_on_off_states(
hass: HomeAssistant, registry: "GroupIntegrationRegistry"
) -> None:
"""Describe group on off states."""
registry.on_off_states(
DOMAIN, # domain
# set with all group ON states
{
STATE_ON,
STATE_CLEANING,
STATE_RETURNING,
STATE_ERROR,
},
STATE_ON, # Default group ON state
STATE_OFF, # Group OFF state
)
```
### Example excluding an entity platform from group entities
New signature for `registry.exclude_domain`:
```python
@callback
def exclude_domain(self, domain: str) -> None:
"""Exclude the current domain."""
...
```
Example `group.py` for the `sensor` entity platform to exclude sensor entities from `group` entities.
```python
"""Describe group states."""
from typing import TYPE_CHECKING
from homeassistant.core import HomeAssistant, callback
if TYPE_CHECKING:
from homeassistant.components.group import GroupIntegrationRegistry
from .const import DOMAIN
@callback
def async_describe_on_off_states(
hass: HomeAssistant, registry: "GroupIntegrationRegistry"
) -> None:
"""Describe group on off states."""
registry.exclude_domain(DOMAIN)
```

View File

@ -0,0 +1,33 @@
---
author: G Johansson
authorURL: https://github.com/gjohansson-ST
title: "LockEntity supports open/opening state"
---
Recently we have added an `open` and `opening` state to `LockEntity`
This is useful if you have locks which can differentiate between `unlocked` (not locked but latched) state and `open` (unlocked and latch withdrawn) state.
`LockEntity` already supports the [`open` method](/docs/core/entity/lock#open) by implementing the feature flag `LockEntityFeature.OPEN`
Example (default implementation):
```python
class MyLock(LockEntity):
@property
def is_opening(self) -> bool:
"""Return true if lock is open."""
return self._state == STATE_OPENING
@property
def is_open(self) -> bool:
"""Return true if lock is open."""
return self._state == STATE_OPEN
async def async_open(self, **kwargs: Any) -> None:
"""Open the door latch."""
self._state = STATE_OPEN
self.async_write_ha_state()
```

View File

@ -0,0 +1,15 @@
---
author: J. Nick Koston
authorURL: https://github.com/bdraco
title: Handling time zones without blocking the event loop
---
Constructing `ZoneInfo` objects may do blocking I/O to load the zone info from disk if the timezone passed is not in the cache.
`dt_util.async_get_time_zone` is now available to replace `dt_util.get_time_zone` to fetch a time zone in the event loop which is async safe and will not do blocking I/O in the event loop.
`hass.config.set_time_zone` is deprecated and replaced with `hass.config.async_set_time_zone`. `hass.config.set_time_zone` will be removed in 2025.6. Setting the time zone only affects tests, as no integration should be calling this function in production.
Examining `dt_util.DEFAULT_TIME_ZONE` directly is deprecated and `dt_util.get_default_time_zone()` should be used instead.
If your integration needs to construct `ZoneInfo` objects in the event loop, it is recommended to use the [`aiozoneinfo` library](https://pypi.org/project/aiozoneinfo/).

View File

@ -0,0 +1,17 @@
---
author: Paulus Schoutsen
authorURL: https://github.com/balloob
authorImageURL: /img/profile/paulus.jpg
authorTwitter: balloob
title: Exposing Home Assistant API to LLMs
---
Since we introduced LLMs in Home Assistant as part of Year of the Voice, we have received the request to allow enabling LLMs to interact with Home Assistant. This is now possible by exposing a Home Assistant API to LLMs.
Home Assistant will come with a built-in Assist API, which follows the capabilities and exposed entities that are also accessible to the built-in conversation agent.
Integrations that interact with LLMs should update their integration to support LLM APIs.
Custom integration authors can create their own LLM APIs to offer LLMs more advanced access to Home Assistant.
See the [LLM API documentation](/docs/core/llm) for more information and [this example pull request](https://github.com/home-assistant/core/pull/117644) on how to integrate the LLM API in your integration.

View File

@ -0,0 +1,11 @@
---
author: G Johansson
authorURL: https://github.com/gjohansson-ST
title: Alarm Control Panel Entity code validation
---
The `AlarmControlPanelEntity` is now enforcing validation of code for alarm control panel entities, which set `code_arm_required` to `True` (default behavior). Service calls fail if no code is provided when a code is required.
Previously this was entirely optional, and a user could skip code entry regardless of it was needed by the integration or not (and as such each integration needed to implement its own check).
As the default behavior is that code is required, custom integrations that don't require a code input need to set `code_arm_required` to `False` or the user will always have to input a code regardless of if it's needed by the service calls.

View File

@ -0,0 +1,9 @@
---
author: J. Nick Koston
authorURL: https://github.com/bdraco
title: Forwarding setup to config entry platforms
---
Calling `hass.config_entries.async_forward_entry_setup` is deprecated and will be removed in Home Assistant 2025.6. Instead, await `hass.config_entries.async_forward_entry_setups` as it can load multiple platforms at once and is more efficient since it does not require a separate import executor job for each platform.
`hass.config_entries.async_forward_entry_setups` must always be awaited if it's called while the config entry is being set up to ensure that it finishes before the config entry setup is complete. For more details, review [this blog post](https://developers.home-assistant.io/blog/2022/07/08/config_entry_forwards).

View File

@ -0,0 +1,32 @@
---
author: J. Nick Koston
authorURL: https://github.com/bdraco
title: Making http path registration async safe with `async_register_static_paths`
---
`hass.http.register_static_path` is deprecated because it does blocking I/O in the event loop, instead call `await hass.http.async_register_static_paths([StaticPathConfig(url_path, path, cache_headers)])`
The arguments to `async_register_static_paths` are the same as `register_static_path` except they are wrapped in the `StaticPathConfig` `dataclass` and an `Iterable` of them is accepted to allow registering multiple paths at once to avoid multiple executor jobs.
For example, if your integration called `hass.http.register_static_path("/integrations/photos", "/config/photos", True)`, it should now call `await hass.http.async_register_static_paths([StaticPathConfig("/integrations/photos", "/config/photos", True)])`
The `StaticPathConfig` `dataclass` should be imported from `homeassistant.components.http`
`hass.http.register_static_path` will be removed in 2025.7
## Example
```python
from pathlib import Path
from homeassistant.components.http import StaticPathConfig
should_cache = False
files_path = Path(__file__).parent / "static"
files2_path = Path(__file__).parent / "static2"
await hass.http.async_register_static_paths([
StaticPathConfig("/api/my_integration/static", str(files_path), should_cache),
StaticPathConfig("/api/my_integration/static2", str(files2_path), should_cache)
])
```

View File

@ -0,0 +1,25 @@
---
author: G Johansson
authorURL: https://github.com/gjohansson-ST
title: "Excluding all state attributes from recording using MATCH_ALL"
---
The way how state attributes are excluded from the recording was previously changed in September 2023.
The previous implementation was limited as there was no way to handle dynamic attributes or any easy way to simply exclude all attributes instead of listing them individually.
It is now possible within an integration to tell recording to not record any attribute by using the `MATCH_ALL` constant, which will automatically remove all attributes from recording except `device_class`, `state_class`, `unit_of_measurement`, and `friendly_name.`
```python
from homeassistant.const import MATCH_ALL
class ExampleEntity(Entity):
"""Implementation of an entity."""
_unrecorded_attributes = frozenset({MATCH_ALL})
```
More details can be found in the [entity documentation](/docs/core/entity#excluding-state-attributes-from-recorder-history).
Background for the original change is in [architecture discussion #964](https://github.com/home-assistant/architecture/discussions/964).

View File

@ -0,0 +1,27 @@
---
author: G Johansson
authorURL: https://github.com/gjohansson-ST
title: "New HVACAction DEFROSTING"
---
The `ClimateEntity` has an `hvac_action` property, which describes what the climate entity is currently doing (which is not the same as its mode).
We have added `DEFROSTING` as a possible `HVACAction` to represent when an entity is currently defrosting.
Defrosting is when the system runs in reverse for some time to melt down accumulated ice. It occurs typically in colder environments and should not be mixed with, for example, cars that are defrosting by heating their windows.
```python
from homeassistant.components.climate.const import HVACAction
class MyClimateEntity(ClimateEntity):
"""Implementation of my climate entity."""
def hvac_action(self) -> HVACAction | None:
"""Return the current running hvac operation if supported."""
return HVACAction.DEFROSTING
```
More details can be found in the [climate entity documentation](/docs/core/entity/climate#hvac-action)
Background for the original change is in [architecture discussion #1090](https://github.com/home-assistant/architecture/discussions/1090).

View File

@ -0,0 +1,10 @@
---
author: Joost Lekkerkerker
authorURL: https://github.com/joostlek
authorImageURL: https://avatars.githubusercontent.com/u/7083755?v=4
title: "model_id added to DeviceInfo"
---
Starting from 2024.8, you can now add a model identifier to the `DeviceInfo` class. This identifier can be used to identify the device model in integrations and the frontend.
For example, the Philips Hue ambiance spot was previously listed as "Hue ambiance spot (LTG002)". This can now be split up, where the `model` is "Hue ambiance spot" and the `model_id` is "LTG002".

View File

@ -0,0 +1,17 @@
---
author: Franck Nijhof
authorURL: https://twitter.com/frenck
authorImageURL: /img/profile/frenck.png
authorTwitter: frenck
title: Services are now actions
---
The term "Services" has been a source of confusion for many users, as it is not immediately clear what it refers to; it could be a web or STT service, but in the context of Home Assistant, it means something entirely different (service calls).
In Home Assistant 2024.8, "Services" (as in service calls) will be renamed to "Actions". This change is part of our ongoing effort to make Home Assistant more user-friendly and easier for new users to understand. The term fits in with the UI changes we have been implementing over the past months (call services no longer exist in our automations and script editors). Effectively, one is performing actions in one's automations.
This change will be reflected in the Home Assistant UI, documentation, and other places where the term "Services" is used. For example, the **"Services"** tab in the Developer Tools will be renamed to **"Actions"**.
For developers, there is no need to worry about this change. In the developer documentation, we will update all references to "services" to "service actions", as we have different types of actions in our backend (for example, device actions). The underlying functionality will remain the same, and the transition is seamless.
This is, just like the end-user change, a terminology change only.

View File

@ -0,0 +1,17 @@
---
author: G Johansson
authorURL: https://github.com/gjohansson-ST
title: "New entity feature flags in FanEntity"
---
As of Home Assistant Core 2024.8, we have added two new flags to `FanEntityFeature`: `TURN_ON`, `TURN_OFF`.
Integrations implementing the `turn_on` service call need to set the `TURN_ON` feature flag.
Integrations implementing the `turn_off` service call need to set the `TURN_OFF` feature flag.
There will be a 6-month deprecation period (2025.2) during which `FanEntity` will set these on behalf of the integrations implementing the respective methods. From 2025.2, integrations will be unable to use the respective methods if entity features have not been set accordingly.
Implementing the methods without setting the respective feature flag, will create a warning log entry guiding the user to create an issue for the integration.
Integrations should set the attribute `_enable_turn_on_off_backwards_compatibility` in your `FanEntity` subclass instance to `False` once it has been migrated into using or not using the new feature flags.
This will stop the automatic setting of the new feature flags during the deprecation period, and should be removed once deprecation has ended.

View File

@ -0,0 +1,40 @@
---
author: G Johansson
authorURL: https://github.com/gjohansson-ST
authorImageURL: https://avatars.githubusercontent.com/u/62932417?v=4
authorTwitter: GJohansson
title: "Climate entity now validates temperature provided in action calls"
---
As of Home Assistant Core 2024.8, we have implemented validation for the temperature action call provided by the `ClimateEntity`.
Integrations no longer need to check this within their own set temperature methods (`async_set_temperature`/`set_temperature`).
However, it's important that integrations specify the `min_temp` and `max_temp` properties correctly, or the user might not be able to set their correct temperature if validation fails.
Likewise, integrations that handle devices which can operate on both `Celsius` and `Fahrenheit` need to convert their respective `min_temp` and `max_temp` values accordingly.
### Example
Converts a device's native min/max value into the temperature_unit specified by the integration.
```python
class MyClimateEntity(ClimateEntity):
"""Implementation of my climate entity."""
@property
def min_temp(self) -> float:
"""Return the minimum temperature."""
return TemperatureConverter.convert(
self.device.min_temp, UnitOfTemperature.CELSIUS, self.temperature_unit
)
@property
def max_temp(self) -> float:
"""Return the maximum temperature."""
return TemperatureConverter.convert(
self.device.max_temp, UnitOfTemperature.CELSIUS, self.temperature_unit
)
```

View File

@ -1,5 +1,5 @@
--- ---
title: "Add-On Communication" title: "Add-on communication"
--- ---
There are different ways of communicating between add-ons inside Home Assistant. There are different ways of communicating between add-ons inside Home Assistant.
@ -9,13 +9,13 @@ There are different ways of communicating between add-ons inside Home Assistant.
We use an internal network that's allowed to communicate with every add-on, including to/from Home Assistant, by using its name or alias. Only add-ons that run on the host network are limited in that they can talk with all internal add-ons by their name, but all other add-ons can't address these add-ons by name. However, using an alias works for both! We use an internal network that's allowed to communicate with every add-on, including to/from Home Assistant, by using its name or alias. Only add-ons that run on the host network are limited in that they can talk with all internal add-ons by their name, but all other add-ons can't address these add-ons by name. However, using an alias works for both!
Names/aliases are used for communication inside Home Assistant. Names/aliases are used for communication inside Home Assistant.
The name is generated using the following format: `{REPO}_{SLUG}`, e.g., `local_xy` or `3283fh_myaddon`. In this example, `{SLUG}` is defined in an add-on's `config.yaml` file. You can use this name as the DNS name also, but you need to replace any `_` with `-` to have a valid hostname. If an add-on is installed locally, `{REPO}` will be `local`. If the add-on is installed from a Github repository, `{REPO}` is a hashed identifier generated from the GitHub repository's URL (ex: `https://github.com/xy/my_hassio_addons`). See [here](https://github.com/home-assistant/supervisor/blob/4ac7f7dcf08abb6ae5a018536e57d078ace046c8/supervisor/store/utils.py#L17) to understand how this identifier is generated. Note that this identifier is required in certain service calls that use the [Supervisor add-on API][supervisor-addon-api]. You can view the repository identifiers for all currently installed add-ons via a GET request to the Supervisor API `addons` endpoint. The name is generated using the following format: `{REPO}_{SLUG}`, e.g., `local_xy` or `3283fh_myaddon`. In this example, `{SLUG}` is defined in an add-on's `config.yaml` file. You can use this name as the DNS name also, but you need to replace any `_` with `-` to have a valid hostname. If an add-on is installed locally, `{REPO}` will be `local`. If the add-on is installed from a Github repository, `{REPO}` is a hashed identifier generated from the GitHub repository's URL (ex: `https://github.com/xy/my_hassio_addons`). See [here](https://github.com/home-assistant/supervisor/blob/4ac7f7dcf08abb6ae5a018536e57d078ace046c8/supervisor/store/utils.py#L17) to understand how this identifier is generated. Note that this identifier is required in certain actions that use the [Supervisor add-on API][supervisor-addon-api]. You can view the repository identifiers for all currently installed add-ons via a GET request to the Supervisor API `addons` endpoint.
Use `supervisor` for communication with the internal API. Use `supervisor` for communication with the internal API.
## Home Assistant Core ## Home Assistant Core
An add-on can talk to the [Home Assistant Core API][core-api] using the internal proxy. This makes it very easy to communicate with the API without knowing the password, port or any other information about the Home Assistant instance. Using this URL: `http://supervisor/core/api` ensures that internal communication is redirected to the right place. The next step is to add `homeassistant_api: true` to the `config.yaml` file and read the environment variable `SUPERVISOR_TOKEN`. Use this as the Home Assistant Core [bearer token](/auth_api.md#making-authenticated-requests) when making requests. An add-on can talk to the [Home Assistant Core API][core-api] using the internal proxy. This makes it very easy to communicate with the API without knowing the password, port or any other information about the Home Assistant instance. Using this URL: `http://supervisor/core/api/` ensures that internal communication is redirected to the right place. The next step is to add `homeassistant_api: true` to the `config.yaml` file and read the environment variable `SUPERVISOR_TOKEN`. Use this as the Home Assistant Core [bearer token](/auth_api.md#making-authenticated-requests) when making requests.
For example `curl -X GET -H "Authorization: Bearer ${SUPERVISOR_TOKEN}" -H "Content-Type: application/json" http://supervisor/core/api/config` For example `curl -X GET -H "Authorization: Bearer ${SUPERVISOR_TOKEN}" -H "Content-Type: application/json" http://supervisor/core/api/config`
@ -23,7 +23,7 @@ There is also a proxy for the [Home Assistant Websocket API][core-websocket] tha
It is also possible to talk directly to the Home Assistant instance, which is named `homeassistant`, over the internal network. However, you'll need to know the configuration that is used by the running instance. It is also possible to talk directly to the Home Assistant instance, which is named `homeassistant`, over the internal network. However, you'll need to know the configuration that is used by the running instance.
We have several services inside Home Assistant to run tasks. Send data over STDIN to an add-on to use the `hassio.addon_stdin` service. We have several actions inside Home Assistant to run tasks. Send data over STDIN to an add-on to use the `hassio.addon_stdin` action.
## Supervisor API ## Supervisor API

View File

@ -1,5 +1,5 @@
--- ---
title: "Add-On Configuration" title: "Add-on configuration"
--- ---
Each add-on is stored in a folder. The file structure looks like this: Each add-on is stored in a folder. The file structure looks like this:
@ -84,7 +84,7 @@ LABEL \
It is possible to use your own base image with `build.yaml` or if you do not need support for automatic multi-arch building you can also use a simple docker `FROM`. You can also suffix the Dockerfile with the specific architecture to use a specific Dockerfile for a particular architecture, i.e. `Dockerfile.amd64`. It is possible to use your own base image with `build.yaml` or if you do not need support for automatic multi-arch building you can also use a simple docker `FROM`. You can also suffix the Dockerfile with the specific architecture to use a specific Dockerfile for a particular architecture, i.e. `Dockerfile.amd64`.
### Build Args ### Build args
We support the following build arguments by default: We support the following build arguments by default:
@ -110,8 +110,12 @@ url: "website with more information about the add-on (e.g., a forum thread for s
ports: ports:
123/tcp: 123 123/tcp: 123
map: map:
- config:rw - type: share
- ssl read_only: False
- type: ssl
- type: homeassistant_config
read_only: False
path: /custom/config/path
image: repo/{arch}-my-custom-addon image: repo/{arch}-my-custom-addon
``` ```
@ -154,7 +158,7 @@ Avoid using `config.yaml` as filename in your add-on for anything other than the
| `privileged` | list | | Privilege for access to hardware/system. Available access: `BPF`, `DAC_READ_SEARCH`, `IPC_LOCK`, `NET_ADMIN`, `NET_RAW`, `PERFMON`, `SYS_ADMIN`, `SYS_MODULE`, `SYS_NICE`, `SYS_PTRACE`, `SYS_RAWIO`, `SYS_RESOURCE` or `SYS_TIME`. | `privileged` | list | | Privilege for access to hardware/system. Available access: `BPF`, `DAC_READ_SEARCH`, `IPC_LOCK`, `NET_ADMIN`, `NET_RAW`, `PERFMON`, `SYS_ADMIN`, `SYS_MODULE`, `SYS_NICE`, `SYS_PTRACE`, `SYS_RAWIO`, `SYS_RESOURCE` or `SYS_TIME`.
| `full_access` | bool | `false` | Give full access to hardware like the privileged mode in Docker. Works only for not protected add-ons. Consider using other add-on options instead of this, like `devices`. If you enable this option, don't add `devices`, `uart`, `usb` or `gpio` as this is not needed. | `full_access` | bool | `false` | Give full access to hardware like the privileged mode in Docker. Works only for not protected add-ons. Consider using other add-on options instead of this, like `devices`. If you enable this option, don't add `devices`, `uart`, `usb` or `gpio` as this is not needed.
| `apparmor` | bool/string | `false` | Enable or disable AppArmor support. If it is enabled, you can also use custom profiles with the name of the profile. | `apparmor` | bool/string | `false` | Enable or disable AppArmor support. If it is enabled, you can also use custom profiles with the name of the profile.
| `map` | list | | List of Home Assistant directories to bind mount into your container. Possible values: `homeassistant_config`, `addon_config`, `ssl`, `addons`, `backup`, `share`, `media`, and `all_addon_configs`. Defaults to `ro`, which you can change by adding `:rw` to the end of the name. | `map` | list | | List of Home Assistant directory types to bind mount into your container. Possible values: `homeassistant_config`, `addon_config`, `ssl`, `addons`, `backup`, `share`, `media`, `all_addon_configs`, and `data`. Defaults to read-only, which you can change by adding the property `read_only: false`. By default, all paths map to `/<type-name>` inside the addon container, but an optional `path` property can also be supplied to configure the path (Example: `path: /custom/config/path`). If used, the path must not be empty, unique from any other path defined for the addon, and not the root path. Note that the `data` directory is always mapped and writable, but the `path` property can be set using the same conventions.
| `environment` | dict | | A dictionary of environment variables to run the add-on with. | `environment` | dict | | A dictionary of environment variables to run the add-on with.
| `audio` | bool | `false` | Mark this add-on to use the internal audio system. We map a working PulseAudio setup into the container. If your application does not support PulseAudio, you may need to install: Alpine Linux `alsa-plugins-pulse` or Debian/Ubuntu `libasound2-plugins`. | `audio` | bool | `false` | Mark this add-on to use the internal audio system. We map a working PulseAudio setup into the container. If your application does not support PulseAudio, you may need to install: Alpine Linux `alsa-plugins-pulse` or Debian/Ubuntu `libasound2-plugins`.
| `video` | bool | `false` | Mark this add-on to use the internal video system. All available devices will be mapped into the add-on. | `video` | bool | `false` | Mark this add-on to use the internal video system. All available devices will be mapped into the add-on.
@ -196,7 +200,9 @@ Avoid using `config.yaml` as filename in your add-on for anything other than the
### Options / Schema ### Options / Schema
The `options` dictionary contains all available options and their default value. Set the default value to `null` if the value is required to be given by the user before the add-on can start. Nested arrays and dictionaries are supported with a maximum depth of two. To make an option optional, put `?` at the end of the data type, otherwise it will be a required value. The `options` dictionary contains all available options and their default value. Set the default value to `null` or define the data type in the `schema` dictionary to make an option mandatory. This way the option needs to be given by the user before the add-on can start. Nested arrays and dictionaries are supported with a maximum depth of two.
To make an option truly optional (without default value), the `schema` dictionary needs to be used. Put a `?` at the end of the data type and *do not* define any default value in the `options` dictionary. If any default value is given, the option becomes a required value.
```yaml ```yaml
message: "custom things" message: "custom things"

View File

@ -152,8 +152,7 @@ Ingress API gateway supports the following:
- Streaming content - Streaming content
- Websockets - Websockets
## Basic ingress example with Nginx
## Basic Ingress Example with Nginx
The following is a basic ingress implementation with an Nginx server. This contains an example`Dockerfile`, `config.yaml`, and `ingress.conf` configuration. The following is a basic ingress implementation with an Nginx server. This contains an example`Dockerfile`, `config.yaml`, and `ingress.conf` configuration.

View File

@ -30,7 +30,7 @@ You can use `{arch}` inside the image name to support multiple architectures wit
Home Assistant assumes that the default branch of your add-on repository matches the latest tag on the container registry. When you're building a new version, it's suggested that you use another branch, ie `build` or do it with a PR on GitHub. After you push the add-on to a container registry, you can merge this branch to master. Home Assistant assumes that the default branch of your add-on repository matches the latest tag on the container registry. When you're building a new version, it's suggested that you use another branch, ie `build` or do it with a PR on GitHub. After you push the add-on to a container registry, you can merge this branch to master.
## Custom Add-ons ## Custom add-ons
You need a Docker Hub account to make your own add-ons. You can build your container images with the Docker `build` command or use our [builder] to simplify the process. Pull our [Builder Docker engine][builder] and run one of the following commands. You need a Docker Hub account to make your own add-ons. You can build your container images with the Docker `build` command or use our [builder] to simplify the process. Pull our [Builder Docker engine][builder] and run one of the following commands.
@ -41,7 +41,7 @@ docker run \
--rm \ --rm \
--privileged \ --privileged \
-v ~/.docker:/root/.docker \ -v ~/.docker:/root/.docker \
homeassistant/amd64-builder \ ghcr.io/home-assistant/amd64-builder \
--all \ --all \
-t addon-folder \ -t addon-folder \
-r https://github.com/xy/addons \ -r https://github.com/xy/addons \
@ -56,7 +56,7 @@ docker run \
--privileged \ --privileged \
-v ~/.docker:/root/.docker \ -v ~/.docker:/root/.docker \
-v /my_addon:/data \ -v /my_addon:/data \
homeassistant/amd64-builder \ ghcr.io/home-assistant/amd64-builder \
--all \ --all \
-t /data -t /data
``` ```

View File

@ -4,11 +4,11 @@ title: "Add-on security"
Home Assistant rates every add-on based on the wanted rights. An add-on with a rating of 6 is very secure. If an add-on has a rating of 1, you shouldn't run this add-on unless you are 100% sure that you can trust the source. Home Assistant rates every add-on based on the wanted rights. An add-on with a rating of 6 is very secure. If an add-on has a rating of 1, you shouldn't run this add-on unless you are 100% sure that you can trust the source.
## API Role ## API role
For access to the Supervisor API you need to define a role or run in default mode. This is only required for the Supervisor API and not the Home Assistant proxy. All of the roles already have access to the default API calls, and do not require any additional settings. For access to the Supervisor API you need to define a role or run in default mode. This is only required for the Supervisor API and not the Home Assistant proxy. All of the roles already have access to the default API calls, and do not require any additional settings.
### Available Roles ### Available roles
| Role | Description | | Role | Description |
|------|-------------| |------|-------------|
@ -36,7 +36,7 @@ As a developer, follow the following best practices to make your add-on secure:
- If you need any API access, make sure that you do not grant permission that aren't needed - If you need any API access, make sure that you do not grant permission that aren't needed
- Sign the image with [Codenotary CAS](https://cas.codenotary.com/) - Sign the image with [Codenotary CAS](https://cas.codenotary.com/)
## Use Home Assistant User backend ## Use Home Assistant user backend
Instead of allowing users to set new login credentials in plain text config, use the Home Assistant [Auth backend](/docs/api/supervisor/endpoints#auth). You can enable the access to the API with `auth_api: true`. Now you are able to send the login credentials to the auth backend and validate them in Home Assistant. Instead of allowing users to set new login credentials in plain text config, use the Home Assistant [Auth backend](/docs/api/supervisor/endpoints#auth). You can enable the access to the API with `auth_api: true`. Now you are able to send the login credentials to the auth backend and validate them in Home Assistant.

View File

@ -32,7 +32,7 @@ docker run \
--privileged \ --privileged \
-v /path/to/addon:/data \ -v /path/to/addon:/data \
-v /var/run/docker.sock:/var/run/docker.sock:ro \ -v /var/run/docker.sock:/var/run/docker.sock:ro \
homeassistant/amd64-builder \ ghcr.io/home-assistant/amd64-builder \
-t /data \ -t /data \
--all \ --all \
--test \ --test \

View File

@ -1,5 +1,5 @@
--- ---
title: "Native App Integration" title: "Native app integration"
sidebar_label: "Introduction" sidebar_label: "Introduction"
--- ---
@ -7,5 +7,5 @@ This guide describes how to build a native Home Assistant app that communicates
- Allow the user to establish a connection and authenticate with their own Home Assistant instance. - Allow the user to establish a connection and authenticate with their own Home Assistant instance.
- Send location and device info back to Home Assistant. - Send location and device info back to Home Assistant.
- Call services, fire events and render templates. - Call service actions, fire events and render templates.
- A view to control the house via an authenticated webview. - A view to control the house via an authenticated webview.

View File

@ -1,5 +1,5 @@
--- ---
title: "Push Notifications" title: "Push notifications"
--- ---
The `mobile_app` integration has a notify platform built in that allows for a generic way to send push notifications to your users without requiring installation of an external custom component. Push notifications can either be delivered via a websocket connection or via a cloud service. The `mobile_app` integration has a notify platform built in that allows for a generic way to send push notifications to your users without requiring installation of an external custom component. Push notifications can either be delivered via a websocket connection or via a cloud service.

View File

@ -151,9 +151,9 @@ This message will inform Home Assistant of new location information.
| `course` | int | The direction in which the device is traveling, measured in degrees and relative to due north. Must be greater than 0. | `course` | int | The direction in which the device is traveling, measured in degrees and relative to due north. Must be greater than 0.
| `vertical_accuracy` | int | The accuracy of the altitude value, measured in meters. Must be greater than 0. | `vertical_accuracy` | int | The accuracy of the altitude value, measured in meters. Must be greater than 0.
## Call a service ## Call a service action
Call a service in Home Assistant. Call a service action in Home Assistant.
```json ```json
{ {
@ -170,9 +170,9 @@ Call a service in Home Assistant.
| Key | Type | Description | Key | Type | Description
| --- | ---- | ----------- | --- | ---- | -----------
| `domain` | string | The domain of the service | `domain` | string | The domain of the service action
| `service` | string | The service name | `service` | string | The service action name
| `service_data` | dict | The data to send to the service | `service_data` | dict | The data to send to the service action
## Fire an event ## Fire an event
@ -289,7 +289,7 @@ There are two errors you may receive:
- `encryption_already_enabled` - Encryption is already enabled for this registration - `encryption_already_enabled` - Encryption is already enabled for this registration
- `encryption_not_available` - Sodium/NaCL is unable to be installed. Cease all future attempts to enable encryption. - `encryption_not_available` - Sodium/NaCL is unable to be installed. Cease all future attempts to enable encryption.
## Stream Camera ## Stream camera
_This requires Home Assistant 0.112 or later._ _This requires Home Assistant 0.112 or later._
@ -320,7 +320,7 @@ The response will include paths for streaming either via HLS or via MJPEG image
If HLS streaming is not available, the `hls_path` will be `null`. See notes above on instance URL for how to construct a full URL. If HLS streaming is not available, the `hls_path` will be `null`. See notes above on instance URL for how to construct a full URL.
## Process Conversation ## Process conversation
_This requires Home Assistant 2023.2.0 or later._ _This requires Home Assistant 2023.2.0 or later._

View File

@ -21,7 +21,7 @@ Home Assistant has a `mobile_app` component that allows applications to register
Once you have tokens to authenticate as a user, it's time to register the app with the mobile app integration in Home Assistant. Once you have tokens to authenticate as a user, it's time to register the app with the mobile app integration in Home Assistant.
### Getting Ready ### Getting ready
First, you must ensure that the `mobile_app` integration is loaded. There are two ways to do this: First, you must ensure that the `mobile_app` integration is loaded. There are two ways to do this:

View File

@ -1,5 +1,5 @@
--- ---
title: "Authenticated Webview" title: "Authenticated WebView"
--- ---
Your application already asked the user to authenticate. This means that your app should not ask the user to authenticate again when they open the Home Assistant UI. Your application already asked the user to authenticate. This means that your app should not ask the user to authenticate again when they open the Home Assistant UI.

View File

@ -10,7 +10,7 @@ The token is available for add-ons and Home Assistant using the
To see more details about each endpoint, click on it to expand it. To see more details about each endpoint, click on it to expand it.
### Addons ### Add-ons
<ApiEndpoint path="/addons" method="get"> <ApiEndpoint path="/addons" method="get">
Return overview information about installed add-ons. Return overview information about installed add-ons.
@ -63,7 +63,35 @@ Get the documentation for an add-on.
</ApiEndpoint> </ApiEndpoint>
<ApiEndpoint path="/addons/<addon>/logs" method="get"> <ApiEndpoint path="/addons/<addon>/logs" method="get">
Returns the raw container logs from docker.
Get logs for an add-on via the Systemd journal backend.
The endpoint accepts the same headers and provides the same functionality as
`/host/logs`.
</ApiEndpoint>
<ApiEndpoint path="/addons/<addon>/logs/follow" method="get">
Identical to `/addons/<addon>/logs` except it continuously returns new log entries.
</ApiEndpoint>
<ApiEndpoint path="/addons/<addon>/logs/boots/<bootid>" method="get">
Get logs for an add-on related to a specific boot.
The `bootid` parameter is interpreted in the same way as in
`/host/logs/boots/<bootid>` and the endpoint otherwise provides the same
functionality as `/host/logs`.
</ApiEndpoint>
<ApiEndpoint path="/addons/<addon>/logs/boots/<bootid>/follow" method="get">
Identical to `/addons/<addon>/logs/boots/<bootid>` except it continuously returns
new log entries.
</ApiEndpoint> </ApiEndpoint>
<ApiEndpoint path="/addons/<addon>/icon" method="get"> <ApiEndpoint path="/addons/<addon>/icon" method="get">
@ -87,7 +115,7 @@ Get details about an add-on
| auto_uart | boolean | `true` if auto_uart access is granted is enabled | | auto_uart | boolean | `true` if auto_uart access is granted is enabled |
| auto_update | boolean | `true` if auto update is enabled | | auto_update | boolean | `true` if auto update is enabled |
| available | boolean | `true` if the add-on is available | | available | boolean | `true` if the add-on is available |
| boot | string | "boot" or "manual" | | boot | string | "auto" or "manual" |
| build | boolean | `true` if local add-on | | build | boolean | `true` if local add-on |
| changelog | boolean | `true` if changelog is available | | changelog | boolean | `true` if changelog is available |
| description | string | The add-on description | | description | string | The add-on description |
@ -503,7 +531,35 @@ Return information about the audio plugin.
</ApiEndpoint> </ApiEndpoint>
<ApiEndpoint path="/audio/logs" method="get"> <ApiEndpoint path="/audio/logs" method="get">
Returns the raw container logs from docker.
Get logs for the audio plugin container via the Systemd journal backend.
The endpoint accepts the same headers and provides the same functionality as
`/host/logs`.
</ApiEndpoint>
<ApiEndpoint path="/audio/logs/follow" method="get">
Identical to `/audio/logs` except it continuously returns new log entries.
</ApiEndpoint>
<ApiEndpoint path="/audio/logs/boots/<bootid>" method="get">
Get logs for the audio plugin container related to a specific boot.
The `bootid` parameter is interpreted in the same way as in
`/host/logs/boots/<bootid>` and the endpoint otherwise provides the same
functionality as `/host/logs`.
</ApiEndpoint>
<ApiEndpoint path="/audio/logs/boots/<bootid>/follow" method="get">
Identical to `/audio/logs/boots/<bootid>` except it continuously returns
new log entries.
</ApiEndpoint> </ApiEndpoint>
<ApiEndpoint path="/audio/mute/input" method="post"> <ApiEndpoint path="/audio/mute/input" method="post">
@ -694,6 +750,18 @@ Reset internal authentication cache, this is useful if you have changed the pass
</ApiEndpoint> </ApiEndpoint>
<ApiEndpoint path="/auth/list" method="get">
List all users in Home Assistant to help with credentials recovery. Requires an admin level authentication token.
**Payload:**
| key | type | description |
| -------- | ------ | ------------------------------------------------------------------ |
| users | list | List of the Home Assistant [users](api/supervisor/models.md#user). |
</ApiEndpoint>
### Backup ### Backup
<ApiEndpoint path="/backups" method="get"> <ApiEndpoint path="/backups" method="get">
@ -1092,7 +1160,35 @@ Returns information about the Home Assistant core
</ApiEndpoint> </ApiEndpoint>
<ApiEndpoint path="/core/logs" method="get"> <ApiEndpoint path="/core/logs" method="get">
Returns the raw container logs from docker.
Get logs for the Home Assistant Core container via the Systemd journal backend.
The endpoint accepts the same headers and provides the same functionality as
`/host/logs`.
</ApiEndpoint>
<ApiEndpoint path="/core/logs/follow" method="get">
Identical to `/core/logs` except it continuously returns new log entries.
</ApiEndpoint>
<ApiEndpoint path="/core/logs/boots/<bootid>" method="get">
Get logs for the Home Assistant Core container related to a specific boot.
The `bootid` parameter is interpreted in the same way as in
`/host/logs/boots/<bootid>` and the endpoint otherwise provides the same
functionality as `/host/logs`.
</ApiEndpoint>
<ApiEndpoint path="/core/logs/boots/<bootid>/follow" method="get">
Identical to `/core/logs/boots/<bootid>` except it continuously returns
new log entries.
</ApiEndpoint> </ApiEndpoint>
<ApiEndpoint path="/core/options" method="post"> <ApiEndpoint path="/core/options" method="post">
@ -1124,10 +1220,24 @@ Passing `image`, `refresh_token`, `audio_input` or `audio_output` with `null` re
<ApiEndpoint path="/core/rebuild" method="post"> <ApiEndpoint path="/core/rebuild" method="post">
Rebuild the Home Assistant core container Rebuild the Home Assistant core container
**Payload:**
| key | type | optional | description |
| --------- | ---------- | -------- | -------------------------------- |
| safe_mode | boolean | True | Rebuild Core into safe mode |
</ApiEndpoint> </ApiEndpoint>
<ApiEndpoint path="/core/restart" method="post"> <ApiEndpoint path="/core/restart" method="post">
Restart the Home Assistant core container Restart the Home Assistant core container
**Payload:**
| key | type | optional | description |
| --------- | ---------- | -------- | -------------------------------- |
| safe_mode | boolean | True | Restart Core into safe mode |
</ApiEndpoint> </ApiEndpoint>
<ApiEndpoint path="/core/start" method="post"> <ApiEndpoint path="/core/start" method="post">
@ -1275,7 +1385,35 @@ Return information about the DNS plugin.
</ApiEndpoint> </ApiEndpoint>
<ApiEndpoint path="/dns/logs" method="get"> <ApiEndpoint path="/dns/logs" method="get">
Returns the raw container logs from docker.
Get logs for the DNS plugin container via the Systemd journal backend.
The endpoint accepts the same headers and provides the same functionality as
`/host/logs`.
</ApiEndpoint>
<ApiEndpoint path="/dns/logs/follow" method="get">
Identical to `/dns/logs` except it continuously returns new log entries.
</ApiEndpoint>
<ApiEndpoint path="/dns/logs/boots/<bootid>" method="get">
Get logs for the DNS plugin container related to a specific boot.
The `bootid` parameter is interpreted in the same way as in
`/host/logs/boots/<bootid>` and the endpoint otherwise provides the same
functionality as `/host/logs`.
</ApiEndpoint>
<ApiEndpoint path="/dns/logs/boots/<bootid>/follow" method="get">
Identical to `/dns/logs/boots/<bootid>` except it continuously returns
new log entries.
</ApiEndpoint> </ApiEndpoint>
<ApiEndpoint path="/dns/options" method="post"> <ApiEndpoint path="/dns/options" method="post">
@ -1550,9 +1688,9 @@ log record per line.
**HTTP Request Headers** **HTTP Request Headers**
| Header | optional | description | | Header | optional | description |
| -------- | -------- | ---------------------------------------------- | | -------- | -------- |-------------------------------------------------------------------------------|
| Accept | true | Type of data (currently only text/plain) | | Accept | true | Type of data (text/plain or text/x-log) |
| Range | true | Range of log entries. The format is `entries=cursor[[:num_skip]:num_entries]` | | Range | true | Range of log entries. The format is `entries=cursor[[:num_skip]:num_entries]` |
:::tip :::tip
@ -1564,6 +1702,11 @@ as `num_skip`. E.g. `Range: entries=:-9:` returns the last 10 entries. Or
API returns the last 100 lines by default. Provide a value for `Range` to see API returns the last 100 lines by default. Provide a value for `Range` to see
logs further in the past. logs further in the past.
The `Accept` header can be set to `text/x-log` to get logs annotated with
extra information, such as the timestamp and Systemd unit name. If no
identifier is specified (i.e. for the host logs containing logs for multiple
identifiers/units), this option is ignored - these logs are always annotated.
</ApiEndpoint> </ApiEndpoint>
<ApiEndpoint path="/host/logs/follow" method="get"> <ApiEndpoint path="/host/logs/follow" method="get">
@ -2044,7 +2187,35 @@ Returns information about the multicast plugin
</ApiEndpoint> </ApiEndpoint>
<ApiEndpoint path="/multicast/logs" method="get"> <ApiEndpoint path="/multicast/logs" method="get">
Returns the raw container logs from docker.
Get logs for the multicast plugin via the Systemd journal backend.
The endpoint accepts the same headers and provides the same functionality as
`/host/logs`.
</ApiEndpoint>
<ApiEndpoint path="/multicast/logs/follow" method="get">
Identical to `/multicast/logs` except it continuously returns new log entries.
</ApiEndpoint>
<ApiEndpoint path="/multicast/logs/boots/<bootid>" method="get">
Get logs for the multicast plugin related to a specific boot.
The `bootid` parameter is interpreted in the same way as in
`/host/logs/boots/<bootid>` and the endpoint otherwise provides the same
functionality as `/host/logs`.
</ApiEndpoint>
<ApiEndpoint path="/multicast/logs/boots/<bootid>/follow" method="get">
Identical to `/multicast/logs/boots/<bootid>` except it continuously returns
new log entries.
</ApiEndpoint> </ApiEndpoint>
<ApiEndpoint path="/multicast/restart" method="post"> <ApiEndpoint path="/multicast/restart" method="post">
@ -3098,7 +3269,35 @@ Returns information about the supervisor
<ApiEndpoint path="/supervisor/logs" method="get"> <ApiEndpoint path="/supervisor/logs" method="get">
Returns the raw container logs from docker. Get logs for the Supervisor container via the Systemd journal backend. If the
Systemd journal gateway fails to provide the logs, raw Docker container logs are
returned as the fallback.
The endpoint accepts the same headers and provides the same functionality as
`/host/logs`.
</ApiEndpoint>
<ApiEndpoint path="/supervisor/logs/follow" method="get">
Identical to `/supervisor/logs` except it continuously returns new log entries.
</ApiEndpoint>
<ApiEndpoint path="/supervisor/logs/boots/<bootid>" method="get">
Get logs for the Supervisor container related to a specific boot.
The `bootid` parameter is interpreted in the same way as in
`/host/logs/boots/<bootid>` and the endpoint otherwise provides the same
functionality as `/host/logs`.
</ApiEndpoint>
<ApiEndpoint path="/supervisor/logs/boots/<bootid>/follow" method="get">
Identical to `/supervisor/logs/boots/<bootid>` except it continuously returns
new log entries.
</ApiEndpoint> </ApiEndpoint>

View File

@ -82,7 +82,7 @@ These models are describing objects that are getting returned from the superviso
| uuid | string | The UUID of the discovery | | uuid | string | The UUID of the discovery |
| config | dict | The configuration | | config | dict | The configuration |
## Host Service ## Host service
| key | type | description | | key | type | description |
| ----------- | ------ | ----------------------- | | ----------- | ------ | ----------------------- |
@ -129,7 +129,7 @@ These models are describing objects that are getting returned from the superviso
| id | integer | The VLAN ID. | | id | integer | The VLAN ID. |
| parent | string | Parent interface which is the vlan attached. | | parent | string | Parent interface which is the vlan attached. |
## Access-Points ## Access-points
| key | type | description | | key | type | description |
| ---------- | ------- | ---------------------------------------------------------------------------- | | ---------- | ------- | ---------------------------------------------------------------------------- |
@ -301,14 +301,14 @@ Response only fields will be in responses but cannot be included in requests.
| child_jobs | list | A list of child [jobs](#job) started by this one | | child_jobs | list | A list of child [jobs](#job) started by this one |
| errors | list | A list of [errors](#job-error) that occurred during execution | | errors | list | A list of [errors](#job-error) that occurred during execution |
## Job Error ## Job error
| key | type | description | | key | type | description |
| ---------- | ------- | ---------------------------------------------- | | ---------- | ------- | ---------------------------------------------- |
| type | string | Type of error that occurred | | type | string | Type of error that occurred |
| message | string | Human-readable description of what went wrong | | message | string | Human-readable description of what went wrong |
## Boot Slot ## Boot slot
| key | type | description | | key | type | description |
| ---------- | ------- | ----------------------------------------------- | | ---------- | ------- | ----------------------------------------------- |
@ -316,6 +316,17 @@ Response only fields will be in responses but cannot be included in requests.
| status | string | Status of the last boot from slot (good or bad) | | status | string | Status of the last boot from slot (good or bad) |
| version | string | Version of OS installed | | version | string | Version of OS installed |
## User
| key | type | description |
| ---------- | ------- | ------------------------------------------------------------- |
| username | string | Username used to login |
| name | string | Name of the user |
| is_owner | boolean | Is the user the owner |
| is_active | boolean | Is the user active |
| local_only | boolean | Can the user login from the network (e.g. via http) |
| group_ids | list | Role(s) the user has (admin, etc) |
## Drive ## Drive
| key | type | description | | key | type | description |

View File

@ -23,7 +23,7 @@ During the command phase, the client attaches a unique identifier to each messag
## Message format ## Message format
Each API message is a JSON serialized object containing a `type` key. After the authentication phase messages also must contain an `id`, an integer that contains the number of interactions. Each API message is a JSON serialized object containing a `type` key. After the authentication phase messages also must contain an `id`, an integer that the caller can use to correlate messages to responses.
Example of an auth message: Example of an auth message:
@ -334,9 +334,9 @@ The server will respond with a result message to indicate that the event was fir
} }
``` ```
## Calling a service ## Calling a service action
This will call a service in Home Assistant. Right now there is no return value. The client can listen to `state_changed` events if it is interested in changed entities as a result of a service call. This will call a service action in Home Assistant. Right now there is no return value. The client can listen to `state_changed` events if it is interested in changed entities as a result of a call.
```json ```json
{ {
@ -353,10 +353,12 @@ This will call a service in Home Assistant. Right now there is no return value.
"target": { "target": {
"entity_id": "light.kitchen" "entity_id": "light.kitchen"
} }
// Must be included for service actions that return response data
"return_response": true
} }
``` ```
The server will indicate with a message indicating that the service is done executing. The server will indicate with a message indicating that the action is done executing.
```json ```json
{ {
@ -374,7 +376,7 @@ The server will indicate with a message indicating that the service is done exec
} }
``` ```
The `result` of the call will always include a `response` to account for services that support responses. When a service that doesn't support responses is called, the value of `response` will be `null`. The `result` of the call will always include a `response` to account for service actions that support responses. When a action that doesn't support responses is called, the value of `response` will be `null`.
## Fetching states ## Fetching states
@ -420,9 +422,9 @@ The server will respond with a result message containing the config.
} }
``` ```
## Fetching services ## Fetching service actions
This will get a dump of the current services in Home Assistant. This will get a dump of the current service actions in Home Assistant.
```json ```json
{ {
@ -431,7 +433,7 @@ This will get a dump of the current services in Home Assistant.
} }
``` ```
The server will respond with a result message containing the services. The server will respond with a result message containing the service actions.
```json ```json
{ {
@ -464,7 +466,7 @@ The server will respond with a result message containing the current registered
} }
``` ```
## Pings and Pongs ## Pings and pongs
The API supports receiving a ping from the client and returning a pong. This serves as a heartbeat to ensure the connection is still alive: The API supports receiving a ping from the client and returning a pong. This serves as a heartbeat to ensure the connection is still alive:
@ -529,7 +531,7 @@ If an error occurs, the `success` key in the `result` message will be set to `fa
} }
``` ```
### Error handling during service calls and translations ### Error handling during service action calls and translations
The JSON below shows an example of an error response. If `HomeAssistantError` error (or a subclass of `HomeAssistantError`) is handled, translation information, if set, will be added to the response. The JSON below shows an example of an error response. If `HomeAssistantError` error (or a subclass of `HomeAssistantError`) is handled, translation information, if set, will be added to the response.

View File

@ -1,5 +1,5 @@
--- ---
title: "Python Library: Authentication" title: "Python library: authentication"
sidebar_label: Authentication sidebar_label: Authentication
--- ---

View File

@ -1,6 +1,6 @@
--- ---
title: "Python Library: Modelling Data" title: "Python library: modelling data"
sidebar_label: Modelling Data sidebar_label: Modelling data
--- ---
Now that we have authentication going, we can start making authenticated requests and fetch data! Now that we have authentication going, we can start making authenticated requests and fetch data!

View File

@ -1,5 +1,5 @@
--- ---
title: Core Architecture title: Core architecture
sidebar_label: Core sidebar_label: Core
--- ---
@ -7,7 +7,7 @@ The Home Assistant Core consists of four main parts. On top of this it includes
- **Event Bus**: facilitates the firing and listening of events -- the beating heart of Home Assistant. - **Event Bus**: facilitates the firing and listening of events -- the beating heart of Home Assistant.
- **State Machine**: keeps track of the states of things and fires a `state_changed` event when a state has been changed. - **State Machine**: keeps track of the states of things and fires a `state_changed` event when a state has been changed.
- **Service Registry**: listens on the event bus for `call_service` events and allows other code to register services. - **Service Registry**: listens on the event bus for `call_service` events and allows other code to register service actions.
- **Timer**: sends a `time_changed` event every 1 second on the event bus. - **Timer**: sends a `time_changed` event every 1 second on the event bus.
<img class='invertDark' <img class='invertDark'

View File

@ -3,9 +3,9 @@ title: "Entities: integrating devices & services"
sidebar_label: "Introduction" sidebar_label: "Introduction"
--- ---
Integrations can represent devices & services in Home Assistant. The data points are represented as entities. Entities are standardized by other integrations like `light`, `switch`, etc. Standardized entities come with services for control, but an integration can also provide their own services in case something is not standardized. Integrations can represent devices & services in Home Assistant. The data points are represented as entities. Entities are standardized by other integrations like `light`, `switch`, etc. Standardized entities come with actions for control, but an integration can also provide their own service actions in case something is not standardized.
An entity abstracts away the internal working of Home Assistant. As an integrator you don't have to worry about how services or the state machine work. Instead, you extend an entity class and implement the necessary properties and methods for the device type that you're integrating. An entity abstracts away the internal workings of Home Assistant. As an integrator, you don't have to worry about how service actions or the state machine work. Instead, you extend an entity class and implement the necessary properties and methods for the device type that you're integrating.
<img className='invertDark' <img className='invertDark'
src='/img/en/architecture/integrating-devices-services.svg' src='/img/en/architecture/integrating-devices-services.svg'
@ -17,7 +17,7 @@ An entity abstracts away the internal working of Home Assistant. As an integrato
Configuration is provided by the user via a [Config Entry](../config_entries_index.md) or in special/legacy cases via [configuration.yaml](../configuration_yaml_index.md). Configuration is provided by the user via a [Config Entry](../config_entries_index.md) or in special/legacy cases via [configuration.yaml](../configuration_yaml_index.md).
The device integration (i.e. `hue`) will use this configuration to set up a connection with the device/service. It will forward the config entry (legacy uses discovery helper) to set up its entities in their respective integrations (light, switch). The device integration can also register their own services for things that are not made standardized. These services are published under the integration's domain, ie `hue.activate_scene`. The device integration (i.e. `hue`) will use this configuration to set up a connection with the device/service. It will forward the config entry (legacy uses discovery helper) to set up its entities in their respective integrations (light, switch). The device integration can also register their own service actions for things that are not made standardized. These actions are published under the integration's domain, ie `hue.activate_scene`.
The entity integration (i.e. `light`) is responsible for defining the abstract entity class and services to control the entities. The entity integration (i.e. `light`) is responsible for defining the abstract entity class and services to control the entities.

View File

@ -1,9 +1,9 @@
--- ---
title: "Integration Architecture" title: "Integration architecture"
sidebar_label: "Integrations" sidebar_label: "Integrations"
--- ---
Home Assistant Core can be extended with **integrations**. Each integration is responsible for a specific domain within Home Assistant. Integrations can listen for or trigger events, offer services, and maintain states. Integrations are made up of a component (the base logic) and platforms (bits that integrate with other integrations). Integrations are written in Python and can do all the goodness that Python has to offer. Out of the box, Home Assistant offers a bunch of [built-in integrations](https://www.home-assistant.io/integrations/). Home Assistant Core can be extended with **integrations**. Each integration is responsible for a specific domain within Home Assistant. Integrations can listen for or trigger events, offer actions, and maintain states. Integrations are made up of a component (the base logic) and platforms (bits that integrate with other integrations). Integrations are written in Python and can do all the goodness that Python has to offer. Out of the box, Home Assistant offers a bunch of [built-in integrations](https://www.home-assistant.io/integrations/).
<img class='invertDark' <img class='invertDark'
src='/img/en/architecture/component-interaction.svg' src='/img/en/architecture/component-interaction.svg'
@ -13,7 +13,7 @@ Home Assistant distinguishes the following integration types:
## Define an Internet of Things domain ## Define an Internet of Things domain
These integrations define a specific device category of Internet of Things devices in Home Assistant, like a light. It's up to the `light` integration to define what data is available in Home Assistant and in what format. It also provides services to control lights. These integrations define a specific device category of Internet of Things devices in Home Assistant, like a light. It's up to the `light` integration to define what data is available in Home Assistant and in what format. It also provides actions to control lights.
For a list of defined domains, see [entities](./core/entity.md). For a list of defined domains, see [entities](./core/entity.md).

View File

@ -1,5 +1,5 @@
--- ---
title: "Architecture Overview" title: "Architecture overview"
--- ---
Home Assistant provides a platform for home control and home automation. Home Assistant is not just an application: it's an embedded system that provides an experience like other consumer off-the-shelf products: onboarding, configuration and updating is all done via an easy to use interface. Home Assistant provides a platform for home control and home automation. Home Assistant is not just an application: it's an embedded system that provides an experience like other consumer off-the-shelf products: onboarding, configuration and updating is all done via an easy to use interface.

View File

@ -1,5 +1,5 @@
--- ---
title: Area Registry title: Area registry
--- ---
The area registry is a registry where Home Assistant keeps track of areas. An area represents a physical location for Home Assistant. It can be used to place devices in different areas. The area registry is a registry where Home Assistant keeps track of areas. An area represents a physical location for Home Assistant. It can be used to place devices in different areas.

View File

@ -0,0 +1,96 @@
---
title: "Blocking operations with asyncio"
---
When writing asyncio code, it's essential to ensure that all blocking operations are done in a separate thread. If blocking operations happen in the event loop, nothing else can run until the operation is complete. For this reason, no blocking operations happen in the event loop, as the entire system will stall for the duration of the blocking operation.
Detailed examples of operations that might block, such as network I/O or heavy computation, are discussed below.
:::tip
Be sure to enable [`asyncio` debug mode](https://docs.python.org/3/library/asyncio-dev.html#debug-mode) and [Home Assistant's built-in debug mode](https://www.home-assistant.io/integrations/homeassistant/#debug) during development as many blocking I/O errors can be detected automatically.
:::
## Solving blocking I/O in the event loop
You may have reached this page because Home Assistant detected and reported a blocking call in the event loop. Beginning in version 2024.7.0, Home Assistant can detect more blocking operations in the event loop to prevent system instability. Before Home Assistant could detect these errors, they may have led to an unresponsive system or undefined behavior. Below are some tips on correcting blocking operations in the event loop.
## Running blocking calls in the executor
In Home Assistant this is usually accomplished by calling `await hass.async_add_executor_job`. In library code, `await loop.run_in_executor(None, ...)` is usually used. Review Python's documentation on [Running Blocking Code](https://docs.python.org/3/library/asyncio-dev.html#running-blocking-code) for tips to avoid pitfalls. Some specific calls may need different approaches.
```python
from functools import partial
def blocking_code(some_arg: str):
...
def blocking_code_with_kwargs(kwarg: bool = False):
...
# When calling a blocking function inside Home Assistant
result = await hass.async_add_executor_job(blocking_code, "something")
result = await hass.async_add_executor_job(partial(blocking_code_with_kwargs, kwarg=True))
# When calling a blocking function in your library code
loop = asyncio.get_running_loop()
result = await loop.run_in_executor(None, blocking_code, "something")
result = await loop.run_in_executor(None, partial(blocking_code_with_kwargs, kwarg=True))
```
### Specific function calls
Depending on the type of blocking call that was detected, the solution may be more nuanced.
#### open
`open` does blocking disk I/O and should be run in the executor with the standard methods above.
:::warning
When an `open` call running in the event loop is fixed, all the blocking reads and writes must also be fixed to happen in the executor. Home Assistant can only detect the `open` call and cannot detect the blocking reads and writes, which means if the blocking read and write calls are not fixed at the same time as the `open` call, they will likely torment users of the integration for a long time as they will be very hard to discover.
:::
#### import_module
When importing a module, the import machinery has to read the module from disk which does blocking I/O. Importing modules is both CPU-intensive and involves blocking I/O, so it is crucial to ensure these operations are executed in the executor.
Importing code in [cpython is not thread-safe](https://github.com/python/cpython/issues/83065). If the module will only ever be imported in a single place, the standard executor calls can be used. If there's a possibility of the same module being imported concurrently in different parts of the application, use the thread-safe `homeassistant.helpers.importlib.import_module` helper.
Example:
```python
platform = await async_import_module(hass, f"homeassistant.components.homeassistant.triggers.{platform_name}")
```
#### sleep
A blocking sleep should be replaced with `await asyncio.sleep` instead. The most common reported blocking `sleep` in the event loop is `pyserial-asyncio` which can be replaced with [`pyserial-asyncio-fast`](https://github.com/home-assistant-libs/pyserial-asyncio-fast) which does not have this issue.
#### putrequest
urllib does blocking I/O and should be run in the executor with the standard methods above. Consider converting the integration to use `aiohttp` or `httpx` instead.
#### glob
`glob.glob` does blocking disk I/O and should be run in the executor with the standard methods above.
#### iglob
`glob.iglob` does blocking disk I/O and should be run in the executor with the standard methods above.
#### walk
`os.walk` does blocking disk I/O and should be run in the executor with the standard methods above.
#### listdir
`os.listdir` does blocking disk I/O and should be run in the executor with the standard methods above.
#### scandir
`os.scandir` does blocking disk I/O and should be run in the executor with the standard methods above.
#### stat
`os.stat` does blocking disk I/O and should be run in the executor with the standard methods above.

View File

@ -1,5 +1,5 @@
--- ---
title: "Categorizing Functions" title: "Categorizing functions"
--- ---
A piece of work within Home Assistant is represented by a function that will be invoked. It will either run inside our event loop or inside our thread pool, depending on if it is async safe. A piece of work within Home Assistant is represented by a function that will be invoked. It will either run inside our event loop or inside our thread pool, depending on if it is async safe.
@ -32,7 +32,7 @@ This is a normal function that is considered safe to be run from within the even
To declare a function as a callback, import the callback annotation from the core package and annotate your function. To declare a function as a callback, import the callback annotation from the core package and annotate your function.
A common use case for a callback in Home Assistant is as a listener for an event or a service call. It can process the incoming information and then schedule the right calls to be made. Example from the automation component. A common use case for a callback in Home Assistant is as a listener for an event or a service action call. It can process the incoming information and then schedule the right calls to be made. Example from the automation engine.
```python ```python
from homeassistant.core import callback from homeassistant.core import callback
@ -40,7 +40,7 @@ from homeassistant.core import callback
@callback @callback
def async_trigger_service_handler(service_call): def async_trigger_service_handler(service_call):
"""Handle automation trigger service calls.""" """Handle automation trigger service action call."""
vars = service_call.data.get(ATTR_VARIABLES) vars = service_call.data.get(ATTR_VARIABLES)
for entity in component.async_extract_from_service(service_call): for entity in component.async_extract_from_service(service_call):
hass.loop.create_task(entity.async_trigger(vars, True)) hass.loop.create_task(entity.async_trigger(vars, True))

View File

@ -1,5 +1,5 @@
--- ---
title: "Asynchronous Programming" title: "Asynchronous programming"
sidebar_label: Introduction sidebar_label: Introduction
--- ---

View File

@ -0,0 +1,165 @@
---
title: "Thread safety with asyncio"
---
Developing with asyncio requires careful attention to thread safety, as nearly all asyncio objects are not thread-safe. If you are just getting started with asyncio, review Python's documentation on [Developing with asyncio](https://docs.python.org/3/library/asyncio-dev.html) for tips to avoid pitfalls.
Home Assistant has some conventions for handling async and non-async code in the same code base. The top highlights are:
- Deciding how to run a function from a helper depends on whether it is decorated with `@callback` to indicate it will not block and is safe to run in the event loop; for more details, see [Working with Async](asyncio_working_with_async.md).
- Most APIs have a sync and async version when calling a function from a thread. The async APIs are prefixed with `async_`. For example, when firing an event from a thread other than the event loop, use `hass.bus.fire` instead of `hass.bus.async_fire`.
:::tip
Be sure to enable [`asyncio` debug mode](https://docs.python.org/3/library/asyncio-dev.html#debug-mode) and [Home Assistant's built-in debug mode](https://www.home-assistant.io/integrations/homeassistant/#debug) during development as many thread safety errors can be detected automatically.
:::
## Solving thread safety errors
You may have reached this page because Home Assistant detected and reported a thread safety error. Beginning in version 2024.5.0, Home Assistant can detect, report, and block some non-thread-safe operations to prevent system instability. Before Home Assistant could detect these errors, they may have led to unexpected restarts or undefined behaviors, as they can corrupt the internal asyncio state. Below are some tips on how to correct non-threaded operations.
## Ensuring code is run in the correct thread
### Built-in helpers that take a callback
When using Home Assistant's built-in helpers such as `event.async_track_state_change_event` or `event.track_state_change_event`, it's important to call the correct API based on which thread the code runs in. If the code runs in a thread other than the event loop, use the non-`async` version.
In the below example, everything will run in the event loop thread, and when `async_track_state_change_event` fires,
`async_update_event_state_callback` will also be run in the event loop thread because it is decorated with `@callback`. If the `@callback` decorator is missing, `async_update_event_state_callback` would be run in the executor, which would make a non-thread-safe call to `async_write_ha_state`.
```python
async def async_added_to_hass(self) -> None:
"""Entity has been added to hass."""
self.async_on_remove(
async_track_state_change_event(
self.hass,
["light.other"],
self.async_update_event_state_callback,
)
)
@callback
def async_update_event_state_callback(self, event: Event[EventStateChangedData]) -> None:
"""Call when entity state changes."""
new_state = event.data["new_state"]
if new_state is None or new_state.state in (STATE_UNAVAILABLE, STATE_UNKNOWN):
return
self.async_write_ha_state()
```
### Specific API calls
You may find you need to call one of the async API calls from a thread other than the event loop thread. In most cases, `hass.add_job` can safely call an async API from another thread. Some helpers have specific sync APIs to use when calling from another thread. Below is a list of the most commonly called async APIs and the method to call them from another thread.
#### hass.async_create_task
When creating a task from a thread other than the event loop thread, instead use `hass.create_task`
#### hass.bus.async_fire
When firing an event from a thread other than the event loop thread, instead use `hass.bus.fire`
#### hass.services.async_register
When registering a service action from a thread other than the event loop thread, instead use `hass.services.register`
#### hass.services.async_remove
When removing a service action from a thread other than the event loop thread, instead use `hass.services.remove`
#### async_write_ha_state
When writing the state of an entity from a thread other than the event loop thread, instead use `self.schedule_update_ha_state`
#### hass.config_entries.async_update_entry
Updating config entry must be done in the event loop thread. There is no sync API to update config entries. If it is not a mistake that the calling function is running in another thread, use `hass.add_job` to schedule a function in the event loop that calls `hass.config_entries.async_update_entry`.
#### async_dispatcher_send
When calling the dispatcher from a thread other than the event loop thread, instead use `dispatcher_send`.
#### async_render_to_info
Templates must be rendered in the event loop thread. There is no sync API to render templates. Use `hass.add_job` to schedule a function in the event loop that calls `async_render_to_info`.
#### area_registry.async_create
The area registry must be modified in the event loop thread. There is no sync API for the area registry. Use `hass.add_job` to schedule a function in the event loop that calls `area_registry.async_create`.
#### area_registry.async_delete
The area registry must be modified in the event loop thread. There is no sync API for the area registry. Use `hass.add_job` to schedule a function in the event loop that calls `area_registry.async_delete`.
#### area_registry.async_update
The area registry must be modified in the event loop thread. There is no sync API for the area registry. Use `hass.add_job` to schedule a function in the event loop that calls `area_registry.async_update`.
#### category_registry.async_create
The category registry must be modified in the event loop thread. There is no sync API for the category registry. Use `hass.add_job` to schedule a function in the event loop that calls `category_registry.async_create`.
#### category_registry.async_delete
The category registry must be modified in the event loop thread. There is no sync API for the category registry. Use `hass.add_job` to schedule a function in the event loop that calls `category_registry.async_delete`.
#### category_registry.async_update
The category registry must be modified in the event loop thread. There is no sync API for the category registry. Use `hass.add_job` to schedule a function in the event loop that calls `category_registry.async_update`.
#### device_registry.async_update_device
The device registry must be modified in the event loop thread. There is no sync API for the device registry. Use `hass.add_job` to schedule a function in the event loop that calls `device_registry.async_update_device`.
#### device_registry.async_remove_device
The device registry must be modified in the event loop thread. There is no sync API for the device registry. Use `hass.add_job` to schedule a function in the event loop that calls `device_registry.async_remove_device`.
#### entity_registry.async_get_or_create
The entity registry must be modified in the event loop thread. There is no sync API for the entity registry. Use `hass.add_job` to schedule a function in the event loop that calls `entity_registry.async_get_or_create`.
#### entity_registry.async_remove
The entity registry must be modified in the event loop thread. There is no sync API for the entity registry. Use `hass.add_job` to schedule a function in the event loop that calls `entity_registry.async_remove`.
#### entity_registry.async_update_entity
The entity registry must be modified in the event loop thread. There is no sync API for the entity registry. Use `hass.add_job` to schedule a function in the event loop that calls `entity_registry.async_update_entity`.
#### floor_registry.async_create
The floor registry must be modified in the event loop thread. There is no sync API for the floor registry. Use `hass.add_job` to schedule a function in the event loop that calls `floor_registry.async_create`.
#### floor_registry.async_delete
The floor registry must be modified in the event loop thread. There is no sync API for the floor registry. Use `hass.add_job` to schedule a function in the event loop that calls `floor_registry.async_delete`.
#### floor_registry.async_update
The floor registry must be modified in the event loop thread. There is no sync API for the floor registry. Use `hass.add_job` to schedule a function in the event loop that calls `floor_registry.async_update`.
#### issue_registry.async_get_or_create
The issue registry must be modified in the event loop thread. Call `issue_registry.create_issue` instead.
#### issue_registry.async_delete
The issue registry must be modified in the event loop thread. Call `issue_registry.delete_issue` instead.
#### issue_registry.async_ignore
The issue registry must be modified in the event loop thread. There is no sync API to ignore an issue in the issue registry. Use `hass.add_job` to schedule a function in the event loop that calls `issue_registry.async_ignore_issue`.
#### label_registry.async_create
The label registry must be modified in the event loop thread. There is no sync API for the label registry. Use `hass.add_job` to schedule a function in the event loop that calls `label_registry.async_create`.
#### label_registry.async_delete
The label registry must be modified in the event loop thread. There is no sync API for the label registry. Use `hass.add_job` to schedule a function in the event loop that calls `label_registry.async_delete`.
#### label_registry.async_update
The label registry must be modified in the event loop thread. There is no sync API for the label registry. Use `hass.add_job` to schedule a function in the event loop that calls `label_registry.async_update`.

View File

@ -54,7 +54,7 @@ http://your-instance.com/auth/authorize?
The user will navigate to this link and be presented with instructions to log in and authorize your application. Once authorized, the user will be redirected back to the passed in redirect uri with the authorization code and state as part of the query parameters. Example: The user will navigate to this link and be presented with instructions to log in and authorize your application. Once authorized, the user will be redirected back to the passed in redirect uri with the authorization code and state as part of the query parameters. Example:
```txt ```txt
https://hass-auth-demo.glitch.me/auth_callback https://hass-auth-demo.glitch.me/auth_callback?
code=12345& code=12345&
state=http%3A%2F%2Fhassio.local%3A8123 state=http%3A%2F%2Fhassio.local%3A8123
``` ```

View File

@ -1,5 +1,5 @@
--- ---
title: "Multi-factor Authentication Modules" title: "Multi-factor authentication modules"
--- ---
Multi-factor Authentication Modules are used in conjunction with [Authentication Provider](auth_auth_provider.md) to provide a fully configurable authentication framework. Each MFA module may provide one multi-factor authentication function. User can enable multiple mfa modules, but can only select one module in login process. Multi-factor Authentication Modules are used in conjunction with [Authentication Provider](auth_auth_provider.md) to provide a fully configurable authentication framework. Each MFA module may provide one multi-factor authentication function. User can enable multiple mfa modules, but can only select one module in login process.
@ -26,7 +26,7 @@ Multi-factor Auth modules shall extend the following methods of `MultiFactorAuth
| `async def async_validate(self, user_id, user_input)` | Yes | Given a user_id and user input, return validation result. | `async def async_validate(self, user_id, user_input)` | Yes | Given a user_id and user input, return validation result.
| `async def async_initialize_login_mfa_step(self, user_id)` | No | Will be called once before display the mfa step of login flow. This is not initialization for the MFA module but the mfa step in login flow. | `async def async_initialize_login_mfa_step(self, user_id)` | No | Will be called once before display the mfa step of login flow. This is not initialization for the MFA module but the mfa step in login flow.
## Setup Flow ## Setup flow
Before user can use a multi-factor auth module, it has to be enabled or set up. All available modules will be listed in user profile page, user can enable the module he/she wants to use. A setup data entry flow will guide user finish the necessary steps. Before user can use a multi-factor auth module, it has to be enabled or set up. All available modules will be listed in user profile page, user can enable the module he/she wants to use. A setup data entry flow will guide user finish the necessary steps.

View File

@ -1,5 +1,5 @@
--- ---
title: "Authentication Providers" title: "Authentication providers"
--- ---
Authentication providers confirm the identity of users. The user proofs their identity by going through the login flow for an auth provider. The auth provider defines the login flow and can ask the user all information this needs. This will commonly be username and password but could also include a 2FA token or other challenges. Authentication providers confirm the identity of users. The user proofs their identity by going through the login flow for an auth provider. The auth provider defines the login flow and can ask the user all information this needs. This will commonly be username and password but could also include a 2FA token or other challenges.

View File

@ -32,7 +32,7 @@ The user that is created during onboarding will be marked as "owner". The owner
Users are a member of one or more groups. Group membership is how a user is granted permissions. Users are a member of one or more groups. Group membership is how a user is granted permissions.
## Permission Policy ## Permission policy
This is the permission policy that describes to which resources a group has access. For more information about permissions and policies, see [Permissions](auth_permissions.md). This is the permission policy that describes to which resources a group has access. For more information about permissions and policies, see [Permissions](auth_permissions.md).

View File

@ -128,9 +128,9 @@ if not user.permissions.check_entity(entity_id, POLICY_CONTROL):
### The context object ### The context object
All service calls, fired events and states in Home Assistant have a context object. This object allows us to attribute changes to events and services. These context objects also contain a user id, which is used for checking the permissions. All service actions, fired events and states in Home Assistant have a context object. This object allows us to attribute changes to events and actions. These context objects also contain a user id, which is used for checking the permissions.
It's crucial for permission checking that actions taken on behalf of the user are done with a context containing the user ID. If you are in a service handler, you should re-use the incoming context `call.context`. If you are inside a WebSocket API or Rest API endpoint, you should create a context with the correct user: It's crucial for permission checking that actions taken on behalf of the user are done with a context containing the user ID. If you are in a service action handler, you should re-use the incoming context `call.context`. If you are inside a WebSocket API or Rest API endpoint, you should create a context with the correct user:
```python ```python
from homeassistant.core import Context from homeassistant.core import Context
@ -158,15 +158,15 @@ The `Unauthorized` exception has various parameters, to identify the permission
| perm_category | The permission category that we tested. Only necessary if we don't have an object ID that the user tried to operate on (like when we create a config entry). | perm_category | The permission category that we tested. Only necessary if we don't have an object ID that the user tried to operate on (like when we create a config entry).
| permission | The permission that we tested, ie `POLICY_READ`. | permission | The permission that we tested, ie `POLICY_READ`.
### Securing a service call handler ### Securing a service action handler
Service calls allow a user to control entities or with the integration as a whole. A service call uses the attached context to see which user invoked the command. Because context is used, it is important that you also pass the call context to all service calls. Actions allow a user to control entities or with the integration as a whole. A service action uses the attached context to see which user invoked the command. Because context is used, it is important that you also pass the call context to all service action.
All services that are registered via the entity component (`component.async_register_entity_service()`) will automatically have their permissions checked. All service actions that are registered via the entity component (`component.async_register_entity_service()`) will automatically have their permissions checked.
#### Checking entity permissions #### Checking entity permissions
Your service call handler will need to check the permissions for each entity that it will act on. Your service action handler will need to check the permissions for each entity that it will act on.
```python ```python
from homeassistant.exceptions import Unauthorized, UnknownUser from homeassistant.exceptions import Unauthorized, UnknownUser
@ -174,7 +174,7 @@ from homeassistant.auth.permissions.const import POLICY_CONTROL
async def handle_entity_service(call): async def handle_entity_service(call):
"""Handle a service call.""" """Handle a service action call."""
entity_ids = call.data["entity_id"] entity_ids = call.data["entity_id"]
for entity_id in entity_ids: for entity_id in entity_ids:
@ -206,12 +206,12 @@ async def async_setup(hass, config):
#### Checking admin permission #### Checking admin permission
Starting Home Assistant 0.90, there is a special decorator to help protect Starting Home Assistant 0.90, there is a special decorator to help protect
services that require admin access. service actions that require admin access.
```python ```python
# New in Home Assistant 0.90 # New in Home Assistant 0.90
async def handle_admin_service(call): async def handle_admin_service(call):
"""Handle a service call.""" """Handle a service action call."""
# Do admin action # Do admin action

View File

@ -1,6 +1,6 @@
--- ---
title: "Bluetooth" title: "Bluetooth"
sidebar_label: "Building a Bluetooth Integration" sidebar_label: "Building a Bluetooth integration"
--- ---
### Best practices for integration authors ### Best practices for integration authors

View File

@ -1,10 +1,10 @@
--- ---
title: Config Flow title: Config flow
--- ---
Integrations can be set up via the user interface by adding support for a config flow to create a config entry. Components that want to support config entries will need to define a Config Flow Handler. This handler will manage the creation of entries from user input, discovery or other sources (like Home Assistant OS). Integrations can be set up via the user interface by adding support for a config flow to create a config entry. Components that want to support config entries will need to define a Config Flow Handler. This handler will manage the creation of entries from user input, discovery or other sources (like Home Assistant OS).
Config Flow Handlers control the data that is stored in a config entry. This means that there is no need to validate that the config is correct when Home Assistant starts up. It will also prevent breaking changes, because we will be able to migrate configuration entries to new formats if the version changes. Config Flow Handlers control the data that is stored in a config entry. This means that there is no need to validate that the config is correct when Home Assistant starts up. It will also prevent breaking changes because we will be able to migrate configuration entries to new formats if the version changes.
When instantiating the handler, Home Assistant will make sure to load all dependencies and install the requirements of the component. When instantiating the handler, Home Assistant will make sure to load all dependencies and install the requirements of the component.
@ -14,7 +14,7 @@ You need to update your integrations manifest to inform Home Assistant that your
## Defining your config flow ## Defining your config flow
Config entries uses the [data flow entry framework](data_entry_flow_index.md) to define their config flows. The config flow needs to be defined in the file `config_flow.py` in your integration folder, extend `homeassistant.config_entries.ConfigFlow` and pass a `domain` key as part of inheriting `ConfigFlow`. Config entries use the [data flow entry framework](data_entry_flow_index.md) to define their config flows. The config flow needs to be defined in the file `config_flow.py` in your integration folder, extend `homeassistant.config_entries.ConfigFlow` and pass a `domain` key as part of inheriting `ConfigFlow`.
```python ```python
from homeassistant import config_entries from homeassistant import config_entries
@ -63,6 +63,8 @@ There are a few step names reserved for system use:
| `user` | Invoked when a user initiates a flow via the user interface or when discovered and the matching and discovery step are not defined. | | `user` | Invoked when a user initiates a flow via the user interface or when discovered and the matching and discovery step are not defined. |
| `reconfigure` | Invoked when a user initiates a flow to reconfigure an existing config entry via the user interface. | | `reconfigure` | Invoked when a user initiates a flow to reconfigure an existing config entry via the user interface. |
| `zeroconf` | Invoked if your integration has been discovered via Zeroconf/mDNS as specified [using `zeroconf` in the manifest](creating_integration_manifest.md#zeroconf). | | `zeroconf` | Invoked if your integration has been discovered via Zeroconf/mDNS as specified [using `zeroconf` in the manifest](creating_integration_manifest.md#zeroconf). |
| `reauth` | Invoked if your integration indicates it [requires reauthentication, e.g., due to expired credentials](#reauthentication). |
| `import` | Reserved for migrating from YAML configuration to config entries. |
## Unique IDs ## Unique IDs
@ -98,11 +100,11 @@ that still allows for discovery, as long as there aren't any instances of the in
```python ```python
if device_unique_id: if device_unique_id:
await self.async_set_unique_id(device_unique_id) await self.async_set_unique_id(device_unique_id)
await self._async_handle_discovery_without_unique_id() await self._async_handle_discovery_without_unique_id()
``` ```
### Unique ID Requirements ### Unique ID requirements
A unique ID is used to match a config entry to the underlying device or API. The unique ID must be stable, should not be able to be changed by the user and must be a string. A unique ID is used to match a config entry to the underlying device or API. The unique ID must be stable, should not be able to be changed by the user and must be a string.
@ -215,7 +217,7 @@ Translations for the config flow handlers are defined under the `config` key in
When the translations are merged into Home Assistant, they will be automatically uploaded to [Lokalise](https://lokalise.co/) where the translation team will help to translate them in other languages. While developing locally, you will need to run `python3 -m script.translations develop` to see changes made to `strings.json` [More info on translating Home Assistant.](translations.md) When the translations are merged into Home Assistant, they will be automatically uploaded to [Lokalise](https://lokalise.co/) where the translation team will help to translate them in other languages. While developing locally, you will need to run `python3 -m script.translations develop` to see changes made to `strings.json` [More info on translating Home Assistant.](translations.md)
## Config Entry Migration ## Config entry migration
As mentioned above - each Config Entry has a version assigned to it. This is to be able to migrate Config Entry data to new formats when Config Entry schema changes. As mentioned above - each Config Entry has a version assigned to it. This is to be able to migrate Config Entry data to new formats when Config Entry schema changes.
@ -227,25 +229,25 @@ The version is made of a major and minor version. If minor versions differ but m
# Example migration function # Example migration function
async def async_migrate_entry(hass, config_entry: ConfigEntry): async def async_migrate_entry(hass, config_entry: ConfigEntry):
"""Migrate old entry.""" """Migrate old entry."""
_LOGGER.debug("Migrating from version %s", config_entry.version) _LOGGER.debug("Migrating configuration from version %s.%s", config_entry.version, config_entry.minor_version)
if config_entry.version > 1: if config_entry.version > 1:
# This means the user has downgraded from a future version # This means the user has downgraded from a future version
return False return False
if config_entry.version == 1: if config_entry.version == 1:
new = {**config_entry.data} new_data = {**config_entry.data}
config_entry.minor_version < 2: if config_entry.minor_version < 2:
# TODO: modify Config Entry data with changes in version 1.2 # TODO: modify Config Entry data with changes in version 1.2
pass pass
config_entry.minor_version < 3: if config_entry.minor_version < 3:
# TODO: modify Config Entry data with changes in version 1.3 # TODO: modify Config Entry data with changes in version 1.3
pass pass
hass.config_entries.async_update_entry(config_entry, data=new, minor_version=3, version=1) hass.config_entries.async_update_entry(config_entry, data=new_data, minor_version=3, version=1)
_LOGGER.debug("Migration to version %s.%s successful", config_entry.version, config_entry.minor_version) _LOGGER.debug("Migration to configuration version %s.%s successful", config_entry.version, config_entry.minor_version)
return True return True
``` ```
@ -274,7 +276,8 @@ class ExampleConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
## Reauthentication ## Reauthentication
Gracefully handling authentication errors such as invalid, expired, or revoked tokens is needed to advance on the [Integration Qualily Scale](integration_quality_scale_index.md). This example of how to add reauth to the OAuth flow created by `script.scaffold` following the pattern in [Building a Python library](api_lib_auth.md#oauth2). Gracefully handling authentication errors such as invalid, expired, or revoked tokens is needed to advance on the [Integration Quality Scale](integration_quality_scale_index.md). This example of how to add reauth to the OAuth flow created by `script.scaffold` following the pattern in [Building a Python library](api_lib_auth.md#oauth2).
If you are looking for how to trigger the reauthentication flow, see [handling expired credentials](integration_setup_failures#handling-expired-credentials).
This example catches an authentication exception in config entry setup in `__init__.py` and instructs the user to visit the integrations page in order to reconfigure the integration. This example catches an authentication exception in config entry setup in `__init__.py` and instructs the user to visit the integrations page in order to reconfigure the integration.
@ -335,7 +338,8 @@ class OAuth2FlowHandler(
) )
return await super().async_oauth_create_entry(data) return await super().async_oauth_create_entry(data)
``` ```
By default, the `async_update_reload_and_abort` helper method aborts the flow with `reauth_successful` after update and reload.
By default, the `async_update_reload_and_abort` helper method aborts the flow with `reauth_successful` after update and reload. By default, the entry will always be reloaded. If the config entry only should be reloaded in case the config entry was updated, specify `reload_even_if_entry_is_unchanged=False`.
Depending on the details of the integration, there may be additional considerations such as ensuring the same account is used across reauth, or handling multiple config entries. Depending on the details of the integration, there may be additional considerations such as ensuring the same account is used across reauth, or handling multiple config entries.

View File

@ -1,5 +1,5 @@
--- ---
title: Config Entries title: Config entries
--- ---
Config Entries are configuration data that are persistently stored by Home Assistant. A config entry is created by a user via the UI. The UI flow is powered by a [config flow handler](config_entries_config_flow_handler.md) as defined by the component. Config entries can also have an extra [options flow handler](config_entries_options_flow_handler.md), also defined by the component. Config Entries are configuration data that are persistently stored by Home Assistant. A config entry is created by a user via the UI. The UI flow is powered by a [config flow handler](config_entries_config_flow_handler.md) as defined by the component. Config entries can also have an extra [options flow handler](config_entries_options_flow_handler.md), also defined by the component.
@ -15,65 +15,79 @@ Config Entries are configuration data that are persistently stored by Home Assis
| migration error | The config entry had to be migrated to a newer version, but the migration failed. | migration error | The config entry had to be migrated to a newer version, but the migration failed.
| failed unload | The config entry was attempted to be unloaded, but this was either not supported or it raised an exception. | failed unload | The config entry was attempted to be unloaded, but this was either not supported or it raised an exception.
More information about surfacing errors and requesting a retry are in [Handling Setup Failures](integration_setup_failures.md/#integrations-using-async_setup_entry). More information about surfacing errors and requesting a retry are in [Handling Setup Failures](integration_setup_failures.md#integrations-using-async_setup_entry).
<svg class='invertDark' width="508pt" height="188pt" viewBox="0.00 0.00 508.00 188.00" xmlns="http://www.w3.org/2000/svg"> <svg class='invertDark' width="508pt" height="188pt" viewBox="0.00 0.00 508.00 188.00" xmlns="http://www.w3.org/2000/svg">
<g id="graph1" class="graph" transform="scale(1 1) rotate(0) translate(4 184)"> <g id="graph1" class="graph" transform="scale(1 1) rotate(0) translate(4 184)">
<title>G</title> <title>G</title>
<polygon fill="none" stroke="none" points="-4,5 -4,-184 505,-184 505,5 -4,5"></polygon> <polygon fill="none" stroke="none" points="-4,5 -4,-184 505,-184 505,5 -4,5"></polygon>
<g id="node1" class="node"><title>not loaded</title> <g id="node1" class="node">
<title>not loaded</title>
<ellipse fill="none" stroke="black" cx="168" cy="-162" rx="51.3007" ry="18"></ellipse> <ellipse fill="none" stroke="black" cx="168" cy="-162" rx="51.3007" ry="18"></ellipse>
<text text-anchor="middle" x="168" y="-157.8" font-family="Times,serif" font-size="14.00">not loaded</text> <text text-anchor="middle" x="168" y="-157.8" font-family="Times,serif" font-size="14.00">not loaded</text>
</g> </g>
<g id="node3" class="node"><title>loaded</title> <g id="node3" class="node">
<title>loaded</title>
<ellipse fill="none" stroke="black" cx="61" cy="-90" rx="36.1722" ry="18"></ellipse> <ellipse fill="none" stroke="black" cx="61" cy="-90" rx="36.1722" ry="18"></ellipse>
<text text-anchor="middle" x="61" y="-85.8" font-family="Times,serif" font-size="14.00">loaded</text> <text text-anchor="middle" x="61" y="-85.8" font-family="Times,serif" font-size="14.00">loaded</text>
</g> </g>
<g id="edge2" class="edge"><title>not loaded-&gt;loaded</title> <g id="edge2" class="edge">
<title>not loaded-&gt;loaded</title>
<path fill="none" stroke="black" d="M140.518,-146.666C123.947,-136.676 103.104,-123.187 86.8392,-111.989"></path> <path fill="none" stroke="black" d="M140.518,-146.666C123.947,-136.676 103.104,-123.187 86.8392,-111.989"></path>
<polygon fill="black" stroke="black" points="88.532,-108.902 78.3309,-106.041 84.5212,-114.639 88.532,-108.902"></polygon> <polygon fill="black" stroke="black" points="88.532,-108.902 78.3309,-106.041 84.5212,-114.639 88.532,-108.902"></polygon>
</g> </g>
<g id="node5" class="node"><title>setup error</title> <g id="node5" class="node">
<title>setup error</title>
<ellipse fill="none" stroke="black" cx="168" cy="-90" rx="52.3895" ry="18"></ellipse> <ellipse fill="none" stroke="black" cx="168" cy="-90" rx="52.3895" ry="18"></ellipse>
<text text-anchor="middle" x="168" y="-85.8" font-family="Times,serif" font-size="14.00">setup error</text> <text text-anchor="middle" x="168" y="-85.8" font-family="Times,serif" font-size="14.00">setup error</text>
</g> </g>
<g id="edge4" class="edge"><title>not loaded-&gt;setup error</title> <g id="edge4" class="edge">
<title>not loaded-&gt;setup error</title>
<path fill="none" stroke="black" d="M162.122,-144.055C161.304,-136.346 161.061,-127.027 161.395,-118.364"></path> <path fill="none" stroke="black" d="M162.122,-144.055C161.304,-136.346 161.061,-127.027 161.395,-118.364"></path>
<polygon fill="black" stroke="black" points="164.894,-118.491 162.087,-108.275 157.911,-118.012 164.894,-118.491"></polygon> <polygon fill="black" stroke="black" points="164.894,-118.491 162.087,-108.275 157.911,-118.012 164.894,-118.491"></polygon>
</g> </g>
<g id="node7" class="node"><title>setup retry</title> <g id="node7" class="node">
<title>setup retry</title>
<ellipse fill="none" stroke="black" cx="291" cy="-90" rx="52.0932" ry="18"></ellipse> <ellipse fill="none" stroke="black" cx="291" cy="-90" rx="52.0932" ry="18"></ellipse>
<text text-anchor="middle" x="291" y="-85.8" font-family="Times,serif" font-size="14.00">setup retry</text> <text text-anchor="middle" x="291" y="-85.8" font-family="Times,serif" font-size="14.00">setup retry</text>
</g> </g>
<g id="edge6" class="edge"><title>not loaded-&gt;setup retry</title> <g id="edge6" class="edge">
<title>not loaded-&gt;setup retry</title>
<path fill="none" stroke="black" d="M189.578,-145.465C206.94,-134.869 231.584,-120.783 252.292,-109.59"></path> <path fill="none" stroke="black" d="M189.578,-145.465C206.94,-134.869 231.584,-120.783 252.292,-109.59"></path>
<polygon fill="black" stroke="black" points="254.022,-112.634 261.19,-104.832 250.722,-106.461 254.022,-112.634"></polygon> <polygon fill="black" stroke="black" points="254.022,-112.634 261.19,-104.832 250.722,-106.461 254.022,-112.634"></polygon>
</g> </g>
<g id="node9" class="node"><title>migration error</title> <g id="node9" class="node">
<title>migration error</title>
<ellipse fill="none" stroke="black" cx="431" cy="-90" rx="69.1427" ry="18"></ellipse> <ellipse fill="none" stroke="black" cx="431" cy="-90" rx="69.1427" ry="18"></ellipse>
<text text-anchor="middle" x="431" y="-85.8" font-family="Times,serif" font-size="14.00">migration error</text> <text text-anchor="middle" x="431" y="-85.8" font-family="Times,serif" font-size="14.00">migration error</text>
</g> </g>
<g id="edge8" class="edge"><title>not loaded-&gt;migration error</title> <g id="edge8" class="edge">
<title>not loaded-&gt;migration error</title>
<path fill="none" stroke="black" d="M207.659,-150.445C252.053,-138.628 324.343,-119.388 374.607,-106.01"></path> <path fill="none" stroke="black" d="M207.659,-150.445C252.053,-138.628 324.343,-119.388 374.607,-106.01"></path>
<polygon fill="black" stroke="black" points="375.588,-109.37 384.351,-103.416 373.787,-102.606 375.588,-109.37"></polygon> <polygon fill="black" stroke="black" points="375.588,-109.37 384.351,-103.416 373.787,-102.606 375.588,-109.37"></polygon>
</g> </g>
<g id="edge10" class="edge"><title>loaded-&gt;not loaded</title> <g id="edge10" class="edge">
<title>loaded-&gt;not loaded</title>
<path fill="none" stroke="black" d="M85.5216,-103.56C102.143,-113.462 123.939,-127.508 141.027,-139.231"></path> <path fill="none" stroke="black" d="M85.5216,-103.56C102.143,-113.462 123.939,-127.508 141.027,-139.231"></path>
<polygon fill="black" stroke="black" points="139.274,-142.276 149.481,-145.116 143.273,-136.53 139.274,-142.276"></polygon> <polygon fill="black" stroke="black" points="139.274,-142.276 149.481,-145.116 143.273,-136.53 139.274,-142.276"></polygon>
</g> </g>
<g id="node12" class="node"><title>failed unload</title> <g id="node12" class="node">
<title>failed unload</title>
<ellipse fill="none" stroke="black" cx="61" cy="-18" rx="61.5781" ry="18"></ellipse> <ellipse fill="none" stroke="black" cx="61" cy="-18" rx="61.5781" ry="18"></ellipse>
<text text-anchor="middle" x="61" y="-13.8" font-family="Times,serif" font-size="14.00">failed unload</text> <text text-anchor="middle" x="61" y="-13.8" font-family="Times,serif" font-size="14.00">failed unload</text>
</g> </g>
<g id="edge12" class="edge"><title>loaded-&gt;failed unload</title> <g id="edge12" class="edge">
<title>loaded-&gt;failed unload</title>
<path fill="none" stroke="black" d="M61,-71.6966C61,-63.9827 61,-54.7125 61,-46.1124"></path> <path fill="none" stroke="black" d="M61,-71.6966C61,-63.9827 61,-54.7125 61,-46.1124"></path>
<polygon fill="black" stroke="black" points="64.5001,-46.1043 61,-36.1043 57.5001,-46.1044 64.5001,-46.1043"></polygon> <polygon fill="black" stroke="black" points="64.5001,-46.1043 61,-36.1043 57.5001,-46.1044 64.5001,-46.1043"></polygon>
</g> </g>
<g id="edge16" class="edge"><title>setup error-&gt;not loaded</title> <g id="edge16" class="edge">
<title>setup error-&gt;not loaded</title>
<path fill="none" stroke="black" d="M173.913,-108.275C174.715,-116.03 174.94,-125.362 174.591,-134.005"></path> <path fill="none" stroke="black" d="M173.913,-108.275C174.715,-116.03 174.94,-125.362 174.591,-134.005"></path>
<polygon fill="black" stroke="black" points="171.094,-133.832 173.878,-144.055 178.077,-134.327 171.094,-133.832"></polygon> <polygon fill="black" stroke="black" points="171.094,-133.832 173.878,-144.055 178.077,-134.327 171.094,-133.832"></polygon>
</g> </g>
<g id="edge14" class="edge"><title>setup retry-&gt;not loaded</title> <g id="edge14" class="edge">
<title>setup retry-&gt;not loaded</title>
<path fill="none" stroke="black" d="M269.469,-106.507C252.104,-117.106 227.436,-131.206 206.71,-142.408"></path> <path fill="none" stroke="black" d="M269.469,-106.507C252.104,-117.106 227.436,-131.206 206.71,-142.408"></path>
<polygon fill="black" stroke="black" points="204.973,-139.368 197.805,-147.17 208.273,-145.541 204.973,-139.368"></polygon> <polygon fill="black" stroke="black" points="204.973,-139.368 197.805,-147.17 208.273,-145.541 204.973,-139.368"></polygon>
</g> </g>
@ -98,23 +112,18 @@ digraph G {
During startup, Home Assistant first calls the [normal component setup](/creating_component_index.md), During startup, Home Assistant first calls the [normal component setup](/creating_component_index.md),
and then call the method `async_setup_entry(hass, entry)` for each entry. If a new Config Entry is and then call the method `async_setup_entry(hass, entry)` for each entry. If a new Config Entry is
created at runtime, Home Assistant will also call `async_setup_entry(hass, entry)` ([example](https://github.com/home-assistant/core/blob/0.68.0/homeassistant/components/hue/__init__.py#L119)). created at runtime, Home Assistant will also call `async_setup_entry(hass, entry)` ([example](https://github.com/home-assistant/core/blob/f18ddb628c3574bc82e21563d9ba901bd75bc8b5/homeassistant/components/hassio/__init__.py#L522)).
### For platforms ### For platforms
If a component includes platforms, it will need to forward the Config Entry to the platform. This can If a component includes platforms, it will need to forward the Config Entry to the platform. This can
be done by calling the forward function on the config entry manager ([example](https://github.com/home-assistant/core/blob/0.68.0/homeassistant/components/hue/bridge.py#L81)): be done by calling the forward function on the config entry manager ([example](https://github.com/home-assistant/core/blob/f18ddb628c3574bc82e21563d9ba901bd75bc8b5/homeassistant/components/hassio/__init__.py#L529)):
```python ```python
# Use `hass.async_create_task` to avoid a circular dependency between the platform and the component await hass.config_entries.async_forward_entry_setups(config_entry, ["light", "sensor", "switch"])
hass.async_create_task(
hass.config_entries.async_forward_entry_setup(
config_entry, "light"
)
)
``` ```
For a platform to support config entries, it will need to add a setup entry method ([example](https://github.com/home-assistant/core/blob/0.68.0/homeassistant/components/light/hue.py#L60)): For a platform to support config entries, it will need to add a setup entry method ([example](https://github.com/home-assistant/core/blob/f18ddb628c3574bc82e21563d9ba901bd75bc8b5/homeassistant/components/hassio/__init__.py#L522)):
```python ```python
async def async_setup_entry(hass, config_entry, async_add_entities): async def async_setup_entry(hass, config_entry, async_add_entities):
@ -123,7 +132,7 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
## Unloading entries ## Unloading entries
Components can optionally support unloading a config entry. When unloading an entry, the component needs to clean up all entities, unsubscribe any event listener and close all connections. To implement this, add `async_unload_entry(hass, entry)` to your component ([example](https://github.com/home-assistant/core/blob/0.68.0/homeassistant/components/hue/__init__.py#L136)). Components can optionally support unloading a config entry. When unloading an entry, the component needs to clean up all entities, unsubscribe any event listener and close all connections. To implement this, add `async_unload_entry(hass, entry)` to your component ([example](https://github.com/home-assistant/core/blob/f18ddb628c3574bc82e21563d9ba901bd75bc8b5/homeassistant/components/hassio/__init__.py#L534)).
For each platform that you forwarded the config entry to, you will need to forward the unloading too. For each platform that you forwarded the config entry to, you will need to forward the unloading too.

View File

@ -1,5 +1,5 @@
--- ---
title: Options Flow title: Options flow
--- ---
An integration that is configured via a config entry can expose options to the user to allow tweaking behavior of the integration, like which devices or locations should be integrated. An integration that is configured via a config entry can expose options to the user to allow tweaking behavior of the integration, like which devices or locations should be integrated.

View File

@ -1,5 +1,5 @@
--- ---
title: "Integration Configuration via YAML" title: "Integration configuration via YAML"
--- ---
`configuration.yaml` is a configuration file defined by the user. It is automatically created by Home Assistant on first launch. It defines which components to load. `configuration.yaml` is a configuration file defined by the user. It is automatically created by Home Assistant on first launch. It defines which components to load.

View File

@ -1,5 +1,5 @@
--- ---
title: "Fetching Bluetooth Data" title: "Fetching Bluetooth data"
--- ---
## Choosing a method to fetch data ## Choosing a method to fetch data

View File

@ -388,7 +388,7 @@ There are two ways to provide a custom icon for an entity, either by providing i
### Icon translations ### Icon translations
This is the preferred and most modern way to provide a custom icon for an entity. Icon translations work similarly to [our regular translations](/docs/internationalization/core#state-of-entities), but instead of translating the state of an entity, they translate the states of an entity to icons. This is the preferred way to provide a custom icon for an entity. Icon translations work similarly to [our regular translations](/docs/internationalization/core#state-of-entities), but instead of translating the state of an entity, they translate the states of an entity to icons.
The `translation_key` property of an entity defines the icon translation to use. This property is used to look up the translation in the `entity` section of the integration's `icons.json` file. The `translation_key` property of an entity defines the icon translation to use. This property is used to look up the translation in the `entity` section of the integration's `icons.json` file.
@ -414,7 +414,7 @@ To differentiate entities and their translations, provide different translation
Notice that icons start with `mdi:` plus an [identifier](https://materialdesignicons.com/). The `default` icon is used when the entity's state is not in the `state` section. The `state` section is optional, and if not provided, the `default` icon will be used for all states. Notice that icons start with `mdi:` plus an [identifier](https://materialdesignicons.com/). The `default` icon is used when the entity's state is not in the `state` section. The `state` section is optional, and if not provided, the `default` icon will be used for all states.
Icons for entity state attributes can also be provided. The following example provides icons for a `climate` entity with its `translation_key` property set to `ubercool`. This entity has a `preset_mode` state attribute, which can be set to `vacation` or `night`. The frontend will use these in, for example, the climate card. Icons for entity state attributes can also be provided in cases where the frontend shows icons for the state attributes. Examples include climate presets and fan modes. It's not possible to provide icons for other state attributes. The following example provides icons for a `climate` entity with its `translation_key` property set to `ubercool`. This entity has a `preset_mode` state attribute, which can be set to `vacation` or `night`. The frontend will use these in, for example, the climate card.
```json ```json
{ {
@ -438,7 +438,7 @@ Icons for entity state attributes can also be provided. The following example pr
### Icon property ### Icon property
Another way to provide an icon for an entity is by setting the `icon` property of an entity, which returns a string referencing the `mdi` icon. As this property is a method, it is possible to return different icons based on custom logic. For example, it could be possible to return different icons based on something that is not part of the entity's state. Another way to provide an icon for an entity is by setting the `icon` property of an entity, which returns a string referencing the `mdi` icon. As this property is a method, it is possible to return different icons based on custom logic unlike with icon translations. For example, it's possible to calculate the icon based on the state as in the example below, or return different icons based on something that is not part of the entity's state.
```python ```python
class MySwitch(SwitchEntity): class MySwitch(SwitchEntity):
@ -461,6 +461,10 @@ State attributes which are not suitable for state history recording should be ex
- `_entity_component_unrecorded_attributes: frozenset[str]` may be set in a base component class, e.g. in `light.LightEntity` - `_entity_component_unrecorded_attributes: frozenset[str]` may be set in a base component class, e.g. in `light.LightEntity`
- `_unrecorded_attributes: frozenset[str]` may be set in an integration's platform e.g. in an entity class defined in platform `hue.light`. - `_unrecorded_attributes: frozenset[str]` may be set in an integration's platform e.g. in an entity class defined in platform `hue.light`.
The `MATCH_ALL` constant can be used to exclude all attributes instead of typing them separately. This can be useful for integrations providing unknown attributes or when you simply want to exclude all without typing them separately.
Using the `MATCH_ALL` constant does not stop recording for `device_class`, `state_class`, `unit_of_measurement`, and `friendly_name` as they might also serve other purposes and, therefore, should not be excluded from recording.
Examples of platform state attributes which are exluded from recording include the `entity_picture` attribute of `image` entities which will not be valid after some time, the `preset_modes` attribute of `fan` entities which is not likely to change. Examples of platform state attributes which are exluded from recording include the `entity_picture` attribute of `image` entities which will not be valid after some time, the `preset_modes` attribute of `fan` entities which is not likely to change.
Examples of integration specific state attributes which are excluded from recording include `description` and `location` state attributes in platform `trafikverket.camera` which do not change. Examples of integration specific state attributes which are excluded from recording include `description` and `location` state attributes in platform `trafikverket.camera` which do not change.

View File

@ -1,6 +1,6 @@
--- ---
title: Air Quality Entity title: Air quality entity
sidebar_label: Air Quality sidebar_label: Air quality
--- ---
## Properties ## Properties
@ -19,9 +19,9 @@ The Air Quality entity does not support attribute shorthand for [property implem
| Name | Type | Default | Description | Name | Type | Default | Description
| ---- | ---- | ------- | ----------- | ---- | ---- | ------- | -----------
| particulate_matter_2_5 | <code>str &#124; int &#124; float &#124; None</code> | **Required** | The particulate matter 2.5 (<= 2.5 μm) level. | particulate_matter_2_5 | <code>str &#124; int &#124; float &#124; None</code> | **Required** | The particulate matter 2.5 (\<= 2.5 μm) level.
| particulate_matter_10 | <code>str &#124; int &#124; float &#124; None</code> | `None` | The particulate matter 10 (<= 10 μm) level. | particulate_matter_10 | <code>str &#124; int &#124; float &#124; None</code> | `None` | The particulate matter 10 (\<= 10 μm) level.
| particulate_matter_0_1 | <code>str &#124; int &#124; float &#124; None</code> | `None` | The particulate matter 0.1 (<= 0.1 μm) level. | particulate_matter_0_1 | <code>str &#124; int &#124; float &#124; None</code> | `None` | The particulate matter 0.1 (\<= 0.1 μm) level.
| air_quality_index | <code>str &#124; int &#124; float &#124; None</code> | `None` | The Air Quality Index (AQI). | air_quality_index | <code>str &#124; int &#124; float &#124; None</code> | `None` | The Air Quality Index (AQI).
| ozone | <code>str &#124; int &#124; float &#124; None</code> | `None` | The O3 (ozone) level. | ozone | <code>str &#124; int &#124; float &#124; None</code> | `None` | The O3 (ozone) level.
| carbon_monoxide | <code>str &#124; int &#124; float &#124; None</code> | `None` | The CO (carbon monoxide) level. | carbon_monoxide | <code>str &#124; int &#124; float &#124; None</code> | `None` | The CO (carbon monoxide) level.

View File

@ -1,6 +1,6 @@
--- ---
title: Alarm Control Panel Entity title: Alarm control panel entity
sidebar_label: Alarm Control Panel sidebar_label: Alarm control panel
--- ---
An alarm control panel entity controls an alarm. Derive a platform entity from [`homeassistant.components.alarm_control_panel.AlarmControlPanelEntity`](https://github.com/home-assistant/core/blob/dev/homeassistant/components/alarm_control_panel/__init__.py). An alarm control panel entity controls an alarm. Derive a platform entity from [`homeassistant.components.alarm_control_panel.AlarmControlPanelEntity`](https://github.com/home-assistant/core/blob/dev/homeassistant/components/alarm_control_panel/__init__.py).
@ -34,7 +34,7 @@ Properties should always only return information from memory and not do I/O (lik
| `disarming` | The alarm is disarming. | `disarming` | The alarm is disarming.
| `triggered` | The alarm is triggered. | `triggered` | The alarm is triggered.
## Supported Features ## Supported features
Supported features are defined by using values in the `AlarmControlPanelEntityFeature` enum Supported features are defined by using values in the `AlarmControlPanelEntityFeature` enum
and are combined using the bitwise or (`|`) operator. and are combined using the bitwise or (`|`) operator.
@ -48,7 +48,7 @@ and are combined using the bitwise or (`|`) operator.
| `AlarmControlPanelEntityFeature.ARM_VACATION` | The alarm supports arming in vacation mode. | `AlarmControlPanelEntityFeature.ARM_VACATION` | The alarm supports arming in vacation mode.
| `AlarmControlPanelEntityFeature.TRIGGER` | The alarm can be triggered remotely. | `AlarmControlPanelEntityFeature.TRIGGER` | The alarm can be triggered remotely.
### Code Formats ### Code formats
Supported code formats are defined by using values in the `CodeFormat` enum. Supported code formats are defined by using values in the `CodeFormat` enum.
@ -75,7 +75,7 @@ class MyAlarm(AlarmControlPanelEntity):
"""Send disarm command.""" """Send disarm command."""
``` ```
### Alarm Arm Home ### Alarm arm home
Send arm home command. Send arm home command.
@ -90,7 +90,7 @@ class MyAlarm(AlarmControlPanelEntity):
"""Send arm home command.""" """Send arm home command."""
``` ```
### Alarm Arm Away ### Alarm arm away
Send arm away command. Send arm away command.
@ -105,7 +105,7 @@ class MyAlarm(AlarmControlPanelEntity):
"""Send arm away command.""" """Send arm away command."""
``` ```
### Alarm Arm Night ### Alarm arm night
Send arm night command. Send arm night command.
@ -120,7 +120,7 @@ class MyAlarm(AlarmControlPanelEntity):
"""Send arm night command.""" """Send arm night command."""
``` ```
### Alarm Arm Vacation ### Alarm arm vacation
Send arm vacation command. Send arm vacation command.
@ -135,7 +135,7 @@ class MyAlarm(AlarmControlPanelEntity):
"""Send arm vacation command.""" """Send arm vacation command."""
``` ```
### Alarm Trigger ### Alarm trigger
Send alarm trigger command. Send alarm trigger command.
@ -150,7 +150,7 @@ class MyAlarm(AlarmControlPanelEntity):
"""Send alarm trigger command.""" """Send alarm trigger command."""
``` ```
### Alarm Custom Bypass ### Alarm custom bypass
Send arm custom bypass command. Send arm custom bypass command.

View File

@ -1,6 +1,6 @@
--- ---
title: Binary Sensor Entity title: Binary sensor entity
sidebar_label: Binary Sensor sidebar_label: Binary sensor
--- ---
A binary sensor is a sensor that can only have two states. Derive entity platforms from [`homeassistant.components.binary_sensor.BinarySensorEntity`](https://github.com/home-assistant/home-assistant/blob/master/homeassistant/components/binary_sensor/__init__.py) A binary sensor is a sensor that can only have two states. Derive entity platforms from [`homeassistant.components.binary_sensor.BinarySensorEntity`](https://github.com/home-assistant/home-assistant/blob/master/homeassistant/components/binary_sensor/__init__.py)

View File

@ -1,5 +1,5 @@
--- ---
title: Button Entity title: Button entity
sidebar_label: Button sidebar_label: Button
--- ---
@ -27,7 +27,7 @@ Other properties that are common to all entities such as `device_class`, `icon`,
The press method can be used to trigger an action towards a device or service. The press method can be used to trigger an action towards a device or service.
It is called by Home Assistant when the user presses the button or the It is called by Home Assistant when the user presses the button or the
service to press the button has been called. action to press the button has been called.
```python ```python
class MyButton(ButtonEntity): class MyButton(ButtonEntity):

View File

@ -1,5 +1,5 @@
--- ---
title: Calendar Entity title: Calendar entity
sidebar_label: Calendar sidebar_label: Calendar
--- ---
@ -37,7 +37,7 @@ Assistant timezone. An entity should call `homeassistant.util.dt.now` to get the
current time which has a `tzinfo` value set to the HomeAssistant timezone or examine current time which has a `tzinfo` value set to the HomeAssistant timezone or examine
`homeassistant.components.util.dt.DEFAULT_TIMEZONE` `homeassistant.components.util.dt.DEFAULT_TIMEZONE`
## Supported Features ## Supported features
Supported features are defined by using values in the `CalendarEntityFeature` enum Supported features are defined by using values in the `CalendarEntityFeature` enum
and are combined using the bitwise or (`|`) operator. and are combined using the bitwise or (`|`) operator.
@ -50,7 +50,7 @@ and are combined using the bitwise or (`|`) operator.
## Methods ## Methods
### Get Events ### Get events
A calendar entity can return events that occur during a particular time range. Some notes for implementors: A calendar entity can return events that occur during a particular time range. Some notes for implementors:
@ -80,7 +80,7 @@ class MyCalendar(CalendarEntity):
"""Return calendar events within a datetime range.""" """Return calendar events within a datetime range."""
``` ```
### Create Events ### Create events
A calendar entity may support creating events by specifying the `CREATE_EVENT` supported feature. Integrations that support mutation must handle rfc5545 fields and best practices such as preserving any new unknown fields that are set and recurring events. A calendar entity may support creating events by specifying the `CREATE_EVENT` supported feature. Integrations that support mutation must handle rfc5545 fields and best practices such as preserving any new unknown fields that are set and recurring events.
@ -93,7 +93,7 @@ class MyCalendar(CalendarEntity):
"""Add a new event to calendar.""" """Add a new event to calendar."""
``` ```
### Delete Events ### Delete events
A calendar entity may support deleting events by specifying the `DELETE_EVENT` supported feature. Integrations that support mutation must support rfc5545 recurring events. A calendar entity may support deleting events by specifying the `DELETE_EVENT` supported feature. Integrations that support mutation must support rfc5545 recurring events.
@ -118,7 +118,7 @@ class MyCalendar(CalendarEntity):
"""Delete an event on the calendar.""" """Delete an event on the calendar."""
``` ```
### Update Events ### Update events
A calendar entity may support updating events by specifying the `UPDATE_EVENT` supported feature. Integrations that support mutation must support rfc5545 recurring events. A calendar entity may support updating events by specifying the `UPDATE_EVENT` supported feature. Integrations that support mutation must support rfc5545 recurring events.

View File

@ -1,5 +1,5 @@
--- ---
title: Camera Entity title: Camera entity
sidebar_label: Camera sidebar_label: Camera
--- ---
@ -23,7 +23,7 @@ Properties should always only return information from memory and not do I/O (lik
| motion_detection_enabled | `bool` | `False` | Indication of whether the camera has motion detection enabled. | | motion_detection_enabled | `bool` | `False` | Indication of whether the camera has motion detection enabled. |
| use_stream_for_stills | `bool` | `False` | Determines whether or not to use the `Stream` integration to generate still images | | use_stream_for_stills | `bool` | `False` | Determines whether or not to use the `Stream` integration to generate still images |
## Supported Features ## Supported features
Supported features are defined by using values in the `CameraEntityFeature` enum Supported features are defined by using values in the `CameraEntityFeature` enum
and are combined using the bitwise or (`|`) operator. and are combined using the bitwise or (`|`) operator.
@ -35,7 +35,7 @@ and are combined using the bitwise or (`|`) operator.
## Methods ## Methods
### Camera Image ### Camera image
When the width and height are passed, scaling should be done on a best-effort basis. The UI will fall back to scaling at the display layer if scaling cannot be done by the camera. When the width and height are passed, scaling should be done on a best-effort basis. The UI will fall back to scaling at the display layer if scaling cannot be done by the camera.
@ -64,7 +64,7 @@ class MyCamera(Camera):
``` ```
### Stream Source ### Stream source
The stream source should return a url that is usable by ffmpeg (e.g. an RTSP url). Requires `CameraEntityFeature.STREAM`. The stream source should return a url that is usable by ffmpeg (e.g. an RTSP url). Requires `CameraEntityFeature.STREAM`.
@ -80,7 +80,7 @@ class MyCamera(Camera):
A common way for a camera entity to render a camera still image is to pass the stream source to `async_get_image` in the `ffmpeg` component. A common way for a camera entity to render a camera still image is to pass the stream source to `async_get_image` in the `ffmpeg` component.
### WebRTC Streams ### WebRTC streams
WebRTC enabled cameras can be used by facilitating a direct connection with the home assistant frontend. This usage requires `CameraEntityFeature.STREAM` with `frontend_stream_type` set to `StreamType.WEB_RTC`. The integration should implement `async_handle_web_rtc_offer` which passes the frontend's SDP offer to the device and returns back the answer. WebRTC enabled cameras can be used by facilitating a direct connection with the home assistant frontend. This usage requires `CameraEntityFeature.STREAM` with `frontend_stream_type` set to `StreamType.WEB_RTC`. The integration should implement `async_handle_web_rtc_offer` which passes the frontend's SDP offer to the device and returns back the answer.

View File

@ -1,5 +1,5 @@
--- ---
title: Climate Entity title: Climate entity
sidebar_label: Climate sidebar_label: Climate
--- ---
@ -52,7 +52,7 @@ enum. If you want another mode, add a preset instead.
| `HVACMode.DRY` | The device is set to dry/humidity mode. | | `HVACMode.DRY` | The device is set to dry/humidity mode. |
| `HVACMode.FAN_ONLY` | The device only has the fan on. No heating or cooling taking place. | | `HVACMode.FAN_ONLY` | The device only has the fan on. No heating or cooling taking place. |
### HVAC Action ### HVAC action
The HVAC action describes the _current_ action. This is different from the mode, because if a device is set to heat, and the target temperature is already achieved, the device will not be actively heating anymore. It is only allowed to use the built-in HVAC actions, provided by the `HVACAction` enum. The HVAC action describes the _current_ action. This is different from the mode, because if a device is set to heat, and the target temperature is already achieved, the device will not be actively heating anymore. It is only allowed to use the built-in HVAC actions, provided by the `HVACAction` enum.
@ -65,6 +65,7 @@ The HVAC action describes the _current_ action. This is different from the mode,
| `HVACAction.DRYING` | Device is drying. | | `HVACAction.DRYING` | Device is drying. |
| `HVACAction.FAN` | Device has fan on. | | `HVACAction.FAN` | Device has fan on. |
| `HVACAction.IDLE` | Device is idle. | | `HVACAction.IDLE` | Device is idle. |
| `HVACAction.DEFROSTING` | Device is defrosting. |
### Presets ### Presets
@ -109,7 +110,7 @@ The device fan can have different swing modes that it wants the user to know abo
| `SWING_HORIZONTAL` | The fan is swinging horizontal. | | `SWING_HORIZONTAL` | The fan is swinging horizontal. |
| `SWING_BOTH` | The fan is swinging both horizontal and vertical. | | `SWING_BOTH` | The fan is swinging both horizontal and vertical. |
## Supported Features ## Supported features
Supported features are defined by using values in the `ClimateEntityFeature` enum Supported features are defined by using values in the `ClimateEntityFeature` enum
and are combined using the bitwise or (`|`) operator. and are combined using the bitwise or (`|`) operator.
@ -146,8 +147,8 @@ class MyClimateEntity(ClimateEntity):
class MyClimateEntity(ClimateEntity): class MyClimateEntity(ClimateEntity):
# Implement one of these methods. # Implement one of these methods.
# The `turn_on` method should set `hvac_mode` to any other than # The `turn_on` method should set `hvac_mode` to any other than
# `HVACMode.OFF` by optimistically setting it from the service handler # `HVACMode.OFF` by optimistically setting it from the service action
# or with the next state update # handler or with the next state update
def turn_on(self): def turn_on(self):
"""Turn the entity on.""" """Turn the entity on."""
@ -162,7 +163,8 @@ class MyClimateEntity(ClimateEntity):
class MyClimateEntity(ClimateEntity): class MyClimateEntity(ClimateEntity):
# Implement one of these methods. # Implement one of these methods.
# The `turn_off` method should set `hvac_mode` to `HVACMode.OFF` by # The `turn_off` method should set `hvac_mode` to `HVACMode.OFF` by
# optimistically setting it from the service handler or with the next state update # optimistically setting it from the service action handler or with the
# next state update
def turn_off(self): def turn_off(self):
"""Turn the entity off.""" """Turn the entity off."""
@ -179,7 +181,8 @@ class MyClimateEntity(ClimateEntity):
# will call `turn_on`/`turn_off` according to the current HVAC mode. # will call `turn_on`/`turn_off` according to the current HVAC mode.
# If implemented, the `toggle` method should set `hvac_mode` to the right `HVACMode` by # If implemented, the `toggle` method should set `hvac_mode` to the right `HVACMode` by
# optimistically setting it from the service handler or with the next state update. # optimistically setting it from the service action handler
# or with the next state update.
def toggle(self): def toggle(self):
"""Toggle the entity.""" """Toggle the entity."""

View File

@ -1,5 +1,5 @@
--- ---
title: Conversation Entity title: Conversation entity
sidebar_label: Conversation sidebar_label: Conversation
--- ---
@ -17,6 +17,15 @@ Properties should always only return information from memory and not do I/O (lik
| ---- | ---- | ------- | ----------- | ---- | ---- | ------- | -----------
| supported_languages | `list[str]` \| `Literal["*"]` | **Required** | The supported languages of the service. Return `"*"` if you support all. | supported_languages | `list[str]` \| `Literal["*"]` | **Required** | The supported languages of the service. Return `"*"` if you support all.
## Supported features
Supported features are defined by using values in the `ConversationEntityFeature` enum
and are combined using the bitwise or (`|`) operator.
| Value | Description
| -------------------------- | -------------------------------------------------------------------------------------------
| `CONTROL` | The entity is able to control Home Assistant.
## Methods ## Methods
### Process ### Process

View File

@ -1,5 +1,5 @@
--- ---
title: Cover Entity title: Cover entity
sidebar_label: Cover sidebar_label: Cover
--- ---
@ -19,7 +19,7 @@ Properties should always only return information from memory and not do I/O (lik
| is_closing | <code>bool &#124; None</code> | `None` | If the cover is closing or not. Used to determine `state`. | is_closing | <code>bool &#124; None</code> | `None` | If the cover is closing or not. Used to determine `state`.
| is_opening | <code>bool &#124; None</code> | `None` | If the cover is opening or not. Used to determine `state`. | is_opening | <code>bool &#124; None</code> | `None` | If the cover is opening or not. Used to determine `state`.
### Device Classes ### Device classes
| Constant | Description | Constant | Description
|----------|-----------------------| |----------|-----------------------|
@ -43,7 +43,7 @@ Properties should always only return information from memory and not do I/O (lik
| `STATE_CLOSING` | The cover is in the process of closing to reach a set position. | `STATE_CLOSING` | The cover is in the process of closing to reach a set position.
| `STATE_CLOSED` | The cover has reach the closed position. | `STATE_CLOSED` | The cover has reach the closed position.
## Supported Features ## Supported features
Supported features are defined by using values in the `CoverEntityFeature` enum Supported features are defined by using values in the `CoverEntityFeature` enum
and are combined using the bitwise or (`|`) operator. and are combined using the bitwise or (`|`) operator.

View File

@ -1,5 +1,5 @@
--- ---
title: Date Entity title: Date entity
sidebar_label: Date sidebar_label: Date
--- ---

View File

@ -1,5 +1,5 @@
--- ---
title: Date/Time Entity title: Date/Time entity
sidebar_label: Date/Time sidebar_label: Date/Time
--- ---

View File

@ -1,6 +1,6 @@
--- ---
title: Device Tracker Entity title: Device tracker entity
sidebar_label: Device Tracker sidebar_label: Device tracker
--- ---
A device tracker is a read-only entity that provides presence information. There are two types of device tracker entities, a ScannerEntity and a TrackerEntity. A device tracker is a read-only entity that provides presence information. There are two types of device tracker entities, a ScannerEntity and a TrackerEntity.

View File

@ -1,5 +1,5 @@
--- ---
title: Fan Entity title: Fan entity
sidebar_label: Fan sidebar_label: Fan
--- ---
@ -21,15 +21,15 @@ Properties should always only return information from memory and not do I/O (lik
| preset_modes | <code>list[str] &#124; None</code> | `None` | The list of supported preset_modes. This is an arbitrary list of str and should not contain any speeds. | | preset_modes | <code>list[str] &#124; None</code> | `None` | The list of supported preset_modes. This is an arbitrary list of str and should not contain any speeds. |
| speed_count | `int` | 100 | The number of speeds the fan supports. | | speed_count | `int` | 100 | The number of speeds the fan supports. |
### Preset Modes ### Preset modes
A fan may have preset modes that automatically control the percentage speed or other functionality. Common examples include `auto`, `smart`, `whoosh`, `eco`, and `breeze`. If no preset mode is set, the `preset_mode` property must be set to `None`. A fan may have preset modes that automatically control the percentage speed or other functionality. Common examples include `auto`, `smart`, `whoosh`, `eco`, and `breeze`. If no preset mode is set, the `preset_mode` property must be set to `None`.
Preset modes should not include named (manual) speed settings as these should be represented as percentages. Preset modes should not include named (manual) speed settings as these should be represented as percentages.
Manually setting a speed must disable any set preset mode. If it is possible to set a percentage speed manually without disabling the preset mode, create a switch or service to represent the mode. Manually setting a speed must disable any set preset mode. If it is possible to set a percentage speed manually without disabling the preset mode, create a switch or service action to represent the mode.
## Supported Features ## Supported features
Supported features are defined by using values in the `FanEntityFeature` enum Supported features are defined by using values in the `FanEntityFeature` enum
and are combined using the bitwise or (`|`) operator. and are combined using the bitwise or (`|`) operator.
@ -40,12 +40,14 @@ and are combined using the bitwise or (`|`) operator.
| `OSCILLATE` | The fan supports oscillation. | | `OSCILLATE` | The fan supports oscillation. |
| `PRESET_MODE` | The fan supports preset modes. | | `PRESET_MODE` | The fan supports preset modes. |
| `SET_SPEED` | The fan supports setting the speed percentage and optional preset modes. | | `SET_SPEED` | The fan supports setting the speed percentage and optional preset modes. |
| `TURN_OFF` | The fan supports turning off. |
| `TURN_ON` | The fan supports turning on. |
## Methods ## Methods
### Set direction ### Set direction
Only implement this method if the flag `SUPPORT_DIRECTION` is set. Only implement this method if the flag `FanEntityFeature.DIRECTION` is set.
```python ```python
class FanEntity(ToggleEntity): class FanEntity(ToggleEntity):
@ -60,7 +62,7 @@ class FanEntity(ToggleEntity):
### Set preset mode ### Set preset mode
Only implement this method if the flag `SUPPORT_PRESET_MODE` is set. Only implement this method if the flag `FanEntityFeature.PRESET_MODE` is set.
```python ```python
class FanEntity(ToggleEntity): class FanEntity(ToggleEntity):
@ -75,7 +77,7 @@ class FanEntity(ToggleEntity):
### Set speed percentage ### Set speed percentage
Only implement this method if the flag `SUPPORT_SET_SPEED` is set. Only implement this method if the flag `FanEntityFeature.SET_SPEED` is set.
```python ```python
class FanEntity(ToggleEntity): class FanEntity(ToggleEntity):
@ -144,6 +146,8 @@ value_in_range = math.ceil(percentage_to_ranged_value(SPEED_RANGE, 50))
### Turn on ### Turn on
Only implement this method if the flag `FanEntityFeature.TURN_ON` is set.
```python ```python
class FanEntity(ToggleEntity): class FanEntity(ToggleEntity):
# Implement one of these methods. # Implement one of these methods.
@ -163,6 +167,8 @@ For new intergrations, `speed` should not be implemented and only `percentage` a
### Turn off ### Turn off
Only implement this method if the flag `FanEntityFeature.TURN_OFF` is set.
```python ```python
class FanEntity(ToggleEntity): class FanEntity(ToggleEntity):
# Implement one of these methods. # Implement one of these methods.
@ -177,6 +183,7 @@ class FanEntity(ToggleEntity):
### Toggle ### Toggle
Optional. If not implemented will default to checking what method to call using the is_on property. Optional. If not implemented will default to checking what method to call using the is_on property.
Only implement this method if the flags `FanEntityFeature.TURN_ON` and `FanEntityFeature.TURN_OFF` are set.
```python ```python
class FanEntity(ToggleEntity): class FanEntity(ToggleEntity):
@ -191,7 +198,7 @@ class FanEntity(ToggleEntity):
### Oscillate ### Oscillate
Only implement this method if the flag `SUPPORT_OSCILLATE` is set. Only implement this method if the flag `FanEntityFeature.OSCILLATE` is set.
```python ```python
class FanEntity(ToggleEntity): class FanEntity(ToggleEntity):

View File

@ -1,5 +1,5 @@
--- ---
title: Humidifier Entity title: Humidifier entity
sidebar_label: Humidifier sidebar_label: Humidifier
--- ---
@ -25,10 +25,10 @@ Properties should always only return information from memory and not do I/O (lik
### Available device classes ### Available device classes
| Constant | Description | Constant | Description |
| ----------------------------------- | ------------------------------------------ | ------------------------------------ | ------------------------------------------ |
| `HumidiferDeviceClass.DEHUMIDIFIER` | A dehumidifier | `HumidifierDeviceClass.DEHUMIDIFIER` | A dehumidifier |
| `HumidifierDeviceClass.HUMIDIFIER` | A humidifier | `HumidifierDeviceClass.HUMIDIFIER` | A humidifier |
### Modes ### Modes
@ -47,7 +47,7 @@ A device can have different modes of operation that it might want to show to the
| `MODE_AUTO` | Device is controlling humidity by itself | | `MODE_AUTO` | Device is controlling humidity by itself |
| `MODE_BABY` | Device is trying to optimize for babies | | `MODE_BABY` | Device is trying to optimize for babies |
## Supported Features ## Supported features
Supported features are defined by using values in the `HumidifierEntityFeature` enum Supported features are defined by using values in the `HumidifierEntityFeature` enum
and are combined using the bitwise or (`|`) operator. and are combined using the bitwise or (`|`) operator.

View File

@ -1,5 +1,5 @@
--- ---
title: Image Entity title: Image entity
sidebar_label: Image sidebar_label: Image
--- ---

View File

@ -1,6 +1,6 @@
--- ---
title: Lawn Mower Entity title: Lawn mower entity
sidebar_label: Lawn Mower sidebar_label: Lawn mower
--- ---
Derive entity platforms from [`homeassistant.components.lawn_mower.LawnMowerEntity`](https://github.com/home-assistant/home-assistant/blob/master/homeassistant/components/lawn_mower/__init__.py) Derive entity platforms from [`homeassistant.components.lawn_mower.LawnMowerEntity`](https://github.com/home-assistant/home-assistant/blob/master/homeassistant/components/lawn_mower/__init__.py)
@ -25,7 +25,7 @@ Properties should always only return information from memory and not do I/O (lik
| `PAUSED` | The lawn mower was active and is now paused. | `PAUSED` | The lawn mower was active and is now paused.
| `ERROR` | The lawn mower encountered an error while active and needs assistance. | `ERROR` | The lawn mower encountered an error while active and needs assistance.
## Supported Features ## Supported features
Supported features are defined by using values in the `LawnMowerEntityFeature` enum Supported features are defined by using values in the `LawnMowerEntityFeature` enum
and are combined using the bitwise or (`|`) operator. and are combined using the bitwise or (`|`) operator.

View File

@ -1,5 +1,5 @@
--- ---
title: Light Entity title: Light entity
sidebar_label: Light sidebar_label: Light
--- ---
@ -25,7 +25,7 @@ A light entity controls the brightness, hue and saturation color value, white va
| supported_color_modes | <code>set[ColorMode] &#124; None</code> | `None` | Flag supported color modes. | supported_color_modes | <code>set[ColorMode] &#124; None</code> | `None` | Flag supported color modes.
| xy_color | <code>tuple[float, float] &#124; None</code> | `None` | The xy color value (float, float). This property will be copied to the light's state attribute when the light's color mode is set to `ColorMode.XY` and ignored otherwise. | xy_color | <code>tuple[float, float] &#124; None</code> | `None` | The xy color value (float, float). This property will be copied to the light's state attribute when the light's color mode is set to `ColorMode.XY` and ignored otherwise.
## Color Modes ## Color modes
New integrations must implement both `color_mode` and `supported_color_modes`. If an integration is upgraded to support color mode, both `color_mode` and `supported_color_modes` should be implemented. New integrations must implement both `color_mode` and `supported_color_modes`. If an integration is upgraded to support color mode, both `color_mode` and `supported_color_modes` should be implemented.
@ -59,7 +59,7 @@ If a light does not implement the `color_mode`, the `LightEntity` will attempt t
| `ColorMode.RGB` | The light can be dimmed and its color can be adjusted. The light's brightness can be set using the `brightness` parameter and read through the `brightness` property. The light's color can be set using the `rgb_color` parameter and read through the `rgb_color` property. `rgb_color` is an (r, g, b) tuple (not normalized for brightness). | `ColorMode.RGB` | The light can be dimmed and its color can be adjusted. The light's brightness can be set using the `brightness` parameter and read through the `brightness` property. The light's color can be set using the `rgb_color` parameter and read through the `rgb_color` property. `rgb_color` is an (r, g, b) tuple (not normalized for brightness).
| `ColorMode.RGBW` | The light can be dimmed and its color can be adjusted. The light's brightness can be set using the `brightness` parameter and read through the `brightness` property. The light's color can be set using the `rgbw_color` parameter and read through the `rgbw_color` property. `rgbw_color` is an (r, g, b, w) tuple (not normalized for brightness). | `ColorMode.RGBW` | The light can be dimmed and its color can be adjusted. The light's brightness can be set using the `brightness` parameter and read through the `brightness` property. The light's color can be set using the `rgbw_color` parameter and read through the `rgbw_color` property. `rgbw_color` is an (r, g, b, w) tuple (not normalized for brightness).
| `ColorMode.RGBWW` | The light can be dimmed and its color can be adjusted. The light's brightness can be set using the `brightness` parameter and read through the `brightness` property. The light's color can be set using the `rgbww_color` parameter and read through the `rgbww_color` property. `rgbww_color` is an (r, g, b, cw, ww) tuple (not normalized for brightness). | `ColorMode.RGBWW` | The light can be dimmed and its color can be adjusted. The light's brightness can be set using the `brightness` parameter and read through the `brightness` property. The light's color can be set using the `rgbww_color` parameter and read through the `rgbww_color` property. `rgbww_color` is an (r, g, b, cw, ww) tuple (not normalized for brightness).
| `ColorMode.WHITE` | The light can be dimmed and its color can be adjusted. In addition, the light can be set to white mode. The light's brightness can be set using the `brightness` parameter and read through the `brightness` property. The light can be set to white mode by using the `white` parameter with the desired brightness as value. Note that there's no `white` property. If both `brighthness` and `white` are present in a service call, the `white` parameter will be updated with the value of `brightness`. If this mode is supported, the light *must* also support at least one of `ColorMode.HS`, `ColorMode.RGB`, `ColorMode.RGBW`, `ColorMode.RGBWW` or `ColorMode.XY` and *must not* support `ColorMode.COLOR_TEMP`. | `ColorMode.WHITE` | The light can be dimmed and its color can be adjusted. In addition, the light can be set to white mode. The light's brightness can be set using the `brightness` parameter and read through the `brightness` property. The light can be set to white mode by using the `white` parameter with the desired brightness as value. Note that there's no `white` property. If both `brighthness` and `white` are present in a service action call, the `white` parameter will be updated with the value of `brightness`. If this mode is supported, the light *must* also support at least one of `ColorMode.HS`, `ColorMode.RGB`, `ColorMode.RGBW`, `ColorMode.RGBWW` or `ColorMode.XY` and *must not* support `ColorMode.COLOR_TEMP`.
| `ColorMode.XY` | The light can be dimmed and its color can be adjusted. The light's brightness can be set using the `brightness` parameter and read through the `brightness` property. The light's color can be set using the `xy_color` parameter and read through the `xy_color` property. `xy_color` is an (x, y) tuple. | `ColorMode.XY` | The light can be dimmed and its color can be adjusted. The light's brightness can be set using the `brightness` parameter and read through the `brightness` property. The light's color can be set using the `xy_color` parameter and read through the `xy_color` property. `xy_color` is an (x, y) tuple.
Note that in color modes `ColorMode.RGB`, `ColorMode.RGBW` and `ColorMode.RGBWW` there is brightness information both in the light's `brightness` property and in the color. As an example, if the light's brightness is 128 and the light's color is (192, 64, 32), the overall brightness of the light is: 128/255 * max(192, 64, 32)/255 = 38%. Note that in color modes `ColorMode.RGB`, `ColorMode.RGBW` and `ColorMode.RGBWW` there is brightness information both in the light's `brightness` property and in the color. As an example, if the light's brightness is 128 and the light's color is (192, 64, 32), the overall brightness of the light is: 128/255 * max(192, 64, 32)/255 = 38%.
@ -75,7 +75,7 @@ There are two white color modes, `ColorMode.COLOR_TEMP` and `ColorMode.WHITE`. T
A lamp with adjustable color temperature is typically implemented by at least two banks of LEDs, with different color temperature, typically one bank of warm-white LEDs and one bank of cold-white LEDs. A lamp with adjustable color temperature is typically implemented by at least two banks of LEDs, with different color temperature, typically one bank of warm-white LEDs and one bank of cold-white LEDs.
A light with non-adjustable color temperature typically only has a single bank of white LEDs. A light with non-adjustable color temperature typically only has a single bank of white LEDs.
### Color Mode when rendering effects ### Color mode when rendering effects
When rendering an effect, the `color_mode` should be set according to the adjustments supported by the When rendering an effect, the `color_mode` should be set according to the adjustments supported by the
effect. If the effect does not support any adjustments, the `color_mode` should be set to `ColorMode.ONOFF`. effect. If the effect does not support any adjustments, the `color_mode` should be set to `ColorMode.ONOFF`.
@ -86,7 +86,7 @@ indicated by the `supported_color_mode` property:
- A light which supports colors is allowed to set color_mode to `ColorMode.ONOFF` or `ColorMode.BRIGHTNESS` when controlled by an effect - A light which supports colors is allowed to set color_mode to `ColorMode.ONOFF` or `ColorMode.BRIGHTNESS` when controlled by an effect
- A light which supports brightness is allowed to set color_mode to `ColorMode.ONOFF` when controlled by an effect - A light which supports brightness is allowed to set color_mode to `ColorMode.ONOFF` when controlled by an effect
## Supported Features ## Supported features
Supported features are defined by using values in the `LightEntityFeature` enum Supported features are defined by using values in the `LightEntityFeature` enum
and are combined using the bitwise or (`|`) operator. and are combined using the bitwise or (`|`) operator.
@ -99,7 +99,7 @@ and are combined using the bitwise or (`|`) operator.
## Methods ## Methods
### Turn on Light Device ### Turn on light device
```python ```python
class MyLightEntity(LightEntity): class MyLightEntity(LightEntity):
@ -111,16 +111,16 @@ class MyLightEntity(LightEntity):
``` ```
Note that there's no `color_mode` passed to the `async_turn_on` method, instead only a single color attribute is allowed. Note that there's no `color_mode` passed to the `async_turn_on` method, instead only a single color attribute is allowed.
It is guaranteed that the integration will only receive a single color attribute in a `turn_on`call, which is guaranteed to be supported by the light according to the light's `supported_color_modes` property. To ensure this, colors in the service call will be translated before the entity's `async_turn_on` method is called if the light doesn't support the corresponding color mode: It is guaranteed that the integration will only receive a single color attribute in a `turn_on`call, which is guaranteed to be supported by the light according to the light's `supported_color_modes` property. To ensure this, colors in the service action call will be translated before the entity's `async_turn_on` method is called if the light doesn't support the corresponding color mode:
| Color type | Translation | Color type | Translation
|--------------|----------------------- |--------------|-----------------------
| color_temp | Will be removed from the service call if not supported and translated to `hs_color`, `rgb_color`, `rgbw_color`, `rgbww_color` or `xy_color` if supported by the light. | color_temp | Will be removed from the service action call if not supported and translated to `hs_color`, `rgb_color`, `rgbw_color`, `rgbww_color` or `xy_color` if supported by the light.
| hs_color | Will be removed from the service call if not supported and translated to `rgb_color`, `rgbw_color`, `rgbww_color` or `xy_color` if supported by the light. | hs_color | Will be removed from the service action call if not supported and translated to `rgb_color`, `rgbw_color`, `rgbww_color` or `xy_color` if supported by the light.
| rgb_color | Will be removed from the service call if not supported and translated to `rgbw_color`, `rgbww_color`, `hs_color` or `xy_color` if supported by the light. | rgb_color | Will be removed from the service action call if not supported and translated to `rgbw_color`, `rgbww_color`, `hs_color` or `xy_color` if supported by the light.
| rgbw_color | Will be removed from the service call if not supported. | rgbw_color | Will be removed from the service action call if not supported.
| rgbww_color | Will be removed from the service call if not supported. | rgbww_color | Will be removed from the service action call if not supported.
| xy_color | Will be removed from the service call if not supported and translated to `hs_color`, `rgb_color`, `rgbw_color` or `rgbww_color` if supported by the light. | xy_color | Will be removed from the service action call if not supported and translated to `hs_color`, `rgb_color`, `rgbw_color` or `rgbww_color` if supported by the light.
:::tip Scaling brightness :::tip Scaling brightness

View File

@ -1,5 +1,5 @@
--- ---
title: Lock Entity title: Lock entity
sidebar_label: Lock sidebar_label: Lock
--- ---
@ -19,8 +19,10 @@ Properties should always only return information from memory and not do I/O (lik
| is_locking | bool | None | Indication of whether the lock is currently locking. Used to determine `state`. | is_locking | bool | None | Indication of whether the lock is currently locking. Used to determine `state`.
| is_unlocking | bool | None | Indication of whether the lock is currently unlocking. Used to determine `state`. | is_unlocking | bool | None | Indication of whether the lock is currently unlocking. Used to determine `state`.
| is_jammed | bool | None | Indication of whether the lock is currently jammed. Used to determine `state`. | is_jammed | bool | None | Indication of whether the lock is currently jammed. Used to determine `state`.
| is_opening | bool | None | Indication of whether the lock is currently opening. Used to determine `state`.
| is_open | bool | None | Indication of whether the lock is currently open. Used to determine `state`.
## Supported Features ## Supported features
Supported features are defined by using values in the `LockEntityFeature` enum Supported features are defined by using values in the `LockEntityFeature` enum
and are combined using the bitwise or (`|`) operator. and are combined using the bitwise or (`|`) operator.

View File

@ -1,6 +1,6 @@
--- ---
title: Media Player Entity title: Media player entity
sidebar_label: Media Player sidebar_label: Media player
--- ---
:::info Incomplete :::info Incomplete
@ -47,9 +47,9 @@ Properties should always only return information from memory and not do I/O (lik
| source_list | <code>list[str] &#124; None</code> | `None` | The list of possible input sources for the media player. (This list should contain human readable names, suitable for frontend display). | source_list | <code>list[str] &#124; None</code> | `None` | The list of possible input sources for the media player. (This list should contain human readable names, suitable for frontend display).
| state | <code>MediaPlayerState &#124; None</code> | `None` | State of the media player. | state | <code>MediaPlayerState &#124; None</code> | `None` | State of the media player.
| volume_level | <code>float &#124; None</code> | `None` | Volume level of the media player in the range (0..1). | volume_level | <code>float &#124; None</code> | `None` | Volume level of the media player in the range (0..1).
| volume_step | <code>float &#124; None</code> | 0.1 | Volume step to use for the `volume_up` and `volume_down` services. | volume_step | <code>float &#124; None</code> | 0.1 | Volume step to use for the `volume_up` and `volume_down` service actions.
## Supported Features ## Supported features
Supported features are defined by using values in the `MediaPlayerEntityFeature` enum Supported features are defined by using values in the `MediaPlayerEntityFeature` enum
and are combined using the bitwise or (`|`) operator. and are combined using the bitwise or (`|`) operator.
@ -59,8 +59,8 @@ and are combined using the bitwise or (`|`) operator.
| `BROWSE_MEDIA` | Entity allows browsing media. | | `BROWSE_MEDIA` | Entity allows browsing media. |
| `CLEAR_PLAYLIST` | Entity allows clearing the active playlist. | | `CLEAR_PLAYLIST` | Entity allows clearing the active playlist. |
| `GROUPING` | Entity can be grouped with other players for synchronous playback. | | `GROUPING` | Entity can be grouped with other players for synchronous playback. |
| `MEDIA_ANNOUNCE` | Entity supports the `play_media` service's announce parameter. | | `MEDIA_ANNOUNCE` | Entity supports the `play_media` action's announce parameter. |
| `MEDIA_ENQUEUE` | Entity supports the `play_media` service's enqueue parameter. | | `MEDIA_ENQUEUE` | Entity supports the `play_media` action's enqueue parameter. |
| `NEXT_TRACK` | Entity allows skipping to the next media track. | | `NEXT_TRACK` | Entity allows skipping to the next media track. |
| `PAUSE` | Entity allows pausing the playback of media. | | `PAUSE` | Entity allows pausing the playback of media. |
| `PLAY` | Entity allows playing/resuming playback of media. | | `PLAY` | Entity allows playing/resuming playback of media. |
@ -94,7 +94,7 @@ The state of a media player is defined by using values in the `MediaPlayerState`
## Methods ## Methods
### Play Media ### Play media
Tells the media player to play media. Implement it using the following: Tells the media player to play media. Implement it using the following:
@ -130,7 +130,7 @@ The `enqueue` attribute is a string enum `MediaPlayerEnqueue`:
When the `announce` boolean attribute is set to `true`, the media player should try to pause the current music, announce the media to the user and then resume the music. When the `announce` boolean attribute is set to `true`, the media player should try to pause the current music, announce the media to the user and then resume the music.
### Browse Media ### Browse media
If the media player supports browsing media, it should implement the following method: If the media player supports browsing media, it should implement the following method:
@ -250,7 +250,7 @@ class MyMediaPlayer(MediaPlayerEntity):
``` ```
:::info :::info
Using the integration name as the `media_content_type` is also acceptable within the `play_media` service if the integration provides handling which does not map to the defined constants. Using the integration name as the `media_content_type` is also acceptable within the `play_media` service action if the integration provides handling which does not map to the defined constants.
::: :::
### Available device classes ### Available device classes

View File

@ -0,0 +1,40 @@
---
title: Notify entity
sidebar_label: Notify
---
A notify entity is an entity that can send a message towards a device or service but remains stateless from the Home Assistant perspective.
A notify entity is derived from the [`homeassistant.components.notify.NotifyEntity`](https://github.com/home-assistant/core/blob/dev/homeassistant/components/notify/__init__.py),
and can be helpful to send notification messages as (but not limited to):
- an SMS
- an email
- a direct message or chat
- a screen message on a device's LCD display
Unlike a `text` entity the `notify` entity has no state that can be set. Instead it represents the date and time of the last message sent.
If you want to represent something that has a text value that can be changed (and thus has an actual state), you should use a `text` entity instead.
## Properties
As this integration is stateless, it doesn't provide any specific properties for itself.
Other properties that are common to all entities such as `icon` and `name` etc are still applicable.
## Methods
### Send message
The send message method is used to send a message to a device or service.
```python
class MyNotifier(NotifyEntity):
# Implement one of these methods.
def send_message(self, message: str, title: str | None = None) -> None:
"""Send a message."""
async def async_send_message(self, message: str, title: str | None = None) -> None:
"""Send a message."""
```

View File

@ -1,5 +1,5 @@
--- ---
title: Number Entity title: Number entity
sidebar_label: Number sidebar_label: Number
--- ---

View File

@ -1,5 +1,5 @@
--- ---
title: Remote Entity title: Remote entity
sidebar_label: Remote sidebar_label: Remote
--- ---
@ -25,7 +25,7 @@ Properties should always only return information from memory and not do I/O (lik
An activity is a predefined activity or macro that puts the remote in a specific state. For example, a "Watch TV" activity may turn on multiple devices and change the channel to a specific channel. An activity is a predefined activity or macro that puts the remote in a specific state. For example, a "Watch TV" activity may turn on multiple devices and change the channel to a specific channel.
## Supported Features ## Supported features
Supported features are defined by using values in the `RemoteEntityFeature` enum Supported features are defined by using values in the `RemoteEntityFeature` enum
and are combined using the bitwise or (`|`) operator. and are combined using the bitwise or (`|`) operator.
@ -38,7 +38,7 @@ and are combined using the bitwise or (`|`) operator.
## Methods ## Methods
### Turn On Command ### Turn on command
```python ```python
class MyRemote(RemoteEntity): class MyRemote(RemoteEntity):
@ -50,7 +50,7 @@ class MyRemote(RemoteEntity):
"""Send the power on command.""" """Send the power on command."""
``` ```
### Turn Off Command ### Turn off command
```python ```python
class MyRemote(RemoteEntity): class MyRemote(RemoteEntity):
@ -62,7 +62,7 @@ class MyRemote(RemoteEntity):
"""Send the power off command.""" """Send the power off command."""
``` ```
### Toggle Command ### Toggle command
```python ```python
class MyRemote(RemoteEntity): class MyRemote(RemoteEntity):
@ -74,7 +74,7 @@ class MyRemote(RemoteEntity):
"""Toggle a device.""" """Toggle a device."""
``` ```
### Send Command ### Send command
```python ```python
class MyRemote(RemoteEntity): class MyRemote(RemoteEntity):
@ -86,7 +86,7 @@ class MyRemote(RemoteEntity):
"""Send commands to a device.""" """Send commands to a device."""
``` ```
### Learn Command ### Learn command
Only implement this method if the flag `SUPPORT_LEARN_COMMAND` is set. Only implement this method if the flag `SUPPORT_LEARN_COMMAND` is set.
@ -100,7 +100,7 @@ class MyRemote(RemoteEntity):
"""Learn a command from a device.""" """Learn a command from a device."""
``` ```
### Delete Command ### Delete command
Only implement this method if the flag `SUPPORT_DELETE_COMMAND` is set. Only implement this method if the flag `SUPPORT_DELETE_COMMAND` is set.

View File

@ -1,5 +1,5 @@
--- ---
title: Scene Entity title: Scene entity
sidebar_label: Scene sidebar_label: Scene
--- ---
@ -34,7 +34,7 @@ class MySwitch(Scene):
``` ```
The activate method can be used to activate the scene towards a device or service. The activate method can be used to activate the scene towards a device or service.
It is called by Home Assistant when the user presses the scene `activate` button or when the `scene.turn_on` service is called to activate the scene. It is called by Home Assistant when the user presses the scene `activate` button or when the `scene.turn_on` action is called to activate the scene.
### Available device classes ### Available device classes

View File

@ -1,5 +1,5 @@
--- ---
title: Select Entity title: Select entity
sidebar_label: Select sidebar_label: Select
--- ---

View File

@ -1,5 +1,5 @@
--- ---
title: Sensor Entity title: Sensor entity
sidebar_label: Sensor sidebar_label: Sensor
--- ---
@ -44,7 +44,7 @@ If specifying a device class, your sensor entity will need to also return the co
| `SensorDeviceClass.DATE` | | Date. Requires `native_value` to be a Python `datetime.date` object, or `None`. | `SensorDeviceClass.DATE` | | Date. Requires `native_value` to be a Python `datetime.date` object, or `None`.
| `SensorDeviceClass.DISTANCE` | km, m, cm, mm, mi, yd, in | Generic distance | `SensorDeviceClass.DISTANCE` | km, m, cm, mm, mi, yd, in | Generic distance
| `SensorDeviceClass.DURATION` | d, h, min, s, ms | Time period. Should not update only due to time passing. The device or service needs to give a new data point to update. | `SensorDeviceClass.DURATION` | d, h, min, s, ms | Time period. Should not update only due to time passing. The device or service needs to give a new data point to update.
| `SensorDeviceClass.ENERGY` | Wh, kWh, MWh, MJ, GJ | Energy, this device class should used for sensors representing energy consumption, for example an electricity meter. Represents _power_ over _time_. Not to be confused with `power`. | `SensorDeviceClass.ENERGY` | Wh, kWh, MWh, MJ, GJ | Energy, this device class should be used for sensors representing energy consumption, for example an electricity meter. Represents _power_ over _time_. Not to be confused with `power`.
| `SensorDeviceClass.ENERGY_STORAGE` | Wh, kWh, MWh, MJ, GJ | Stored energy, this device class should be used for sensors representing stored energy, for example the amount of electric energy currently stored in a battery or the capacity of a battery. Represents _power_ over _time_. Not to be confused with `power`. | `SensorDeviceClass.ENERGY_STORAGE` | Wh, kWh, MWh, MJ, GJ | Stored energy, this device class should be used for sensors representing stored energy, for example the amount of electric energy currently stored in a battery or the capacity of a battery. Represents _power_ over _time_. Not to be confused with `power`.
| `SensorDeviceClass.ENUM` | | The sensor has a limited set of (non-numeric) states. The `options` property must be set to a list of possible states when using this device class. | `SensorDeviceClass.ENUM` | | The sensor has a limited set of (non-numeric) states. The `options` property must be set to a list of possible states when using this device class.
| `SensorDeviceClass.FREQUENCY` | Hz, kHz, MHz, GHz | Frequency | `SensorDeviceClass.FREQUENCY` | Hz, kHz, MHz, GHz | Frequency

View File

@ -1,5 +1,5 @@
--- ---
title: Siren Entity title: Siren entity
sidebar_label: Siren sidebar_label: Siren
--- ---
@ -14,7 +14,7 @@ Properties should always only return information from memory and not do I/O (lik
| Name | Type | Default | Description | | Name | Type | Default | Description |
| ----------------------- | ------ | ------------------------------------- | --------------------------------------------------------------------------------------- | | ----------------------- | ------ | ------------------------------------- | --------------------------------------------------------------------------------------- |
| is_on | bool | `None` | Whether the device is on or off. | | is_on | bool | `None` | Whether the device is on or off. |
| available_tones | list or dict | `NotImplementedError()` | The list or dictionary of available tones on the device to pass into the `turn_on` service. If a dictionary is provided, when a user uses the dict value of a tone, it will get converted to the corresponding dict key before being passed on to the integration platform. Requires `SUPPORT_TONES` feature. | | available_tones | list or dict | `NotImplementedError()` | The list or dictionary of available tones on the device to pass into the `turn_on` service action. If a dictionary is provided, when a user uses the dict value of a tone, it will get converted to the corresponding dict key before being passed on to the integration platform. Requires `SUPPORT_TONES` feature. |
### Tones ### Tones
@ -26,16 +26,16 @@ Supported features constants are combined using the bitwise or (`|`) operator.
| Name | Description | | Name | Description |
| ------------------------- | ---------------------------------------------------------------------------------------------------------------- | | ------------------------- | ---------------------------------------------------------------------------------------------------------------- |
| `SirenEntityFeature.TONES` | The device supports different tones (the tone can be passed in to `turn_on` service). | | `SirenEntityFeature.TONES` | The device supports different tones (the tone can be passed in to `turn_on` service action). |
| `SirenEntityFeature.DURATION` | The device supports setting a duration for the tone (the duration can be passed in to `turn_on` service). | | `SirenEntityFeature.DURATION` | The device supports setting a duration for the tone (the duration can be passed in to `turn_on` service action). |
| `SirenEntityFeature.VOLUME_SET` | The device supports setting the volume level of the device (the volume level can be passed in to `turn_on` service). | | `SirenEntityFeature.VOLUME_SET` | The device supports setting the volume level of the device (the volume level can be passed in to `turn_on` service action). |
## Methods ## Methods
### Turn on ### Turn on
There are three optional input parameters that can be passed into the service call, each gated by a supported feature flag. If the corresponding flag isn't set when a given input parameter is provided in the service call, it will be filtered out from the service call by the base platform before being passed to the integration. There are three optional input parameters that can be passed into the service action call, each gated by a supported feature flag. If the corresponding flag isn't set when a given input parameter is provided in the service action call, it will be filtered out from the call by the base platform before being passed to the integration.
| Parameter Name | Data Validation | Supported Feature Flag | | Parameter Name | Data Validation | Supported Feature Flag |
|---------------- |--------------------------------------- |------------------------ | |---------------- |--------------------------------------- |------------------------ |

View File

@ -1,11 +1,11 @@
--- ---
title: Speech To Text Entity title: Speech-to-text entity
sidebar_label: Speech To Text sidebar_label: Speech-to-text
--- ---
A speech to text (STT) entity allows other integrations or applications to stream speech data to the STT API and get text back. A speech-to-text (STT) entity allows other integrations or applications to stream speech data to the STT API and get text back.
A speech to text entity is derived from the [`homeassistant.components.stt.SpeechToTextEntity`](https://github.com/home-assistant/core/blob/dev/homeassistant/components/stt/__init__.py). A speech-to-text entity is derived from the [`homeassistant.components.stt.SpeechToTextEntity`](https://github.com/home-assistant/core/blob/dev/homeassistant/components/stt/__init__.py).
## Properties ## Properties

View File

@ -1,10 +1,10 @@
--- ---
title: Switch Entity title: Switch entity
sidebar_label: Switch sidebar_label: Switch
--- ---
A switch entity turns on or off something, for example a relay. Derive a platform entity from [`homeassistant.components.switch.SwitchEntity`](https://github.com/home-assistant/core/blob/dev/homeassistant/components/switch/__init__.py). A switch entity turns on or off something, for example a relay. Derive a platform entity from [`homeassistant.components.switch.SwitchEntity`](https://github.com/home-assistant/core/blob/dev/homeassistant/components/switch/__init__.py).
To represent something which can be turned on or off but can't be controlled, for example a wall switch which transmits its state but can't be turned on or off from Home Assistant, a Binary Sensor is a better choice. To represent something which has an on or off state but can't be controlled, for example a wall switch which transmits its state but can't be turned on or off from Home Assistant, a Binary Sensor is a better choice.
To represent something which doesn't have a state, for example a door bell push button, a custom event or a Device Trigger is a better choice. To represent something which doesn't have a state, for example a door bell push button, a custom event or a Device Trigger is a better choice.
## Properties ## Properties
@ -17,7 +17,7 @@ Properties should always only return information from memory and not do I/O (lik
| ---- | ---- | ------- | ----------- | ---- | ---- | ------- | -----------
| is_on | boolean | `None` | If the switch is currently on or off. | is_on | boolean | `None` | If the switch is currently on or off.
## Deprecated Properties ## Deprecated properties
The following properties are deprecated and should not be used by new integrations. Provide them as sensors instead. The following properties are deprecated and should not be used by new integrations. Provide them as sensors instead.
@ -28,7 +28,7 @@ Name | Type | Default | Description
## Methods ## Methods
### Turn On ### Turn on
Turn the switch on. Turn the switch on.
@ -43,7 +43,7 @@ class MySwitch(SwitchEntity):
"""Turn the entity on.""" """Turn the entity on."""
``` ```
### Turn Off ### Turn off
Turn the switch off. Turn the switch off.

View File

@ -1,5 +1,5 @@
--- ---
title: Text Entity title: Text entity
sidebar_label: Text sidebar_label: Text
--- ---

View File

@ -1,5 +1,5 @@
--- ---
title: Time Entity title: Time entity
sidebar_label: Time sidebar_label: Time
--- ---

View File

@ -1,6 +1,6 @@
--- ---
title: To-do List Entity title: To-do list entity
sidebar_label: To-do List sidebar_label: To-do list
--- ---
A To-do list entity is an entity that represents a To-do list. A To-do list contains A To-do list entity is an entity that represents a To-do list. A To-do list contains
@ -20,7 +20,7 @@ Properties should only return information from memory and not do I/O (like netwo
A `TodoListEntity` state is the count of incomplete items in the To-do list. A `TodoListEntity` state is the count of incomplete items in the To-do list.
## Supported Features ## Supported features
Supported features are defined by using values in the `TodoListEntityFeature` enum Supported features are defined by using values in the `TodoListEntityFeature` enum
and are combined using the bitwise or (`|`) operator. and are combined using the bitwise or (`|`) operator.
@ -37,10 +37,9 @@ and are combined using the bitwise or (`|`) operator.
## Methods ## Methods
### Create to-do items
### Create To-do items A to-do list entity may support creating to-do items by specifying the `CREATE_TODO_ITEM`
A To-do list entity may support creating To-do items by specifying the `CREATE_TODO_ITEM`
supported feature. supported feature.
```python ```python
@ -52,9 +51,9 @@ class MyTodoListEntity(TodoListEntity):
"""Add an item to the To-do list.""" """Add an item to the To-do list."""
``` ```
### Delete To-do items ### Delete to-do items
A To-do list entity may support deleting To-do items by specifying the `DELETE_TODO_ITEM` A To-do list entity may support deleting to-do items by specifying the `DELETE_TODO_ITEM`
supported feature. Integrations must support deleting multiple items. supported feature. Integrations must support deleting multiple items.
```python ```python
@ -66,9 +65,9 @@ class MyTodoListEntity(TodoListEntity):
"""Delete an item from the to-do list.""" """Delete an item from the to-do list."""
``` ```
### Update To-do items ### Update to-do items
A To-do list entity may support updating To-do items by specifying the `UPDATE_TODO_ITEM` A to-do list entity may support updating to-do items by specifying the `UPDATE_TODO_ITEM`
supported feature. The `TodoItem` field `uid` is always present and indicates supported feature. The `TodoItem` field `uid` is always present and indicates
which item should be updated. The item passed to update is a copy of the original which item should be updated. The item passed to update is a copy of the original
item with fields updated or cleared. item with fields updated or cleared.
@ -82,12 +81,12 @@ class MyTodoListEntity(TodoListEntity):
"""Add an item to the To-do list.""" """Add an item to the To-do list."""
``` ```
### Move To-do items ### Move to-do items
A To-do list entity may support re-ordering To-do items in the list by specifying A to-do list entity may support re-ordering to-do items in the list by specifying
the `MOVE_TODO_ITEM` supported feature. The To-do item with the specified `uid` the `MOVE_TODO_ITEM` supported feature. The to-do item with the specified `uid`
should be moved to the position in the list after the one specified by `previous_uid` (`None` means move to the first should be moved to the position in the list after the one specified by `previous_uid` (`None` means move to the first
position in the To-do list). position in the to-do list).
```python ```python
from homeassistant.components.todo import TodoListEntity from homeassistant.components.todo import TodoListEntity

View File

@ -1,6 +1,6 @@
--- ---
title: Text To Speech Entity title: Text-to-speech entity
sidebar_label: Text To Speech sidebar_label: Text-to-speech
--- ---
A text-to-speech (TTS) entity enables Home Assistant to speak to you. A text-to-speech (TTS) entity enables Home Assistant to speak to you.

View File

@ -1,5 +1,5 @@
--- ---
title: Update Entity title: Update entity
sidebar_label: Update sidebar_label: Update
--- ---
@ -33,7 +33,7 @@ Properties should always only return information from memory and not do I/O (lik
Other properties that are common to all entities such as `device_class`, `entity_category`, `icon`, `name` etc are still applicable. Other properties that are common to all entities such as `device_class`, `entity_category`, `icon`, `name` etc are still applicable.
## Supported Features ## Supported features
Supported features are defined by using values in the `UpdateEntityFeature` enum. Supported features are defined by using values in the `UpdateEntityFeature` enum.
@ -42,7 +42,7 @@ Supported features are defined by using values in the `UpdateEntityFeature` enum
| 'BACKUP' | A backup can be made automatically, before installing an update. | 'BACKUP' | A backup can be made automatically, before installing an update.
| 'INSTALL' | The update can be installed from Home Assistant. | 'INSTALL' | The update can be installed from Home Assistant.
| 'PROGRESS' | This integration is able to provide progress information. If omitted, Home Assistant will try to provide a progress status; although it is better if the progress can be extracted from the device or service API. | 'PROGRESS' | This integration is able to provide progress information. If omitted, Home Assistant will try to provide a progress status; although it is better if the progress can be extracted from the device or service API.
| 'SPECIFIC_VERSION' | A specific version of an update can be installed using the `update.install` service. | 'SPECIFIC_VERSION' | A specific version of an update can be installed using the `update.install` service action.
| 'RELEASE_NOTES' | The entity provides methods to fetch a complete changelog. | 'RELEASE_NOTES' | The entity provides methods to fetch a complete changelog.
## Methods ## Methods

View File

@ -1,5 +1,5 @@
--- ---
title: Vacuum Entity title: Vacuum entity
sidebar_label: Vacuum sidebar_label: Vacuum
--- ---
@ -35,7 +35,7 @@ Properties should always only return information from memory and not do I/O (lik
| `STATE_RETURNING` | The vacuum is done cleaning and is currently returning to the dock, but not yet docked. | `STATE_RETURNING` | The vacuum is done cleaning and is currently returning to the dock, but not yet docked.
| `STATE_ERROR` | The vacuum encountered an error while cleaning. | `STATE_ERROR` | The vacuum encountered an error while cleaning.
## Supported Features ## Supported features
Supported features are defined by using values in the `VacuumEntityFeature` enum Supported features are defined by using values in the `VacuumEntityFeature` enum
and are combined using the bitwise or (`|`) operator. and are combined using the bitwise or (`|`) operator.

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