[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index] [List Home]
[paho-dev] Simple subscribing with Python client

Hi all,

I thought there might be interest in a new feature I've just been
adding to the Paho Python client (see the develop branch).

You may already be familiar with the paho.mqtt.publish module which
has the single() and multiple() functions, designed to give a very
simple way of publishing messages reliably and without much code. They
connect, publish, then disconnect cleanly.

paho.mqtt.publish.single("sensor/temperature", "36")

I've put together a complementary module called subscribe. This gives
you two helper functions:

simple() connects to a broker, subscribes to a set of topics and once
a user defined number of messages has been received disconnects
cleanly and returns those messages. It can be told to ignore stale
retained messages or not. So for example:

# Retrieve the first "fresh" (without retained bit) message
msg = paho.mqtt.subscribe.simple("sensor/temperature", retained=False)
print(msg.payload)

# Retrieve the first 5 messages
msgs = paho.mqtt.subscribe.simple("sensor/+", msg_count=5)
for m in msgs:
    print("%s %s" % (m.topic, m.payload))

The second function, callback() connects a broker, subscribes to a set
of topics and then passes any incoming messages to a user defined
callback. So a quick program to print out incoming messages would
become

def msg_print(client, userdata, msg):
    print("%s %s" % (msg.topic, msg.payload))

paho.mqtt.client.subscribe.callback(msg_print, "#")

I think that both functions together remove the need for a lot of
quick custom code.

Cheers,

Roger