Trying to create a generalised light toggle script

Because light.toggle ignores color_name I can’t reset my coloured hue light with a toggle of my smart light switch. So, not wanting to produce a script for every switch, I’ve been trying to create a generalised script to do the job and am tearing my last remaining hair out. Can anyone see where I am going wrong, please. Or show me a better way !

test_toggle:
  alias: test light toggle
  sequence:
    - service: script.turn_on
      entity_id: script.light_toggle
      data:
        variables:
          lght: 'office'

light_toggle:
  alias: toggle light to white
  sequence:
    - service_template: script.light_toggle_{% if is_state("{{ 'light.' ~ lght }}" , 'off') %}on{% else %}off{% endif %}
      data_template:
        variables:
          thislight: "{{ lght }}"
      
light_toggle_on:
  alias: light_on
  sequence:
  - service: light.turn_on
    data_template:
      entity_id: "{{ 'light.' ~ thislight }}"
      color_name: white
      brightness: 255
light_toggle_off:
  alias: light_off
  sequence:
  - service: light.turn_off
    data_template:
      entity_id: "{{ 'light.' ~ thislight }}"

This works:

  test_toggle:
    alias: test light toggle
    sequence:
    - service: script.light_toggle
      data:
        name: 'office'

  light_toggle:
    alias: toggle light to white
    sequence:
    - service_template: >
        script.light_toggle_{{ 'on' if is_state('light.'~name, 'off') else 'off' }}
      data_template:
        name: '{{ name }}'
        
  light_toggle_on:
    alias: light_on
    sequence:
    - service: light.turn_on
      data_template:
        entity_id: 'light.{{ name }}'
        color_name: white
        brightness: 255

  light_toggle_off:
    alias: light_off
    sequence:
    - service: light.turn_off
      data_template:
        entity_id: 'light.{{ name }}'

If you provide the full entity_id (light.office) instead of just the entity’s name (office) then the scripts become a bit simpler:

  test_toggle:
    alias: test light toggle
    sequence:
    - service: script.light_toggle
      data:
        entity: 'light.office'

  light_toggle:
    alias: toggle light to white
    sequence:
    - service_template: >
        script.light_toggle_{{ 'on' if is_state(entity, 'off') else 'off' }}
      data_template:
        entity: '{{ entity }}'
        
  light_toggle_on:
    alias: light_on
    sequence:
    - service: light.turn_on
      data_template:
        entity_id: '{{ entity }}'
        color_name: white
        brightness: 255

  light_toggle_off:
    alias: light_off
    sequence:
    - service: light.turn_off
      data_template:
        entity_id: '{{ entity }}'
2 Likes

Thanks so much. More script language syntax learned as well.!

1 Like