I’m setting up some template sensors for Tomorrow.io to get their weather and pollen data via their API.
I’ve got them working, but some of them give numeric value codes to signify meanings (e.g. precipitation type gives 0-4 for none, rain, snow, freezing rain or ice pellets), and I’d like to convert those values into their meanings.
At the moment I’ve got 4 rest sensors actually pulling the data. One example is:
- resource: !secret tomorrowio
scan_interval: 1800
sensor:
- name: "Tomorrowio Day 0"
value_template: "{{ value_json.data.timelines[0].intervals[0]['values']['temperature'] }}"
json_attributes_path: "$.data.timelines[0].intervals[0].values"
json_attributes:
- temperature
- temperatureApparent
- humidity
- windSpeed
- windGust
- pressureSurfaceLevel
- precipitationIntensity
- precipitationProbability
- precipitationType
- sunriseTime
- sunsetTime
- visibility
- cloudCover
- cloudBase
- cloudCeiling
- moonPhase
- weatherCode
- grassIndex
- treeIndex
- weedIndex
The resource secret is the string for pulling data from the API, and includes the api key and the list of fields to pull data for plus other stuff like location co-ords (lat/long).
That rest sensor pulls all the categories for today (timelines[0].intervals[0]
) and there are copy sensors for tomorrow and the two following days ( using timelines[0].intervals[1]
, timelines[0].intervals[2]
and timelines[0].intervals[3]
respectively).
These then feed into individual template sensors for each category. So for example for the precipitationType
category I have the following template:
- sensor:
- name: Precipitation Type
unique_id: tomorrowio_precipitation_type
state: >
{% set pvar = {
0: "None",
1: "Rain",
2: "Snow",
3: "Freezing Rain",
4: "Ice Pellets"
} %}
{{ pvar.get(state_attr('sensor.tomorrowio_day_0', 'precipitationType')) }}
icon: 'mdi:weather-snowy-rainy'
attributes:
Today: >
{% set pvar = {
0: "None",
1: "Rain",
2: "Snow",
3: "Freezing Rain",
4: "Ice Pellets"
} %}
{{ pvar.get(state_attr('sensor.tomorrowio_day_0', 'precipitationType')) }}
Tomorrow: >
{% set pvar = {
0: "None",
1: "Rain",
2: "Snow",
3: "Freezing Rain",
4: "Ice Pellets"
} %}
{{ pvar.get(state_attr('sensor.tomorrowio_day_1', 'precipitationType')) }}
Today + 2: >
{% set pvar = {
0: "None",
1: "Rain",
2: "Snow",
3: "Freezing Rain",
4: "Ice Pellets"
} %}
{{ pvar.get(state_attr('sensor.tomorrowio_day_2', 'precipitationType')) }}
Today + 3: >
{% set pvar = {
0: "None",
1: "Rain",
2: "Snow",
3: "Freezing Rain",
4: "Ice Pellets"
} %}
{{ pvar.get(state_attr('sensor.tomorrowio_day_3', 'precipitationType')) }}
That works fine, but it can’t be the most optimal set-up as there’s so much repetition of the variable to convert the numeric value across to the corresponding text label.
What would be the best way to optimise the code there to not repeat so much of the category definitions etc?