|
| 1 | +import time |
| 2 | +from umqtt.robust import MQTTClient |
| 3 | + |
| 4 | + |
| 5 | +def sub_cb(topic, msg): |
| 6 | + print((topic, msg)) |
| 7 | + |
| 8 | + |
| 9 | +c = MQTTClient("umqtt_client", "localhost") |
| 10 | +# Print diagnostic messages when retries/reconnects happens |
| 11 | +c.DEBUG = True |
| 12 | +c.set_callback(sub_cb) |
| 13 | +# Connect to server, requesting not to clean session for this |
| 14 | +# client. If there was no existing session (False return value |
| 15 | +# from connect() method), we perform the initial setup of client |
| 16 | +# session - subscribe to needed topics. Afterwards, these |
| 17 | +# subscriptions will be stored server-side, and will be persistent, |
| 18 | +# (as we use clean_session=False). |
| 19 | +# |
| 20 | +# There can be a problem when a session for a given client exists, |
| 21 | +# but doesn't have subscriptions a particular application expects. |
| 22 | +# In this case, a session needs to be cleaned first. See |
| 23 | +# example_reset_session.py for an obvious way how to do that. |
| 24 | +# |
| 25 | +# In an actual application, it's up to its developer how to |
| 26 | +# manage these issues. One extreme is to have external "provisioning" |
| 27 | +# phase, where initial session setup, and any further management of |
| 28 | +# a session, is done by external tools. This allows to save resources |
| 29 | +# on a small embedded device. Another extreme is to have an application |
| 30 | +# to perform auto-setup (e.g., clean session, then re-create session |
| 31 | +# on each restart). This example shows mid-line between these 2 |
| 32 | +# approaches, where initial setup of session is done by application, |
| 33 | +# but if anything goes wrong, there's an external tool to clean session. |
| 34 | +if not c.connect(clean_session=False): |
| 35 | + print("New session being set up") |
| 36 | + c.subscribe(b"foo_topic") |
| 37 | + |
| 38 | +while 1: |
| 39 | + c.wait_msg() |
| 40 | + |
| 41 | +c.disconnect() |
0 commit comments