script:
  - id: fan_control_power
    then:
      - lambda: |-
          // Normal On:
          // switch fan on when either temperature or humidity is above "max", unless humidity/temperature is below "min"
          if (
            !id(fan_speed).state &&
            (
              (id(bme280_temperature).state >= atoi(id(temperature_max).state.c_str()) && id(bme280_humidity).state    >= atoi(id(humidity_min).state.c_str())) ||
              (id(bme280_humidity).state    >= atoi(id(humidity_max).state.c_str())    && id(bme280_temperature).state >= atoi(id(temperature_min).state.c_str()))
            )
          ) {
            ESP_LOGI("fan", "Fan On");
            auto call = id(fan_speed).turn_on();
            call.perform();
          }

          // Forced Off, ignoring Hysteresis:
          // switch fan off when either temperature or humidity are below "min", unless humidity/temperature is above "max"
          else if (
            id(fan_speed).state &&
            (
              (id(bme280_temperature).state <= atoi(id(temperature_min).state.c_str()) && id(bme280_humidity).state    <= atoi(id(humidity_max).state.c_str())) ||
              (id(bme280_humidity).state    <= atoi(id(humidity_min).state.c_str())    && id(bme280_temperature).state <= atoi(id(temperature_max).state.c_str()))
            )
          ) {
            ESP_LOGI("fan", "Fan Off (forced)");
            auto call = id(fan_speed).turn_off();
            call.perform();
          }

          // Normal Off, respecting Hysteresis:
          // switch fan off when both temperature and humidity are below "max minus hysteresis"
          else if (
            id(fan_speed).state &&
            (
              id(bme280_temperature).state <= atoi(id(temperature_max).state.c_str()) - atoi(id(temperature_hysteresis).state.c_str()) && 
              id(bme280_humidity).state    <= atoi(id(humidity_max).state.c_str())    - atoi(id(humidity_hysteresis).state.c_str())
            )
          ) {
            ESP_LOGI("fan", "Fan Off");
            auto call = id(fan_speed).turn_off();
            call.perform();
          }