Home Assistant

Home Assistant Script Tutorial For Dummies

If you are new to Home Assistant one of the first questions you may be asking is how can I make a series of sequential events occur in the event of some kind of other action.

For example you may want a smart light switch to turn on the main light, a lamp and the TV in the living room. Or perhaps you would like the bedroom light and heating to switch on in the morning when the temperature is colder than 10 degrees celsius and the sun has not risen?

You may also want to add a delay between these events, for example all the lights turn off a couple of minutes after you turn the TV off, giving you time to leave the living room and not be plunged into darkness!

Bitmoji Image

Prerequisite

You will of course need Home Assistant installed and running. We will also be using the file editor add-on so if you didn’t install it yet go ahead and click the Supervisor button on the side bar, then click the add-on store tab at the bottom of the page.

Install file editor

Scroll down the page and find the file editor plug in, click on it and click install to add the plugin. Once installed you should see the file editor option appear in the sidebar.

Entities

You should also have an understanding of what an entity is in Home Assistant, so I will cover it here briefly. 

An entity is the terminology used to describe an object within Home Assistant. Entities are grouped by their type, for example all lights are grouped into the light entity category and switches are grouped into the switch entity category. 

Each entity has a name that Home Assistant uses for reference called the entity_id. This name needs to be compatible with the Home Assistant programming, therefore it does not contain spaces or exotic characters that may disrupt the programming. If in doubt just stick to numbers, letters and use an underscore “_” for a space. Do not use brackets, symbols or spaces. 

Home Assistant also allows us to assign a friendly name to objects, which is more human readable. The friendly name serves as a reference for us but is not used by the code.

If you wish to edit the entity_id or friendly name you can do so in the integrations menu found on the supervisor menu.

When we want to reference an entity in Home Assistant we use the following syntax.

entity.entity_id

For example, I have a lamp in the corner of my room that looks a little like a tree, I use it a lot for an example in my tutorials. This lamp is of course part of the light entity group and its name is treelamp. Therefore if I wish to reference it in Home Assistant I can using the following.

light.treelamp

The same method would be used to reference a switch. Here is another entity from my Home Assistant setup, a smart plug that I use to control the kettle.

switch.kettle

Now that we understand how to reference entities in Home Assistant we can take a look at creating our first script!

What is a script

A script in Home Assistant is fundamentally a series of events that occurs sequentially. Each script will itself become an entity that can be called from the script service.

Call from a button or automation

This means we can create a button to run the script from the overview page or call the script from an automation.

Let’s say for example we wanted to create an automation that turns on all the living room lights and boils the kettle when we get out of bed. We can write an automation that triggers our script using the change of state of a bed occupancy sensor. Cool!

I have a seperate beginners tutorial on how to create an automation that you should also check out if you are new to Home Assistant.

Variables

One other powerful feature of a script is that it has the ability to be passed variables. This means that when we call the script, we can also specify chosen attributes within the script differently.

For example we could write a script that turns off everything in the living room, but delays turning the main light off. We could call the script and pass the variable for delay in seconds.

This means that different actions which call the script could specify a different length of time that the main light should be left on for.

Configuration

The developers of Home Assistant are constantly making it easier to use by adding more graphical user interface elements. My beginners guide to automation covers how to create an automation using the GUI.

Graphical editor

At the time of writing the graphical interface for editing scripts is still in its infancy and to get the most out of a script you will still need to write code.

Therefore I would recommend getting to grips with writing the script in YAML. It can look confusing and complex at first but don’t worry!

Bitmoji Image

It is quite simple to understand when broken down into smaller chunks. If you do wish to try the graphical editor for scripts, you can find it by clicking configuration from the sidebar and then clicking scripts.

Alternatively if you find it easier, you could create your script using the GUI and then edit or add to the YAML afterwards.

Add the script integration

In order to use scripts we need to add the script integration to our configuration.yaml file. This will tell Home Assistant which file to load the script code from.

You can specify a filename of your choice but for this tutorial we will use the default file scripts.yaml found in the main config directory along with configuration.yaml.

If you do not have this file then we will need to create it. Click on file editor from the sidebar, then click the new file icon at the top of the list of files. Enter the name scripts.yaml and click ok.

Next we need to to add the script integration to the configuration.yaml file, so go ahead and open it in the editor. We need to tell Home Assistant to use scripts.yaml, simply add the following line of code to the end of your configuration file.

script: !include scripts.yaml

You can only have one instance of the “script:” integration within your configuration.yaml file, so if you already have it just replace it with the following code.

If you did want to keep everything in your configuration.yaml file and you don’t want to split up the files, you can omits the !include syntax and just add the script beneath the script integration.

script:
   # your scripts here, be sure to indent them with two spaces

If you do want to use scripts.yaml then you need to move any existing scripts to the new file. Any scripts that you already had in this section should be cut from configuration.yaml and pasted to the scripts.yaml file.

Now Home Assistant will load your scripts from scripts.yaml, so go ahead and save the file.

Writing a script

First we need to open our scripts.yaml file. It should be blank but if you have already used the graphical editor, it will have placed any scripts that you saved in this file.

If you wish to keep them you can leave them as is and just add your new manually written scripts beneath them, along with any scripts you may need to move from configuration.yaml.

Example script

For this tutorial we will write a bedtime routine script. The script will be triggered from an automation that fires it at 11pm.

First the LED lights and main light will turn blue to warn us that it is bedtime. Then all of the lights and the TV will turn off after a 2 minute delay, except the main light which will remain on for a further minute to allow us time to exit the room.

Define the new script

First we will define a new script called “bedtime.” We will give it a friendly name and description. Following the description we will begin the sequence.

bedtime:
    alias: Time for bed
    description: 'Turns off lights and TV in living room at bed time'
    sequence:

One very important point to make is that YAML is very sensitive to spacing. You must ensure that your indentations and spacing are correct in the file or you will get syntax errors. This is the number one cause of problems when people are editing YAML.

Add the first actions

Next we will add the first actions, these will occur as soon as the script starts. First we change the colour of the LED strip to blue.

After we specify sequence we will use the “-” operator to denote the start of a list item, think of it as similar to a bullet point.

bedtime:
    alias: Time for bed
    description: 'Turns off lights and TV in living room at bed time'
    sequence:
        - alias: LED Strip turn blue
          service: light.turn_on

Define the service

We will define the service as light.turn_on in order to turn on the LED strip (if it is not already on) and this also gives us the option to change the color.

You can see a full list of services using the dropdown services box in the file editor sidebar. The services are well documented on the Home Assistant website if you require further information.

Add the entity and data

Next we will add the entity_id for the LED strip we wish to control and we will use rgb_color to specify the colour.

The colour is specified by entering a value of 0 to 255 representing the brightness level of red, green and blue respectively.

rgb_color: [red value, green value, blue value]

You can use this handy tool to pick a colour and generate the necessary RGB values.

bedtime:
    alias: Time for bed
    description: 'Turns off lights and TV in living room at bed time'
    sequence:
        - alias: LED Strip turn blue
          service: light.turn_on
          data:
            entity_id: light.living_room_leds  
            rgb_color: [0,0,255]

Add the second entity

Now that we have added the LED strip, we can copy the code and change the entity_id to the one for the main light.

In my case this is light.lohasone but you should choose your own entity. You can see a list of entities in the search entities box on the file editor sidebar.

bedtime:
    alias: Time for bed
    description: 'Turns off lights and TV in living room at bed time'
    sequence:
        - alias: LED Strip turn blue
          service: light.turn_on
          data:
            entity_id: light.living_room_leds  
            rgb_color: [0,0,255]

        - alias: Main Light turn blue
          service: light.turn_on
          data:
            entity_id: light.lohasone
            rgb_color: [0,0,255]

Add the delay

Now that we have defined our first action and our bedtime warning script has turned the lights blue, we will add a delay before everything in the room turns off.

Note that the script will work sequentially from top to bottom. First the lights will turn blue, then the delay will occur. After the delay the script will continue with the elements written below.

bedtime:
    alias: Time for bed
    description: 'Turns off lights and TV in living room at bed time'
    sequence:
        - alias: LED Strip turn blue
          service: light.turn_on
          data:
            entity_id: light.living_room_leds  
            rgb_color: [0,0,255]

        - alias: Main Light turn blue
          service: light.turn_on
          data:
            entity_id: light.lohasone
            rgb_color: [0,0,255]

        - delay:
            seconds: 30

Turn off the lamp, LEDs and TV

Following the delay we will turn off the LED strip, the lamp and the TV. We will leave the main light on for a couple more minutes to allow some time to leave the room before it is completely dark!

This is the same as before but we will use the light.turn_off service instead. We can also omit the attribute for colour.

bedtime:
    alias: Time for bed
    description: 'Turns off lights and TV in living room at bed time'
    sequence:
        - alias: LED Strip turn blue
          service: light.turn_on
          data:
            entity_id: light.living_room_leds  
            rgb_color: [0,0,255]

        - alias: Main Light turn blue
          service: light.turn_on
          data:
            entity_id: light.lohasone
            rgb_color: [0,0,255]
            
        - delay:
            seconds: 30
            
        - alias: Turn TV off
          service: media_player.turn_off
          data:
            entity_id: media_player.massive_sony
        
        - alias: Tree Lamp off
          service: light.turn_off
          data:
            entity_id: light.treelamp
            
        - alias: LED Strip off
          service: light.turn_off
          data:
            entity_id: light.living_room_leds  

Turn off the main light

Finally we will add another delay and then the light.turn_off service for the main light. This will be the time that the main light remains on for before switching off.

This completes our script and the finished code should look something like this.

bedtime:
    alias: Time for bed
    description: 'Turns off lights and TV in living room at bed time'
    sequence:
        - alias: LED Strip turn blue
          service: light.turn_on
          data:
            entity_id: light.living_room_leds  
            rgb_color: [0,0,255]

        - alias: Main Light turn blue
          service: light.turn_on
          data:
            entity_id: light.lohasone
            rgb_color: [0,0,255]
            
        - delay:
            seconds: 30
            
        - alias: Turn TV off
          service: media_player.turn_off
          data:
            entity_id: media_player.massive_sony
        
        - alias: Tree Lamp off
          service: light.turn_off
          data:
            entity_id: light.treelamp
            
        - alias: LED Strip off
          service: light.turn_off
          data:
            entity_id: light.living_room_leds           

        - delay:
            minutes: 2

        - alias: Turn Main Light Off
          service: light.turn_off
          data:
            entity_id: light.lohasone

Create an entity button

Now that we have completed our script, we can create an entity button in the user interface in order to test it. Alternatively if you would like fire the script at a particular time such as bedtime, the information explaining how to do this can be found in this tutorial.

Open the UI editor

First goto the overview page and click configure UI in the top right-hand corner.

Create a new entity button card

Then click the orange circle with the plus icon to create a new lovelace card.

Next we need to choose entity button so go ahead and click it in the list of cards.

You will be presented with a graphical editor that is used to set up the button. All we need to do is choose our script entity script.bedtime in the entity box at the top.

You can change the other options too if you would like to alter the appearance of the button. If you would like to use a different icon, you can find a list of the MDI icons here.

You need to alter the format a little, for example the MDI icon site will give the name as follows.

mdi-script-outline

To use this in Home Assistant, we would need to change the “-” sign after “mdi” to a colon.

mdi:script-outline

Test the script

Once you have entered the script entity, click save. This will add the card to our lovelace page. Now we can go ahead and click the button to test the script!

If you have left the script tap action as toggle the button will turn grey when the script is running. You can click the button again to stop the script.

Next steps…

Congratulations, you have successfully made it to the end of this tutorial! I hope that it has given you a better understanding of scripts in Home Assistant.

Thanks for visiting and please be sure to leave a comment below! Then go ahead and try out one of these tutorials.

Bitmoji Image

Leave a Reply

Your email address will not be published. Required fields are marked *

back to top