Better way to write this template sensor?

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?

You sound like someone who might want to vote for this Feature Request:

If Template Variables were available, you could create a pvar template variable that could be referenced by all the templates in your Template Sensor’s state and all its attributes.

Yup, voted.

The code I posted works, but it’s so messy and repetitive I thought there has to be a better way of doing it than my basic learner attempt there…

Isn’t Tomorrow.io just the new name for Climacell ? There’s an integration for Climacell, is that using the same data ? I’m using it and it now includes pollen info (today only, no forecast)

It is, but I was aiming to include the forecast elements as well.

Ah ok, I’m also using just the tomorrow.io pollen forecast and Climacell for the weather

Thanks for the thought and input though.

As I said originally, the code and sensor set-up works, it just looks very unoptimised and repetitive. I was always taught if you’re writing the same stuff multiple times, you’re doing it wrong…

But I guess there isn’t any better way of doing it at the moment, at least without the template variables that the feature request is about. So hopefully that can be introduced at some point in the near future and I can clean things up by only defining the variables once rather than 5 times per sensor.

Coming to this thread way late. Sorry to bump but it sounds like we’re pursuing the same goals:

Good News: The official ClimaCell Integration now includes both (i) more current condition attributes in the weather entity; and (ii) the integration adds a number of additional sensors (disabled by default) to provide easier access to those sensors. Bottomline: Current Conditions are now a breeze. Either they have a sensor assigned or the sensor you need can be broken out with a simple template:

state: "{{ (state_attr('weather.climacell_nowcast', 'temperature')) }}"

Bad News: Forecast information still seems difficult (i.e. beyond my skill) to access via the ClimaCell Integration. While we are given three weather entities (nowcast, daily, and hourly), each with piles of forecast data embedded in them, I can’t figure out how to get them out with a template.

My Current Problem:

Moving over from DarkSky, I need to extract a ClimaCell precipitation forecast for (i) today; and (ii) tomorrow for my lawn irrigation automation.

Any ideas? The integration’s entity is: weather.climacell_daily. Here’s the layout for the entity through the current day and tomorrow. I need to create four sensors (the two precip amounts and the two precip probabilities).

Any ideas?

temperature: 81
humidity: 50
ozone: 61.69
pressure: 29.89
wind_bearing: 22.13
wind_speed: 3.09
visibility: 9.94
attribution: Powered by ClimaCell
forecast: 
- datetime: '2021-09-06T10:00:00+00:00'
  condition: cloudy
  precipitation: 0
  precipitation_probability: 0
  temperature: 87
  templow: 64
  wind_bearing: 167.98
  wind_speed: 4.43
- datetime: '2021-09-07T10:00:00+00:00'
  condition: cloudy
  precipitation: 0.0288
  precipitation_probability: 5
  temperature: 90
  templow: 66
  wind_bearing: 129.61
  wind_speed: 9.04

Suppose you want to extract today’s precipitation-
{{ state_attr('weather.climacell_daily', 'forecast')[0].precipitation }}

…and for tomorrow’s-
{{ state_attr('weather.climacell_daily', 'forecast')[1].precipitation }}

Try pasting the above code in Developer Tools —> Template. Check if you got the correct result.

1 Like

Well, I’ll be darned. That was not even close to what I was trying. Thank you! It worked perfectly.

Question: What documentation would you recommend for me to have figured this out on my own? I came up empty inside HA’s documentation and was struggling to find what I needed with the jinja website.

This video maybe worth watching to expand your knowledge regarding template.