Scripting: How do I return a device to a previous state?

Here is my use case:

  1. I have a light that is at current state of (ON or OFF)
  2. Some trigger/condition happens
  3. That light flashes
  4. Light should return to original state

I don’t see any function or a way to store the current state in the script. How can I accomplish this? Ideally without external scripting.

You can do this with Appdaemon if you want to go that route. A less-flexible way that I did things in YAML is described here:

I use a boolean to remember the dim state (or off).

Storing it another object is an interesting idea. Thanks.

1 Like

I went the appdaemon route. Appreciate any feedback or test results.

I wrote this as generic as I could, so it can be used with most entity types.

  • Fire an event called “staterestore”
  • entity_id is required for all invocations
  • An event call with solely entity_id will restore the original state
  • You must include state “on” or “off” for non restore invocations
  • Other event_data will be provisioned to the device and the original attributes stored
  • On restore the original attributes and state will be provisioned
  • A listener is added to the invoked entity_id and on change will clear the stored attributes
  • (Script turns light off, someone turns it on, on script’s restore it will stay on)

AppDaemon Setup

staterestore:
  module: staterestore
  class: StateRestore

Sample Usage

testrestore:
  alias: Test Restore
  sequence:
  - event: staterestore
    event_data:
      brightness: 50
      entity_id: light.light01
      state: on
      white_value: 0
      rgb_color:
      - 22
      - 165
      - 0
testrestorereturn:
  alias: Test Restore Return
  sequence:
  - event: staterestore
    event_data:
      entity_id: light.light01

Nice solution, something lke thisshould part of the standard featureset!

If I understand this correctly it requires all light.turn_xxx actions to be replace by staterestore, where you store (cache) the attributes so they can be reapplied when needed.

For some situations it would be nice not to rely on a cached value but to get/retrieve the atributes from the actual light and store it in your component. That will make automations foulproof; like

Store light attributes entity_id: light.light01
do something with light.light01(eg flash or set brightness)
restore light attributes entity_id: light.light01

The solution does that. It copies the current attributes of the device and stores it. When you call restore, the cache values are enacted. So the flow is like this:

Capture current state
store it
push state from script invocation
....
Call Restore
if the state hasn't changed then apply cached values from initial contact
if it has changed, do nothing.

Hey guys… how would I go about installing this script? I assume it’s a python_script… so you set it up via https://www.home-assistant.io/components/python_script/?

1 Like