How to create automation when phone disconected for a period of time?

I appreciate this is probably a very simple question, but I’m only a few days into the HA universe and know nothing about coding or YAML.

I’m trying to create an automation that makes HA stream a message through my speakers when my phone connects to the router, and it works.

However, what condition do I need to add to run this automation only if my phone was disconnected for a certain period, for example, more than 30 minutes? I tried the following, but it doesn’t seem to work:

triggers:
  - type: connected
    device_id: b32dfb1b6715a0cb67b845dfad628949
    entity_id: 8fc48416e33d5f8603a94985b27f2b85
    domain: binary_sensor
    trigger: device
conditions:
  - condition: state
    entity_id: binary_sensor.192_XX_XX_XX
    state: "off"
    for:
      hours: 0
      minutes: 30
      seconds: 0
actions:
  - target:
      entity_id: media_player.g_speakers
    data:
      volume_level: 0.5
    action: media_player.volume_set
  - action: chime_tts.say
    target:
      entity_id: media_player.g_speakers
    data:
      cache: false
      message: |

Thank you.

Post the full automation instead in a code block so it’s readable.

I assume connected means the binary sensor is on. So a condition that it should be off wont work.

I would do like this:

triggers:
  - trigger: state
    entity_id: binary_sensor.192_XX_XX_XX
    state: "on"
    id: "connected" 
  - trigger: state
    entity_id: binary_sensor.192_XX_XX_XX
    state: "off"
    for:
      hours: 0
      minutes: 30
      seconds: 0
    id: "disconnected"
conditions: []
actions:
  - target:
      entity_id: media_player.g_speakers
    data:
      volume_level: 0.5
    action: media_player.volume_set
  - action: chime_tts.say
    target:
      entity_id: media_player.g_speakers
    data:
      cache: false
      message: "Phone {{trigger.id}}"

Well, now it plays the message after the period of time, but even if I don’t connect back to my wifi.

What?
I don’t understand what you mean?

Well, what I want is to stream a message when my phone connects to the router, only if it was disconnected for more than 30 minutes. If it was disconnected for just 20 minutes, I don’t want the message streamed.

Currently, it streams the message after 30 minutes of disconnection, even if my phone doesn’t reconnect.

Ok… That wasn’t clear.
In that case your initial post was more correct.
But you need to switch the condition to a template.

{{ now().timestamp() -  states.binary_sensor.192_XX_XX_XX.last_changed.timestamp() > 1800 }}

Just to let you know.
192 addresses are internal on your LAN and not something anyone can track you by.
I also have 192.
192.168.0.147 to be specific is my HA.

1 Like

Wait… I messed up…

{{ now().timestamp() -  trigger.from_state.state.last_changed.timestamp() > 1800 }}

is probably correct

Now it works like a charm. Thank you.