This commit is contained in:
Paulus Schoutsen 2019-09-23 13:29:45 -07:00
parent 2d1286ecb8
commit fd3f6a4d0c
8 changed files with 746 additions and 0 deletions

View File

@ -1612,6 +1612,26 @@
},
"version-0.98.0/version-0.98.0-hassio_addon_tutorial": {
"title": "Tutorial: Making your first add-on"
},
"version-0.99.0/version-0.99.0-creating_component_index": {
"title": "Creating your first integration"
},
"version-0.99.0/version-0.99.0-dev_101_states": {
"title": "Using States"
},
"version-0.99.0/version-0.99.0-development_checklist": {
"title": "Development Checklist",
"sidebar_label": "Introduction"
},
"version-0.99.0/version-0.99.0-entity_weather": {
"title": "Weather Entity",
"sidebar_label": "Weather"
},
"version-0.99.0/version-0.99.0-hassio_addon_config": {
"title": "Add-On Configuration"
},
"version-0.99.0/version-0.99.0-lovelace_custom_card": {
"title": "Lovelace: Custom Cards"
}
},
"links": {

View File

@ -0,0 +1,45 @@
---
title: Creating your first integration
id: version-0.99.0-creating_component_index
original_id: creating_component_index
---
Alright, you learned about the [manifest](creating_integration_manifest.md), so it's time to write your first code for your integration. AWESOME. Don't worry, we've tried hard to keep it as easy as possible. From a Home Assistant development environment, type the following and follow the instructions:
```python
python3 -m script.scaffold
```
This will set you up with everything that you need to build an integration that is able to be set up via the user interface. More extensive examples of integrations are available from [our example repository](https://github.com/home-assistant/example-custom-config/tree/master/custom_components/).
## The minimum
The scaffold integration contains a bit more than just the bare minimum. The minimum is that you define a `DOMAIN` constant that contains the domain of the integration. The second part is that it needs to define a setup method that returns a boolean if the set up was successful.
```python
DOMAIN = 'hello_state'
def setup(hass, config):
hass.states.set('hello_state.world', 'Paulus')
# Return boolean to indicate that initialization was successful.
return True
```
And if you prefer an async component:
```python
DOMAIN = 'hello_state'
async def async_setup(hass, config):
hass.states.async_set('hello_state.world', 'Paulus')
# Return boolean to indicate that initialization was successful.
return True
```
To load this, add `hello_state:` to your `configuration.yaml` file and create a file `<config_dir>/custom_components/hello_state/__init__.py` with one of the two codeblocks above to test it locally.
## What the scaffold offers
When using the scaffold script, it will go past the bare minimum of an integration. It will include a config flow, tests for the config flow and basic translation infrastructure to provide internationalization for your config flow.

View File

@ -0,0 +1,130 @@
---
title: Using States
id: version-0.99.0-dev_101_states
original_id: dev_101_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.
[Description of the state object.](https://www.home-assistant.io/docs/configuration/state_object/)
## Using states in your component
This is a simple tutorial/example on how to create and set states. We will do our work in a component called "hello_state". The purpose of this component is to display a given text in the frontend.
To get started, create the file `<config dir>/custom_components/hello_state.py` and copy the below example code.
```python
"""
Support for showing text in the frontend.
For more details about this component, please refer to the documentation at
https://developers.home-assistant.io/docs/en/dev_101_states.html
"""
import logging
_LOGGER = logging.getLogger(__name__)
DOMAIN = 'hello_state'
def setup(hass, config):
"""Setup the Hello State component. """
_LOGGER.info("The 'hello state' component is ready!")
return True
```
1. In the file header we decided to add some details: A short description and the link to the documentation.
2. We want to do some logging. This means that we import the Python logging module and create an alias.
3. The component name is equal to the domain name.
4. The `setup` function will take care of the initialization of our component.
The component will only write a log message. Keep in mind for later that you have several options for the severity:
- `_LOGGER.info(msg)`
- `_LOGGER.warning(msg)`
- `_LOGGER.error(msg)`
- `_LOGGER.critical(msg)`
- `_LOGGER.exception(msg)`
5. We return `True` if everything is ok.
Add the component to your `configuration.yaml` file.
```yaml
hello_state:
```
After a start or a restart of Home Assistant the component will create an entry in the log.
```bash
16-03-12 14:16:42 INFO (MainThread) [custom_components.hello_state] The 'hello state' component is ready!
```
The next step is the introduction of configuration options. A user can pass configuration options to our component via `configuration.yaml`. To use them we'll use the passed in `config` variable to our `setup` method.
```python
import logging
_LOGGER = logging.getLogger(__name__)
DOMAIN = 'hello_state'
CONF_TEXT = 'text'
DEFAULT_TEXT = 'No text!'
def setup(hass, config):
"""Set up the Hello State component. """
# Get the text from the configuration. Use DEFAULT_TEXT if no name is provided.
text = config[DOMAIN].get(CONF_TEXT, DEFAULT_TEXT)
# States are in the format DOMAIN.OBJECT_ID
hass.states.set('hello_state.Hello_State', text)
return True
```
To use the latest feature of our component, update the entry in your `configuration.yaml` file.
```yaml
hello_state:
text: 'Hello, World!'
```
Thanks to `DEFAULT_TEXT` variable the component will launch even if no `text:` field is used in the `configuration.yaml` file. Quite often there are variables which are required. It's important to check if all mandatory configuration variables are provided. If not, the setup should fail. We will use `voluptuous` as a helper to achieve this. The next listing shows the essential parts.
```python
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
CONFIG_SCHEMA = vol.Schema({
DOMAIN: vol.Schema({
vol.Required(CONF_TEXT): cv.string,
})
}, extra=vol.ALLOW_EXTRA)
```
Now, when `text:` is missing from the config, Home Assistant will alert the user and not setup your component.
After a start or a restart of Home Assistant the component will be visible in the frontend if the `configuration.yaml` file is up-to-date.
<p class='img'>
<img src='/img/en/development/create-component01.png' />
</p>
In order to expose attributes for a platform, you will need to define a property called `device_state_attributes` on the entity class, which will return a dictionary of attributes:
```
@property
def device_state_attributes(self):
"""Return device specific state attributes."""
return self._attributes
```
> Entities also have a similar property `state_attributes`, which normally doesn't need to be defined by new platforms. This property is used by base components to add standard sets of attributes to a state. Example: The light component uses `state_attributes` to add brightness to the state dictionary. If you are designing a new component, you should define `state_attributes` instead.
To get your component included in the Home Assistant releases, follow the steps described in the [Submit your work](development_submitting.md) section. Basically you only need to move your component in the `homeassistant/component/` directory of your fork and create a Pull Request.

View File

@ -0,0 +1,17 @@
---
title: Development Checklist
sidebar_label: Introduction
id: version-0.99.0-development_checklist
original_id: development_checklist
---
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).
- New dependencies are added to `requirements_all.txt` (if applicable), using `python3 -m script.gen_requirements_all`
- New codeowners are added to `CODEOWNERS` (if applicable), using `python3 -m script.hassfest`
- 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).

View File

@ -0,0 +1,59 @@
---
title: Weather Entity
sidebar_label: Weather
id: version-0.99.0-entity_weather
original_id: entity_weather
---
## Properties
> Properties should always only return information from memory and not do I/O (like network requests). Implement `update()` or `async_update()` to fetch data.
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| state | string | **Required** | The current weather condition.
| temperature | float | **Required** | The current temperature in °C or °F.
| pressure | float | `None` | The current air pressure in hPa or inHg.
| humidity | float | `None` | The current humidity in %.
| visibility | float | `None` | The current visibility in km or mi.
| wind_speed | float | `None` | The current wind speed in km/h or mi/h.
| wind_bearing | string | `None` | The current wind bearing, 1-3 letters.
| forecast | array | `None` | Daily or Hourly forecast data.
| attribution | string | `None` | The branding text required by the API provider.
Properties have to follow the units defined in the `unit_system`.
### Forecast
Forecast data should either be daily or hourly.
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| datetime | string | **Required** | UTC Date time in RFC 3339 format.
| temperature | float | **Required** | The higher temperature in °C or °F
| condition | string | `None` | The weather condition at this point.
| templow | float | `None` | The lower daily Temperature in °C or °F
### Recommended values for state and condition
These weather conditions are included in our translation files and also show the corresponding icon.
| Condition | Description
| --------- | -----------
| clear-night | Clear night
| cloudy | Many clouds
| exceptional | Exceptional
| fog | Fog
| hail | Hail
| lightning | Lightning/ thunderstorms
| lightning-rainy | Lightning/ thunderstorms and rain
| partlycloudy | A few clouds
| pouring | Pouring rain
| rainy | Rain
| snowy | Snow
| snowy-rainy | Snow and Rain
| sunny | Sunshine
| windy | Wind
| windy-variant | Wind and clouds
This means that the `weather` platforms don't need to support languages.

View File

@ -0,0 +1,231 @@
---
title: Add-On Configuration
id: version-0.99.0-hassio_addon_config
original_id: hassio_addon_config
---
Each add-on is stored in a folder. The file structure looks like this:
```text
addon_name/
apparmor.txt
build.json
CHANGELOG.md
config.json
Dockerfile
icon.png
logo.png
README.md
run.sh
```
## Add-on script
As with every Docker container, you will need a script to run when the container is started. A user might run many add-ons, so it is encouraged to try to stick to Bash scripts if you're doing simple things.
All our Images have also [bashio][bashio] installed. It contains a set of commonly used operations and can be used to be included in add-ons to reduce code duplication across add-ons and therefore making it easier to develop and maintain add-ons.
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.
```bash
CONFIG_PATH=/data/options.json
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
## Add-on Docker file
All add-ons are based on latest Alpine Linux. Hass.io will automatically substitute the right base image based on the machine architecture. Add `tzdata` if you need run in a different timezone. `tzdata` Is is already added to our base images.
```
ARG BUILD_FROM
FROM $BUILD_FROM
ENV LANG C.UTF-8
# Install requirements for add-on
RUN apk add --no-cache jq
# Copy data for add-on
COPY run.sh /
RUN chmod a+x /run.sh
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:
```
LABEL io.hass.version="VERSION" io.hass.type="addon" io.hass.arch="armhf|aarch64|i386|amd64"
```
It is possible to use own base image with `build.json` or if you do not need support for automatic multi-arch building you can also use a simple docker `FROM`.
### Build Args
We support the following build arguments by default:
| ARG | Description |
|-----|-------------|
| BUILD_FROM | Hold image for dynamic builds or buildings over our systems.
| BUILD_VERSION | Add-on version (read from `config.json`).
| BUILD_ARCH | Hold current build arch inside.
## Add-on config
The config for an add-on is stored in `config.json`.
```json
{
"name": "xy",
"version": "1.2",
"slug": "folder",
"description": "long description",
"arch": ["amd64"],
"url": "website with more information about add-on (ie a forum thread for support)",
"startup": "application",
"boot": "auto",
"ports": {
"123/tcp": 123
},
"map": ["config:rw", "ssl"],
"options": {},
"schema": {},
"image": "repo/{arch}-my-custom-addon"
}
```
| Key | Type | Required | Description |
| --- | ---- | -------- | ----------- |
| name | string | yes | Name of the add-on
| version | string | yes | Version of the add-on
| slug | string | yes | Slug of the add-on
| description | string | yes | Description of the add-on
| arch | list | yes | List of supported arch: `armhf`, `armv7`, `aarch64`, `amd64`, `i386`.
| machine | list | no | Default it support any machine type. You can select that this add-on run only on specific machines.
| url | url | no | Homepage of the addon. Here you can explain the add-ons and options.
| startup | bool | yes | `initialize` will start addon on setup of Hass.io. `system` is for things like databases and not dependent on other things. `services` will start before Home Assistant, while `application` is started afterwards. Finally `once` is for applications that don't run as a daemon.
| webui | string | no | A URL for web interface of this add-on. Like `http://[HOST]:[PORT:2839]/dashboard`, the port needs the internal port, which will be replaced with the effective port. It is also possible to bind the proto part to a config options with: `[PROTO:option_name]://[HOST]:[PORT:2839]/dashboard` and he lookup if they is True and going to `https`.
| boot | string | yes | `auto` by system and manual or only `manual`
| ports | dict | no | Network ports to expose from the container. Format is `"container-port/type": host-port`. If host-port is `null`, the mapping is disabled.
| ports_description | dict | no | Network ports description mapping. Format is `"container-port/type": "description of this port"`.
| host_network | bool | no | If that is True, the add-on run on host network.
| host_ipc | bool | no | Default False. Allow to share the IPC namespace with others.
| host_dbus | bool | no | Default False. Map Host dbus service into add-on.
| host_pid | bool | no | Default False. Allow to run container on host PID namespace. Work only for not protected add-ons.
| devices | list | no | Device list to map into the add-on. Format is: `<path_on_host>:<path_in_container>:<cgroup_permissions>`. i.e. `/dev/ttyAMA0:/dev/ttyAMA0:rwm`
| udev | bool | no | Default False. Set this True, if your container run a own udev process.
| auto_uart | bool | no | Default False. Auto mapping all UART/Serial device from host into add-on.
| homeassistant | string | no | Pin a minimum required Home Assistant version for such Add-on. Value is a version string like `0.91.2`.
| hassio_role | str | no | Default `default`. Role based access to Hass.io API. Available: `default`, `homeassistant`, `backup`, `manager`, `admin`.
| hassio_api | bool | no | This add-on can access to Hass.io REST API. It set the host alias `hassio`.
| homeassistant_api | bool | no | This add-on can access to Hass.io Home-Assistant REST API proxy. Use `http://hassio/homeassistant/api`.
| docker_api | bool | no | Allow read-oly access to docker API for add-on. Work only for not protected add-ons.
| privileged | list | no | Privilege for access to hardware/system. Available access: `NET_ADMIN`, `SYS_ADMIN`, `SYS_RAWIO`, `SYS_TIME`, `SYS_NICE`, `SYS_RESOURCE`, `SYS_PTRACE`, `SYS_MODULE`, `DAC_READ_SEARCH`.
| full_access | bool | no | Give full access to hardware like the privileged mode in docker. Work only for not protected add-ons.
| apparmor | bool/string | no | Enable or disable AppArmor support. If it is enable, you can also use custom profiles with the name of the profile.
| map | list | no | List of maps for additional Hass.io folders. Possible values: `config`, `ssl`, `addons`, `backup`, `share`. Defaults to `ro`, which you can change by adding `:rw` to the end of the name.
| environment | dict | no | A dict of environment variable to run add-on.
| audio | bool | no | Boolean. Mark this add-on to use internal an audio system. The ALSA configuration for this add-on will be mount automatic.
| gpio | bool | no | Boolean. If this is set to True, `/sys/class/gpio` will map into add-on for access to GPIO interface from kernel. Some library need also `/dev/mem` and `SYS_RAWIO` for read/write access to this device. On system with AppArmor enabled, you need disable AppArmor or better for security, provide you own profile for the add-on.
| devicetree | bool | no | Boolean. If this is set to True, `/device-tree` will map into add-on.
| kernel_modules | bool | no | Map host kernel modules and config into add-on (readonly).
| stdin | bool | no | Boolean. If that is enable, you can use the STDIN with Hass.io API.
| legacy | bool | no | Boolean. If the docker image have no hass.io labels, you can enable the legacy mode to use the config data.
| options | dict | yes | Default options value of the add-on
| schema | dict | yes | Schema for options value of the add-on. It can be `False` to disable schema validation and use custom options.
| image | string | no | For use with Docker Hub and other container registries.
| timeout | integer | no | Default 10 (second). The timeout to wait until the docker is done or will be killed.
| tmpfs | string | no | Mount a tmpfs file system in `/tmpfs`. Valide format for this option is : `size=XXXu,uid=N,rw`. Size is mandatory, valid units (`u`) are `k`, `m` and `g` and `XXX` has to be replaced by a number. `uid=N` (with `N` the uid number) and `rw` are optional.
| discovery | list | no | A list of services they this Add-on allow to provide for Home Assistant. Currently supported: `mqtt`
| services | list | no | A list of services they will be provided or consumed with this Add-on. Format is `service`:`function` and functions are: `provide` (this add-on can provide this service), `want` (this add-on can use this service) or `need` (this add-on need this service to work correctly).
| auth_api | bool | no | Allow access to Home Assistent user backend.
| ingress | bool | no | Enable the ingress feature for the Add-on
| ingress_port | integer | no | Default `8099`. For Add-ons they run on host network, you can use `0` and read the port later on API.
| ingress_entry | string | no | Modify the URL entry point from `/`.
| panel_icon | string | no | Default: mdi:puzzle. MDI icon for the menu panel integration.
| panel_title | string | no | Default add-on name, but can Modify with this options.
| panel_admin | bool | no | Default True. Make menu entry only available with admin privileged.
### Options / Schema
The `options` dictionary contains all available options and their default value. Set the default value to `null` if the value is required to be given by the user before the add-on can start, and it show it inside default values. Only nested arrays and dictionaries are supported with a deep of two size. If you want make an option optional, put `?` to the end of data type, otherwise it will be a required value.
```json
{
"message": "custom things",
"logins": [
{ "username": "beer", "password": "123456" },
{ "username": "cheep", "password": "654321" }
],
"random": ["haha", "hihi", "huhu", "hghg"],
"link": "http://example.com/",
"size": 15,
"count": 1.2
}
```
The `schema` looks like `options` but describes how we should validate the user input. For example:
```json
{
"message": "str",
"logins": [
{ "username": "str", "password": "str" }
],
"random": ["match(^\w*$)"],
"link": "url",
"size": "int(5,20)",
"count": "float",
"not_need": "str?"
}
```
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
- port
- match(REGEX)
- list(val1|val2|...)
## Add-on extended build
Additional build options for an add-on is stored in `build.json`. This file will be read from our build systems.
You need this only, if you not use the default images or need additionals things.
```json
{
"build_from": {
"armhf": "mycustom/base-image:latest"
},
"squash": false,
"args": {
"my_build_arg": "xy"
}
}
```
| 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!
| args | no | Allow to set additional Docker build arguments as a dictionary.
We provide a set of [Base-Images][hassio-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.
[hassio-base]: https://github.com/home-assistant/hassio-base

View File

@ -0,0 +1,243 @@
---
title: Lovelace: Custom Cards
id: version-0.99.0-lovelace_custom_card
original_id: lovelace_custom_card
---
[Lovelace](https://www.home-assistant.io/lovelace/) is our new approach to defining your user interface for Home Assistant. We offer a lot of built-in cards, but you're not just limited to the ones that we decided to include in the Lovelace UI. You can build and use your own!
## API
You define your custom card as a [custom element](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements). It's up to you to decide how to render your DOM inside your element. You can use Polymer, Angular, Preact or any other popular framework (except for React [more info on React here](https://custom-elements-everywhere.com/#react)).
```js
const element = document.createElement('some-custom-card');
```
Home Assistant will call `setConfig(config)` when the configuration changes (rare). If you throw an exception if the configuration is invalid, Lovelace will render an error card to notify the user.
```js
try {
element.setConfig(config);
} catch (err) {
showErrorCard(err.message, config);
}
```
Home Assistant will set the `hass` property when the state of Home Assistant changes (frequent). Whenever the state changes, the component will have to update itself to represent the latest state.
```js
element.hass = hass;
```
Your card can define a `getCardSize` method that returns the size of your card as a number. A height of 1 is equivalent to 50 pixels. This will help Home Assistant distribute the cards evenly over the columns. A card size of `1` will be assumed if the method is not defined.
```js
if ('getCardSize' in element) {
return element.getCardSize();
} else {
return 1;
}
```
## Defining your card
Create a new file in your Home Assistant config dir as `<config>/www/content-card-example.js` and put in the following contents:
```js
class ContentCardExample extends HTMLElement {
set hass(hass) {
if (!this.content) {
const card = document.createElement('ha-card');
card.header = 'Example card';
this.content = document.createElement('div');
this.content.style.padding = '0 16px 16px';
card.appendChild(this.content);
this.appendChild(card);
}
const entityId = this.config.entity;
const state = hass.states[entityId];
const stateStr = state ? state.state : 'unavailable';
this.content.innerHTML = `
The state of ${entityId} is ${stateStr}!
<br><br>
<img src="http://via.placeholder.com/350x150">
`;
}
setConfig(config) {
if (!config.entity) {
throw new Error('You need to define an entity');
}
this.config = config;
}
// The height of your card. Home Assistant uses this to automatically
// distribute all cards over the available columns.
getCardSize() {
return 3;
}
}
customElements.define('content-card-example', ContentCardExample);
```
## Referencing your new card
In our example card we defined a card with the tag `content-card-example` (see last line), so our card type will be `custom:content-card-example`. And because you created the file in your `<config>/www` directory, it will be accessible in your browser via the url `/local/` (if you have recently added the www folder you will need to re-start home assistant for files to be picked up).
```yaml
# Example Lovelace configuration
resources:
- url: /local/content-card-example.js
type: js
views:
- name: Example
cards:
- type: "custom:content-card-example"
entity: input_boolean.switch_tv
```
## Advanced example
Resources to load in Lovelace can be imported as a JS script, an HTML import or as a JS module import. Below is an example of a custom card using JS modules that does all the fancy things.
![Screenshot of the wired card](/img/en/frontend/lovelace-ui-custom-card-screenshot.png)
Create a new file in your Home Assistant config dir as `<config>/www/wired-cards.js` and put in the following contents:
```js
import "https://unpkg.com/wired-card@0.8.1/wired-card.js?module";
import "https://unpkg.com/wired-toggle@0.8.0/wired-toggle.js?module";
import {
LitElement,
html,
css
} from "https://unpkg.com/lit-element@2.0.1/lit-element.js?module";
function loadCSS(url) {
const link = document.createElement("link");
link.type = "text/css";
link.rel = "stylesheet";
link.href = url;
document.head.appendChild(link);
}
loadCSS("https://fonts.googleapis.com/css?family=Gloria+Hallelujah");
class WiredToggleCard extends LitElement {
static get properties() {
return {
hass: {},
config: {}
};
}
render() {
return html`
<wired-card elevation="2">
${this.config.entities.map(ent => {
const stateObj = this.hass.states[ent];
return stateObj
? html`
<div class="state">
${stateObj.attributes.friendly_name}
<wired-toggle
.checked="${stateObj.state === "on"}"
@change="${ev => this._toggle(stateObj)}"
></wired-toggle>
</div>
`
: html`
<div class="not-found">Entity ${ent} not found.</div>
`;
})}
</wired-card>
`;
}
setConfig(config) {
if (!config.entities) {
throw new Error("You need to define entities");
}
this.config = config;
}
// The height of your card. Home Assistant uses this to automatically
// distribute all cards over the available columns.
getCardSize() {
return this.config.entities.length + 1;
}
_toggle(state) {
this.hass.callService("homeassistant", "toggle", {
entity_id: state.entity_id
});
}
static get styles() {
return css`
:host {
font-family: "Gloria Hallelujah", cursive;
}
wired-card {
background-color: white;
padding: 16px;
display: block;
font-size: 18px;
}
.state {
display: flex;
justify-content: space-between;
padding: 8px;
align-items: center;
}
.not-found {
background-color: yellow;
font-family: sans-serif;
font-size: 14px;
padding: 8px;
}
wired-toggle {
margin-left: 8px;
}
`;
}
}
customElements.define("wired-toggle-card", WiredToggleCard);
```
And for your configuration:
```yaml
# Example Lovelace configuration
resources:
- url: /local/wired-cards.js
type: module
views:
- name: Example
cards:
- type: "custom:wired-toggle-card"
entities:
- input_boolean.switch_ac_kitchen
- input_boolean.switch_ac_livingroom
- input_boolean.switch_tv
```
## Recommended Design Elements
We are currently migrating from using Paper Elements to MWC (Material Web Component) Elements.
If an element exists in the below repository for MWC. We recommended using it.
- [MWC (Material Web Components)](https://material-components.github.io/material-components-web-components/demos/index.html)
If an element does not exist in MWC, we default to using Paper Elements.
- [Paper Elements](https://www.webcomponents.org/collection/PolymerElements/paper-elements)
## Advanced Resources
Community Maintained Boiler Plate Card - Advanced Template (Typescript, Rollup, Linting, etc.)
- [Boilerplate Card](https://github.com/custom-cards/boilerplate-card)
Developer Documentation for [HACS](https://hacs.netlify.com/) (Home Assitant Community Store).
- [HACS Plugin Docs](https://hacs.netlify.com/developer/plugin/)

View File

@ -1,4 +1,5 @@
[
"0.99.0",
"0.98.0",
"0.97.0",
"0.96.0",