Regulate fan speed based on humidity

I’m trying to regulate a fan based on the humidity in a room. I want to do this when the humidity is in a range for a certain period.

I created a template to transform the humidity percentage to a fan speed, low(33), medium(66) or high(100).

{% if states.sensor.lumi_lumi_weather_humidity.state|float > 75 %}
100
{% elif states.sensor.lumi_lumi_weather_humidity.state|float > 60 %}
66
{% else %}
33
{% endif %}

Now I just need to setup an automation that sets the fan speed based on this template with a For value of 10 minutes.

service: fan.set_percentage
data:
  percentage: | {{ trigger.to_state.state }}
  target:
    entity_id: fan.mechanical_ventilation

The problem is that I can’t use a state (because it doesn’t have a value_template) nor a template (because it needs to return a boolean result) nor a numeric (below or above are required) trigger.

I came up with a workaround by creating a template sensor and using that entity as a state trigger. This works but I don’t like it for 2 reasons:

  • Can’t create a blueprint out of it (or: it is not reusable)
  • Configuration needs to be changed to adjust the values

Question Is it possible to trigger an automation based on such a template so I can have everything inside the automation?

try:

trigger:
  - platform: state
    entity_id: sensor.lumi_lumi_weather_humidity
action:
  - service: fan.set_percentage
    data:
      percentage: >
        {% if states.sensor.lumi_lumi_weather_humidity.state|float > 75 %}
          100
        {% elif states.sensor.lumi_lumi_weather_humidity.state|float > 60 %}
          66
        {% else %} 
          33
        {% endif %}
      target:
        entity_id: fan.mechanical_ventilation

that will trigger on every state change of the humidity sensor.

then it evaluates the state of the humidity sensor and will set the speed of the fan based on that state.

That is what I started with, however this won’t work for me since I can’t set the for: property:

I only want to change the fan speed when the humidity is in a range for a certain period. (For example, adjust fan speed to when humidity is medium for 5 minutes) the last part does not work since the humidity often fluctuates.

In the meantime I decided that it needs to be a bit smarter than that, the humidity should take into consideration that the thresholds also change, it should look at the deviation from the average in the same room (over the last 24 hours or so).

So I thought about it and now I think that I want the fan to be at medium when humidity is 10% higher than it was on average over the last 24 hours, and on high when it is 20% higher. (actual numbers to be decided).

Solved it by creating a statistics sensor with max_age of 24 hours and a template sensor that converts the statistics change attribute to fan percentages. No I only have a simple automation left that triggers on the template sensor state (with a for condition) which sets the actual fan sensor.