home assistant switch template

The template platform creates switches that combines components.

For example, if you have a garage door with a toggle switch that operates the motor and a sensor that allows you know whether the door is open or closed, you can combine these into a switch that knows whether the garage door is open or closed.

This can simplify the GUI and make it easier to write automations. You can mark the integrations you have combined as hidden so they don’t appear themselves.

Configuration

To enable Template Switches in your installation, add the following to your configuration.yaml file:

Configuration Variables

List of your switches.

Name to use in the frontend.

( string | list ) (Optional)

A list of entity IDs so the switch only reacts to state changes of these entities. This can be used if the automatic analysis fails to find all relevant entities.

Defines a template to set the state of the switch.

Defines a template to get the available state of the component. If the template returns true , the device is available . If the template returns any other value, the device will be unavailable . If availability_template is not configured, the component will always be available .

Defines an action to run when the switch is turned on.

Defines an action to run when the switch is turned off.

Defines a template for the icon of the switch.

Defines a template for the picture of the switch.

Considerations

If you are using the state of a platform that takes extra time to load, the Template Switch may get an unknown state during startup. This results in error messages in your log file until that platform has completed loading. If you use is_state() function in your template, you can avoid this situation. For example, you would replace << states.switch.source.state == 'on') >> with this equivalent that returns true / false and never gives an unknown result: << is_state('switch.source', 'on') >>

Examples

In this section you find some real-life examples of how to use this switch.

Copy Switch

This example shows a switch that copies another switch.

Toggle Switch

This example shows a switch that takes its state from a sensor and toggles a switch.

Sensor and Two Switches

This example shows a switch that takes its state from a sensor, and uses two momentary switches to control a device.

Change The Icon

This example shows how to change the icon based on the day/night cycle.

Change The Entity Picture

This example shows how to change the entity picture based on the day/night cycle.

Очередь просмотра

Очередь

  • Удалить все
  • Отключить

YouTube Premium

Хотите сохраните это видео?

  • Пожаловаться

Пожаловаться на видео?

Выполните вход, чтобы сообщить о неприемлемом контенте.

Понравилось?

Не понравилось?

Текст видео

This video is a tutorial on how to configure binary sensors and template switches in Home Assistant

Here are a couple of links for you.

Let’s start by setting up our binary sensor.

sudo vi binary_sensor.yaml

— platform: command_line name: mqtt_server command: sudo systemctl status mosquitto.service | awk ‘FNR==3 < print $3 >‘ device_class: connectivity payload_on: «(running)» payload_off: «(dead)»

You can then save that and restart home assistant if you want to see what that looks like.

sudo systemctl restart home-assistant@hass.service

Next lets add a couple of shell commands to use with our template switch.

sudo vi shell_command.yaml

start_mosquitto: ‘sudo systemctl start mosquitto.service’
stop_mosquitto: ‘sudo systemctl stop mosquitto.service’

Save that and then lets add our template switch.

sudo vi switch.yaml

— platform: template scan_interval: 5 switches: mosquitto: friendly_name: ‘Mosquitto Service’ value_template: «<< is_state('binary_sensor.mosquitto','on') >>» turn_on: — service: shell_command.start_mosquitto turn_off: — service: shell_command.stop_mosquitto

Once again, restart home assistant and you should be good to go.

If you like the video, please subscribe to my channel. If you have any questions or comments, hit me up below and if you are looking for a tutorial on something in particular, let me know and I will see if I can’t get it out here for you.

Пришло время переводить выключатели на ESPEasy в Home Assistant

  • Home Assistant 0.70
  • Esp прошитый ESPEasy Mega
  • Реле
  • Переключатель

Приступим к сборке, если делаем новый переключатель.

Подключаем ESP с прошивкой ESPEasy к реле следующим образом:

ESP пин 3v3 к VCC реле
ESP пин GND к GND реле
ESP пин D6 (Gpio-12) к IN реле

В ESPEasy создаем переключатель Switch input — Switch для реле во вкладке Devices.

Приводим его к следующему виду:

Имя: relay
Enabled: — галочка
Internal PullUp: — галочка
Inversed Logic: — пусто
1st GPIO: GPIO-12 (D6)
Switch Type: Switch
Switch Button Type: Normal Switch
Send Boot state: — галочка
Send to Controller: — пусто
IDX: — номер Dummy переключателя в Domoticz (если активно Send to Controller)
Values Name: state

Управляется реле командой (192.168.0.23 это адрес ESPEasy):

Включить:
Выключить:

Включаем нулем если реле сделали нормально закрытым, и единицей, если нормально открытым

Выполнив переходы в браузере, реле сработает и выдаст ответ:

Мы будем управлять через MQTT.

Для этого переходив во вкладку Controllers и добавляем первым контроллером OpenHUB MQTT. Прописываем адрес брокера, порт и не меняя остальные настройки сохраняем.

Теперь создаем переключатель Switch input — Switch для переключателя во вкладке Devices:

Имя: button
Enabled: — галочка
Internal PullUp: — галочка
Inversed Logic: — пусто
1st GPIO: GPIO-14 (D5)
Switch Type: Switch
Switch Button Type: Normal Switch
Send Boot state: — пусто (если активировать, то при загрузке esp синхронизирует реле с выключателем: если был свет включен, то при загрузке тоже будет включен)
Send to Controller: — пусто
Values Name: state

Подключим обычный (любой) переключатель света:
от ESP пин GPIO-14 (D5 на NodeMCU) в разрыв переключателя и на GND ESP:

Включаем Rules в Tools> Advanced

Переходим на вкладку Rules и вставляем туда следующее:

Теперь при физическом нажатии переключателя, будет меняться статус реле — включаться и выключаться.

В Home Assistant переходим в switches.yaml и добавляем следующее:

Пояснения:
ESPEasy публикует и слушает данные в MQTT следующим образом:
/esp_switch_bedroom/gpio/12
esp_switch_bedroom — это название нашей esp, заданное во вкладке Main
gpio/12 — тут все ясно
и отправив 1 или 0 мы включим или выключим реле на ESPEasy

Так как мы русскоговорящие, названия устройств в Home Assistans нам хочется видеть тоже на русском. Но name: bedroom_switch обязательно должно быть на английском, так как от этого имени формируется название устройства в Dev, и именно это название из dev мы будем распределять по группам в будущем (- switch.bedroom_switch)

Если же поставить name: Выключатель, то в dev он примет вид switch.__

Он будет работать, но ровно до тех пор, пока мы не решим добавить еще один выключатель, так как он получит точно же такое имя switch.__

Весь этот набор отлично вмещается в глубокие подрозетники

Оцените статью