MQTT Automation ignore if retain flag is set

So i have setup an automation that triggers on MQTT and depending on {{ trigger.payload }} does something. Works great. However, the system sending the MQTT payload, has set the retain flag. So every time HA starts up (or refresh automations), it triggers the automation as it appears as part of the realod it re-subscribes to the topic, and gets the retained data.

I can not change the sending system so it doesn’t set the retain flag :frowning:

What attributes are accessible in trigger? as trigger.retained and trigger.retain don’t seem to be set :frowning:

There isn’t anything in the incoming MQTT message to indicate the reason it was sent.

One option you might try is to disable the automation for a certain amount of time after HA startup. But, there again, HA might actually subscribe when the automation is enabled, which wouldn’t help. :thinking:

thats not correct. MQTT payloads indicate if it was a retained value that was sent. All other clients can check for this flag.

The client can detect that is a retained messages by examining the message.retain flag in the on message callback as shown in the code snippet below:

def on_message(client, userdata, message):
print("message received  ",str(message.payload.decode("utf-8")),\
      "topic",message.topic,"retained ",message.retain)
if message.retain==1:
    print("This is a retained message")

http://www.steves-internet-guide.com/mqtt-retained-messages-example/

Just need to know what HA does with this information?

Write an automation in HA to publish to the same topic with a blank message (with the retain flag set) once you have actioned receiving the message with the retain flag. This will clear the message from the broker.

That sounds confusing. I mean an automation like this:

  1. trigger on the topic/message as you normally would
  2. do your actions for this trigger as you normally would
  3. publish a blank message to the topic with the retain flag set (to clear the message from the broker)

i.e. just append this action to the end of your existing automation:

- service: mqtt.publish
  data_template:
    payload: ""
    topic: 'your/topic/here'
    retain: true
1 Like

I see what you doing… then in that same automation, activate the automation that will get the “cleared” retained message, which is blank, son won’t trigger. good work around. Hopefully they expose the retain flag, as that would be much simpler :slight_smile:

1 Like