256dpi / arduino-mqtt

MQTT library for Arduino
MIT License
1.01k stars 232 forks source link

onMessage called every time that publish to a topic #261

Closed alirezaimi closed 1 year ago

alirezaimi commented 3 years ago

Hi every time that my esp board publish a message to mqtt server, the onMessage method called, why ?!

how can i detect who send the message and filter it ?

hgscania commented 2 years ago

Hi, I have same issue. when publish a message, onMessage called and QoS=-1. Ho to solve this?!

newHagen commented 1 year ago

Hi,

is it possible that you subscribed to the same topic you're publishing? That would certainly trigger such a feedback loop.

256dpi commented 1 year ago

Closing as probably solved.

alirezaimi commented 1 year ago

No ! How can this problem solved ?! it's open for solving and not solved !

256dpi commented 1 year ago

As @biteater pointed out, the only reason for the onMessage callback to be called is because of a subscription to a topic. And if you publish to the same topic you will also receive your own message. That is how MQTT works, there is nothing we can do about it.

alirezaimi commented 1 year ago

And this is not a loop ?! I must publish to a topic other than a topic that subscribe to it ? this is the right way ?

newHagen commented 1 year ago

Yes, exactly.

If you subscribe to 'foo' and you submit data to 'foo', this will trigger the onMessage-callback because a message has been published to this topic. The only way to prevent this is to not subscribe to the very same topic you are publishing to.

Subscribe to 'foo' and publish to 'bar' and everything is fine.

To stay within the same namespace for a device you might want to use topics like 'foo/status' to publish your data and subscribe to 'foo/cmd' to receive data or commands on your device.