How do I extract part of the topic for a notification message? [Solved]

Hi there,

I’m planing to notify my Home Assistant app when a MQTT device goes offline (ideally for more than 30s) and have started building the automation but I don’t know what code I’d put in the message template. I’ve found a fair bit online about trigger.topic.split but not sure how I’d use that. Can anyone point me in the right direction?

automation:
  - id: mqtt_offline_notification
    alias: "MQTT Offline Notification"
    description: "Send notification when LWT goes offline."

    trigger:
      # run whenever any LWT sensor state changes to offline for more than 5s
      platform: mqtt
      topic: tele/+/LWT
      payload: 'offline'
    condition: []
    action:
    - service: notify.mobile_app_nokia_7_1
      data_template:
        message:

I’d need to extract ‘washer’ from a topic like this tele/washer/LWT


- service: notify.mobile_app_nokia_7_1
      data_template:
        message: "The {{trigger.topic.split('/')[1]}} is offline."

If you split this string:
tele/washer/LWT

at each / character, it produces a list containing three items:
['tele', 'washer', 'LWT']

The items are numbered starting with zero. That’s why the template uses [1] to refer to washer.

4 Likes

That’s brilliant, thank you! I’ll test in the morning. Any idea what happens if two go offline at the same time?

The default mode (for the action) is single. That means if the first instance of the action is still running when the automation is triggered again, the second attempted instance will be rejected (and a warning message is logged). You can change that behavior by setting mode to queued (or parallel).

Script Modes

1 Like

Awesome, thank you. Last question. Can I add in other topic to the same trigger (that also report ‘offline’)?

You can add more MQTT Triggers, just keep in mind how the template handles the topic (i.e. gets the second word in the topic).

Thanks. OK, I lied about the last question. :stuck_out_tongue_winking_eye:

Have you got some advice on how I could add a condition so that if the device comes back online within 30s, it stops the automation? My testing is going well but I’m getting notified even though the device connected back to the broker 2 seconds later.

Also worth noting, the payload topic in the trigger is case sensitive.

I don’t know of an easy way to do that using a condition. Maybe someone else has a clever way to do it.

What about a service_template that activates an input_boolean that tracks the state; Offline or Online? Then we could call another service to action the notifier based on a condition that the input_boolean is on for more than x? Just spit-balling out loud :thinking: