Automation help: AND and OR

I was somewhat surprised that I couldn’t find a specific example to follow. I’m relatively new to HA and this is my first automatons with multiple triggers and multiple conditions.

Essentially what I’m attempting is Disable Nabu Casa cloud connection if both phones are home and enable if either phone leaves. I’m not using the iphone integration for presence tho. The binary sensors used in the automation DO work… On= Home, Off= away.

Essentially the logic boils down to:

  • if phone_1 = off OR phone_2 = off then enable cloud.
  • if phone_1 = on AND phone_2 = on then disable cloud

The first case is relatively straight forward, the second case I fought with for way too long, convinced it needed to be split in two for awhile, but I think I’ve got it correct below: if someone could just confirm… suggestions welcome as well. (to be honest, due to weather conditions today and tomorrow this is hard to test, other wise I’d just test by leaving and returning until I was sure it was correct.)

Thanks!

alias: enable cloud connections
description: ''
trigger:
  - type: turned_off
    platform: device
    device_id: <redacted string 1>
    entity_id: binary_sensor.<redacted 1>_iphone
    domain: binary_sensor
  - type: turned_off
    platform: device
    device_id: <redacted string 2>
    entity_id: binary_sensor.<redacted 2>_iphone
    domain: binary_sensor
condition: []
action:
  - service: cloud.remote_connect
    data: {}
mode: single

alias: Disable cloud Connection
description: ''
trigger:
  - type: turned_on
    platform: device
    device_id: <redacted string 1>
    entity_id: binary_sensor.<redacted 1>_iphone
    domain: binary_sensor
  - type: turned_on
    platform: device
    device_id: <redacted string 2>
    entity_id: binary_sensor.<redacted 2>_iphone
    domain: binary_sensor
condition:
  - type: is_on
    condition: device
    device_id: <redacted string 1>
    entity_id: binary_sensor.<redacted 1>_iphone
    domain: binary_sensor
  - type: is_on
    condition: device
    device_id: <redacted string 2>
    entity_id: binary_sensor.<redacted 2>_iphone
    domain: binary_sensor
action:
  - service: cloud.remote_disconnect
    data: {}
mode: queued
max: 10

I could send you to many resources on conditions, but it would make me sad to do so, because I would be encouraging you to use the wrong logic.

The most efficient way to do this is to put your devices in a group…

group:
  everyone:
    entities:
      - binary_sensor.<redacted 1>_iphone
      - binary_sensor.<redacted 2>_iphone

And then use the state of the group to toggle the connection…

alias: toggle remote connection 
trigger:
  platform: state
  entity_id: group.everyone
action:
  service: "{{ 'cloud.remote_connect' if trigger.to_state.state == 'off' else 'cloud.remote_disconnect' }}"

As you can see, that replaces your 48 lines of code with 11 and does the job far better.

3 Likes

yep, that’s a much cleaner approach, I’m glad I asked.

1 Like