Saving status in an automation

I wrote an automation that turns a lamp in my living room on and sets its color to red if a gate to my backyard is left open for more than 30 seconds.

When the gate closes I want to set the lamp back to its original state before the automation was triggered. How do I save the on or off state at the start and restore it later?

If I posted this in the wrong place, please let me know where it should have gone. TIA

You can use the scene.create service to save the light’s state. Here is an example using this technique with a climate device. Post your automation and we can point you in the direction of how to set it up for your devices and situation.

Thank you @Didgeridrew - that works great.

I added a service scene.create with a snapshot_entities: light.living_room_lamp to save the state

And at the end a scene.turn_on to restore the lamp’s original state before the automation.

alias: Gate left open monitor
description: ""
trigger:
  - type: opened
    platform: device
    device_id: 5a4a79ff69b6fddb5de5d15bde4af201
    entity_id: binary_sensor.lumi_lumi_sensor_magnet_aq2_opening_2
    domain: binary_sensor
    for:
      hours: 0
      minutes: 1
      seconds: 0
condition: []
action:
  - service: notify.mobile_app_victors_phone
    data:
      message: "Gate has been left open "
  - service: scene.create
    data:
      scene_id: save_living_room_lamp_state
      snapshot_entities: light.living_room_lamp
  - service: light.turn_on
    data:
      rgb_color:
        - 255
        - 0
        - 0
    target:
      device_id: 03a2459eae6e2fc26c8f086c0959f6b6
  - delay:
      hours: 0
      minutes: 2
      seconds: 0
      milliseconds: 0
  - service: light.turn_on
    data:
      color_temp: 361
    target:
      device_id: 03a2459eae6e2fc26c8f086c0959f6b6
    enabled: false
  - service: scene.turn_on
    data: {}
    target:
      entity_id: scene.save_living_room_lamp_state
mode: single