Humidity control of a bathroom fan in Home Assistant

I recently decided I wanted a Home Assistant automation to turn on the bathroom fan. I already had an ESPHome temperature/humidity sensor so it seemed simple enough - just trigger the fan when the humidity reached a certain level.

The problem was what level? Humidity in the bathroom varies with the time of year and how long the shower is on. This looked like it could become a messy automation with a lot of tweaking.

It turned out what I really wanted to trigger on was the rate of change of humidity; a spike in humidity is a good indicator the shower is on. The time window and the rate of change are the only things to tweak. Once you’re happy with that, the absolute humidity doesn’t matter.

I messed about for a while trying to calculate this, then I discovered HA already had it covered with the derivative integration. I created a sensor like this:

sensor:
- platform: derivative
  name: Bathroom humidity change
  source: sensor.bathroom_humidity
  unit_time: min
  time_window: "00:05:00"

which gives me a sensor to trigger the automation on:

- alias: "Bathroom: Turn on fan on fast change in humidity"
  trigger:
    platform: numeric_state
    entity_id: sensor.bathroom_humidity_change
    above: 2 # Over n minutes the slope went above this value
  action:
    service: switch.turn_on
    entity_id: switch.bathroom_fan

Now that it’s on, it needs to be turned off some time later. I went with the easy way out and just left it on for a set time. It could probably trigger on a negative value as the humidity decreases but I suspect that would be touchy to calibrate.

- alias: "Bathroom: Turn off fan after a while"
  trigger:
    platform: state
    entity_id: switch.bathroom_fan
    to: 'on'
    for:
      minutes: 30
  action:
    service: switch.turn_off
    entity_id: switch.bathroom_fan

Finally for tweaking, and just because I can, I added a graph to show the interaction of the humidity and the sensor:

Ian Slinger @ianjs