Thermostat Automation with pre-saved variable

Hi,

I do have two automation for my thermostat which the first one turns off the thermostat when no one is at home and the second one turn it back on when someone is back at home. my problem is I want to get the latest hvac_mode saved into a variable when turning off the thermostat and call it back when I need to turn back the thermostat. I created below automation and a sensor to keep the last operation mode but it doesn’t work. could anyone help me with this please?

sensors.yaml

thermostat_mode:
        friendly_name: "Thermostat Operation Mode"
        value_template: >-
          {% if is_state('climate.thermostat', 'heat') %}
            heat
          {% elif is_state('climate.thermostat', 'cool') %}
            cool
          {% endif %}

automation.yaml

- id: '1561438325619'
  alias: Thermostat Away Mode
  trigger:
  - entity_id: group.all_devices
    from: home
    platform: state
  condition: []
  action:
  - data:
      entity_id: climate.thermostat
    service: climate.turn_off


- id: '1561589408139'
  alias: Thermostat Home Mode
  trigger:
  - entity_id: group.all_devices
    platform: state
    to: home
  condition: []
  action:
  - data_template:
      hvac_mode: '{{states.sensor.thermostat_mode.state}}'
    entity_id: climate.thermostat
    service: climate.set_hvac_mode

in my sensor I’m trying to just keep cool or heat and not other modes like off but when I turn off the thermostat my sensor value will be empty and when thermostat is on it’s either cool or heat.
I’m not sure why the sensor value becomes empty when I do have 2 ifs to only change the value between cool and heat. in fact my first automation is ruining my sensor value but second automation works fine. What should I do on my sensor template to prevent that?

Because when climate.thermostat updates sensor.thermostat_mode will be as well. It will evaluate the value_template, which will return nothing (effectively an empty string) and that will be used to set the state.

Try this:

thermostat_mode:
        friendly_name: "Thermostat Operation Mode"
        value_template: >-
          {% if is_state('climate.thermostat', 'heat') %}
            heat
          {% elif is_state('climate.thermostat', 'cool') %}
            cool
          {% else %}
            {{ states('sensor.thermostat_mode') }}
          {% endif %}

If climate.thermostat changes to something other than heat or cool, then it will set sensor.thermostat_mode to it’s current state.

1 Like

It worked, Thank you

1 Like