Error when turning on lights after TV is switched off

Hi
I have some code that has served me well for many years, but it has creating an error when the some cases.

It’s a simple two-automation function.
One automation that turns off the light when the TV is turned on, and stores in a boolean if the light was on or off.

The other is turning on the light again when the TV is turned of,f based on the boolean value that was stored.

It has one problem, though: if the light was unavailable when the boolean was stored, this code will not work since the complete string will be: light.turn_unavailible light.light_1

- alias: Turn off lights for TV session
  triggers:
  - trigger: state
    entity_id: media_player.lg_webos_tv
    to: 'on'
  actions:
  - action: input_boolean.turn_{{ states('light.light_1') }}
    entity_id: input_boolean.light_memory
  - action: light.turn_off
    target:
      entity_id: light.light_1

- alias: Turn on light after TV session
  triggers:
  - trigger: state
    entity_id: media_player.lg_webos_tv
    to: 'off'
  actions:
  - action: light.turn_{{ states('input_boolean.light_memory') }}
    target:
      entity_id: light.light_1

Any ideas to make this code better?

I’d have to test, but can you use

action: input_boolean.turn_{{'on' if is_state('light.light_1', 'on') else 'off'}}

Edit: Initial tests worked

Thanks for your suggestion.
Hmm… don’t you mean:

action: light.turn_{{'on' if is_state('light.light_1', 'on') else 'off'}}

My example was based off the code you posted and can be applied to both actions.

The point I was making was the template code can be adjusted to eliminate the unavailable state.

Ahh… I see : )

Me ← stupid

Thanks again

1 Like

If you can, please take the time to mark my previous post as the Solution.

That ensures this thread is closed out and more importantly, useful to other users who encounter similar issues.

Seems like you have created a manual scene.
Scene create and scene turn on seems like a more reliable method.

Agreed, or a conditional Automation.