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

The automation was normally ‘off’ and turned to ‘on’ when motion sensor went from ‘on’ to ‘off’ so it was different, that is why I noticed it. But if it is normal then it is ok I guess?

Automation did not trigger at all after reboot even though the motion sensor did change it’s state. So I had to remove the automation couple of times before it started to work again and triggered when motion sensor went to ‘on’. The automation was working fine before that. But haven’t had time to look at it closer. Need to change HA logging to debug to see if there is any errors, there were no mentions in logs of the automation.

But actually, regarding the automation you gave me, there were mentions in logs about something that “entity script.switch_off_lights_delay already exists”. Do not know if that was a problem or just an normal error since haven’t had time to look into it :slight_smile:

Edit: There has been problems with the automation in >0.85.x. Interesting thing is that my automations have seem to be always ‘off’ and when triggered, go to ‘on’ and then ‘off’ again

this sounds somewhat unfamiliar to me, so Im not sure yet this is ‘normal’… Exactly what did you notice?
The automation should be on, for the motion sensor being able to trigger it. Put differently: If the automation isn’t on, the motion sensor can spot motion as much as it can but the automation won’t be triggered, since it is off.

As said, If the automation isn’t set to on, either manually or by restore state or by initial_state: on in the automation, it won’t run.
You shouldn’t rewrite your automations, that is useless. You should only have to set the automation to on, or trigger it manually. Once. from there, restore_state should take care for you, or use the initial_state: on in the automation

since that’s what is in my example, restarting HA should always see to it this automation is on. If not, you have other problems… if it only a matter of triggering, then the trigger isn’t working as expected.

That clarifies a lot. Thanks.

I found from github a similar case, the automation did not work after update. But when changing the alias, it did and this is the same as I have noticed and was fixed when I rewrite the rule and actually changed the alias. I did not think this was important but it actually is.

But it has been fixed by multiple people by triggering automations manually, setting the initial_state or by checking the sensor entity_id.

A yes, I have an id with the identical alias for all of my automations… and yes2 this is what I was referring to as reason why I didn’t yet update, several issues with naming and other automation entity_ids.

1 Like

The code does not work. The script never gets called :frowning: But I got the lights on automation to work, I added the initial_state: on to it.

the binary_sensor was sensor in the code so that is why it did not work. Now the script is called but the light won’t turn off. There is a huge error in the logs:

Error while executing automation automation.bathroom_lights_off_when_no_motion. Unknown error for call_service at pos 1:

Traceback (most recent call last):
  File "/usr/local/lib/python3.6/site-packages/homeassistant/components/automation/__init__.py", line 382, in action
    await script_obj.async_run(variables, context)
  File "/usr/local/lib/python3.6/site-packages/homeassistant/helpers/script.py", line 131, in async_run
    await self._handle_action(action, variables, context)
  File "/usr/local/lib/python3.6/site-packages/homeassistant/helpers/script.py", line 210, in _handle_action
    action, variables, context)
  File "/usr/local/lib/python3.6/site-packages/homeassistant/helpers/script.py", line 299, in _async_call_service
    context=context
  File "/usr/local/lib/python3.6/site-packages/homeassistant/helpers/service.py", line 85, 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.

Here is the code:

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
      to: 'on'
    - platform: state
      entity_id: binary_sensor.bathroom_motion_sensor_timing
      to: 'off'
  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:
  alias: Switch off lights
  sequence:
    - delay:
        minutes: >
          {{ '15' if states('sensor.zha_01ddaf89_1_1029' ) | int >= 50 else '2' }}
    - service: light.turn_off
      entity_id: light.bathroom

Binary_sensor

binary_sensor:
  - platform: template
    sensors:
      bathroom_motion_sensor_timing:
        friendly_name: 'Bathroom motion sensor timing'
        value_template: >
          {{ is_state('sensor.bathroom_motion_sensor','on')}}
        delay_off:
          minutes: 1
        device_class: motion

Before checking the automation : can you confirm the binary sensor to work? Motion sets it to on and when no motion has been for 1 minute state changes to Off? If motion has been detected within the delay timing starts again to again for the minute to pass?

1 Like

Binary sensor seems to be working like you descripted.

Which is good news…:wink:

What I don’t understand is why the new automation won’t work when the original did work as designed?

1 Like

I’ll test this evening and report tomorrow :slight_smile:

Update, yesterday evening and today morning the automation worked really well actually. Do not know if there are errors in HA but at least all the timings worked and the lights turned on and off like I wanted to. Even the shower was noticed and the lights stayed on during that and when the humidity dropped after, the lights went off sooner than the 15 minutes because the shower was over and there were movement and the timer started again when movement stopped.

So currently everything works like I wanted to! I do not have the working code at me right now but will post it later today here. I actually do not know what is different compared to the one couple of posts ago. But later today we will see when I have to code with me :slight_smile:

Thank you @Mariusthvdb so much.

1 Like

Great. I would have hoped so…
As I said a few iterations ago: start with a good and solid architecture, and you can always build on that to expand and further refine. This is a great example of that. And again, a solid way of dong it. No hacky templates. plain simple and robust logic, all in 1 expandable package.

Cool, and as always, glad to have been of help.

Here are the working codes.

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
      to: 'on'
    - platform: state
      entity_id: binary_sensor.bathroom_motion_sensor_timing
      to: 'off'
  condition:
    condition: time
    after: '06:00:00'
    before: '00:00:00'
  action:
    - service: script.turn_off
      entity_id: script.switch_off_lights
    - condition: template
      value_template: >
        {{ is_state('sensor.bathroom_motion_sensor', 'off') }}
    - service: script.switch_off_lights

config (binary_sensor)

binary_sensor:
  - platform: template
    sensors:
      bathroom_motion_sensor_timing:
        friendly_name: 'Bathroom motion sensor timing'
        value_template: >
          {{ is_state('sensor.bathroom_motion_sensor','on')}}
        delay_off:
          minutes: 1
        device_class: motion

And finally the script

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

Has there been some changes to way HA deals with scripts or binary_sensors? The automation seem to have worsened after update from 0.85 upwards. Mainly it works fine but it has started to do a thing where the timer is not being cancelled so the lights go out even when someone is in bathroom. The humidity part still works as expected.

I also updated Hue CC so my hue motion sensor is now binary_sensor also and not just sensor like in the code above. Otherwise the code remains the same.

After testing I can confirm that something has changed in HA but I am not able to find what. Sometimes the timer just is not stopping and the lights are turned off even when there is motion…

sorry to heat that, Ive not experienced issues yet with my timed sensors, but am still on 84.3 and 87.1

there has been a change to time_pattern, but that is for triggers only, not condition. Check https://www.home-assistant.io/docs/automation/trigger/#time-pattern-trigger for that.

I noticed that but there are no “time” that I use except in condition and that is working fine.

The fault has to be in cancelling the script but it is really hard to debug since it only happens in certain conditions like brushing teeth and standing still and then moving. Might need to take my laptop to bathroom and try to replicate the problem :smiley:

I need to try to narrow it down first by trying to move during the 1minute period on binary_sensor and if that works normally then trying to move on the script’s delay period…

yes, and maybe experiment with the sensor’s sensitivity ( and delay time, set it a bit longer to give it some slack time to respond). I set my sensors sensitivity based on expected motion, or presence. High when away, to get them burglars…, low when a sleep for the bedroom lights :wink:

I was not able to regenerate the problem while debugging. All the timers worked normally but still the problem persists since this morning it happened again.

It might be that the automation is not run again at some times but there is really no way for me to tell if this is really happening or not since I can only see last_updated time…

Sensitivity shows as “2” in my HA. But the lx and dark:true actually never changes, they are always the same. Is this bug on the CC or malfunction on my config?

Any ideas how to debug this?

that doesn’t sound good. Try and cover a motion sensor so it is dark, while watching the sense in HA. It really should change within a second or 2. If that doesn’t happen, maybe your sensors aren’t 'live; any longer.

You didn’t happen to upgrade the Hue CC without change your sensors from sensor to binary_sensor…?

I’ll try that!

sensors are changed to binary_sensor and also changed from hue to hue_custom and changed filenames accordingly etc. Also the state of the motion sensor is changing normally (at least when monitored).