1#!/usr/local/bin/python3.8
2# -*- coding: utf-8 -*-
3
4# Copyright (c) 2014 Roger Light <roger@atchoo.org>
5#
6# All rights reserved. This program and the accompanying materials
7# are made available under the terms of the Eclipse Distribution License v1.0
8# which accompanies this distribution.
9#
10# The Eclipse Distribution License is available at
11#   http://www.eclipse.org/org/documents/edl-v10.php.
12#
13# Contributors:
14#    Roger Light - initial implementation
15# Copyright (c) 2014 Roger Light <roger@atchoo.org>
16# All rights reserved.
17
18# This demonstrates the session present flag when connecting.
19
20import context  # Ensures paho is in PYTHONPATH
21import paho.mqtt.client as mqtt
22
23
24def on_connect(mqttc, obj, flags, rc):
25    if obj == 0:
26        print("First connection:")
27    elif obj == 1:
28        print("Second connection:")
29    elif obj == 2:
30        print("Third connection (with clean session=True):")
31    print("    Session present: " + str(flags['session present']))
32    print("    Connection result: " + str(rc))
33    mqttc.disconnect()
34
35
36def on_disconnect(mqttc, obj, rc):
37    mqttc.user_data_set(obj + 1)
38    if obj == 0:
39        mqttc.reconnect()
40
41
42def on_log(mqttc, obj, level, string):
43    print(string)
44
45
46mqttc = mqtt.Client(client_id="asdfj", clean_session=False)
47mqttc.on_connect = on_connect
48mqttc.on_disconnect = on_disconnect
49# Uncomment to enable debug messages
50# mqttc.on_log = on_log
51mqttc.user_data_set(0)
52mqttc.connect("mqtt.eclipse.org", 1883, 60)
53
54mqttc.loop_forever()
55
56# Clear session
57mqttc = mqtt.Client(client_id="asdfj", clean_session=True)
58mqttc.on_connect = on_connect
59mqttc.user_data_set(2)
60mqttc.connect("mqtt.eclipse.org", 1883, 60)
61mqttc.loop_forever()
62