Paho MQTT client: how to ignore messages published by myself?

Question:

My Paho MQTT client does the following:

  1. Subscribe to mytopic/#
  2. Do something
  3. Publish to mytopic/#

Problem:
The published message in step 3 arrives at step 1. I’d like to avoid adding a sender-attribute to the payload.

Is there a proper way of ignoring self-published messages? Something like the following (pseudocode):

def on_message(self, client, userdata, message):
    if client.id == message.sender_client_id:  # Is there anything like the sender_client_id?
        return

Any idea? Thanks!

Asked By: Mr. B.

||

Answers:

This logic should work:

  1. Assign an id to every client
  2. every client publish on mytopic/{id}
  3. every client sub to mytopic/#

ignore messages where message.topic starts with mytopic/{id}

Answered By: Vanojx1

As of the MQTT v5 spec you can tell the broker not to send your own messages back to you as part of the subscription message.

This removes the need to add the identifier so you can then choose to ignore it.

This does of course rely on both the broker and the MQTT client supporting MQTT v5

Answered By: hardillb
def on_message(self, client, userdata, message):
    if client.id == message.sender_client_id:  # Is there anything like the sender_client_id?
        return

In your pseudocode, you are asking for the client’s identity but this is exactly opposite to the MQTT specification. In MQTT, two different clients are unaware of each other’s identity, they only communicate via the MQTT broker by subscribing to the topics.

Answered By: Rajat Bansal

If you are using MQTT v5, you can pass the noLocal option to the paho client when subscribing. This option tells the broker not to send back your own messages.

from paho.mqtt.subscribeoptions import SubscribeOptions
...
options = SubscribeOptions(qos=1, noLocal=True)
client.subscribe('mytopic/#', options=options)
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.