Automation to retrieve and Publish hourly weather

Hey all, I was looking for ages but wasn’t able to find a concise answer to extracting (and publishing) the hourly weather.

This small automation will use the service as described here:

- id: forward_hourly_weather
  alias: "Forward Hourly Weather to MQTT"
  trigger:
    - platform: time_pattern
      # You can also match on interval. This will match every 5 minutes
      minutes: "/5"
  action:
    - service: weather.get_forecasts
      target:
        entity_id: weather.forecast_home
      data:
        type: hourly
      response_variable: my_hourly_forecast
    - delay: '00:00:05'  # Adjust the delay as needed to give the service call time to complete
    - service: mqtt.publish
      data_template:
        topic: home/weather_hourly/set
        payload: >-
          {
            {% for forecasts in my_hourly_forecast['weather.forecast_home'].forecast %}
              {{ forecasts.datetime}} : {{ forecasts.condition}} :  {{ forecasts.precipitation}}
            {% endfor %}
          }

The part I struggled with was what to do with the “response_variable”.
This simply iterates throught it and extracts the datetime, condition and precipitation.

You can add others as you need.
I hope this helps someone.

This is nice.
I don’t see anything exactly like this in the Blueprints exchange.
I think it would be awesome for the community and for yourself if you converted this into a blueprint to share.

I’ll be glad to help any way I can.

If it’s an hourly forecast, why is the Time Pattern Trigger set to publish it every 5 minutes?

Is delay: '00:00:05' necessary? Because there are many examples employing weather.get_forecasts, even in a Trigger-based Template Sensor, and none intentionally pause after executing the service call.

1 Like

FYI: Meteorologisk institutt (Met.no) - Home Assistant Gives you daily and hourly forecasts as well.

image

image

image

That’s a great idea, I would be glad to give it a try.

@123 I don’t think it’s necessary, I just wasn’t sure if the service needs a certain time to respond before blasting the values out.

@Coolie1101

Yeah, the thing is that you can’t simply use the service, if you put the forecast into the states you only see the Daily forecast, to get the hourly you have to use the service, then use some template trickery to “exctract” the value from the returned varaible.

I have also extended it to now send daily notifications at 07:00 (a request by my wife as she often forgets her umbrella); see code below:

It sends one notification to my phone and the other to our telegram home group.

This is the thing, it needs so much “templaterly” to extract the data in a meaningful way, or maybe I’m just not skilled enough :slight_smile:

- id: rain_notification
  alias: "Rain notification for the day"
  trigger:
    - platform: time
      at: '07:00:00'
  action:
    - service: weather.get_forecasts
      target:
        entity_id: weather.forecast_home
      data:
        type: hourly
      response_variable: my_hourly_forecast
    - service: notify.mobile_app_pixel_7_pro
      data_template:
        message: >    
          {% set rain_forecast = namespace(times=[]) %}
          {% for forecasts in my_hourly_forecast['weather.forecast_home'].forecast %}
            {% if 'rainy' in forecasts.condition.lower() %}
              {% set forecast_time = forecasts.datetime | as_datetime %}
              {% if forecast_time.hour >= 7 and forecast_time.hour < 22 %}
                {% set rain_forecast.times = rain_forecast.times + [forecasts.datetime | regex_replace('T', ' ') | regex_replace('\+\d{2}:\d{2}', '') | regex_replace(':\d{2}$', '')] %}
              {% endif %}
            {% endif %}
          {% endfor %}

          {% if rain_forecast.times %}
            Rain is expected at the following times:\n{{ rain_forecast.times | join('\n') }}\nDon't forget your umbrella!
          {% else %}
            No rain in the forecast. Enjoy your day!
          {% endif %}
        title: "Hourly Forecast Notification"
        data:
          persistent: true  
    - service: notify.telagram_notifier
      data_template:
        message: >    
          {% set rain_forecast = namespace(times=[]) %}
          {% for forecasts in my_hourly_forecast['weather.forecast_home'].forecast %}
            {% if 'rainy' in forecasts.condition.lower() %}
              {% set forecast_time = forecasts.datetime | as_datetime %}
              {% if forecast_time.hour >= 7 and forecast_time.hour < 22 %}
                {% set rain_forecast.times = rain_forecast.times + [forecasts.datetime | regex_replace('T', ' ') | regex_replace('\+\d{2}:\d{2}', '') | regex_replace(':\d{2}$', '')] %}
              {% endif %}
            {% endif %}
          {% endfor %}

          {% if rain_forecast.times %}
            Rain is expected at the following times: 
            {{ rain_forecast.times | join('\n') }} 
            Don't forget your umbrella!
          {% else %}
            No rain in the forecast. Enjoy your day!
          {% endif %}
        title: "Rain Forecast"

Templated script variables can help to reduce duplication and improve legibility.

- id: rain_notification
  alias: "Rain notification for the day"
  trigger:
    - platform: time
      at: '07:00:00'
  action:
    - service: weather.get_forecasts
      target:
        entity_id: weather.forecast_home
      data:
        type: hourly
      response_variable: my_hourly_forecast

    - variables:
        rainy_times: >
          {{ my_hourly_forecast['weather.forecast_home'].forecast
            | selectattr('condition', 'eq', 'rainy') 
            | map(attribute='datetime') | map('as_datetime')
            | select('ge', today_at('07:00'))
            | select('lt', today_at('22:00'))
            | map('as_timestamp') | map('timestamp_custom', '%H:%M')
            | list }}
        rain_msg:
          - "Rain is expected at the following times: "
          - "{{ rainy_times | join('\n') }}"
          - "Don't forget your umbrella!"
        no_rain_msg: "No rain in the forecast. Enjoy your day!"
        msg: "{{ rain_msg | join('\n') if rainy_times else no_rain_msg }}"

    - service: notify.mobile_app_pixel_7_pro
      data_template:
        message: '{{ msg }}'
        title: "Hourly Forecast Notification"
        data:
          persistent: true 

    - service: notify.telagram_notifier
      data_template:
        message: '{{ msg }}'
        title: "Rain Forecast"

NOTES

Let me know if the newlines in the messages are correctly passed to the two notifiers (I don’t have a means of testing it).


BTW, is telagram the actual spelling in your system or is that a typo (and should be telegram)?

Sheesh, well done, this works wonders. I have replaced the original one with this version. Thanks so much.

I have no rain coming up, so I can’t see if the adding of multiple times will work or not, I’ll report back as soon as I have some rainy times.

Sadly, it was the name of my notifier an I never noticed, I’ve now renamed it everywhere and fixed it, thanks for spotting :slight_smile:

For testing purposes, you can temporarily change rainy to sunny (or whatever is your current weather condition) just to confirm the message’s appearance is correct.

Or just plan an outdoor activity and then the weather is sure to become rainy. :wink:

Great idea :wink:

It works fine (I changed it to ‘sunny’), thanks again:

image

You’re welcome and glad to hear the message is displayed correctly.

Please consider marking my post above with the Solution tag. It will automatically place a checkmark next to the topic’s title and place a link in the first post that leads to the Solution. This helps other users find answers to similar questions.

For more information about the Solution tag, refer to guideline 21 in the FAQ.