Fan Speed Automation based on Temperature and Humidity

Hello,

I’m trying to build a Fan Automation based on Temperature and Humidity with a custom formula within ESPHome.

I’ve played around a bit with templates and it kinda works, but it doesn’t feel right:

text_sensor:
  - platform: template
    name: "Fan Test"
    id: fan_test
    update_interval: 5s
    lambda: |-
      if(id(hum).state < 35 && id(temp).state < 25) {
        return {"OFF"};
      } else if(id(hum).state < 40) {
        return {"LOW"};
      } else {
        return {"HIGH"};
      }
    on_value:
      then:
        lambda: |-
          if(x == "LOW") {
            id(fan_).turn_on().set_speed(FAN_SPEED_LOW).perform();
          } else if(x == "HIGH") {
            id(fan_).turn_on().set_speed(FAN_SPEED_HIGH).perform();
          } else {
            id(fan_).turn_off().perform();
          }

(the formula is just for testing the code)

The function calls to turn on / off and set speed look strange, but it seems right according to the c++ source code: https://github.com/esphome/esphome/blob/ab48e4a466d907a5d466fe0859b57159524732d6/esphome/components/fan/fan_state.cpp

And it seems a bit cumbersome to first return OFF / LOW / HIGH strings, and afterwards use these strings to trigger the according action.

Is this the right way to do it, or is there a better or simpler way to get this working?

(Basically I want a thermostat for temperature and humidity, which then controls a fan with multiple speeds)

Thanks in advance!

Could you use a climate control with a template (which takes into account humidity) for temperature?

I guess yes (?). But would that make things simpler?
Or maybe I didn’t understand what tried to tell me.