Home » Blog » YAML & Jinja Templating Course Episode 7: Create your own Sensors!

YAML & Jinja Templating Course Episode 7: Create your own Sensors!

Hi, This is episode 7 of the Yaml and Jinja templating course. In this episode, I’m going to show you how to create your own template sensors in Home Assistant! As an example, I’ll show you how to display the number of lights that are on and which lights are specifically on your dashboard. And, as a bonus, I’ll show you how to display how many lights are on per room in your house. Let’s get started!


โญโญโญ NOTE: โญโญโญ

This article accompanies a YouTube video. I wrote it for people who would rather read than watch a video. To keep doing this, I want to ask you to check out the video, leave a comment under the video, give the video a thumbs up, and subscribe to my YouTube channel. This means that the video is offered more often to new visitors so that they also stay informed of the latest Home Assistant tutorials.

Thank you for your support!

Ed

Click here to watch the video

In the past 6 episodes of this course, I have shown you how to work with Yaml and Jinja in Home Assistant. If you haven’t seen those episodes yet, go to this playlist to watch them. During those episodes, I used the developer tools to explain the Yaml and Jinja code. Today, I’m going to show you how to use the code to create your own sensor so you can use it on your dashboards, in scripts, or automations. In Episode 6, I explained how to query the number of lights that are on in your house using a template. I will use this example again in this episode. So, make sure to watch Episode 6 first if you haven’t done so yet. Furthermore, you asked how to see which lights are on specifically and how many lights are on per room in your house. I will also explain that in this episode!

How do you create your own sensor in Home Assistant?

You can create your own sensor in Home Assistant in several ways, and I’ll show you two of them. The simplest way is to use a template helper. This allows you to create a sensor that returns a state, but you cannot include additional attribute values in your sensor (yet). However, for most applications, this is sufficient. Later in this tutorial, I’ll show you a more advanced way to create sensors, where you can store multiple values in the attributes of the sensor.

Deploying a Template Helper

Let’s create a sensor as an example that shows what part of the day it is today. If you don’t understand the code, I recommend watching the other episodes of this course where I explain everything.

  • Go to Settings -> Devices & Services.
  • Click the Helpers tab.
  • Click Create Helper.
  • Select the Template helper.
  • We are going to create a sensor that returns a value, so select Template a Sensor. If you want to return the value “on” or “off,” you can use a binary sensor.
  • Give the template a name, for example, “partofday.”
  • Put the following code in the State template field:
{% set time = now().hour %}
{% if (time >= 18) %}
  evening
{% elif (time >= 12) %}
  afternoon
{% elif (time >= 5) %}
  morning
{% elif (time >= 0) %}
  night
{% endif %}
  • For Unit of measurement, device class, and state class, you don’t need to select anything for this sensor.
  • You can add this sensor as a custom sensor to a device. It doesn’t really make sense to attach this sensor to a device, but let’s attach it to the “sun” device so you can see what this does.
  • In the Preview, you will see the current value of this sensor so you can check if your template code is correct.
  • Click Create and then click Finish.

You have now created a new sensor. Let’s test it out.

  • Go to the Developer Tools and click the States tab.
  • Search for “partofday.”
  • You will now see your sensor and the value that the template has returned.
  • Now, let’s see if this sensor has been added to the “sun” device.
  • Click Settings > Devices & Services.
  • Click the Devices tab.
  • Search for Sun.
  • Click the Sun device.
  • And ta-da! You will find the sensor you just created as part of this device.

So, this way you can quickly create your own sensor in Home Assistant.

Creating advanced templates.

However, sometimes you want to create a more comprehensive sensor that includes additional values in attributes alongside the sensor value. In such cases, the template helper is too limited to use, and it’s better to define your template sensor in a templates file so that you can manage all your templates centrally.

Install Studio Code Server or File Editor.

To do this, you need to use a text editor that allows you to edit files on your Home Assistant server. You can easily install such a text editor within Home Assistant itself. There are two text editors you can use, namely Studio Code Server or File Editor. I prefer Studio Code Server.

  • To install Studio Code Server, go to Settings -> Add-ons.
  • Then search for Studio Code Server.
  • Click on Studio Code Server.
  • Click Install.
  • Check all the checkboxes if you want and click Start.
  • Studio Code Server is now installed.

With Studio Code Server, you can view and edit all files on your Home Assistant server. I personally like to have all template sensors in one file, so I create a templates.yaml file for this purpose. Then, from the configuration.yaml file, I reference this templates.yaml file.

  • Open Studio Code Server.
  • Here you will see an overview of all files on your Home Assistant server.
  • Make sure you have selected and expanded the config folder.
  • Click on the New File icon.
  • A new file will be created. Name this file: templates.yaml.
  • Next, open this file.
  • Add the following lines to this file:
- sensor:

Below this line, we will create our templates later.

  • Save the templates.yaml file by pressing ctrl-s or command-s.
  • Now open your configuration.yaml file.
  • Add the following line to this file:
template: !include templates.yaml
  • This ensures that the templates.yaml file is loaded into Home Assistant.
  • Save the configuration.yaml file by pressing ctrl-s or command-s.

You now have everything set up to add your own sensors, but you need to restart Home Assistant first to ensure that the code in your templates.yaml file is read.

  • Go to the Developer Tools and click on the YAML tab.
  • Click on Check Configuration.
  • If you have entered the code correctly, you will receive a green notification.
  • Click Restart and then click Restart Home Assistant.
I need your help!

You will be doing me a huge favor if you subscribe to my channel if you haven’t already. And, you will help me a lot if you also give this video a thumbs up and leave a comment. This way, YouTube will present this video to new people, making the channel grow! In the video description, you will also find information about how you can sponsor me so that I can continue to make these tutorials for you.

Thank you!

Adding your first sensor

After Home Assistant has restarted, we can add a sensor. Let’s use the template code that I explained in episode 6, which shows the number of lights that are on in your house.

We do this using the following code:

    - name: "Number Lights On"
      unique_id: eeb772ce-c4c0-4ec2-b649-ef27e26e26b0
      icon: mdi:lightbulb-group
      state: >
        {{ states.light 
          | rejectattr('entity_id', 'in', label_entities('Group')) 
          | rejectattr('entity_id', 'in', label_entities('Dummylight'))
          | selectattr('state', 'eq', 'on')
          | list | count }}
  • In the first line, we give our sensor a name. In this case, it’s “Number Lights On”. This name also serves as the entity ID that you can later find among the entities in Home Assistant.
  • Next, we assign a unique_id to the sensor. You can easily generate this unique ID in Studio Code Server by right-clicking and choosing “generate UUID at Cursor”. By assigning a unique_id to this sensor, you can later edit certain properties of this sensor, such as the area, in the Home Assistant UI. Without a unique_id, you cannot edit these properties later, so make sure your sensor always has a unique_id.
  • In the next line, I define the icon that I want to assign to this sensor. In this case, I have chosen mdi:lightbulb-group, but you can use any icon that you think fits best.
  • Finally, we come to the actual state that this sensor should return. We start this line with a greater-than sign (>).
  • In the following lines, we use the code that I explained in episode 6.
  • Save the templates.yaml file and your sensor is now created.

We still need to activate this sensor in Home Assistant.

  • To do that, go to Developer Tools and select the YAML tab.
  • Scroll down and click on Template Entities. This will reload your templates in Home Assistant.

Let’s now test if our new sensor is working. Exciting!

  • Select the States tab in the Developer Tools.
  • Search for “Number Lights On”.
  • You will now see the number of lights that are on in your house. From now on, you can use the entity sensor.number_lights_on in your automations, scripts, and dashboards.

Congratulations! You have now created your first custom sensor.

What lights are exactly on?

You asked me how to see which lights are exactly on. Let’s expand the sensor so we can see that too. For that, I’m going to add attributes to our sensor.

  • Open the templates.yaml file again.
  • As you can see, I have added the following code:
      attributes:
        light_names: >
          {{ states.light | rejectattr('entity_id', 'in', label_entities('Group')) 
            | rejectattr('entity_id', 'in', label_entities('Dummylight')) 
            | selectattr('state', 'eq', 'on')
            | map(attribute='name')
            | list
            | sort }}
  • The first line is the “attributes” line, where I will add attributes below. For this example, there’s only one attribute, but you can add as many as you like.
  • I have created the attribute “light_names” here.
  • Below that, I copied almost the same code used for the state, but I added one line that returns only the names of the lights.
  • Then, I turn it into a list again and sort that list alphabetically.
  • Note: a state can only contain 255 characters, while an attribute can hold much longer values. That’s why I choose to store the names of the lights that are on in an attribute rather than in the state of a separate sensor.
  • Save the templates.yaml file again and go back to the Developer Tools to reload the Template Entities.

If you now go to the States tab and check your Number Lights On sensor, you will see that an attribute named “light_names” has been added, which contains the names of the lights that are currently on.

What lights are on in a specific room?

I will show you shortly how to display these names on your dashboard, but first, I want to answer another question you had. Namely, how can I see which lights are on per room in my house?

Well, it’s actually quite simple once you understand how I made the previous sensor. Take a look at this code:

    - name: "Number Lights On in Office"
      unique_id: 19bb2a01-9c35-4099-813e-81494c2616e6
      icon: mdi:lightbulb-group
      state: >
        {{ states.light
          | rejectattr('entity_id', 'in', label_entities('Group')) 
          | rejectattr('entity_id', 'in', label_entities('Dummylight')) 
          | selectattr('entity_id', 'in', area_entities('Office')) 
          | selectattr('state', 'eq', 'on')
          | list 
          | count }}
      attributes:
        light_names: >
          {{ states.light | rejectattr('entity_id', 'in', label_entities('Group')) 
            | rejectattr('entity_id', 'in', label_entities('Dummylight')) 
            | selectattr('entity_id', 'in', area_entities('Office')) 
            | selectattr('state', 'eq', 'on')
            | map(attribute='name')
            | list
            | sort }}

As you can see, the code is almost identical to the previous sensor, but I’ve added an additional filter, specifically this line where I filter on the area_entity “Office”. This way, I can show how many and which lights are on in my office. You can create such a sensor for each area in your house and display how many lights are on per area.

When I check this in the Developer Tools, you’ll see that indeed I only get the lights in my office in this sensor.

Oh, I showed you earlier that you can assign a sensor to a device when using a template helper. Unfortunately, you cannot (yet) do this when creating your template sensors in this advanced way.

Show the values of a custom template sensor on a dashboard

Now that we have created our sensor, I will show you how to display its values on your dashboard. We will use the markdown card for this purpose.

  • Open any dashboard and click on the pencil icon in the top right corner.
  • Create a new view by clicking on the plus icon.
  • Give the view a title and click save.
  • Click Add card.
  • Search for the markdown card and select the markdown card.
  • Give the markdown card a title. In my case, I name the title “What Lights are on?”.
  • Remove the example content and replace it with this code:
Total lights on: {{ states('sensor.number_lights_on') }}

{% for item in state_attr('sensor.number_lights_on','light_names') %}
  {{item}}
{%- endfor %}
  • If you don’t understand this code, also take a look at episode 3 where I explain, among other things, how for loops work and how you can iterate through a list using a for loop.
  • In the first line, I display the state value of the sensor “number_lights_on”.
  • In the lines below, I have created a for-loop that iterates through the items in the attribute “light_names” and displays them one by one.
  • Click Save and then click Done.

Nice! Now you can see how many and which lights are on in your house. Oh, and yes, I know, you can also do this with the custom auto-entities card, but that’s not the purpose of this tutorial.

So now you know how to create your own custom template sensors. I’m really curious to hear what sensors you’ve come up with. Let me know in the comments!

Thank you for watching. I hope my videos help you understand Yaml, Jinja, and Home Assistant better. If they do and you find them valuable, you can support me by sponsoring me through Patreon, Ko-Fi, or by becoming a paid member of my channel like these people do. This support allows me to keep doing this work. Thank you.

And don’t forget to give this video a thumbs up and subscribe to my channel if you haven’t already.

I’ll see you soon in my next video.

Bye Bye!



Back to all articles