Saturday, 1 February 2025

Home Assistant: Simple Sensor

This post is part of a group of posts all associated with the acquisition of information from external resources and making it available in Home Assistant.

Simple Sensor

In order to set up Home Assistant to collect data at regular intervals from web sites / devices and make the information available, sensors can be used.

This is a really simple example.

Step 1: Include File for Sensor Settings

Update 'configuration.yaml' to include a separate file which will include all of the sensor configurations:

$ sudo vi configuration.yaml

...

sensor: !include sensors.yaml

Note: This is 'sensor:' and not 'sensors:'

 Step 2: Add a Sensor

Create a 'sensors.yaml' file alongside the 'configuration.yaml' file

$ vi sensors.yaml

- platform: rest
 name: "Json Test - Random Number"
 resource: "http://www.randomnumberapi.com/api/v1.0/randomnumber"
 method: GET
 value_template: "{{ value_json[0] }}"
 scan_interval: 900
Note: The lines are not indented at all

Step 3: Check Things

Visit your Home Assistant / Developer Tools / Yaml page, and select "check configuration", and if everything is OK, select "Restart".

Once restarted, visit Home Assistant / Settings / Device and Services / Entities, and search for "Json Test - Random Number" in the list - select it, and you should see the results (in this case, the random number is 48).


What have we Just Done

We have changed the configuration of Home Assistant to use a separate sensors.yaml file - this allows us to keep all of our sensors together.

We have added a sensor to the sensors.yaml file.

Every 15 minutes (900 seconds) in this example, a JSON file will be extracted from the given resource, and the contents parsed.

The first entry will be pulled out of the json file, and will be used for the "Json Test - Random Number".

Note that this is a really simple example, and the returned JSON is just a list of just one number.

It is likely that you will have a more complex result, and you will need to replace the 'value_json[0]' with a more complex search pattern.

In this case, it is recommended that you paste your 'resource' url into a web browser, and copy the resulting json into the form at the JSON Path Finder, this will parse the JSON, and allow you to click on a field within the data and extract the corresponding path.


In the above example, the JSON has come from the openweathermap website, and the path for the description is x.weather[0].description.  

This would be translated to value_json["weather"][0]['description'] in the Home Assistant settings.







No comments:

Post a Comment