If statement in automation to determine triggers "for:" time

that would be something like this:

   - alias: 'Bathroom lights off when no motion'
     id: 'Bathroom lights off when no motion'
     initial_state: 'on'
     trigger:
       platform: state
       entity_id: sensor.bathroom_motion_sensor
     condition:
       condition: time
       after: '07:00:00'
       before: '00:00:00'
     action:
       service_template: >
         script.turn_{{ 'on' if is_state('sensor.bathroom_motion_sensor',’off’) else 'off' }}
         entity_id: script.switch_off_lights_delay

and have the delay set based on the humidity in the script.

script:

switch_off_lights_delay:
  alias: Switch off lights with delay
  sequence:
    - delay:
        minutes: >
          {{ '15' if states('sensor.zha_01ddaf89_1_1029' ) | int >= 50 else '5' }}
    - service: light.turn_off
      entity_id: light.bathroom

but you made me remind me of one thing, and it is important: If you want to control the action from HA, you must select ‘do nothing’ in the Hue App Accessory configuration.

Or, and that would be even cooler…
have it switch off by default after 15 minutes (the long wait time in your template) and set the automation template only to use hum<35 to switch of earlier in case of no motion.

That way you would combine both devices smartly :wink:

If not, and you want to keep it all in HA, the automation and script would work just as fine

1 Like

That is actually one solution to use also Hue since I do own the gateway. I’d prefer not to use Hue app but that makes it simpler.

I’m having difficulties understanding how the action part works on that code. I understand that it either gets script.turn_on or script.turn_off but do I create both of those scripts to scripts.yaml and then script.turn_on_lights_delay.

Sorry for maybe stupid question but I have not been playing with scripts in HA…

no these are service calls, calling the entity_id of the dedicated script. Ive added an example, which is as short as possible.

this script is turned on if motion is Off and sets the timer delay depending on the humidity. Whenever motion has been detected, it will be switched Off again by the automation, to prevent the lights from being switched off.
If motion is detected again, again the script will be triggered. etc etc

I see the confusion… sorry for that, renamed to switch_off_lights_delay in post above to make it clearer…

above is the setup fully relying on HA (and needs the action in the accessory configuration of the App to be : do nothing.

Just for illustrative purposes, if you wanted to use switch off in the App, set that to do so after 30 minutes by default, and change the automation to act in case of the exception, hum<50:

   - alias: 'Bathroom lights off when no motion'
     id: 'Bathroom lights off when no motion'
     initial_state: 'on'
     trigger:
       - platform: state
         entity_id: sensor.bathroom_motion_sensor
     condition:
       - condition: time
         after: '07:00:00'
         before: '00:00:00'
       - condition: template
         value_template: >
           {{ states('sensor.zha_01ddaf89_1_1029' ) | int < 50 }}
     action:
       service_template: >
         script.turn_{{ 'on' if is_state('sensor.bathroom_motion_sensor',’off’) else 'off' }}
       entity_id: script.switch_off_lights_delay

and have the script only switch_off after 5 minutes:

switch_off_lights_delay:
  alias: Switch off lights with delay
  sequence:
    - delay:
        minutes: 5
    - service: light.turn_off
      entity_id: light.bathroom
1 Like

These are really helpful! I will try them when I get home and will report back :slight_smile:
Thank you!

Tested the code and it looks like this now.

in automations

- alias: 'Bathroom lights off when no motion'
  id: 'Bathroom lights off when no motion'
  initial_state: 'on'
  trigger:
    platform: state
    entity_id: sensor.bathroom_motion_sensor
  condition:
    condition: time
    after: '07:00:00'
    before: '00:00:00'
  action:
    service_template: >
      script.turn_{{ 'on' if is_state('sensor.bathroom_motion_sensor','off') else 'off' }}
      entity_id: script.switch_off_lights_delay

and in scripts

switch_off_lights_delay:
  alias: Switch off lights with delay
  sequence:
    - delay:
        minutes: >
          {{ '2' if states('sensor.zha_01ddaf89_1_1029' ) | int >= 50 else '1' }}
    - service: light.turn_off
      entity_id: light.bathroom

automation triggers but nothing happens to the light because the script does not trigger.

Edit:
If I had script.turn_on in the automation it did trigger the script and lights turned off after right time. If I put the code like it is now I get this error in logs:
Template rendered invalid service: script.turn_on entity_id: script.switch_off_lights_delay
Eventhough the script is working

cool, so that means we are ok up to and including the delay!
now about the service_template: somehow the dev-service page also reacts differently with scripts. See for your self: if you select automation.turn_on in the service, the bar below, all available automations are in the dropdown.
If you select script.turn_on in the service (which should imply this to be a valid service) there are no scripts available in the dropdown. When you put {"entity_id":"script.switch_off_lights_delay"} and hit enter, i think it will work. Could you please check that?

If so, we only have to adjust the syntax, and we’re ready to go. Maybe @pnbruckner and @petro can help here please?.
I know we can call a script directly using

service: script.switch_off_lights_delay

but have to have an extra look how we can do that in a service_template, where the else part does have to be script.turn_off and use entity_id: script.switch_off_lights_delay

if it really can’t be done, we must use this solution:

change the service_template in the automation to:

action:
  service_template: >
    {% if is_state('sensor.bathroom_motion_sensor','off') %} script.delay_script_on
    {% else %} script.delay_script_off
    {% endif %}

and have these 2 scripts:

script:
  delay_script_on:
    alias: Delay script on
    sequence:
      - delay:
          minutes: >
            {{ '2' if states('sensor.zha_01ddaf89_1_1029' ) | int >= 50 else '1' }}
      - service: light.turn_off
        entity_id: light.bathroom

  delay_script_off:
    alias: Delay script off
    sequence:
      service: script.turn_off
      entity_id: script.delay_script_on
1 Like

just to be sure: where and when do you get his error? Is it after a restart and when actually running the automation? Or is it in the HA automation editor. If the latter, that might be an unsupported but still valid. There are more cases in the forum here where the editor complains, but automations still run fine.
If the former, and actual running of the automation causes issues, we have to test the setup I made in the post above.

I saw it when I tested it in production. So the code was in automation and in scripts and I triggered by walking under the physical motion sensor. And the error was in actual HA logs that you can see when you click the icon in HA GUI. Can’t remember what it looked like since not at home but it is in the same row as the template tester thing.

ok cool, so a true error :wink:
please test my secondary setup, with the 2 separate scripts for on an off

I will when I get home :slight_smile: Thanks.

right, please do. Thing is, Ive just tested the same setup, with a few adjusted entities in my HA instance, and the original script/automation set works as expected, and no errors arise…

17

Did have to make 1 extra service call, which I had expected tbh. We have to cancel the script first, before we call it again in the automation. This is to prevent calling an already running script, in the case of turn_on.

What I did notice when copying from the community here, is sometimes incorrect quotes are used. These quotes pass the config checker, but don’t pass the real life situation. And have unrelated errors in the logs, causing one to search in the wrong direction…
So always check all quotes extra before hating restart.

this is what I just tested:

script:
  switch_off_lights_delay:
    alias: Switch off lights with delay
    sequence:
      - delay:
          minutes: >
            {{ '1' if states('input_number.presence_timer' ) | int >= 150 else '2' }}
      - service: light.turn_off
        entity_id: light.living

and automation:

  - alias: 'Living lights off when no motion'
    id: 'Living lights off when no motion'
    initial_state: 'on'
    trigger:
      platform: state
      entity_id: binary_sensor.auditorium_motion_sensor
    condition: []
    action:
      - service: script.turn_off
        entity_id: script.switch_off_lights_delay
      - service_template: >
          script.turn_{{ 'on' if is_state('binary_sensor.auditorium_motion_sensor','off') else 'off' }}
        entity_id: script.switch_off_lights_delay

tested the various timings with the input_numner and the correct change in switch_off delay.
also tested movement during the delay, causing restart of the automation, script and timing again.

so for now, this minimal setup has your desired effect.

there’s one thing you need to consider still:
what will happen when the humidity changes to below/above the threshold during the delay.
Right now, humidity isn’t a trigger for the automation, and I think that is correct. One could argue an extra numeric trigger for humidity with a below, or above setting, depending on the rest of the automation.
This would however complicate things considerably, so Id suggest you see first how you fare with the current combination, and come back with results, and see if a further adjustment would be desired.

Also, set the Hue app accessory details to a correct level of movement and light sensitivity. We can program everything you want in HA, but if the App sets the motion sensor to insensitive, it won’t ever trigger …:wink:

check this, it might save you lot of headaches (see overrides part)

wow, that’s a nice package, thanks for posting! never saw it before, so will study with much interest.

for the current topic, this still might be overkill, and way more complex than 1 small automation and accompanying script. But it sure could be very interesting if it would cover the whole Home :wink:

Never gotten around to Appdeamon myself, but since this seems to be a complete component, it might be easier on the learning curve…

me neither, but it was trasformed to a custom_compopnent, so now its way easier

check my config

lithingsm:
      guest_room: 
        sensor: binary_sensor.pir_guest_room
        entity: light.standing_lamp
        service_data:
          brightness: 255
        start_time: '18:00:00'
        end_time: '07:00:00'
        delay: 120
        sensor_type_duration: True
        overrides:
          - media_player.denon_receiver
          - binary_sensor.auto_lights_override
          - binary_sensor.guest_room_lights_override


    binary_sensor:
      - platform: template
        sensors: 
          guest_room_lights_override:
            value_template: '{% if is_state("binary_sensor.pir_guest_room", "on") and states("sensor.illumination_guest_room")|float < 8 %} off {% else %} on {% endif %}'
            device_class: motion        
            friendly_name: Not motion-low light guest room
     - platform: template
        sensors: 
          auto_lights_override:
            friendly_name: 'Auto Lights Override'
            value_template: >-
              {{  not ( ( state_attr('sun.sun','elevation')|int < 5  or ( state_attr('sun.sun','elevation')|int < 15 and states('sensor.dark_sky_cloud_coverage')|int > 90 ) )         
            }}

I will! cool.
A quick glance though shows the value_template in your overrides, that resemble the beginning of this thread though… It’s always the finetuning when automatic takeover causes us to be bothered by exceptions :wink:

to finalyze this thread, thanks to the OP @Jonde :+1: I now have this little but effective combination added to my setup, which will easily be translated to a broader set of lighting scene in my use-case:

automation:
  - alias: 'Living lights off when no motion'
    id: 'Living lights off when no motion'
#    initial_state: 'on'  #use restore state for this
    trigger:
      platform: state
      entity_id: binary_sensor.auditorium_motion_sensor #use the new Hue CC creating binary_sensors for the motion_sensor
    condition: [] # took these out since I don't need that
    action:
      - service: script.turn_off
        entity_id: script.switch_off_lights_delay
      - condition: template
        value_template: >
          {{ is_state('binary_sensor.auditorium_motion_sensor', 'off') }} #need only to check for state 'off' now
      - service: script.switch_off_lights_delay 

and script:

  switch_off_lights_delay:
    alias: Switch off lights with delay
    sequence:
      - delay:
          minutes: >
            {{ states('input_number.lighting_timer' )|int }}  # I use another template, but that is of no importance, as long as the templates evaluates to a correct number ;-)
      - service: light.turn_off
        entity_id: light.living # further development can use variables here, to make it more generic and re-usable with other lights and scenarios 

this is new:

input_number:
  lighting_timer:
    name: Lighting timer
    icon: mdi:timer
    initial: 20
    min: 0
    max: 60
    step: 10

and getting back to the OP’s needs, this should do it:

automation:

- alias: 'Bathroom lights off when no motion'
  id: 'Bathroom lights off when no motion'
  initial_state: 'on'
  trigger:
    platform: state
    entity_id: sensor.bathroom_motion_sensor
  condition:
    condition: time
    after: '07:00:00'
    before: '00:00:00'
  action:
    - service: script.turn_off
      entity_id: script.switch_off_lights_delay
    - condition: template
      value_template: >
        {{ is_state('sensor.bathroom_motion_sensor', 'off') }}
    - service: script.switch_off_lights_delay

script:

switch_off_lights_delay:
  alias: Switch off lights with delay
  sequence:
    - delay:
        minutes: >
          {{ '2' if states('sensor.zha_01ddaf89_1_1029' ) | int >= 50 else '1' }}
    - service: light.turn_off
      entity_id: light.bathroom

__EDIT__UPDATE

since this automation is now working very promptly, I can see it being triggered to run the script more often than motion explains. And I should have anticipated that… sorry.
triggers with platform state trigger in each change in the state, not necessarily the state.state, but also the attributes changes. Since this is a motion_sensor with many attributes that change constantly:

39

we need to narrow down the triggering to only trigger on to: 'on' and to: 'off'

Ive changed the automation accordingly, adding also an extra condition that seems superflous but ensures for 100% the action won’t take place if condition isn’t met:

  - alias: 'Living lights off when no motion'
    id: 'Living lights off when no motion'
#    initial_state: 'on'
    trigger:
     - platform: state
       entity_id: binary_sensor.auditorium_motion_sensor
       to: 'on'
     - platform: state
       entity_id: binary_sensor.auditorium_motion_sensor
       to: 'off'
    condition:
      condition: template
      value_template: >
        {{ trigger.to_state.state in ['on','off'] }}
    action:
      - service: script.turn_off
        entity_id: script.switch_off_lights_delay
      - condition: template
        value_template: >
          {{ is_state('binary_sensor.auditorium_motion_sensor', 'off') }}
#          {{ trigger.to_state.state == 'off' }}
      - service: script.switch_off_lights_delay

I would ultimately use the {{ trigger.to_state.state == 'off' }} condition, but somehow this doesn’t pass, I don’t understand why just yet, because I use that in many automation elsewhere in the setup…

There’s so much info here, can you give me a rundown?

cool, main point is still here: Why won't this trigger.to_state.state evaluate correctly?

Yet another problem. I copied your code and made sure all the quotes are OK and so on. Automation triggers, script triggers but I get this in HA logs and the light won’t turn off.

Error doing job: Task exception was never retrieved

Traceback (most recent call last):
  File "/usr/local/lib/python3.6/site-packages/homeassistant/components/automation/__init__.py", line 294, in async_trigger
    await self._async_action(self.entity_id, variables, context)
  File "/usr/local/lib/python3.6/site-packages/homeassistant/components/automation/__init__.py", line 378, in action
    await script_obj.async_run(variables, context)
  File "/usr/local/lib/python3.6/site-packages/homeassistant/helpers/script.py", line 130, in async_run
    await self._handle_action(action, variables, context)
  File "/usr/local/lib/python3.6/site-packages/homeassistant/helpers/script.py", line 172, in _handle_action
    action, variables, context)
  File "/usr/local/lib/python3.6/site-packages/homeassistant/helpers/script.py", line 261, in _async_call_service
    context=context
  File "/usr/local/lib/python3.6/site-packages/homeassistant/helpers/service.py", line 81, in async_call_from_config
    domain, service_name, service_data, blocking=blocking, context=context)
  File "/usr/local/lib/python3.6/site-packages/homeassistant/core.py", line 1121, in async_call
    self._execute_service(handler, service_call))
  File "/usr/local/lib/python3.6/site-packages/homeassistant/core.py", line 1143, in _execute_service
    await handler.func(service_call)
  File "/usr/local/lib/python3.6/site-packages/homeassistant/components/script.py", line 94, in turn_off_service
    in component.async_extract_from_service(service)], loop=hass.loop)
  File "/usr/local/lib/python3.6/asyncio/tasks.py", line 304, in wait
    raise ValueError('Set of coroutines/Futures is empty.')
ValueError: Set of coroutines/Futures is empty

This is an error not yet experienced here. As a matter of fact, I don’t get any error, and the set runs perfectly. Switches on and off, triggers the script depending on set conditions and cancels and retriggers when motion happens during delay.

The error is about a loop , but there is no loop, it is why I made the adjustment in the action part, to first stop the script and consecutively run it if condition is met. You did take that version?