Save sensor states for a while

I’m using this automations snippet to send a notification when the alarm is triggered:

- id: alarm_triggered_armed_home
  alias: Trigger alarm while armed home
  hide_entity: false
  initial_state: true
  trigger:
    - platform: state
      entity_id: binary_sensor.radar_east
      to: 'on'
    - platform: state
      entity_id: binary_sensor.radar_west
      to: 'on'
  condition:
    - condition: state
      entity_id: alarm_control_panel.alarm
      state: armed_home
  action:
    service: alarm_control_panel.alarm_trigger
    entity_id: alarm_control_panel.alarm

- id: send_notification_when_alarm_triggered
  alias: 'Send notification when alarm triggered'
  initial_state: true
  trigger:
    - platform: state
      entity_id: alarm_control_panel.alarm
      to: 'triggered'
  action:
    - service: camera.snapshot
      data:
        entity_id: camera.garden
        filename: '/tmp/ipcamera_snapshot.jpg'
    - service: notify.pushbullet
      data:
        title: "Alarm!"
        message: "Sensor east: {{ states.binary_sensor.radar_east.state }}, Sensor west: {{ states.binary_sensor.radar_west.state }}"
        data:
          file: '/tmp/ipcamera_snapshot.jpg'

It works but the problem is the message always reports both sensors as ‘off’. I guess this is due the delay between the trigger and the publishing of the notification: the sensor has already turned off and I cannot know which one was triggered.

Is there a way to save for a while the state, or better another approach for this use case?

In an automation’s condition and action sections there is an automatically created variable called trigger that provides information about the trigger event. Find more details here. So, e.g., you could add an action to the first automation that saves the entity_id or friendly_name of the sensor that triggered the automation into an input_text, then use the state of that input_text in the message of the second automation. Let me know if you need any more detailed suggestions.

1 Like

Got it. Thank you for the clear explanation. I will try to change the code by myself. If I will encounter some difficulties I will kindly ask you again an help.

It worked, thanks! Just a minor question: the doc page you linked doesn’t show the friendy_name as available data in trigger variable. It’s a non-documented feature or I can retrieve the entity_id only?

trigger.to_state is the entity’s state object that caused the trigger. Therefore you can get the usual information from a state object, such as trigger.to_state.attributes.friendly_name.

1 Like