Help with under bed lighting automation

Hey all,

 I am trying to put together an automation with my bed occupancy sensor. I want the automation to turn on my underbed lights if I get out of bed between 8pm and 5am. I also only want the automation to fire only if I had been laying in bed for 5 minutes or more prior to getting out of bed. 

  This is the automation that I have now and it does not seem to be turning on the lights when I get out of bed after waiting 5 minutes. 
alias: Turn on under bed lights 
description: Turns on the under-bed lights if you've been in bed for 5 minutes or more and then get out of bed.
trigger:
  - platform: state
    entity_id: binary_sensor.master_bedrrom_bed_sensor_sean_seans_bed_occupied
    from: 'on'
    to: 'off'
condition:
  - condition: template
    value_template: >
      {{ as_timestamp(now()) - as_timestamp(states.binary_sensor.master_bedrrom_bed_sensor_sean_seans_bed_occupied.last_changed) > 300 }}
action:
  - service: switch.turn_on
    target:
      entity_id: switch.master_bedroom_smart_plug_switch
mode: single
  Any help would be appreciated. P.S. the bedrrom is correct.

The last_changed you are getting with your template is from the same event that triggered the automation. To get the previous value you will need to use the trigger variable’s from_state property.

alias: Turn on under bed lights 
description: Turns on the under-bed lights if you've been in bed for 5 minutes or more and then get out of bed.
trigger:
  - platform: state
    entity_id: binary_sensor.master_bedrrom_bed_sensor_sean_seans_bed_occupied
    from: 'on'
    to: 'off'
condition:
  - condition: template
    value_template: >
      {{ now() - trigger.from_state.last_changed >= timedelta(minutes=5) }}
action:
  - service: switch.turn_on
    target:
      entity_id: switch.master_bedroom_smart_plug_switch
mode: single

HA Docs - Available Trigger Data

1 Like

Thank you it worked. I was trying to figure it out and used ChatGPT to try and help and I think made me more confused and lost. Thank you.

Just FYI, it’s best to avoid ChatGPT and other bullshit engines for HA configuration and templating. They are bad at Home Assistant and usually produce configurations which contain errors that are difficult for new users to recognize because they seem plausible.