aiomqtt
aiomqtt copied to clipboard
Is it necessary to create a topic filter?
Here is the code sample from the readme:
async with Client("test.mosquitto.org") as client:
async with client.filtered_messages("floors/+/humidity") as messages:
await client.subscribe("floors/#")
async for message in messages:
print(message.payload.decode())
I don't understand why both client.filtered_messages("floors/+/humidity")
and client.subscribe("floors/#")
are required here, since mqtt topics are already filtered by the mqtt broker. As far as I understand, we could just subscribe to client.subscribe("floors/+/humidity")
.
So I would like to understand if the client.filtered_messages
is really necessary and why/when to use it.
Good question! :)
Indeed, you can just use subscribe("floors/+/humidity")
combined with unfiltered_messages
. This way, you get all messages that match the floors/+/humidity
topic.
For some use cases, you want to subscribe to a general topic such as floors/#
but handle the messages differently based on the actual topic of each received message. For this purpose, you use filtered_messages("floors/basement/#")
, filtered_messages("floors/2nd-floor/#")
, and then a single unfiltered_messages
for the rest (everything from floors/#
that isn't explicitly floors/basement
or floors/2nd-floor
). Does it make sense?
For some use cases, you want to subscribe to a general topic such as
floors/#
but handle the messages differently based on the actual topic of each received message.
Hmm, I don't really understand because we could subscribe to both floors/basement/#
and floors/2nd-floor/#
independently and to tasks according to our needs. But I'm new to mqtt and I might miss some use cases.
I don't need filters anyway, but if I remove the line with the client.filtered_messages
, I don't know how to handle incoming messages... Could you provide a few lines of code with a topic subscription without a filter?
Hmm, I don't really understand because we could subscribe to both floors/basement/# and floors/2nd-floor/# independently and to tasks according to our needs
True, and you get all of said messages interleaved. We use filtered_messages
to deinterleave the messages. Of course, if your use case doesn't require deinterleaving, then just go ahead and use unfiltered_messages
. :+1:
I don't need filters anyway [...]
Great, just use unfiltered_messages
. :) Something like:
async with Client("test.mosquitto.org") as client:
async with client.unfiltered_messages() as messages: # Receive all messages
await client.subscribe("#") # Tell the server to send me all messages
async for message in messages:
print(message.payload.decode())
Thank you! Maybe you could add this explanation in the readme?
Glad to help. :)
You're welcome to make a PR that improves the documentation. :+1: That's a nice way to contribute to this project and help others avoid the same situation.
I'll close this off, as this is covered in the documentation now.