Mr. B.
Mr. B.

Reputation: 8717

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

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!

Upvotes: 0

Views: 2958

Answers (4)

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)

Upvotes: 4

Rajat Bansal
Rajat Bansal

Reputation: 41

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.

Upvotes: 1

Vanojx1
Vanojx1

Reputation: 5584

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}

Upvotes: 1

hardillb
hardillb

Reputation: 59816

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

Upvotes: 3

Related Questions