home assistant скрипты автоматизации

Scripts

The script integration allows users to specify a sequence of actions to be executed by Home Assistant. These are run when you turn the script on. The script integration will create an entity for each script and allow them to be controlled via services.

Configuration

The sequence of actions is specified using the Home Assistant Script Syntax.

Configuration Variables

Friendly name for the script.

Icon for the script.

A description of the script that will be displayed in the Services tab under Developer Tools.

Variables that will be available inside your templates

The value of the variable. Any YAML is valid. Templates can also be used to pass a value to the variable.

Information about the script field parameters; see the Passing variables to scripts section below. Please note: In order for this description to be displayed in the Services tab of the Developer Tools, the script description must be defined as well.

A parameter field used by this script. All sub-options are only used for creating a representation of this script in the UI.

The name of this script parameter field.

A description of this of this script parameter.

Marks this field as an advanced parameter. This causes it only to be shown in the UI, when the user has advanced mode enabled.

Mark if this field is required. This is a UI only feature.

An example value. This will only be shown in table of options available in the Services tab of the Developer Tools.

The default value for this field, as shown in the UI.

The selector to use for this input. A selector defines how the input is displayed in the frontend UI.

Controls what happens when script is invoked while it is still running from one or more previous invocations. See Script Modes.

When max is exceeded (which is effectively 1 for single mode) a log message will be emitted to indicate this has happened. This option controls the severity level of that log message. See Log Levels for a list of valid options. Or silent may be specified to suppress the message from being emitted.

The sequence of actions to be performed in the script.

Script Modes

ModeDescription
singleDo not start a new run. Issue a warning.
restartStart a new run after first stopping previous run.
queuedStart a new run after all previous runs complete. Runs are guaranteed to execute in the order they were queued.
parallelStart a new, independent run in parallel with previous runs.

home assistant скрипты автоматизации. script modes. home assistant скрипты автоматизации фото. home assistant скрипты автоматизации-script modes. картинка home assistant скрипты автоматизации. картинка script modes. The script integration allows users to specify a sequence of actions to be executed by Home Assistant. These are run when you turn the script on. The script integration will create an entity for each script and allow them to be controlled via services.

Full Configuration

Passing variables to scripts

As part of the service, variables can be passed along to a script so they become available within templates in that script.

There are two ways to achieve this. One way is using the generic script.turn_on service. To pass variables to the script with this service, call it with the desired variables:

The other way is calling the script as a service directly. In this case, all service data will be made available as variables. If we apply this approach on the script above, it would look like this:

Using the variables in the script requires the use of templates:

Script variables that may be used by templates include those provided from the configuration, those that are passed when started from a service and the this variable whose value is a dictionary of the current script’s state.

Waiting for Script to Complete

When calling a script “directly” (e.g., script.NAME ) the calling script will wait for the called script to finish. If any errors occur that cause the called script to abort, the calling script will be aborted as well.

When calling a script (or multiple scripts) via the script.turn_on service the calling script does not wait. It starts the scripts, in the order listed, and continues as soon as the last script is started. Any errors that occur in the called scripts that cause them to abort will not affect the calling script.

home assistant скрипты автоматизации. script wait. home assistant скрипты автоматизации фото. home assistant скрипты автоматизации-script wait. картинка home assistant скрипты автоматизации. картинка script wait. The script integration allows users to specify a sequence of actions to be executed by Home Assistant. These are run when you turn the script on. The script integration will create an entity for each script and allow them to be controlled via services.

Источник

Script Syntax

Scripts are a sequence of actions that Home Assistant will execute. Scripts are available as an entity through the standalone Script component but can also be embedded in automations and Alexa/Amazon Echo configurations.

When the script is executed within an automation the trigger variable is available. See Available-Trigger-Data.

The script syntax basic structure is a list of key/value maps that contain actions. If a script contains only 1 action, the wrapping list can be omitted.

Call a Service

The most important one is the action to call a service. This can be done in various ways. For all the different possibilities, have a look at the service calls page.

Activate a Scene

Scripts may also use a shortcut syntax for activating scenes instead of calling the scene.turn_on service.

Variables

The variables action allows you to set/override variables that will be accessible by templates in actions after it. See also script variables for how to define variables accessible in the entire script.

Test a Condition

The condition action only stops executing the current sequence block. When it is used inside a repeat action, only the current iteration of the repeat loop will stop. When it is used inside a choose action, only the actions within that choose will stop.

Delay

Delays are useful for temporarily suspending your script and start it at a later moment. We support different syntaxes for a delay as shown below.

All forms accept templates.

These actions allow a script to wait for entities in the system to be in a certain state as specified by a template, or some event to happen as expressed by one or more triggers.

Wait Template

This action evaluates the template, and if true, the script will continue. If not, then it will wait until it is true.

The template is re-evaluated whenever an entity ID that it references changes state. If you use non-deterministic functions like now() in the template it will not be continuously re-evaluated, but only when an entity ID that is referenced is changed. If you need to periodically re-evaluate the template, reference a sensor from the Time and Date component that will update minutely or daily.

Wait for Trigger

This action can use the same triggers that are available in an automation’s trigger section. See Automation Trigger. The script will continue whenever any of the triggers fires. All previously defined trigger_variables, variables and script variables are passed to the trigger.

Wait Timeout

Wait Variable

After each time a wait completes, either because the condition was met, the event happened, or the timeout expired, the variable wait will be created/updated to indicate the result.

This can be used to take different actions based on whether or not the condition was met, or to use more than one wait sequentially while implementing a single timeout overall.

Fire an Event

This action allows you to fire an event. Events can be used for many things. It could trigger an automation or indicate to another integration that something is happening. For instance, in the below example it is used to create an entry in the logbook.

You can also use event_data to fire an event with custom data. This could be used to pass data to another script awaiting an event trigger.

The event_data accepts templates.

Raise and Consume Custom Events

The following automation example shows how to raise a custom event called event_light_state_changed with entity_id as the event data. The action part could be inside a script or an automation.

The following automation example shows how to capture the custom event event_light_state_changed with an Event Automation Trigger, and retrieve corresponding entity_id that was passed as the event trigger data, see Available-Trigger-Data for more details.

Repeat a Group of Actions

This action allows you to repeat a sequence of other actions. Nesting is fully supported. There are three ways to control how many times the sequence will be run.

Counted Repeat

This form accepts a count value. The value may be specified by a template, in which case the template is rendered when the repeat step is reached.

While Loop

This form accepts a list of conditions (see conditions page for available options) that are evaluated before each time the sequence is run. The sequence will be run as long as the condition(s) evaluate to true.

Repeat Until

This form accepts a list of conditions that are evaluated after each time the sequence is run. Therefore the sequence will always run at least once. The sequence will be run until the condition(s) evaluate to true.

Repeat Loop Variable

fielddescription
firstTrue during the first iteration of the repeat sequence
indexThe iteration number of the loop: 1, 2, 3, …
lastTrue during the last iteration of the repeat sequence, which is only valid for counted loops

Choose a Group of Actions

This action allows you to select a sequence of other actions from a list of sequences. Nesting is fully supported.

Each sequence is paired with a list of conditions. (See the conditions page for available options and how multiple conditions are handled.) The first sequence whose conditions are all true will be run. An optional default sequence can be included which will be run only if none of the sequences from the list are run.

An optional alias can be added to each of the sequences, excluding the default sequence.

The choose action can be used like an “if” statement. The first conditions / sequence pair is like the “if/then”, and can be used just by itself. Or additional pairs can be added, each of which is like an “elif/then”. And lastly, a default can be added, which would be like the “else.”

More choose can be used together. This is the case of an IF-IF.

The following example shows how a single automation can control entities that aren’t related to each other but have in common the same trigger.

When the sun goes below the horizon, the porch and garden lights must turn on. If someone is watching the TV in the living room, there is a high chance that someone is in that room, therefore the living room lights have to turn on too. The same concept applies to the studio room.

Источник

Home Assistant: немного о шаблонах

Тема шаблонов (Templates) в HA всегда вызывает много вопросов, причем порой и у пользователей системы со стажем. Здесь я хочу собрать некоторое кол-во примеров с комментариями, которые помогут лучше понять принцип работы и синтаксис темплейтов.

Для погружения в тему, начать стоит как всегда с изучения официальной документации, а так же руководства на шаблонизатор Jinja2, именно его под капотом использует HA.
Шаблоны можно применять во множестве мест, начиная от объектов (например, создав собственный sensor или switch) и заканчивая скриптами, автоматизациями и интерфейсом lovelace. С их помощью можно получать необходимые данные из объектов (сущностей) — стейты и атрибуты, при необходимости модифицировать их, а так же реализовывать всевозможную логику (переменные, циклы, проверки и т.д.). Это по-настоящему мощный инструмент, открывающий массу возможностей.

Один из главных инструментов для работы с шаблонами находится в разделе «Панель разработчика» — «Шаблоны» (/developer-tools/template), здесь можно в он-лайн режиме проверить корректность составленного шаблона и оценить его результат. Не забывайте про него, это сохранит множество времени и нервов при отладке сложных конструкций, а так же поможет лучше понять как все это работает.

home assistant скрипты автоматизации. ha devtool templates 01. home assistant скрипты автоматизации фото. home assistant скрипты автоматизации-ha devtool templates 01. картинка home assistant скрипты автоматизации. картинка ha devtool templates 01. The script integration allows users to specify a sequence of actions to be executed by Home Assistant. These are run when you turn the script on. The script integration will create an entity for each script and allow them to be controlled via services.

Коротко про синтаксис

Обратите внимание на оформление, в шаблонах могут использоваться строки с разным обрамлением:

По умолчанию, каждая строка шаблона на выходе будет оканчиваться символом новой строки «\n».
Причем даже те строки, которые ничего не выводят (например, объявление переменной — <% set a = 123 %>).
Об этом необходимо помнить и учитывать при составлении темплейта.
К примеру, если шаблон используется для вывода чего-либо на экран, можно потратить уйму времени в борьбе с лишними пустыми строками на выходе.
Для управления этим поведением в jinja2 существует специальный механизм:

Помимо этого, стоит уделить время ресурсу yaml-multiline.info, на котором можно наглядно разобраться с вопросом форматирования и переноса строк в YAML’е (символы |, > и т.д.), это бывает полезно при форматировании многострочных шаблонов.

Отдельно стоит упомянуть о том, какие операторы можно использовать в шаблонах.
Полную информацию об этом стоит искать в документации на jinja, а вкратце это:

Помимо этого, в выражениях можно использовать фильтры jinja и HA, передавая значения в них через символ «|».
Пример: ((states(‘sensor.0x158d0003230618_pressure’) | float) / 1.333) | round(2)

Важные моменты в документации, на которые стоит обратить особое внимание:

Примеры

Сенсоры и их атрибуты

С помощью шаблонов можно создавать как бинарные (on\off), так и обычные сенсоры:

В примерах выше используются простые выражения (Expressions) с использованием встроенных в HA функций is_state() и state_attr(). С полным перечнем функций и правилами их применения лучше всего ознакомится в документации.

Более интересный пример:

Здесь в качестве стейта (state) сенсора date_formatted будет выведен результат выражения
<< as_timestamp(states('sensor.date_time_iso')) | timestamp_custom('%d.%m.%Y') >> и дополнительно, в виде атрибута — день недели, получаемый с помощью ряда операций.

home assistant скрипты автоматизации. ha devtool states 01. home assistant скрипты автоматизации фото. home assistant скрипты автоматизации-ha devtool states 01. картинка home assistant скрипты автоматизации. картинка ha devtool states 01. The script integration allows users to specify a sequence of actions to be executed by Home Assistant. These are run when you turn the script on. The script integration will create an entity for each script and allow them to be controlled via services.

В качестве значения сенсора можно использовать произвольный текст, в этом примере в зависимости от состояния датчика двери (геркона) в стейт будет записан текст «Открыта» или «Закрыта» (речь про дверь):

Более комплексный пример:

Темплейты можно использовать практически во всех возможных местах, например в именах будущих сенсоров:

Или меняя иконку сенсора в зависимости от различных условий:

Switches

В выключателях так же есть возможность использовать шаблоны.
Например, можно создать выключатель телевизора с разными действиями на включение и выключение:

Скрипты и автоматизации

Самое широкое применение шаблоны встречают в скриптах и автоматизациях.

Скрипт для запуска уборки роботом-пылесосом конкретной комнаты (в интерфейсе input_select.room_to_vacuum это выпадающий список с комнатами):

Автоматизация, меняющая мощность работы робота-пылесоса:

Оповещение о произошедшей ошибке.
С помощью шаблона можно получить текст ошибки из атрибута error:

Автоматизация меняющая яркость лампы по двойному клику на кнопку (по кругу):

Плавное включение света в заданное в интерфейсе HA время (будильник):

Постепенное увеличение громкости:

Изменение громкости у выбранного из выпадающего списка источника:

Отправка оповещений о приходе или уходе из дома:

В примере выше сообщение будет выглядеть примерно так — «Александр скорее всего вне дома.»
Шаблон соберется в одну строку, т.к. перед ним указан символ «>», означающий замену символов новой строки на пробелы.

Еще одно оповещение, на этот раз о температуре в комнате (холодно или жарко):

Команда для телеграм-бота, возвращающая имена находящихся дома:

Здесь, в отличии от предыдущего примера, перед шаблоном указан символ «|», означающий сохранение всех переносов строк в шаблоне. Лишняя пустая строка из вывода убрана с помощью конструкции «<%-«.

Еще одна команда для бота, присылающая текущую погоду:

Здесь, в зависимости от стейта сенсора weather.gismeteo (sunny, rainy, snowy и т.д.) отправляется картинка соответствующая текущей погоде (картинки подготовлены заранее).

Я постарался собрать здесь как можно более разнообразные примеры использования шаблонов в HA, но т.к. эта тема невероятно обширная, получилось это у меня слабо… =)
В будущем я надеюсь дополнить заметку другими интересными (с разных точек зрения) примерами.

Источник

Умный дом в котором я живу. Использование скриптов Python в автоматизациях Home Assitant

Когда я писал прошлый пост Умный дом в котором я живу. Зональная уборка роботом пылесосом у меня возникла идея заменить при выборе комнат для уборки выпадающий список

home assistant скрипты автоматизации. 1590581310122876760. home assistant скрипты автоматизации фото. home assistant скрипты автоматизации-1590581310122876760. картинка home assistant скрипты автоматизации. картинка 1590581310122876760. The script integration allows users to specify a sequence of actions to be executed by Home Assistant. These are run when you turn the script on. The script integration will create an entity for each script and allow them to be controlled via services.

home assistant скрипты автоматизации. 1590573766160820461. home assistant скрипты автоматизации фото. home assistant скрипты автоматизации-1590573766160820461. картинка home assistant скрипты автоматизации. картинка 1590573766160820461. The script integration allows users to specify a sequence of actions to be executed by Home Assistant. These are run when you turn the script on. The script integration will create an entity for each script and allow them to be controlled via services.

Но встал вопрос как передавать параметры уборки роботу.

Т.е. из отдельных блоков комнат [х1,у1,х2,y2,count] мы должны собрать строку

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

Итак, собственных возможностей HA не хватает, чтобы написать перебор всех возможных вариантов уборки. Поэтому, можно задействовать скрипты на Питоне, что существенно расширяет возможности автоматизации. В configuration.yaml прописываем

home assistant скрипты автоматизации. 1590574476170240232. home assistant скрипты автоматизации фото. home assistant скрипты автоматизации-1590574476170240232. картинка home assistant скрипты автоматизации. картинка 1590574476170240232. The script integration allows users to specify a sequence of actions to be executed by Home Assistant. These are run when you turn the script on. The script integration will create an entity for each script and allow them to be controlled via services.

и в каталоге config создаем директорию python_scripts

и в ней уже файл скрипта variant.py

home assistant скрипты автоматизации. 159057491413299582. home assistant скрипты автоматизации фото. home assistant скрипты автоматизации-159057491413299582. картинка home assistant скрипты автоматизации. картинка 159057491413299582. The script integration allows users to specify a sequence of actions to be executed by Home Assistant. These are run when you turn the script on. The script integration will create an entity for each script and allow them to be controlled via services.

Как это работает. Мы должны передать пылесосу массив состоящий из параметров комнат, которые мы будем убирать.

Скрипт принимает на вход состояния выключателей input_boolean и рассовывает их по переменным. затем он на основе значений переменных или добавляет параметры комнаты или нет.

Закомментированная строчка выплевывает передаваемый роботу массив в лог HA, что удобно для отладки.

Источник

Особенности автоматизаций в Home Assistant

home assistant скрипты автоматизации. . home assistant скрипты автоматизации фото. home assistant скрипты автоматизации-. картинка home assistant скрипты автоматизации. картинка . The script integration allows users to specify a sequence of actions to be executed by Home Assistant. These are run when you turn the script on. The script integration will create an entity for each script and allow them to be controlled via services.

Что необходимо сделать:

При двойном нажатии на одну из кнопок Xiaomi (или при включении автоматизации под названием Сигнализация в веб интерфейсе НА) происходит активация или дезактивация сигнализации

При наличии движения на одном из датчиков движения должно происходить следующее:

Возникавшие сложности

Итоговая реализация

Используются следующие элементы системы Home Assistant:

Разберем конфигурацию

Для начала нам нужно понимать откуда нам брать названия сенсоров, кнопок, датчиков и автоматизаций чтобы их использовать в коде. Для этого мы идем в раздел «Элементы» из инструментов разработчика

home assistant скрипты автоматизации. . home assistant скрипты автоматизации фото. home assistant скрипты автоматизации-. картинка home assistant скрипты автоматизации. картинка . The script integration allows users to specify a sequence of actions to be executed by Home Assistant. These are run when you turn the script on. The script integration will create an entity for each script and allow them to be controlled via services.

а дальше уже из списка который у нас появился, мы выбираем названия элементов, которые нам нужны для работы:

home assistant скрипты автоматизации. . home assistant скрипты автоматизации фото. home assistant скрипты автоматизации-. картинка home assistant скрипты автоматизации. картинка . The script integration allows users to specify a sequence of actions to be executed by Home Assistant. These are run when you turn the script on. The script integration will create an entity for each script and allow them to be controlled via services.

Ну а дальше пошло самое веселье. Начинаем вставлять код в файл automations.yaml

Создавая это я столкнулся со следующими проблемами. Автоматизация Alarm Status Sound конфликтовала с автоматизацией Motion Detection когда использовалось штатное решение отработки по состоянию приведенное ниже:

и так как файл автоматизаций отрабатывает последовательно все что в нем написано, то в моем случае сначала начиналась сработка сирены по датчику движения, а потом система видела что статус сигнализации находится в режиме ‘On’ и начинала последовательность прописанную в автоматизации ‘Alarm Status Sound’ назначенную для сигнализации в режиме ‘On’ и сигнализация прекращала орать и проигрывала звук включения сигнализации. ну вы понимаете.

Именно поэтому в данной конфигурации ‘Alarm Status Sound’ срабатывает только при изменении состояния автоматизации ‘Motion Detection’.

Ну а то, что происходит при срабатывании самой сигнализации прописано в файле scripts.yaml и довольно скучно на фоне написанного ранее:

Без задержек получается что Текст проигрывается одновременно с последним указанным рингтоном шлюза, так как на шлюз пришли сразу две одинаковых команды и он выполняет последнюю. И получается каша.

Упомянутые кастомизации

Когда мы настраиваем автоматизации, они появляются на основном экране Home Assistant и вводят в заблуждение. По факту нам кроме основной кнопки включения/отключения сигнализации, на главном экране больше ничего и не нужно.

Поэтому мы берем файл customize.yaml и вставляем туда параметры

где hidden: true скрывает ненужные нам автоматизации и скрипты с главного экрана и все становится значительно удобней.

Выводы:

Все это делалось не только для того, чтобы одна мохнатая морда получила предынфарктное состояние при попытке залезть на подоконник или стол.

Данный пример показывает вариации автоматизаций с использованием различных совмещенных параметров отслеживания состояний различных автоматизаций и датчиков, и аккумулирует найденные мной примеры конфигурации в некий набор шаблонов, которые можно будет в дальнейшем использовать для автоматизации процессов в доме.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *