Using the python paho mqtt client I want to get all messages in a given topic and disconnect from the broker.
I can easily do this using simple() as shown here, yet only if I specify the message count using msg_count. This would be fine if the message count were predictable or if there was a means to count the messages in a given topic.
import paho.mqtt.subscribe as mqtt_subscribe
messages = mqtt_subscribe.simple('proxies/#', msg_count=4, hostname='mqtt.somewhere.io')
for m in messages:
print(m.payload.decode())
I'm also able to get all the messages in my topic using the example shown in Getting Started. However, this uses a loop_forever() and I simply want to get all messages and disconnect. I've tried other loop*() functions, yet none are offering the results I'm seeking.
The Callback Example also returns all messages yet it isn't clear to me how to disconnect from this.
And lastly, I can also use the mosquitto_sub client with a timeout to get all messages: mosquitto_sub -h mqtt.somewhere.io -t "proxies/#" -W 1 But I'd prefer to be consistent with the paho client and better understand it.
A given topics doesn't have a "count" of messages. There is potentially 1 retained message, after that there could be zero to infinite messages sent over infinite time.
If the problem is that you don't know how many topics there are with retained messages attached, because you have used a wildcard, then you can wait for the first message that doesn't have the retained bit set in the header, because retained messages will be delivered before any other messages on connection.
If the client has an existing persistent session then the broker may have queued past messages (missed by the client while it was not connected) for that specific client, but there is no way to get the count of those messages. But this depends on the client having been previously connected and subscribed at a high QoS level.
You may need to adjust your thinking here.