Home Assistant template Weather sensor with local values

Learn how to create a custom weather station in Home Assistant that combines local sensor data with external forecasts. This guide covers setting up Python scripts, helper inputs, automations, and template sensors for accurate and comprehensive weather information.

Home Assistant template Weather sensor with local values

I have a local weather station in my Home Assistant setup that provides me with the temperature, wind speed, wind direction and finally the amount of rain. A long time ago I created a template weather sensor, which could use these specific values while pulling other values from another weather sensor. Unfortunately, I lost the forecast capabilities in the process.

This post describes how to keep the forecast capabilities.

To achieve this, we will:

  • Store the forecast of an existing weather integration, in the attributes of an entity
  • Have a python script that can help set those attributes
  • Have an automation that regularly calls the weather.get_forecasts service to pull the latest forecast and store it
  • Finally configure our template weather sensor to read the stored forecast

Step 1: Preparing the Python Script to Set Attributes

First, create a Python script that sets the state and attributes of an entity. This script will allow you to dynamically update the state and attributes of your weather entity.

# Ensure 'entity_id' is provided
if 'entity_id' not in data:
  logger.warning("===== entity_id is required if you want to set something.")
else:
  data = data.copy()
  inputEntity = data.pop('entity_id')
  inputStateObject = hass.states.get(inputEntity)
  
  # Retrieve current state and attributes of the entity
  if inputStateObject:
    inputState = inputStateObject.state
    inputAttributesObject = inputStateObject.attributes.copy()
  else:
    inputState = 'unknown'
    inputAttributesObject = {}
  
  # Update state if provided
  if 'state' in data:
    inputState = data.pop('state')
  
  logger.debug("===== new attrs: {}".format(data))
  
  # Update attributes with provided data
  inputAttributesObject.update(data)
  
  # Set the new state and attributes for the entity
  hass.states.set(inputEntity, inputState, inputAttributesObject)

Save this script in the python_scripts folder of your Home Assistant configuration directory, e.g., python_scripts/set_state.py.

As a bonus, you can now override the state and attributes of almost any entity, programatically, by calling the above python script.

Step 2: Prepare Helper Inputs to Store the Attributes

Next, create helper inputs to store the forecast attributes. These helpers will be used to store and retrieve forecast data. Open up the devices and entities page, and add the input helper. I used a text helper, but it doesn't really matter what it is, as we'll be storing data in the attributes. I called my helper input_text.weather_openweathermap_forecast.

We cannot use the state of the text helper, because it is limited to 255 characters. In testing, a typical forecast was up to 13.000 characters long.

Step 3: Prepare an Automation to Periodically Update the Forecast

Create an automation that periodically updates the forecast data in the helper inputs using the Python script.

In the below automation, I call the weather.get_forecasts service on my two weather integrations. Once to get an hourly forecast, and another to get a daily forecast. I do this because I have different views that either need hourly or daily forecasts.

It then calls the set_state script to set the two attributes: forecast_daily and forecast_hourly.

automation:
  - alias: Update Forecast Data
    trigger:
      - platform: time_pattern
        hours: "/1"  # Update every hour
    action:
      - variables:
          forecasts_hourly: null
          forecasts_daily: null
      - service: weather.get_forecasts
        target:
          entity_id: weather.openweathermap_hourly
        data:
          type: hourly
        response_variable: forecasts_hourly
      - service: weather.get_forecasts
        target:
          entity_id: weather.openweathermap_daily
        data:
          type: daily
        response_variable: forecasts_daily
      - service: python_script.set_state
        metadata: {}
        data:
          entity_id: input_text.weather_openweathermap_forecast
          forecast_daily: "{{ forecasts_daily['weather.openweathermap_daily']['forecast'] }}"
          forecast_hourly: "{{ forecasts_hourly['weather.openweathermap_hourly']['forecast'] }}"

This automation triggers every hour to fetch the latest forecast data and updates the input helpers.

Step 4: Configure the Template Sensor to Read from the Helper Attributes

Finally, configure a template sensor to read from the helper attributes and combine local sensor data with the external forecast.

weather:
  - platform: template
    unique_id: "weather.openweathermap_daily_local"
    name: "OpenWeatherMap Daily with Local Data"

    # The two forecasts I'm interested in. You could also expand to also set the `twice_daily` forecast.
    forecast_hourly_template: "{{ state_attr('input_text.weather_openweathermap_forecast', 'forecast_hourly') }}"
    forecast_daily_template: "{{ state_attr('input_text.weather_openweathermap_forecast', 'forecast_daily') }}"

    # All the other values can come from either an existing weather integration, or another sensor like your local weather station.
    # See https://www.home-assistant.io/integrations/weather.template/ for more information
    condition_template: "{{ states('weather.openweathermap_daily') }}"
    visibility_template: "{{ state_attr('weather.openweathermap_daily', 'visibility') }}"

    # In my case, I pull these values locally.
    temperature_template: "{{ states('sensor.local_temperature') | float }}"
    humidity_template: "{{ states('sensor.local_humidity') | float }}"
    pressure_template: "{{ states('sensor.local_pressure') | float }}"
    wind_speed_template: "{{ states('sensor.local_wind_speed') | float }}"
    wind_bearing_template: "{{ states('sensor.local_wind_direction') | float }}"

Replace the relevant bits in the configuration according to your local setup.

Conclusion

By following these steps, you can create a custom template weather station in Home Assistant that combines local sensor data with external forecast capabilities. This setup ensures that you have accurate, up-to-date weather information tailored to your specific location and preferences.