Collection of fixes and improvements (#516)

This commit is contained in:
Franck Nijhof 2020-05-11 17:12:01 +02:00 committed by GitHub
parent b31d871c6a
commit 08884e2cca
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
60 changed files with 448 additions and 407 deletions

View File

@ -7,23 +7,21 @@ Add-ons for Hass.io allow the user to extend the functionality around Home Assis
Under the hood, add-ons are Docker images published in [Docker Hub](https://hub.docker.com/). Developers can create [GitHub](https://github.com) repositories that contain multiple references to add-ons for easy sharing with the community.
1. [Tutorial: Making your first add-on](hassio_addon_tutorial.md)
1. [Configuration](hassio_addon_config.md)
1. [Communication](hassio_addon_communication.md)
1. [Local Testing](hassio_addon_testing.md)
1. [Publishing](hassio_addon_publishing.md)
1. [Presentation](hassio_addon_presentation.md)
1. [Repositories](hassio_addon_repository.md)
1. [Security](hassio_addon_security.md)
- [Tutorial: Making your first add-on](add-ons/tutorial.md)
- [Configuration](add-ons/configuration.md)
- [Communication](add-ons/communication.md)
- [Local Testing](add-ons/testing.md)
- [Publishing](add-ons/publishing.md)
- [Presentation](add-ons/presentation.md)
- [Repositories](add-ons/repository.md)
- [Security](add-ons/security.md)
Useful links:
* [Supervisor](https://github.com/home-assistant/supervisor)
* [Core Add-ons](https://github.com/home-assistant/hassio-addons)
* [Build environment](https://github.com/home-assistant/hassio-build)
* [base images](https://github.com/home-assistant/docker-base)
* [Builder](https://github.com/home-assistant/hassio-builder)
* [Home Assistant community Add-ons](https://github.com/hassio-addons)
* [HassOS embedded Linux](https://github.com/home-assistant/hassos)
* [Home Assistant Dockerfile](https://github.com/home-assistant/docker)
- [Supervisor](https://github.com/home-assistant/supervisor)
- [Core Add-ons](https://github.com/home-assistant/hassio-addons)
- [Docker base images](https://github.com/home-assistant/docker-base)
- [Builder](https://github.com/home-assistant/hassio-builder)
- [Home Assistant community Add-ons](https://github.com/hassio-addons)
- [Home Assistant Operating System](https://github.com/home-assistant/operating-system)
- [Home Assistant Docker](https://github.com/home-assistant/docker)

View File

@ -9,7 +9,7 @@ There are different ways for communication 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!
Names/aliases are used for communication inside Hass.io.
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.json` file. You can use this name as the DNS name also, but you need 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/hassio/blob/587047f9d648b8491dc8eef17dc6777f81938bfd/hassio/addons/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 hassio 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.json` file. You can use this name as the DNS name also, but you need 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/hassio/blob/587047f9d648b8491dc8eef17dc6777f81938bfd/hassio/addons/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 hassio API `addons` endpoint.
Use `supervisor` for communication with the internal API.
@ -30,6 +30,7 @@ We have several services for Hass.io inside Home Assistant to run tasks. Send da
To enable calls to the [Supervisor API][supervisor-api], add `hassio_api: true` to the `config.json` file and read the environment variable `SUPERVISOR_TOKEN`. Now you can use the API over the URL: `http://supervisor/`. Use the `SUPERVISOR_TOKEN` with header `Authorization: Bearer`. You may also need to change the Supervisor API role to `hassio_role: default`.
Add-ons can call some API commands without needing to set `hassio_api: true`:
- `/core/api`
- `/core/api/stream`
- `/core/websocket`
@ -42,7 +43,7 @@ Add-ons can call some API commands without needing to set `hassio_api: true`:
## Services API
We have an internal services API to make services public to other add-ons without the user need to add additional configuration. An add-on can get the full configuration for a service to use and to connect to. The add-on need to mark the usage of a service over his [configuration](hassio_addon_config.md) in order to be able to access a service. All supported services, including its available options, are documented in the [API documentation][supervisor-services-api].
We have an internal services API to make services public to other add-ons without the user need to add additional configuration. An add-on can get the full configuration for a service to use and to connect to. The add-on need to mark the usage of a service over his [configuration](configuration.md) in order to be able to access a service. All supported services, including its available options, are documented in the [API documentation][supervisor-services-api].
Supported services are:

View File

@ -26,8 +26,8 @@ All our Images have also [bashio][bashio] installed. It contains a set of common
When developing your script:
- `/data` is a volume for persistent storage.
- `/data/options.json` contains the user configuration. You can use bashio or `jq` inside your shell script to parse this data.
- `/data` is a volume for persistent storage.
- `/data/options.json` contains the user configuration. You can use Bashio or `jq` inside your shell script to parse this data.
```shell
CONFIG_PATH=/data/options.json
@ -36,9 +36,11 @@ TARGET="$(jq --raw-output '.target' $CONFIG_PATH)"
```
So if your `options` contain
```json
{ "target": "beer" }
```
then there will be a variable `TARGET` containing `beer` in the environment of your bash file afterwards.
[bashio]: https://github.com/hassio-addons/bashio
@ -64,7 +66,8 @@ CMD [ "/run.sh" ]
```
If you don't use local build on device or our build script, make sure that the Dockerfile have also a set of labels include:
```
```dockerfile
LABEL io.hass.version="VERSION" io.hass.type="addon" io.hass.arch="armhf|aarch64|i386|amd64"
```
@ -196,16 +199,17 @@ The `schema` looks like `options` but describes how we should validate the user
```
We support:
- str / str(min,) / str(,max) / str(min,max)
- bool
- int / int(min,) / int(,max) / int(min,max)
- float / float(min,) / float(,max) / float(min,max)
- email
- url
- password
- port
- match(REGEX)
- list(val1|val2|...)
- `str` / `str(min,)` / `str(,max)` / `str(min,max)`
- `bool`
- `int` / `int(min,)` / `int(,max)` / `int(min,max)`
- `float` / `float(min,)` / `float(,max)` / `float(min,max)`
- `email`
- `url`
- `password`
- `port`
- `match(REGEX)`
- `list(val1|val2|...)`
## Add-on extended build
@ -227,7 +231,7 @@ You need this only, if you not use the default images or need additionals things
| Key | Required | Description |
| --- | -------- | ----------- |
| build_from | no | A dictionary with the hardware architecture as the key and the base Docker image as value.
| squash | no | Default `False`. Be carfully with this option, you can not use the image for caching stuff after that!
| squash | no | Default `False`. Be carefully with this option, you can not use the image for caching stuff after that!
| args | no | Allow to set additional Docker build arguments as a dictionary.
We provide a set of [Base-Images][docker-base] which should cover a lot of needs. If you don't want use the Alpine based version or need a specific Image tag, feel free to pin this requirements for you build with `build_from` option.

View File

@ -39,7 +39,7 @@ It is likely you are going to release newer versions of your add-on in the futur
A changelog is a file which contains a curated, chronologically ordered list of notable changes for each version of your add-on and is generally published as the `CHANGELOG.md` file.
If you are in need of a guide on keeping a changelog, we would recommend checking the [keep a changelog](http://keepachangelog.com) website. They have developed a standard that is used by many opensource projects around the world.
If you are in need of a guide on keeping a changelog, we would recommend checking the [keep a changelog](http://keepachangelog.com) website. They have developed a standard that is used by many open source projects around the world.
## AppArmor
@ -50,13 +50,14 @@ You can use own security profile for you Add-on with AppArmor. Default it is ena
Ingress allow users to access the add-on web interface via the Home Assistant UI. Authentication is handled by Home Assistant, so neither the user nor the add-on developer will need to care about the security or port forwarding. Users love this feature, however it is not every time simple to implement for the add-on developer.
To add Ingress support, follow the following steps:
- The add-on will need to provide the web interface on port `8099`. Make sure that the add-on accepts only connections from `172.30.32.2` on that port and that the connections are treated as authenticated.
- Update add-on configuration and set `ingress: true`. Here it is also possible to configure the Ingress port (default 8099).
- Update add-on configuration and set `ingress: true`. Here it is also possible to configure the Ingress port (default 8099).
- If you need to configure the application inside your add-on with the right path and port, query the add-on info API endpoint.
- If the application doesn't support relative paths or you can't set a base url, you can use nginx filter to replace the URL with correct path.
Ingress API gateway supports the following:
* HTTP/1.x
* Streaming content
* Websockets
- HTTP/1.x
- Streaming content
- Websockets

View File

@ -2,13 +2,13 @@
title: "Create an add-on repository"
---
An add-on repository can contain one or more add-ons. Each add-on is stored in its own unique folder. To be indentified as a repository, the repository must contain a configuration file.
An add-on repository can contain one or more add-ons. Each add-on is stored in its own unique folder. To be identified as a repository, the repository must contain a configuration file.
Check the [Example add-on repository](https://github.com/home-assistant/addons-example) for further details.
## Installing a repository
A user can add a repository by going to the Supervisor panel in Home Assistant, clicking on the store icon in the top right, copy/paste the URL of your repostory into the repository textarea and click on **Save**.
A user can add a repository by going to the Supervisor panel in Home Assistant, clicking on the store icon in the top right, copy/paste the URL of your repository into the repository textarea and click on **Save**.
## Repository configuration

View File

@ -22,10 +22,11 @@ Once you have located your add-on directory, it's time to get started!
## Step 1: The basics
- Create a new directory called `hello_world`
- Inside that directory create three files.
- Create a new directory called `hello_world`
- Inside that directory create three files.
`Dockerfile`:
```dockerfile
ARG BUILD_FROM
FROM $BUILD_FROM
@ -40,6 +41,7 @@ CMD [ "/run.sh" ]
```
`config.json`:
```json
{
"name": "Hello world",
@ -55,32 +57,34 @@ CMD [ "/run.sh" ]
```
`run.sh`:
```shell
#!/usr/bin/with-contenv bashio
echo Hello world!
```
Make sure your editor is using UNIX-like line breaks (LF), not Dos/Windows (CRLF).
## Step 2: Installing and testing your add-on
Now comes the fun part, time to open the Home Assistant UI and install and run your add-on.
- Open the Home Assistant frontend
- Go to the Supervisor panel
- On the top right click the shopping basket to go to the add-on store.
- Open the Home Assistant frontend
- Go to the Supervisor panel
- On the top right click the shopping basket to go to the add-on store.
![Screenshot of the Home Assistant Supervisor main panel](/img/en/hass.io/screenshots/main_panel_addon_store.png)
- On the top right click the refresh button
- You should now see a new card called "Local" that lists your add-on!
- On the top right click the refresh button
- You should now see a new card called "Local" that lists your add-on!
![Screenshot of the local repository card](/img/en/hass.io/screenshots/local_repository.png)
- Click on your add-on to go to the add-on details page.
- Install your add-on
- Start your add-on
- Refresh the logs of your add-on, you should now see "Hello world!" in your logs.
- Click on your add-on to go to the add-on details page.
- Install your add-on
- Start your add-on
- Refresh the logs of your add-on, you should now see "Hello world!" in your logs.
![Screenshot of the add-on logs](/img/en/hass.io/tutorial/addon_hello_world_logs.png)
@ -98,9 +102,9 @@ Until now we've been able to do some basic stuff, but it's not very useful yet.
To do this, we will need to update our files as follows:
- `Dockerfile`: Install Python 3
- `config.json`: Make the port from the container available on the host
- `run.sh`: Run the Python 3 command to start the HTTP server
- `Dockerfile`: Install Python 3
- `config.json`: Make the port from the container available on the host
- `run.sh`: Run the Python 3 command to start the HTTP server
Add to your `Dockerfile` before `RUN`:

View File

@ -85,6 +85,7 @@ Once the user hits their maximum amount of notifications sent in the rate limit
The notify platform does not itself implement any kind of rate limit protections. Users will be able to keep sending you notifications, so you should reject them with a 429 status code as early in your logic as possible.
## Example server implementation
The below code is a Firebase Cloud Function that forwards notifications to Firebase Cloud Messaging. To deploy this, you should create a new Firestore database named `rateLimits`. Then, you can deploy the following code.
Also, ensure that you have properly configured your project with the correct authentication keys for APNS and FCM.

View File

@ -65,6 +65,7 @@ Sodium is a modern, easy-to-use software library for encryption, decryption, sig
:::
### Choosing a library
Libraries that wrap Sodium exist for most modern programming languages and platforms. Sodium itself is written in C.
Here are the libraries we suggest using, although you should feel free to use whatever works well for you.
@ -96,12 +97,12 @@ This message will inform Home Assistant of new location information.
```json
{
"type": "update_location",
"data": {
"gps": [12.34, 56.78],
"gps_accuracy": 120,
"battery": 45
}
"type": "update_location",
"data": {
"gps": [12.34, 56.78],
"gps_accuracy": 120,
"battery": 45
}
}
```
@ -122,14 +123,14 @@ Call a service in Home Assistant.
```json
{
"type": "call_service",
"data": {
"domain": "light",
"service": "turn_on",
"service_data": {
"entity_id": "light.kitchen"
}
}
"type": "call_service",
"data": {
"domain": "light",
"service": "turn_on",
"service_data": {
"entity_id": "light.kitchen"
}
}
}
```
@ -145,13 +146,13 @@ Fire an event in Home Assistant.
```json
{
"type": "fire_event",
"data": {
"event_type": "my_custom_event",
"event_data": {
"something": 50
}
}
"type": "fire_event",
"data": {
"event_type": "my_custom_event",
"event_data": {
"something": 50
}
}
}
```
@ -166,15 +167,15 @@ Renders one or more templates and returns the result(s).
```json
{
"type": "render_template",
"data": {
"my_tpl": {
"template": "Hello {{ name }}, you are {{ states('person.paulus') }}.",
"variables": {
"name": "Paulus"
}
}
}
"type": "render_template",
"data": {
"my_tpl": {
"template": "Hello {{ name }}, you are {{ states('person.paulus') }}.",
"variables": {
"name": "Paulus"
}
}
}
}
```
@ -191,18 +192,18 @@ Update your app registration. Use this if the app version changed or any of the
```json
{
"type": "update_registration",
"data": {
"app_data": {
"push_token": "abcd",
"push_url": "https://push.mycool.app/push"
},
"app_version": "2.0.0",
"device_name": "Robbies iPhone",
"manufacturer": "Apple, Inc.",
"model": "iPhone XR",
"os_version": "23.02"
}
"type": "update_registration",
"data": {
"app_data": {
"push_token": "abcd",
"push_url": "https://push.mycool.app/push"
},
"app_version": "2.0.0",
"device_name": "Robbies iPhone",
"manufacturer": "Apple, Inc.",
"model": "iPhone XR",
"os_version": "23.02"
}
}
```
@ -223,7 +224,7 @@ Get all enabled zones.
```json
{
"type": "get_zones"
"type": "get_zones"
}
```
@ -245,7 +246,7 @@ Enables encryption support for an existing registration
```json
{
"type": "enable_encryption"
"type": "enable_encryption"
}
```

View File

@ -75,4 +75,3 @@ Only some of the keys are allowed during updates:
| state | bool, float, int, string | Yes | The state of the sensor |
| type | string | Yes | The type of the sensor. Must be one of `binary_sensor` or `sensor` |
| unique_id | string | Yes | An identifier unique to this installation of your app. You'll need this later. Usually best when its a safe version of the sensor name |

View File

@ -4,6 +4,6 @@ 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.
To make this possible, the Home Assistant UI supports [external authentication](frontend_external_auth). This allows your app to provide hooks so that the frontend will ask your app for access tokens.
To make this possible, the Home Assistant UI supports [external authentication](frontend/external-authentication.md). This allows your app to provide hooks so that the frontend will ask your app for access tokens.
Note that this feature requires a direct connection to the instance.

View File

@ -6,8 +6,8 @@ Home Assistant provides a RESTful API on the same port as the web frontend. (def
If you are not using the [`frontend`](https://www.home-assistant.io/components/frontend/) in your setup then you need to add the [`api` component](https://www.home-assistant.io/components/api/) to your `configuration.yaml` file.
* http://IP_ADDRESS:8123/ is an interface to control Home Assistant.
* http://IP_ADDRESS:8123/api/ is a RESTful API.
- `http://IP_ADDRESS:8123/` is an interface to control Home Assistant.
- `http://IP_ADDRESS:8123/api/` is a RESTful API.
The API accepts and returns only JSON encoded objects.
@ -16,10 +16,10 @@ All API calls have to be accompanied by the header `Authorization: Bearer ABCDEF
There are multiple ways to consume the Home Assistant Rest API. One is with `curl`:
```shell
$ curl -X GET \
-H "Authorization: Bearer ABCDEFGH" \
-H "Content-Type: application/json" \
http://IP_ADDRESS:8123/ENDPOINT
curl -X GET \
-H "Authorization: Bearer ABCDEFGH" \
-H "Content-Type: application/json" \
http://IP_ADDRESS:8123/ENDPOINT
```
Another option is to use Python and the [Requests](http://docs.python-requests.org/en/latest/) module.
@ -36,7 +36,8 @@ headers = {
response = get(url, headers=headers)
print(response.text)
```
Another option is to use the Restful Command component https://www.home-assistant.io/components/rest_command/ in a Home Assistant automation or script.
Another option is to use the [Restful Command integration](https://www.home-assistant.io/components/rest_command/) in a Home Assistant automation or script.
```yaml
turn_light_on:
@ -72,8 +73,8 @@ Returns a message if the API is up and running.
Sample `curl` command:
```shell
$ curl -X GET -H "Authorization: Bearer ABCDEFGH" \
-H "Content-Type: application/json" http://localhost:8123/api/
curl -X GET -H "Authorization: Bearer ABCDEFGH" \
-H "Content-Type: application/json" http://localhost:8123/api/
```
#### GET /api/config
@ -124,8 +125,8 @@ Returns the current configuration as JSON.
Sample `curl` command:
```shell
$ curl -X GET -H "Authorization: Bearer ABCDEFGH" \
-H "Content-Type: application/json" http://localhost:8123/api/config
curl -X GET -H "Authorization: Bearer ABCDEFGH" \
-H "Content-Type: application/json" http://localhost:8123/api/config
```
#### GET /api/discovery_info
@ -144,8 +145,8 @@ Returns basic information about the Home Assistant instance as JSON.
Sample `curl` command:
```shell
$ curl -X GET -H "Authorization: Bearer ABCDEFGH" \
-H "Content-Type: application/json" http://localhost:8123/api/discovery_info
curl -X GET -H "Authorization: Bearer ABCDEFGH" \
-H "Content-Type: application/json" http://localhost:8123/api/discovery_info
```
#### GET /api/events
@ -168,8 +169,8 @@ Returns an array of event objects. Each event object contains event name and lis
Sample `curl` command:
```shell
$ curl -X GET -H "Authorization: Bearer ABCDEFGH" \
-H "Content-Type: application/json" http://localhost:8123/api/events
curl -X GET -H "Authorization: Bearer ABCDEFGH" \
-H "Content-Type: application/json" http://localhost:8123/api/events
```
#### GET /api/services
@ -197,8 +198,8 @@ Returns an array of service objects. Each object contains the domain and which s
Sample `curl` command:
```shell
$ curl -X GET -H "Authorization: Bearer ABCDEFGH" \
-H "Content-Type: application/json" http://localhost:8123/api/services
curl -X GET -H "Authorization: Bearer ABCDEFGH" \
-H "Content-Type: application/json" http://localhost:8123/api/services
```
#### GET /api/history/period/<timestamp>
@ -242,21 +243,21 @@ You can pass the following optional GET parameters:
Sample `curl` commands:
```shell
$ curl -X GET -H "Authorization: Bearer ABCDEFGH" \
-H "Content-Type: application/json" \
http://localhost:8123/api/history/period/2016-12-29T00:00:00+02:00
curl -X GET -H "Authorization: Bearer ABCDEFGH" \
-H "Content-Type: application/json" \
http://localhost:8123/api/history/period/2016-12-29T00:00:00+02:00
```
```shell
$ curl -X GET -H "Authorization: Bearer ABCDEFGH" \
-H "Content-Type: application/json" \
http://localhost:8123/api/history/period/2016-12-29T00:00:00+02:00?filter_entity_id=sensor.temperature
curl -X GET -H "Authorization: Bearer ABCDEFGH" \
-H "Content-Type: application/json" \
http://localhost:8123/api/history/period/2016-12-29T00:00:00+02:00?filter_entity_id=sensor.temperature
```
```shell
$ curl -X GET -H "Authorization: Bearer ABCDEFGH" \
-H "Content-Type: application/json" \
http://localhost:8123/api/history/period/2016-12-29T00:00:00+02:00?end_time=2016-12-31T00%3A00%3A00%2B02%3A00
curl -X GET -H "Authorization: Bearer ABCDEFGH" \
-H "Content-Type: application/json" \
http://localhost:8123/api/history/period/2016-12-29T00:00:00+02:00?end_time=2016-12-31T00%3A00%3A00%2B02%3A00
```
#### GET /api/states
@ -283,8 +284,8 @@ Returns an array of state objects. Each state has the following attributes: enti
Sample `curl` command:
```shell
$ curl -X GET -H "Authorization: Bearer ABCDEFGH" \
-H "Content-Type: application/json" http://localhost:8123/api/states
curl -X GET -H "Authorization: Bearer ABCDEFGH" \
-H "Content-Type: application/json" http://localhost:8123/api/states
```
#### GET /api/states/<entity_id>
@ -310,9 +311,9 @@ Returns a state object for specified entity_id. Returns 404 if not found.
Sample `curl` command:
```shell
$ curl -X GET -H "Authorization: Bearer ABCDEFGH" \
-H "Content-Type: application/json" \
http://localhost:8123/api/states/sensor.kitchen_temperature
curl -X GET -H "Authorization: Bearer ABCDEFGH" \
-H "Content-Type: application/json" \
http://localhost:8123/api/states/sensor.kitchen_temperature
```
#### GET /api/error_log
@ -328,9 +329,9 @@ Retrieve all errors logged during the current session of Home Assistant as a pla
Sample `curl` command:
```shell
$ curl -X GET -H "Authorization: Bearer ABCDEFGH" \
-H "Content-Type: application/json" \
http://localhost:8123/api/error_log
curl -X GET -H "Authorization: Bearer ABCDEFGH" \
-H "Content-Type: application/json" \
http://localhost:8123/api/error_log
```
#### GET /api/camera_proxy/camera.<entity_id>
@ -340,9 +341,9 @@ Returns the data (image) from the specified camera entity_id.
Sample `curl` command:
```shell
$ curl -X GET -H "Authorization: Bearer ABCDEFGH" \
-H "Content-Type: application/json" \
http://localhost:8123/api/camera_proxy/camera.my_sample_camera?time=1462653861261 -o image.jpg
curl -X GET -H "Authorization: Bearer ABCDEFGH" \
-H "Content-Type: application/json" \
http://localhost:8123/api/camera_proxy/camera.my_sample_camera?time=1462653861261 -o image.jpg
```
#### POST /api/states/<entity_id>
@ -383,10 +384,10 @@ The return code is 200 if the entity existed, 201 if the state of a new entity w
Sample `curl` command:
```shell
$ curl -X POST -H "Authorization: Bearer ABCDEFGH" \
-H "Content-Type: application/json" \
-d '{"state": "25", "attributes": {"unit_of_measurement": "°C"}}' \
http://localhost:8123/api/states/sensor.kitchen_temperature
curl -X POST -H "Authorization: Bearer ABCDEFGH" \
-H "Content-Type: application/json" \
-d '{"state": "25", "attributes": {"unit_of_measurement": "°C"}}' \
http://localhost:8123/api/states/sensor.kitchen_temperature
```
#### POST /api/events/<event_type>
@ -445,20 +446,20 @@ Sample `curl` commands:
Turn the light on:
```shell
$ curl -X POST -H "Authorization: Bearer ABCDEFGH" \
-H "Content-Type: application/json" \
-d '{"entity_id": "switch.christmas_lights"}' \
http://localhost:8123/api/services/switch/turn_on
curl -X POST -H "Authorization: Bearer ABCDEFGH" \
-H "Content-Type: application/json" \
-d '{"entity_id": "switch.christmas_lights"}' \
http://localhost:8123/api/services/switch/turn_on
```
Send a MQTT message:
```shell
$ curl -X POST \
-H "Content-Type: application/json" \
-H "x-ha-access:YOUR_PASSWORD" \
-d '{"payload": "OFF", "topic": "home/fridge", "retain": "True"}' \
http://localhost:8123/api/services/mqtt/publish
curl -X POST \
-H "Content-Type: application/json" \
-H "x-ha-access:YOUR_PASSWORD" \
-d '{"payload": "OFF", "topic": "home/fridge", "retain": "True"}' \
http://localhost:8123/api/services/mqtt/publish
```
:::tip
@ -484,9 +485,9 @@ Paulus is at work!
Sample `curl` command:
```shell
$ curl -X POST -H "Authorization: Bearer ABCDEFGH" \
-H "Content-Type: application/json" \
-d '{"template": "It is {{ now() }}!"}' http://localhost:8123/api/template
curl -X POST -H "Authorization: Bearer ABCDEFGH" \
-H "Content-Type: application/json" \
-d '{"template": "It is {{ now() }}!"}' http://localhost:8123/api/template
```
#### POST /api/config/core/check_config
@ -495,7 +496,7 @@ Trigger a check of `configuration.yaml`. No additional data needs to be passed i
If the check is successful, the following will be returned:
```javascript
```json
{
"errors": null,
"result": "valid"
@ -504,7 +505,7 @@ If the check is successful, the following will be returned:
If the check fails, the errors attribute in the object will list what caused the check to fail. For example:
```javascript
```json
{
"errors": "Integration not found: frontend:",
"result": "invalid"
@ -517,7 +518,7 @@ Set up event forwarding to another Home Assistant instance.
Requires a JSON object that represents the API to forward to.
```javascript
```json
{
"host": "machine",
"api_password": "my_super_secret_password",
@ -535,11 +536,11 @@ It will return a message if event forwarding was set up successfully.
#### DELETE /api/event_forwarding
Cancel event forwarding to another Home Assistant instance.<br />
Cancel event forwarding to another Home Assistant instance.
Requires a JSON object that represents the API to cancel forwarding to.
```javascript
```json
{
"host": "machine",
"api_password": "my_super_secret_password",

View File

@ -3,9 +3,9 @@ title: "Components Architecture"
sidebar_label: "Components"
---
Home Assistant can be extended with **components**. Each component is responsible for a specific domain within Home Assistant. Components can listen for or trigger events, offer services, and maintain states. Components 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 components](https://www.home-assistant.io/components/).
Home Assistant can be extended with **components**. Each component is responsible for a specific domain within Home Assistant. Components can listen for or trigger events, offer services, and maintain states. Components 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 components](https://www.home-assistant.io/integrations/).
<img class='invertDark'
<img class='invertDark'
src='/img/en/architecture/component_interaction.png'
alt='Diagram showing interaction between components and the Home Assistant core.' />

View File

@ -21,10 +21,10 @@ The component is responsible for defining the Abstract Entity Class and services
The Entity Component is responsible for:
- Distributing the configuration to the platforms
- Forward config entries and discoveries
- Collect entities for service calls
- Optionally maintain a group of all entities
- Distributing the configuration to the platforms
- Forward config entries and discoveries
- Collect entities for service calls
- Optionally maintain a group of all entities
## Entity Platform

View File

@ -5,11 +5,11 @@ sidebar_label: "Introduction"
Before we dive into the Home Assistant architecture, let's get a clear overview of the home automation landscape as a whole. This way, we can show how the different parts of Home Assistant fit into the picture.
For more information about each part in this overview, <a href='https://www.home-assistant.io/blog/2014/12/26/home-control-home-automation-and-the-smart-home/'>check out our blog</a>. Here's the tl;dr version of the blog:
For more information about each part in this overview, [check out our blog](https://www.home-assistant.io/blog/2014/12/26/home-control-home-automation-and-the-smart-home). Here's the tl;dr version of the blog:
* Home Control is responsible for collecting information and controlling devices.
* Home Automation triggers commands based on user configurations.
* Smart Home triggers commands based on previous behavior.
- Home Control is responsible for collecting information and controlling devices.
- Home Automation triggers commands based on user configurations.
- Smart Home triggers commands based on previous behavior.
<img class='invertDark'
src='/img/en/architecture/home_automation_landscape.svg'
@ -18,10 +18,10 @@ For more information about each part in this overview, <a href='https://www.home
The Home Assistant core is responsible for Home Control. Home Assistant contains four parts which make this possible:
* **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.
* **Service Registry**: listens on the event bus for `call_service` events and allows other code to register services.
* **Timer**: sends a `time_changed` event every 1 second on the event bus.
- **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.
- **Service Registry**: listens on the event bus for `call_service` events and allows other code to register services.
- **Timer**: sends a `time_changed` event every 1 second on the event bus.
<img class='invertDark'
alt='Overview of the Home Assistant core architecture'

View File

@ -8,4 +8,4 @@ If you are not familiar yet with asyncio, please watch the below video. It's a g
<iframe width="560" height="315" src="https://www.youtube.com/embed/M-UcUs7IMIM" frameborder="0" allowfullscreen></iframe>
</div>
[rob]: https://github.com/rob-smallshire
[rob]: https://github.com/rob-smallshire

View File

@ -109,6 +109,5 @@ If you want to spawn a task that will not block the current async context, you c
hass.async_create_task(async_say_hello(hass, target))
```
[dev-docs]: https://dev-docs.home-assistant.io/en/master/api/core.html
[dev-docs-async]: https://dev-docs.home-assistant.io/en/dev/api/util.html#module-homeassistant.util.async

View File

@ -13,8 +13,8 @@ Before you can ask the user to authorize their instance with your application, y
The client ID you need to use is the website of your application. The redirect url has to be of the same host and port as the client ID. For example:
- client id: `https://www.my-application.io`
- redirect uri: `https://www.my-application.io/hass/auth_callback`
- client id: `https://www.my-application.io`
- redirect uri: `https://www.my-application.io/hass/auth_callback`
If you require a different redirect url (ie, if building a native app), you can add an HTML tag to the content of the website of your application (the client ID) with an approved redirect url. For example, add this to your site to whitelist redirect uri `hass://auth`:
@ -25,6 +25,7 @@ If you require a different redirect url (ie, if building a native app), you can
Home Assistant will scan the first 10kB of a website for link tags.
## Authorize
<a href='https://www.websequencediagrams.com/?lz=dGl0bGUgQXV0aG9yaXphdGlvbiBGbG93CgpVc2VyIC0-IENsaWVudDogTG9nIGludG8gSG9tZSBBc3Npc3RhbnQKABoGIC0-IFVzZXI6AEMJZSB1cmwgAD4JACgOOiBHbyB0bwAeBWFuZCBhAC0ICgBQDgB1DACBFw5jb2RlAHELAE4RZXQgdG9rZW5zIGZvcgAoBgBBGlQAJQUK&s=qsd'>
<img class='invertDark' src='/img/en/auth/authorize_flow.png' alt='Overview of how the different parts interact' />
</a>
@ -35,7 +36,7 @@ Home Assistant will scan the first 10kB of a website for link tags.
The authorize url should contain `client_id` and `redirect_uri` as query parameters.
```
```txt
http://your-instance.com/auth/authorize?
client_id=https%3A%2F%2Fhass-auth-demo.glitch.me&
redirect_uri=https%3A%2F%2Fhass-auth-demo.glitch.me%2F%3Fauth_callback%3D1
@ -43,7 +44,7 @@ http://your-instance.com/auth/authorize?
Optionally you can also include a `state` parameter, this will be added to the redirect uri. The state is perfect to store the instance url that you are authenticating with. Example:
```
```txt
http://your-instance.com/auth/authorize?
client_id=https%3A%2F%2Fhass-auth-demo.glitch.me&
redirect_uri=https%3A%2F%2Fhass-auth-demo.glitch.me%2Fauth_callback&
@ -52,7 +53,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:
```
```txt
https://hass-auth-demo.glitch.me/auth_callback
code=12345&
state=http%3A%2F%2Fhassio.local%3A8123
@ -74,7 +75,7 @@ All requests to the token endpoint need to contain the exact same client ID as w
Use the grant type `authorization_code` to retrieve the tokens after a user has successfully finished the authorize step. The request body is:
```
```txt
grant_type=authorization_code&
code=12345&
client_id=https%3A%2F%2Fhass-auth-demo.glitch.me
@ -106,7 +107,7 @@ An HTTP status code of 400 will be returned if an invalid request has been issue
Once you have retrieved a refresh token via the grant type `authorization_code`, you can use it to fetch new access tokens. The request body is:
```
```txt
grant_type=refresh_token&
refresh_token=IJKLMNOPQRST&
client_id=https%3A%2F%2Fhass-auth-demo.glitch.me
@ -138,7 +139,7 @@ An HTTP status code of 400 will be returned if an invalid request has been issue
:::
The token endpoint is also capable of revoking a refresh token. Revoking a refresh token will immediately revoke the refresh token and all access tokens that it has ever granted. To revoke a refresh token, make the following request:
```
```txt
token=IJKLMNOPQRST&
action=revoke
```
@ -209,7 +210,8 @@ print(response.text)
```
### Example: NodeJS
```JavaScript
```javascript
fetch('https://your.awesome.home/api/error/all', {
headers: { Authorization: 'Bearer ABCDEFGH' }
}).then(function (response) {
@ -255,7 +257,7 @@ The response will contain the signed path:
Some things to note about a signed path:
- If the refresh token is deleted, the signed url is no longer valid.
- If the user is deleted, the signed url is no longer valid (because the refresh token will be deleted).
- If Home Assistant is restarted, the signed url is no longer valid.
- Access is only validated when the request is received. If a response takes longer than the expiration time (ie, downloading a large file), the download will continue after the expiration date has passed.
- If the refresh token is deleted, the signed url is no longer valid.
- If the user is deleted, the signed url is no longer valid (because the refresh token will be deleted).
- If Home Assistant is restarted, the signed url is no longer valid.
- Access is only validated when the request is received. If a response takes longer than the expiration time (ie, downloading a large file), the download will continue after the expiration date has passed.

View File

@ -31,6 +31,7 @@ Multi-factor Auth modules shall extend the following methods of `MultiFactorAuth
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.
Each MFA module need to implement a setup flow handler extends from `mfa_modules.SetupFlow` (if only one simple setup step need, `SetupFlow` can be used as well). For example for Google Authenticator (TOTP, Time-based One Time Password) module, the flow will need to be:
- Generate a secret and store it on instance of setup flow
- Return `async_show_form` with a QR code in the description (injected as base64 via `description_placeholders`)
- User scans code and enters a code to verify it scanned correctly and clock in synced

View File

@ -149,7 +149,6 @@ The `Unauthorized` exception has various parameters, to identify the permission
| # Not all actions have an ID (like adding config entry)
| # We then use this fallback to know what category was unauth
| Parameter | Description
| --------- | -----------
| context | The context of the current call.

View File

@ -99,7 +99,7 @@ During startup, Home Assistant first calls the [normal component setup](https://
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/home-assistant/blob/0.68.0/homeassistant/components/hue/__init__.py#L119)).
#### For platforms
### For platforms
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/home-assistant/blob/0.68.0/homeassistant/components/hue/bridge.py#L81)):

View File

@ -13,7 +13,7 @@ Not all existing code follow the requirements in this checklist. This cannot be
1. Follow our [Style guidelines](development_guidelines.md)
2. Use existing constants from [`const.py`](https://github.com/home-assistant/home-assistant/blob/dev/homeassistant/const.py)
* Only add new constants to `const.py` if they are widely used. Otherwise keep them on components level
- Only add new constants to `const.py` if they are widely used. Otherwise keep them on components level
### 1. Requirements
@ -23,21 +23,21 @@ Not all existing code follow the requirements in this checklist. This cannot be
### 2. Configuration
1. Voluptuous schema present for [configuration validation](development_validation.md)
2. Default parameters specified in voluptuous schema, not in `setup(…)`
3. Schema using as many generic config keys as possible from `homeassistant.const`
4. If your component has platforms, define a `PLATFORM_SCHEMA` instead of a `CONFIG_SCHEMA`.
5. If using a `PLATFORM_SCHEMA` to be used with `EntityComponent`, import base from `homeassistant.helpers.config_validation`
6. Never depend on users adding things to `customize` to configure behavior inside your component.
1. Voluptuous schema present for [configuration validation](development_validation.md)
2. Default parameters specified in voluptuous schema, not in `setup(…)`
3. Schema using as many generic config keys as possible from `homeassistant.const`
4. If your component has platforms, define a `PLATFORM_SCHEMA` instead of a `CONFIG_SCHEMA`.
5. If using a `PLATFORM_SCHEMA` to be used with `EntityComponent`, import base from `homeassistant.helpers.config_validation`
6. Never depend on users adding things to `customize` to configure behavior inside your component.
### 3. Component/platform communication
1. You can share data with your platforms by leveraging `hass.data[DOMAIN]`.
2. If the component fetches data that causes its related platform entities to update, you can notify them using the dispatcher code in `homeassistant.helpers.dispatcher`.
1. You can share data with your platforms by leveraging `hass.data[DOMAIN]`.
2. If the component fetches data that causes its related platform entities to update, you can notify them using the dispatcher code in `homeassistant.helpers.dispatcher`.
### 4. Communication with devices/services
1. All API specific code has to be part of a third party library hosted on PyPi. Home Assistant should only interact with objects and not make direct calls to the API.
1. All API specific code has to be part of a third party library hosted on PyPi. Home Assistant should only interact with objects and not make direct calls to the API.
```python
# bad
@ -62,6 +62,7 @@ Keep a new integration to the minimum functionality needed for someone to get va
- Do not submit pull requests that depend on other work which is still unmerged.
### 6. Event names
Prefix component event names with the domain name. For example, use `netatmo_person` instead of `person` for the `netatmo` component.
### 7. Tests

View File

@ -17,5 +17,4 @@ If your integration is not using config entries, it will have to use our discove
To do this, you will need to use the `load_platform` and `async_load_platform` methods from the discovery helper.
- See also a [full example that implements this logic](https://github.com/home-assistant/example-custom-config/tree/master/custom_components/example_load_platform/)

View File

@ -7,8 +7,8 @@ Each integration is stored inside a directory named after the integration domain
The bare minimum content of this folder looks like this:
- `manifest.json`: The manifest file describes the integration and its dependencies. [More info](creating_integration_manifest.md)
- `__init__.py`: The component file. If the integration only offers a platform, you can keep this file limited to a docstring introducing the integration `"""The Mobile App integration."""`.
- `manifest.json`: The manifest file describes the integration and its dependencies. [More info](creating_integration_manifest.md)
- `__init__.py`: The component file. If the integration only offers a platform, you can keep this file limited to a docstring introducing the integration `"""The Mobile App integration."""`.
## Integrating devices - `light.py`, `switch.py` etc
@ -25,7 +25,7 @@ If your integration is going to register services, it will need to provide a des
Home Assistant will look for an integration when it sees the domain referenced in the config file (i.e. `mobile_app:`) or if it is a dependency of another integration. Home Assistant will look at the following locations:
* `<config directory>/custom_components/<domain>`
* `homeassistant/components/<domain>` (built-in integrations)
- `<config directory>/custom_components/<domain>`
- `homeassistant/components/<domain>` (built-in integrations)
You can override a built-in integration by having an integration with the same domain in your `config/custom_components` folder. Note that overriding built-in components is not recommended as you will no longer get updates. It is recommended to pick a unique name.

View File

@ -11,24 +11,25 @@ Not all existing platforms follow the requirements in this checklist. This canno
### 0. Common
1. Follow our [Style guidelines](development_guidelines.md)
2. Use existing constants from [`const.py`](https://github.com/home-assistant/home-assistant/blob/dev/homeassistant/const.py)
* Only add new constants to `const.py` if they are widely used. Otherwise keep them on platform level
* Use `CONF_MONITORED_CONDITIONS` instead of `CONF_MONITORED_VARIABLES`
1. Follow our [Style guidelines](development_guidelines.md)
2. Use existing constants from [`const.py`](https://github.com/home-assistant/home-assistant/blob/dev/homeassistant/const.py)
- Only add new constants to `const.py` if they are widely used. Otherwise keep them on platform level
- Use `CONF_MONITORED_CONDITIONS` instead of `CONF_MONITORED_VARIABLES`
### 1. Requirements
1. Requirements have been added to [`manifest.json`](creating_integration_manifest.md). The `REQUIREMENTS` constant is deprecated.
2. Requirement version should be pinned: `"requirements": ['phue==0.8.1']`
3. We no longer want requirements hosted on GitHub. Please upload to PyPi.
1. Requirements have been added to [`manifest.json`](creating_integration_manifest.md). The `REQUIREMENTS` constant is deprecated.
2. Requirement version should be pinned: `"requirements": ['phue==0.8.1']`
3. We no longer want requirements hosted on GitHub. Please upload to PyPi.
### 2. Configuration
1. If the platform can be set up directly, add a voluptuous schema for [configuration validation](development_validation.md)
2. Voluptuous schema extends schema from component<br />(e.g., `hue.light.PLATFORM_SCHEMA` extends `light.PLATFORM_SCHEMA`)
3. Default parameters specified in voluptuous schema, not in `setup_platform(...)`
4. Your `PLATFORM_SCHEMA` should use as many generic config keys as possible from `homeassistant.const`
5. Never depend on users adding things to `customize` to configure behavior inside your platform.
1. If the platform can be set up directly, add a voluptuous schema for [configuration validation](development_validation.md)
2. Voluptuous schema extends schema from component
(e.g., `hue.light.PLATFORM_SCHEMA` extends `light.PLATFORM_SCHEMA`)
3. Default parameters specified in voluptuous schema, not in `setup_platform(...)`
4. Your `PLATFORM_SCHEMA` should use as many generic config keys as possible from `homeassistant.const`
5. Never depend on users adding things to `customize` to configure behavior inside your platform.
```python
import voluptuous as vol
@ -51,13 +52,13 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
### 3. Setup Platform
1. Verify that the passed in configuration (user/pass/host etc.) works.
2. Group your calls to `add_devices` if possible.
3. If the platform adds extra services, the format should be `<domain of your integration>.<service name>`. So if your integration's domain is "awesome_sauce" and you are making a light platform, you would register services under the `awesome_sauce` domain. Make sure that your services [verify permissions](auth_permissions.md#checking-permissions).
1. Verify that the passed in configuration (user/pass/host etc.) works.
2. Group your calls to `add_devices` if possible.
3. If the platform adds extra services, the format should be `<domain of your integration>.<service name>`. So if your integration's domain is "awesome_sauce" and you are making a light platform, you would register services under the `awesome_sauce` domain. Make sure that your services [verify permissions](auth_permissions.md#checking-permissions).
### 4. Entity
1. Extend the entity from the integration you're building a platform for.
1. Extend the entity from the integration you're building a platform for.
```python
from homeassistant.components.light import Light
@ -67,15 +68,15 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
"""Hue light component."""
```
2. Avoid passing in `hass` as a parameter to the entity. When the entity has been added to Home Assistant, `hass` will be set on the entity when the entity is added to Home Assistant. This means you can access `hass` as `self.hass` inside the entity.
3. Do not call `update()` in constructor, use `add_entities(devices, True)` instead.
4. Do not do any I/O inside properties. Cache values inside `update()` instead.
5. When dealing with time, state and/or attributes should not contain relative time since something happened. Instead, it should store UTC timestamps.
6. Leverage the [entity lifecycle callbacks](entity_index.md#lifecycle-hooks) to attach event listeners or clean up connections.
2. Avoid passing in `hass` as a parameter to the entity. When the entity has been added to Home Assistant, `hass` will be set on the entity when the entity is added to Home Assistant. This means you can access `hass` as `self.hass` inside the entity.
3. Do not call `update()` in constructor, use `add_entities(devices, True)` instead.
4. Do not do any I/O inside properties. Cache values inside `update()` instead.
5. When dealing with time, state and/or attributes should not contain relative time since something happened. Instead, it should store UTC timestamps.
6. Leverage the [entity lifecycle callbacks](entity_index.md#lifecycle-hooks) to attach event listeners or clean up connections.
### 5. Communication with devices/services
1. All API specific code has to be part of a third party library hosted on PyPi. Home Assistant should only interact with objects and not make direct calls to the API.
1. All API specific code has to be part of a third party library hosted on PyPi. Home Assistant should only interact with objects and not make direct calls to the API.
```python
# bad

View File

@ -9,8 +9,8 @@ To create a platform, you will need to create a file with the domain name of the
We have created two example integrations that should give you a look at how this works:
- [Example sensor platform](https://github.com/home-assistant/example-custom-config/tree/master/custom_components/example_sensor/): hello world of platforms.
- [Example light platform](https://github.com/home-assistant/example-custom-config/tree/master/custom_components/example_light/): showing best practices.
- [Example sensor platform](https://github.com/home-assistant/example-custom-config/tree/master/custom_components/example_sensor/): hello world of platforms.
- [Example light platform](https://github.com/home-assistant/example-custom-config/tree/master/custom_components/example_light/): showing best practices.
### Interfacing with devices

View File

@ -227,16 +227,16 @@ _The example is about config entries, but works with other parts that use data e
The flow works as follows:
1. The user starts config flow in Home Assistant.
2. Config flow prompts the user to finish the flow on an external website.
3. The user opens the external website.
4. Upon completion of the external step, the user's browser will be redirected to a Home Assistant endpoint to deliver the response.
5. The endpoint validates the response, and upon validation, marks the external step as done and returns JavaScript code to close the window: `<script>window.close()</script>`.
1. The user starts config flow in Home Assistant.
2. Config flow prompts the user to finish the flow on an external website.
3. The user opens the external website.
4. Upon completion of the external step, the user's browser will be redirected to a Home Assistant endpoint to deliver the response.
5. The endpoint validates the response, and upon validation, marks the external step as done and returns JavaScript code to close the window: `<script>window.close()</script>`.
To be able to route the result of the external step to the Home Assistant endpoint, you will need to make sure the config flow ID is included. If your external step is an OAuth2 flow, you can leverage the oauth2 state for this. This is a variable that is not interpreted by the authorization page but is passed as-is to the Home Assistant endpoint.
6. The window closes and the Home Assistant user interface with the config flow will be visible to the user again.
7. The config flow has automatically advanced to the next step when the external step was marked as done. The user is prompted with the next step.
6. The window closes and the Home Assistant user interface with the config flow will be visible to the user again.
7. The config flow has automatically advanced to the next step when the external step was marked as done. The user is prompted with the next step.
Example configuration flow that includes an external step.

View File

@ -20,11 +20,11 @@ The Home Assistant instance contains four objects to help you interact with the
Depending on what you're writing, there are different ways the `hass` object is made available.
**Component**<br />
**Component**
Passed into `setup(hass, config)` or `async_setup(hass, config)`.
**Platform**<br />
**Platform**
Passed into `setup_platform(hass, config, add_devices, discovery_info=None)` or `async_setup_platform(hass, config, async_add_devices, discovery_info=None)`.
**Entity**<br />
**Entity**
Available as `self.hass` once the entity has been added via the `add_devices` callback inside a platform.

View File

@ -4,9 +4,9 @@ title: "Using States"
Home Assistant keeps track of the states of entities in a state machine. The state machine has very few requirements:
- Each state is related to an entity identified by an entity id. This id is made up of a domain and an object id. For example `light.kitchen_ceiling`. You can make up any combination of domain and object id, even overwriting existing states.
- Each state has a primary attribute that describes the state of the entity. In the case of a light this could be for example "on" and "off". You can store anything you want in the state, as long as it's a string (will be converted if it's not).
- You can store more information about an entity by setting attributes. Attributes is a dictionary that can contain any data that you want. The only requirement is that it's JSON serializable, so you're limited to numbers, strings, dictionaries and lists.
- Each state is related to an entity identified by an entity id. This id is made up of a domain and an object id. For example `light.kitchen_ceiling`. You can make up any combination of domain and object id, even overwriting existing states.
- Each state has a primary attribute that describes the state of the entity. In the case of a light this could be for example "on" and "off". You can store anything you want in the state, as long as it's a string (will be converted if it's not).
- You can store more information about an entity by setting attributes. Attributes is a dictionary that can contain any data that you want. The only requirement is that it's JSON serializable, so you're limited to numbers, strings, dictionaries and lists.
[Description of the state object.](https://www.home-assistant.io/docs/configuration/state_object/)

View File

@ -11,27 +11,27 @@ If you use the workflow below, it is important that you force push the update as
You should have added an additional `remote` after you clone your fork. If you did not, do it now before proceeding.
```shell
$ git remote add upstream https://github.com/home-assistant/core.git
git remote add upstream https://github.com/home-assistant/core.git
```
```shell
# Run this from your feature branch
$ git fetch upstream dev # to pull the latest changes into a local dev branch
$ git rebase upstream/dev # to put those changes into your feature branch before your changes
git fetch upstream dev # to pull the latest changes into a local dev branch
git rebase upstream/dev # to put those changes into your feature branch before your changes
```
If rebase detects conflicts, repeat this process until all changes have been resolved:
1. `git status` shows you the file with the conflict; edit the file and resolve the lines between `<<<< | >>>>`
3. Add the modified file: `git add <file>` or `git add .`
4. Continue rebase: `git rebase --continue`
5. Repeat until you've resolved all conflicts
2. Add the modified file: `git add <file>` or `git add .`
3. Continue rebase: `git rebase --continue`
4. Repeat until you've resolved all conflicts
After rebasing your branch, you will have rewritten history relative to your GitHub fork's branch. When you go to push you will see an error that your history has diverged from the original branch. In order to get your GitHub fork up-to-date with your local branch, you will need to force push, using the following command:
```shell
# Run this from your feature branch
$ git push origin --force
git push origin --force
```
Other workflows are covered in detail in the [Github documentation](https://help.github.com/articles/fork-a-repo/).

View File

@ -3,7 +3,6 @@ title: "Development Checklist"
sidebar_label: Introduction
---
Before you commit any changes, check your work against these requirements:
- All communication to external devices or services must be wrapped in an external Python library hosted on [pypi](https://pypi.python.org/pypi).
@ -12,4 +11,4 @@ Before you commit any changes, check your work against these requirements:
- The `.coveragerc` file is updated to exclude your platform if there are no tests available or your new code uses a third-party library for communication with the device, service, or sensor
- The code is formatted using Black, as per these [guidelines](https://developers.home-assistant.io/blog/2019/07/31/black.html). This can be done running the command `black --fast homeassistant`.
- Documentation is developed for [home-assistant.io](https://home-assistant.io/)
* Visit the [website documentation](https://www.home-assistant.io/developers/documentation/) for more information about contributing to [home-assistant.io](https://github.com/home-assistant/home-assistant.github.io).
- Visit the [website documentation](https://www.home-assistant.io/developers/documentation/) for more information about contributing to [home-assistant.io](https://github.com/home-assistant/home-assistant.io).

View File

@ -46,8 +46,8 @@ Also note that `_LOGGER.info` is reserved for the core, use `_LOGGER.debug` for
Instead of order the imports manually, use [`isort`](https://github.com/timothycrosley/isort).
```shell
$ pip3 install isort
$ isort homeassistant/components/sensor/fixer.py
pip3 install isort
isort homeassistant/components/sensor/fixer.py
```
### Use new style string formatting

View File

@ -8,4 +8,3 @@ Home Assistant is built from the ground up to be easily extensible using integra
Before you start, make sure that you have read up on the [Home Assistant architecture](architecture_index.md) so that you are familiar with the concepts that make up Home Assistant.
If you run into trouble following this documentation, don't hesitate to join our #devs_backend channel on [Discord](https://www.home-assistant.io/join-chat/).

View File

@ -8,36 +8,36 @@ Always base your Pull Requests of of the current **`dev`** branch, not `master`.
Submit your improvements, fixes, and new features to Home Assistant one at a time, using GitHub [Pull Requests](https://help.github.com/articles/using-pull-requests). Here are the steps:
1. From your fork's dev branch, create a new branch to hold your changes:
1. From your fork's dev branch, create a new branch to hold your changes:
`git checkout -b some-feature`
`git checkout -b some-feature`
2. Make your changes, create a [new platform](creating_platform_index.md), develop a [new component](creating_component_index.md), or fix [issues](https://github.com/home-assistant/home-assistant/issues).
2. Make your changes, create a [new platform](creating_platform_index.md), develop a [new component](creating_component_index.md), or fix [issues](https://github.com/home-assistant/home-assistant/issues).
3. [Test your changes](development_testing.md) and check for style violations.
3. [Test your changes](development_testing.md) and check for style violations.
4. If everything looks good according to these [musts](development_checklist.md), commit your changes:
4. If everything looks good according to these [musts](development_checklist.md), commit your changes:
`git add .`
`git commit -m "Add some-feature"`
* Write a meaningful commit message and not only `Update` or `Fix`.
* Use a capital letter to start with your commit message.
* Don't prefix your commit message with `[bla.bla]` or `platform:`.
* Consider adding tests to ensure that your code works.
- Write a meaningful commit message and not only `Update` or `Fix`.
- Use a capital letter to start with your commit message.
- Don't prefix your commit message with `[bla.bla]` or `platform:`.
- Consider adding tests to ensure that your code works.
5. Push your committed changes back to your fork on GitHub:
5. Push your committed changes back to your fork on GitHub:
`git push origin HEAD`
6. Follow [these steps](https://help.github.com/articles/creating-a-pull-request/) to create your pull request.
6. Follow [these steps](https://help.github.com/articles/creating-a-pull-request/) to create your pull request.
* On GitHub, navigate to the main page of the Home Assistant repository.
* In the "Branch" menu, choose the branch that contains your commits (from your fork).
* To the right of the Branch menu, click **New pull request**.
* Use the base branch dropdown menu to select the branch you'd like to merge your changes into, then use the compare branch drop-down menu to choose the topic branch you made your changes in. Make sure the Home Assistant branch matches with your forked branch (`dev`) else you will propose ALL commits between branches.
* Type a title and complete the provided description for your pull request.
* Click **Create pull request**.
- On GitHub, navigate to the main page of the Home Assistant repository.
- In the "Branch" menu, choose the branch that contains your commits (from your fork).
- To the right of the Branch menu, click **New pull request**.
- Use the base branch dropdown menu to select the branch you'd like to merge your changes into, then use the compare branch drop-down menu to choose the topic branch you made your changes in. Make sure the Home Assistant branch matches with your forked branch (`dev`) else you will propose ALL commits between branches.
- Type a title and complete the provided description for your pull request.
- Click **Create pull request**.
7. Check for comments and suggestions on your pull request and keep an eye on the [CI output](https://travis-ci.org/home-assistant/home-assistant/).
7. Check for comments and suggestions on your pull request and keep an eye on the [CI output](https://travis-ci.org/home-assistant/home-assistant/).

View File

@ -10,7 +10,7 @@ As it states in the [Style guidelines section](development_guidelines.md) all co
Local testing is done using [Tox](https://tox.readthedocs.io), which has been installed as part of running `script/setup` in the [virtual environment](development_environment.md). To start the tests, activate the virtual environment and simply run the command:
```shell
$ tox
tox
```
It might be required that you install additional packages depending on your distribution/operating system:
@ -50,22 +50,22 @@ $ tox -e py38 -- tests/test_core.py --duration=10
Running `tox` will invoke the full test suite. Even if you specify which tox target to run, you still run all tests inside that target. That's not very convenient to quickly iterate on your code! To be able to run the specific test suites without `tox`, you'll need to install the test dependencies into your Python environment:
```shell
$ pip3 install -r requirements_test_all.txt -c homeassistant/package_constraints.txt
pip3 install -r requirements_test_all.txt -c homeassistant/package_constraints.txt
```
Now that you have all test dependencies installed, you can run tests on individual files:
```shell
$ flake8 homeassistant/core.py
$ pylint homeassistant/core.py
$ pydocstyle homeassistant/core.py
$ py.test tests/test_core.py
flake8 homeassistant/core.py
pylint homeassistant/core.py
pydocstyle homeassistant/core.py
py.test tests/test_core.py
```
You can also run linting tests against all changed files, as reported by `git diff upstream/dev... --diff-filter=d --name-only`, using the `lint` script:
```shell
$ script/lint
script/lint
```
### Preventing linter errors
@ -73,8 +73,8 @@ $ script/lint
Save yourself the hassle of extra commits just to fix style errors by enabling the Flake8 git commit hook. Flake8 will check your code when you try to commit to the repository and block the commit if there are any style errors, which gives you a chance to fix them!
```shell
$ pip3 install flake8 flake8-docstrings
$ flake8 --install-hook=git
pip3 install flake8 flake8-docstrings
flake8 --install-hook=git
```
The `flake8-docstrings` extension will check docstrings according to [PEP257](https://www.python.org/dev/peps/pep-0257/) when running Flake8.

View File

@ -13,6 +13,7 @@ See [this instagram blog post](https://instagram-engineering.com/let-your-code-t
We've added a script to start a run of our test suite or a test module and tell the `monkeytype` program to analyze the run.
### Basic workflow
1. Run `script/monkeytype tests/path/to/your_test_module.py`.
2. Run `monkeytype stub homeassistant.your_actual_module`.
3. Look at output from the monkeytyped typing stub. If not totally bad, apply the stub to your module. You most likely will need to manually edit the typing in the last step.

View File

@ -4,7 +4,7 @@ title: "Create a new page"
For a platform or integration page, the fastest way is to make a copy of an existing page and edit it. The [Integration overview](https://www.home-assistant.io/integrations/) and the [Examples section](https://www.home-assistant.io/cookbook/) are generated automatically, so there is no need to add a link to those pages.
Please honor the [Standards](documentation_standards.md) we have for the documentation.
Please honor the [Standards](documenting/standards.md) we have for the documentation.
If you start from scratch with a page, you need to add a header. Different sections of the documentation may need different headers.
@ -100,7 +100,7 @@ When you're writing code that is to be executed on the terminal, do not prefix t
### Templates
For the [configuration templating](https://www.home-assistant.io/docs/configuration/templating/) [Jinja](http://jinja.pocoo.org/) is used. Check the [Documentation Standards](documentation_standards.md) for further details.
For the [configuration templating](https://www.home-assistant.io/docs/configuration/templating/) [Jinja](http://jinja.pocoo.org/) is used. Check the [Documentation Standards](documenting/standards.md) for further details.
If you are don't escape templates then they will be rendered and appear blank on the website.

View File

@ -6,26 +6,26 @@ To ensure that the documentation for Home Assistant is consistent and easy to fo
## General Documentation
* The language of the documentation should be American-English.
* Don't put two spaces after a period and avoid the "Oxford comma".
* There is no limit for the line length. You are allowed to write in a flowing text style. This will make it easier to use the GitHub online editor in the future.
* Be objective and not gender favoring, polarizing, race related or religion inconsiderate.
* The case of brand names, services, protocols, integrations and platforms must match its respective counterpart. e.g., "Z-Wave" **not** "Zwave", "Z-wave", "Z Wave" or "ZWave". Also, "Input Select" **not** "input select" or "Input select".
* Do not use ALL CAPITALS for emphasis - use italics instead.
- The language of the documentation should be American-English.
- Don't put two spaces after a period and avoid the "Oxford comma".
- There is no limit for the line length. You are allowed to write in a flowing text style. This will make it easier to use the GitHub online editor in the future.
- Be objective and not gender favoring, polarizing, race related or religion inconsiderate.
- The case of brand names, services, protocols, integrations and platforms must match its respective counterpart. e.g., "Z-Wave" **not** "Zwave", "Z-wave", "Z Wave" or "ZWave". Also, "Input Select" **not** "input select" or "Input select".
- Do not use ALL CAPITALS for emphasis - use italics instead.
## Integration and Platform Pages
* The **Configuration Variables** section must use the `{% configuration %}` tag.
* The **Configuration Variables** section is only used for YAML configuration.
* Configuration variables must document the requirement status (`false` or `true`).
* Configuration variables must document the default value, if any.
* Configuration variables must document the accepted value types (see [Configuration variables details](documentation_create_page.md#configuration)).
* For configuration variables that accept multiple types, separate the types with a comma (i.e. `string, int`).
* Use YAML sequence syntax in the sample code if it is supported.
* All examples should be formatted to be included in `configuration.yaml` unless explicitly stated.
* Use capital letters and `_` to indicate that the value needs to be replaced. E.g., `api_key: YOUR_API_KEY` or `api_key: REPLACE_ME`.
* If you know that the API key or value contains [control characters](https://en.wikipedia.org/wiki/YAML#Syntax), e.g., `#`, `[`, `?`, etc., wrap it in quotes and add a note.
* Integration and platform names should be a link to their respective documentation pages.
- The **Configuration Variables** section must use the `{% configuration %}` tag.
- The **Configuration Variables** section is only used for YAML configuration.
- Configuration variables must document the requirement status (`false` or `true`).
- Configuration variables must document the default value, if any.
- Configuration variables must document the accepted value types (see [Configuration variables details](documenting/create-page.md#configuration)).
- For configuration variables that accept multiple types, separate the types with a comma (i.e. `string, int`).
- Use YAML sequence syntax in the sample code if it is supported.
- All examples should be formatted to be included in `configuration.yaml` unless explicitly stated.
- Use capital letters and `_` to indicate that the value needs to be replaced. E.g., `api_key: YOUR_API_KEY` or `api_key: REPLACE_ME`.
- If you know that the API key or value contains [control characters](https://en.wikipedia.org/wiki/YAML#Syntax), e.g., `#`, `[`, `?`, etc., wrap it in quotes and add a note.
- Integration and platform names should be a link to their respective documentation pages.
Example configuration block
@ -41,28 +41,28 @@ some_key:
## Templates
* All examples containing Jinja2 templates should be wrapped **outside** of the code markdown with the `{% raw %}` tag.
* Do not use `states.switch.source.state` in templates. Instead use `states()` and `is_state()`.
* Use double quotes (`"`) for ([more information](#single-vs-double-quotation-marks)):
* `friendly_name`
* Single-line templates:
* `value_template`
* `level_template`
* `icon_template`
* Children of `data_template`
* Use single quotes (`'`) for ([more information](#single-vs-double-quotation-marks):
* Strings inside of templates:
* States
* Entity IDs
* `unit_of_measurement`
* No whitespace around pipe character (`|`) for Jinja2 filters.
* Single whitespace after Jinja2 opening delimiters ({% raw %}`{{`{% endraw %}).
* Single whitespace before Jinja2 closing delimiters ({% raw %}`}}`{% endraw %}).
* Do not quote values for:
* `device_class`
* `platform`
* `condition`
* `service`
- All examples containing Jinja2 templates should be wrapped **outside** of the code markdown with the `{% raw %}` tag.
- Do not use `states.switch.source.state` in templates. Instead use `states()` and `is_state()`.
- Use double quotes (`"`) for ([more information](#single-vs-double-quotation-marks)):
- `friendly_name`
- Single-line templates:
- `value_template`
- `level_template`
- `icon_template`
- Children of `data_template`
- Use single quotes (`'`) for ([more information](#single-vs-double-quotation-marks):
- Strings inside of templates:
- States
- Entity IDs
- `unit_of_measurement`
- No whitespace around pipe character (`|`) for Jinja2 filters.
- Single whitespace after Jinja2 opening delimiters ({% raw %}`{{`{% endraw %}).
- Single whitespace before Jinja2 closing delimiters ({% raw %}`}}`{% endraw %}).
- Do not quote values for:
- `device_class`
- `platform`
- `condition`
- `service`
## Renaming Pages

View File

@ -17,11 +17,10 @@ Properties should always only return information from memory and not do I/O (lik
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| state | string | **Required** | One of the states listed in the **states** section.
| state | string | **Required** | One of the states listed in the **states** section.
| code_format | string | `None` | One of the states listed in the **code formats** section.
| changed_by | string | `None` | Last change triggered by.
### States
| Value | Description
@ -36,7 +35,6 @@ Properties should always only return information from memory and not do I/O (lik
| `disarming` | The alarm is disarming.
| `triggered` | The alarm is triggered.
### Code Formats
| Value | Description
@ -45,10 +43,10 @@ Properties should always only return information from memory and not do I/O (lik
| Number | Code is a number (Shows ten-key pad on frontend).
| Any | Code is a string.
## Methods
### Alarm Disarm
Send disarm command.
```python
@ -63,6 +61,7 @@ class MyAlarm(AlarmControlPanelEntity):
```
### Alarm Arm Home
Send arm home command.
```python
@ -77,6 +76,7 @@ class MyAlarm(AlarmControlPanelEntity):
```
### Alarm Arm Away
Send arm away command.
```python
@ -91,6 +91,7 @@ class MyAlarm(AlarmControlPanelEntity):
```
### Alarm Arm Night
Send arm night command.
```python
@ -105,6 +106,7 @@ class MyAlarm(AlarmControlPanelEntity):
```
### Alarm Trigger
Send alarm trigger command.
```python
@ -119,6 +121,7 @@ class MyAlarm(AlarmControlPanelEntity):
```
### Alarm Custom Bypass
Send arm custom bypass command.
```python

View File

@ -29,6 +29,7 @@ Properties should always only return information from memory and not do I/O (lik
| supported_features | int (bitwise) | Value determined from `current_cover_position` and `current_cover_tilt_position` | Describes the supported features. See the related table below for details.
### Device Classes
| Constant | Description
|----------|-----------------------|
| `DEVICE_CLASS_AWNING` | Control of an awning, such as an exterior retractible window, door, or patio cover.
@ -43,6 +44,7 @@ Properties should always only return information from memory and not do I/O (lik
| `DEVICE_CLASS_WINDOW` | Control of a physical window that opens and closes or may tilt.
### States
| Constant | Description
|----------|------------------------|
| `STATE_OPENING` | The cover is in the process of opening to reach a set position.
@ -50,7 +52,6 @@ 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_CLOSED` | The cover has reach the closed position.
### Supported Features
Supported features constants are combined using the bitwise or (`|`) operator.

View File

@ -20,7 +20,6 @@ Properties should always only return information from memory and not do I/O (lik
| speed_list | list | None| Get the list of available speeds. The allowed values are "off", "low", "medium" and "high". Use the corresponding constants SPEED_OFF, SPEED_LOW, SPEED_MEDIUM, SPEED_HIGH. |
| supported_features | int | 0 | Flag supported features |
## Supported Features
| Constant | Description |
@ -29,8 +28,6 @@ Properties should always only return information from memory and not do I/O (lik
| 'SUPPORT_SET_SPEED' | The fan supports setting the speed.
| 'SUPPORT_OSCILLATE' | The fan supports oscillation.
## Methods
### Set direction

View File

@ -21,8 +21,8 @@ A light entity controls the brightness, hue and saturation color value, white va
| supported_features | int | int | Flag supported features.
| white_value | int | None | Return the white value of this light between 0..255.
## Support Feature
## Support Feature
| Constant | Description
|----------|-----------------------
| `SUPPORT_BRIGHTNESS` | Controls the brightness of a light source
@ -35,7 +35,7 @@ A light entity controls the brightness, hue and saturation color value, white va
## Methods
# Turn on Light Device
### Turn on Light Device
```python
class MyLightEntity(LightEntity):
@ -46,7 +46,7 @@ class MyLightEntity(LightEntity):
"""Turn device on."""
```
# Turn Off Light Device
### Turn Off Light Device
```python
class MyLightEntity(LightEntity):

View File

@ -25,7 +25,8 @@ Properties should always only return information from memory and not do I/O (lik
| media_image_remotely_accessible | boolean | False | Return `True` if property `media_image_url` is accessible outside of the home network.
| device_class | string | `None` | Type of media player.
# Supported Features
## Supported Features
| Constant | Description
| -------- | -----------
| `SUPPORT_CLEAR_PLAYLIST` | Entity allows clearing the active playlist.
@ -46,31 +47,39 @@ Properties should always only return information from memory and not do I/O (lik
| `SUPPORT_VOLUME_STEP` | Entity volume can be adjusted up and down.
## Methods
### Select sound mode
Optional. Switch the sound mode of the media player.
class MyMediaPlayer(MediaPlayerEntity):
# Implement one of these methods.
```python
class MyMediaPlayer(MediaPlayerEntity):
# Implement one of these methods.
def select_sound_mode(self, sound_mode):
"""Switch the sound mode of the entity."""
def select_sound_mode(self, sound_mode):
"""Switch the sound mode of the entity."""
def async_select_sound_mode(self, sound_mode):
"""Switch the sound mode of the entity."""
def async_select_sound_mode(self, sound_mode):
"""Switch the sound mode of the entity."""
```
### Select source
Optional. Switch the selected input source for the media player.
class MyMediaPlayer(MediaPlayerEntity):
# Implement one of these methods.
```python
class MyMediaPlayer(MediaPlayerEntity):
# Implement one of these methods.
def select_source(self, source):
"""Select input source."""
def select_source(self, source):
"""Select input source."""
def async_select_source(self, source):
"""Select input source."""
def async_select_source(self, source):
"""Select input source."""
```
### Mediatype
Required. Returns one of the defined constants from the below list that matches the mediatype
| CONST |
@ -87,18 +96,21 @@ Required. Returns one of the defined constants from the below list that matches
|MEDIA_TYPE_GAME|
|MEDIA_TYPE_APP|
class MyMediaPlayer(MediaPlayerEntity):
# Implement the following method.
```python
class MyMediaPlayer(MediaPlayerEntity):
# Implement the following method.
@property
def media_content_type(self):
"""Content type of current playing media."""
```
@property
def media_content_type(self):
"""Content type of current playing media."""
:::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.
:::
### Available device classes
Optional. What type of media device is this. It will possibly map to google device types.
| Value | Description

View File

@ -15,8 +15,8 @@ An entity is looked up in the registry based on a combination of the plaform typ
Good sources for a unique ID:
- Serial number of a device
- MAC address of a device
- latitude/longitude
- Serial number of a device
- MAC address of a device
- latitude/longitude
If a device has a single serial but provides multiple entities, combine the serial with unique identifiers for the entities. For example, if a device measures both temperature and humidity, you can uniquely identify the entities using `{serial}-{sensor_type}`.

View File

@ -68,7 +68,9 @@ class MySwitch(SwitchEntity):
```
### Available device classes
Optional. What type of device this. It will possibly map to google device types.
| Value | Description
| ----- | -----------
| outlet | Device is an outlet for power.

View File

@ -19,8 +19,8 @@ Properties should always only return information from memory and not do I/O (lik
| cleaning_mode_list | list | `NotImplementedError()`| List of available fan speeds and cleaning modes.
| error | string | **Required** with `STATE_ERROR` | An error message if the vacuum is in `STATE_ERROR`.
## States
| State | Description
| ----- | -----------
| `STATE_CLEANING` | The vacuum is currently cleaning.
@ -33,25 +33,33 @@ Properties should always only return information from memory and not do I/O (lik
## Methods
### `turn_on` or `async_turn_on`
Turn the vacuum on and start cleaning.
### `turn_off`or `async_turn_off`
### `turn_off` or `async_turn_off`
Turn the vacuum off stopping the cleaning and returning home.
### `return_to_base` or `async_return_to_base`
Set the vacuum cleaner to return to the dock.
### `stop` or `async_stop`
Stop the vacuum cleaner, do not return to base.
### `clean_spot` or `async_clean_spot`
Perform a spot clean-up.
### `locate` or `async_locate`
Locate the vacuum cleaner.
### `set_cleaning_mode` or `async_set_cleaning_mode`
Set the cleaning mode.
### `send_command` or `async_send_command`
Send a command to a vacuum cleaner.

View File

@ -23,6 +23,7 @@ The allowed operation modes are specified in the base component and implementati
Properties have to follow the units defined in the `unit_system`.
## States
| State | Description
| ----- | -----------
| `STATE_ECO` | Energy efficient mode, provides energy savings and fast heating.
@ -34,14 +35,19 @@ Properties have to follow the units defined in the `unit_system`.
| `STATE_OFF` | The water heater is off.
## Methods
### `set_temperature` or `async_set_temperature`
Sets the temperature the water heater should heat water to.
### `set_operation_mode`or `async_set_operation_mode`
Sets the operation mode of the water heater. Must be in the operation_list.
### `turn_away_mode_on` or `async_turn_away_mode_on`
Set the water heater to away mode.
### `turn_away_mode_off` or `async_turn_away_mode_off`
Set the water heater back to the previous operation mode. Turn off away mode.

View File

@ -39,7 +39,7 @@ The more info dialog can be triggered from any component in the app by firing a
## Data Flow
The frontend leverages the [Websocket API](external_api_websocket.md) and the [Rest API](external_api_rest.md) to interact with Home Assistant.
The frontend leverages the [Websocket API](api/websocket.md) and the [Rest API](api/rest.md) to interact with Home Assistant.
The data is made available as the `hass` property which is passed down to every component. The `hass` property contains the whole application state and has methods to call APIs.
@ -57,6 +57,4 @@ For the routing, we use the [`<app-route>`](https://www.polymer-project.org/blog
We use Webpack to bundle up the application. We have various gulp scripts to help with generating the icon set and the index.html.
We're aggresively code splitting our application by leveraging the dynamic import syntax (`import('path/to/some/file.js')`). When encountering an `import()`, Webpack will split the code into different chunks and makes sure that they are loaded when needed.
We're aggressively code splitting our application by leveraging the dynamic import syntax (`import('path/to/some/file.js')`). When encountering an `import()`, Webpack will split the code into different chunks and makes sure that they are loaded when needed.

View File

@ -26,7 +26,7 @@ The Home Assistant user interface is currently served to browsers in modern Java
If you do need to run with ES5 support, you will need to load the ES5 custom elements adapter before defining your element:
```js
```javascript
window.loadES5Adapter().then(function() {
customElements.define('my-panel', MyCustomPanel)
});

View File

@ -91,6 +91,7 @@ In our example card we defined a card with the tag `content-card-example` (see l
Add a resource to your Lovelace config with URL `/local/content-card-example.js` and type `module`.
You can then use your card in your Lovelace configuration:
```yaml
# Example Lovelace configuration
views:
@ -281,7 +282,6 @@ window.customCards.push({
});
```
## Recommended Design Elements
We are currently migrating from using Paper Elements to MWC (Material Web Component) Elements.

View File

@ -16,9 +16,9 @@ Do not use development mode in production. Home Assistant uses aggressive cachin
The first step is to fork the [frontend repository][hass-frontend] and add the upstream remote. You can place the forked repository anywhere on your system.
```shell
$ git clone git@github.com:YOUR_GIT_USERNAME/frontend.git
$ cd frontend
$ git remote add upstream https://github.com/home-assistant/home-assistant/frontend.git
git clone git@github.com:YOUR_GIT_USERNAME/frontend.git
cd frontend
git remote add upstream https://github.com/home-assistant/home-assistant/frontend.git
```
### Configuring Home Assistant
@ -38,7 +38,7 @@ frontend:
Node.js is required to build the frontend. The preferred method of installing node.js is with [nvm](https://github.com/creationix/nvm). Install nvm using the instructions in the [README](https://github.com/creationix/nvm#install-script), and install the correct node.js by running the following command:
```shell
$ nvm install
nvm install
```
[Yarn](https://yarnpkg.com/en/) is used as the package manager for node modules. [Install yarn using the instructions here.](https://yarnpkg.com/en/docs/install)
@ -46,8 +46,8 @@ $ nvm install
Next, development dependencies need to be installed to bootstrap the frontend development environment. First activate the right Node version and then download all the dependencies:
```shell
$ nvm use
$ script/bootstrap
nvm use
script/bootstrap
```
## Development
@ -55,8 +55,8 @@ $ script/bootstrap
During development, you will need to run the development script to maintain a development build of the frontend that auto updates when you change any of the source files. To run this server, run:
```shell
$ nvm use
$ script/develop
nvm use
script/develop
```
Make sure you have cache disabled and correct settings to avoid stale content:
@ -68,13 +68,13 @@ Instructions are for Google Chrome
1. Disable cache by ticking the box in `Network` > `Disable cache`
<p class='img'>
<img src='/img/en/development/disable-cache.png' />
<img src='/img/en/development/disable-cache.png' />
</p>
2. Enable Bypass for network in `Application` > `Service Workers` > `Bypass for network`
<p class='img'>
<img src='/img/en/development/bypass-for-network.png' />
<img src='/img/en/development/bypass-for-network.png' />
</p>
## Creating pull requests
@ -82,15 +82,15 @@ Instructions are for Google Chrome
If you're planning on issuing a PR back to the Home Assistant codebase you need to fork the frontend project and add your fork as a remote to the Home Assistant frontend repo.
```shell
$ git remote add fork <github URL to your fork>
git remote add fork <github URL to your fork>
```
When you've made your changes and are ready to push them change to the working directory for the frontend project and then push your changes
``` bash
$ git add -A
$ git commit -m "Added new feature X"
$ git push -u fork HEAD
git add -A
git commit -m "Added new feature X"
git push -u fork HEAD
```
## Building the frontend
@ -100,8 +100,8 @@ If you're making changes to the way the frontend is packaged, it might be necess
To test it out inside Home Assistant, run the following command from the main Home Assistant repository:
```shell
$ pip3 install -e /path/to/hass/frontend/
$ hass --skip-pip
pip3 install -e /path/to/hass/frontend/
hass --skip-pip
```
[hass-frontend]: https://github.com/home-assistant/frontend

View File

@ -2,7 +2,7 @@
title: "External Bus"
---
The frontend is able to set up a message bus with an external app that is embedding the Home Assistant frontend. This system is a generalization of the [external auth](frontend_external_auth.md), making it easier to add more commands in the future without extensive plumbing on either the app or frontend side.
The frontend is able to set up a message bus with an external app that is embedding the Home Assistant frontend. This system is a generalization of the [external authentication](frontend/external-authentication.md), making it easier to add more commands in the future without extensive plumbing on either the app or frontend side.
## Message exchange

View File

@ -3,16 +3,17 @@ title: "Debugging Home Assistant"
---
:::info
This section is not for end users. End users should use the [SSH add-on] to SSH into Home Assistant. This is for <b>developers</b> of Home Assistant. Do not ask for support if you are using these options.
This section is not for end users. End users should use the [SSH add-on] to SSH into Home Assistant. This is for **developers** of Home Assistant. Do not ask for support if you are using these options.
:::
[SSH add-on]: https://www.home-assistant.io/addons/ssh/
[SSH add-on]: https://github.com/home-assistant/hassio-addons/tree/master/ssh
The following debug tips and tricks are for developers who are running the Home Assistant image and are working on the base image. If you use the generic Linux installer script, you should be able to access your host and logs as per your host.
## Debug Supervisor
Visual Studio Code config:
```json
{
"version": "0.2.0",
@ -37,11 +38,13 @@ Visual Studio Code config:
You need set the dev mode on supervisor and enable debug with options. You need also install the Remote debug Add-on from Developer Repository to expose the debug port to Host.
## SSH access to the host
:::info
SSH access through the [SSH add-on] (which will give you SSH access through port 22) will not provide you with all the necessary privileges, and you will be asked for a username and password when typing the 'login' command. You need to follow the steps below, which will setup a separate SSH access through port 22222 with all necessary privileges.
:::
### Home Assistant OS
### Home Assistant Operating System
Use a USB drive formatted with FAT, ext4, or NTFS and name it CONFIG (case sensitive). Create an `authorized_keys` file (no extension) containing your public key, and place it in the root of the USB drive. File needs to be ANSI encoded (not UTF-8) and must have Unix line ends (LF), not Windows (CR LF). See [Generating SSH Keys](#generating-ssh-keys) section below if you need help generating keys. From the UI, navigate to the Supervisor system page and choose "Import from USB". You can now access your device as root over SSH on port 22222. Alternatively, the file will be imported from the USB when the Home Assistant OS device is rebooted.
:::tip

View File

@ -11,15 +11,16 @@ For this guide, we're going to assume that you have an Hass.io instance up and r
To develop for the frontend, we're going to need API access to the supervisor.
- Add our developer Add-on repository: https://github.com/home-assistant/hassio-addons-development
- Add our developer Add-on repository: <https://github.com/home-assistant/hassio-addons-development>
- Install the Add-on "Remote API proxy"
For some API commands you need explicit the Home Assistant API token, but 99% of the functionality work with `Remote API proxy`. This token change sometimes but you can read the current legal token on host system with:
```shell
$ docker inspect homeassistant | grep HASSIO_TOKEN
docker inspect homeassistant | grep HASSIO_TOKEN
```
## Having Home Assistant connect to remote Hass.io
## Having Home Assistant connect to remote Hass.io
The connection with the supervisor is hidden inside the host and is only accessible from applications running on the host. So to make it accessible for our Home Assistant instance we will need to route the connection to our computer running Home Assistant. We're going to do this by forwarding the API with "Remote API proxy" add-on.

View File

@ -4,7 +4,7 @@ title: "Fetching Data"
Your integration will need to fetch data from an API to be able to provide this to Home Assistant. This API can be available over the web (local or cloud), sockets, serial ports exposed via USB sticks, etc.
# Push vs Poll
## Push vs Poll
APIs come in many different shapes and forms but at its core they fall in two categories: push and poll.
@ -17,11 +17,11 @@ Because polling is so common, Home Assistant by default assumes that your entity
- If you are executing from within an async function and don't need your entity update method called, call `Entity.async_write_ha_state()`. This is an async callback that will write the state to the state machine within yielding to the event loop.
- `Entity.schedule_update_ha_state(force_refresh=False)`/`Entity.async_schedule_update_ha_state(force_refresh=False)` will schedule an update of the entity. If `force_refresh` is set to `True`, Home Assistant will call your entities update method (`update()`/`async_update()`) prior to writing the state.
# Polling API endpoints
## Polling API endpoints
We're going to explain a few different API types here and the best way to integrate them in Home Assistant. Note that some integrations will encounter a combination of the ones below.
## Coordinated, single API poll for data for all entities
### Coordinated, single API poll for data for all entities
This API will have a single method to fetch data for all the entities that you have in Home Assistant. In this case we will want to have a single periodical poll on this endpoint, and then let entities know as soon as new data is available for them.
@ -125,7 +125,7 @@ class MyEntity(entity.Entity):
await self.coordinator.async_request_refresh()
```
## Separate polling for each individual entity
### Separate polling for each individual entity
Some APIs will offer an endpoint per device. It sometimes won't be possible to map a device from your API to a single entity. If you create multiple entities from a single API device endpoint, please see the previous section.
@ -141,7 +141,7 @@ from datetime import timedelta
SCAN_INTERVAL = timedelta(seconds=5)
```
# Request Parallelism
## Request Parallelism
:::info
This is an advanced topic.

View File

@ -8,14 +8,14 @@ The Integration Quality Scale scores each integration based on the code quality
Suggestions for changes can be done by creating an issue in the [architecture repo](https://github.com/home-assistant/architecture/issues/).
:::
# No score
## No score
This integration passes the bare minimum requirements to become part of the index.
- Satisfy all requirements for [creating components](creating_component_code_review.md) and [creating platforms](creating_platform_code_review.md).
- Configurable via `configuration.yaml`
# Silver 🥈
## Silver 🥈
This integration is able to cope when things go wrong. It will not print any exceptions nor will it fill the log with retry attempts.
@ -28,7 +28,7 @@ This integration is able to cope when things go wrong. It will not print any exc
- Set `available` property to `False` if appropriate ([docs](entity_index.md#generic-properties))
- Entities have unique ID (if available) ([docs](entity_registry_index.md#unique-id-requirements))
# Gold 🥇
## Gold 🥇
This is a solid integration that is able to survive poor conditions and can be configured via the user interface.
@ -45,7 +45,7 @@ This is a solid integration that is able to survive poor conditions and can be c
- Supports entities being disabled and leverages `Entity.entity_registry_enabled_default` to disable less popular entities ([docs](entity_index.md#advanced-properties))
- If the device/service API can remove entities, the integration should make sure to clean up the entity and device registry.
# Platinum 🏆
## Platinum 🏆
Best of the best. The integration is completely async, meaning it's super fast. Integrations that reach platinum level will require approval by the code owner for each PR.
@ -54,6 +54,6 @@ Best of the best. The integration is completely async, meaning it's super fast.
- Integration + dependency are async
- Uses aiohttp and allows passing in websession (if making HTTP requests)
# Internal 🏠
## Internal 🏠
Integrations which are part of Home Assistant are not rated but marked as **internal**.

View File

@ -12,7 +12,6 @@ An intent is a description of a user's intention. Intents are generated by user
/>
</a>
Intents are fired by components that receive them from external sources/services. Conversation, Alexa, API.ai and Snips are currently sourcing intents.
Any component can handle intents. This makes it very easy for developers to integrate with all voice assistants at once.

View File

@ -99,7 +99,7 @@ To differentiate entities and their translations, provide different device class
In order to test changes to translation files, the translation strings must be compiled into Home Assistants translation directories by running the following script:
```shell
$ python3 -m script.translations develop
python3 -m script.translations develop
```
### Introducing new strings

View File

@ -6,7 +6,7 @@ title: "Custom Component Localization"
Unlike localized strings merged in the `home-assistant` repository, custom components cannot take advantage of Lokalise for user-submitted translations. However, custom component authors can still include translations with their components. These will be read from the `translations` directory, adjacent to the component source. They are named `<platform name>.<language_code>.json`, e.g., for the German translation of a sensor `sensor.de.json`, unless the translation is for the custom component only, in which case the file is named `<language_code>.json` in the `translations` directory.
These files follow the same formatting as [backend translation string files](internationalization_backend_localization.md), but a copy will exist for each translated language.
These files follow the same formatting as [backend translation string files](internationalization/core.md), but a copy will exist for each translated language.
The language codes follow the [BCP47](https://tools.ietf.org/html/bcp47) format. The [frontend translation files](https://github.com/home-assistant/home-assistant-polymer/tree/master/translations) can also be referred to if you are unsure of the correct language code to use.

View File

@ -20,6 +20,7 @@ The translation of the Home Assistant frontend is still a work in progress. More
Some translation strings will contain special placeholders that will be replaced later. Placeholders shown in square brackets `[]` are [Lokalise key references](https://docs.lokalise.com/en/articles/1400528-key-referencing). These are primarily used to link translation strings that will be duplicated. Different languages may not have the same duplicates as English, and are welcome to link duplicate translations that are not linked in English. Placeholders shown in curly brackets `{}` are [translation arguments](https://formatjs.io/guides/message-syntax/) that will be replaced with a live value when Home Assistant is running. Any translation argument placeholders present in the original string must be included in the translated string. These may include special syntax for defining plurals or other replacement rules. The linked format.js guide explains the syntax for adding plural definitions and other rules.
## Rules
1. Only native speakers should submit translations.
2. Stick to [Material Design guidelines](https://material.io/guidelines/style/writing.html).
3. Don't translate or change proper nouns like `Home Assistant`, `Hass.io` or `Hue`.
@ -28,8 +29,10 @@ Some translation strings will contain special placeholders that will be replaced
6. If text will be duplicated across different translation keys, make use of the Lokalise key reference feature where possible. The base translation provides examples of this underneath the `states` translations. Please see the [Lokalise key referencing](https://docs.lokalise.com/en/articles/1400528-key-referencing) documentation for more details.
## Adding a new language
If your language is not listed you can request it at [GitHub](https://github.com/home-assistant/home-assistant-polymer/issues/new). Please provide both the English name and the native name for your language. For example:
```
```txt
English Name: German
Native Name: Deutsch
```
@ -39,6 +42,7 @@ Region specific translations (`en-US`, `fr-CA`) will only be included if transla
:::
### Maintainer steps to add a new language
1. Language tags have to follow [BCP 47](https://tools.ietf.org/html/bcp47). A list of most language tags can be found here: [IANA sutbtag registry](http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry). Examples: `fr`, `fr-CA`, `zh-Hans`. Only include the country code if country specific overrides are being included, and the base language is already translated.
2. Add the language tag and native name in `src/translations/translationMetadata.json`. Examples: "Français", "Français (CA)"
3. Add the new language in Lokalize.

View File

@ -20,7 +20,7 @@ const features = [
</p>
<p>
<b>
<a href="docs/frontend_index">Frontend</a>.
<a href="docs/frontend">Frontend</a>.
</b>{" "}
Explains how to develop the user interface of Home Assistant.
</p>
@ -50,17 +50,13 @@ const features = [
<a href="docs/development_index">Add a new integration</a>
</li>
<li>
<a href="docs/internationalization_index">
Translate Home Assistant
</a>
<a href="docs/internationalization">Translate Home Assistant</a>
</li>
<li>
<a href="docs/frontend_index">Improve the frontend</a>
<a href="docs/frontend">Improve the frontend</a>
</li>
<li>
<a href="docs/external_api_rest">
Extract data from the Home Assistant API
</a>
<a href="docs/api/rest">Extract data from the Home Assistant API</a>
</li>
</ul>
<h3>Source Code</h3>