sub-class.py 2.0 KB
Newer Older
1 2 3 4 5 6
#!/usr/bin/python

# Copyright (c) 2013 Roger Light <roger@atchoo.org>
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Distribution License v1.0
A
Alexis BRENON 已提交
7
# which accompanies this distribution.
8
#
A
Alexis BRENON 已提交
9
# The Eclipse Distribution License is available at
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
#   http://www.eclipse.org/org/documents/edl-v10.php.
#
# Contributors:
#    Roger Light - initial implementation

# This example shows how you can use the MQTT client in a class.

import sys
try:
    import paho.mqtt.client as mqtt
except ImportError:
    # This part is only required to run the example from within the examples
    # directory when the module itself is not installed.
    #
    # If you have the module installed, just use "import paho.mqtt.client"
    import os
    import inspect
    cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],"../src")))
    if cmd_subfolder not in sys.path:
        sys.path.insert(0, cmd_subfolder)
    import paho.mqtt.client as mqtt

A
Alexis BRENON 已提交
32
class MyMQTTClass(mqtt.Client):
33

A
Alexis BRENON 已提交
34
    def on_connect(self, mqttc, obj, flags, rc):
35 36
        print("rc: "+str(rc))

A
Alexis BRENON 已提交
37
    def on_message(self, mqttc, obj, msg):
38 39
        print(msg.topic+" "+str(msg.qos)+" "+str(msg.payload))

A
Alexis BRENON 已提交
40
    def on_publish(self, mqttc, obj, mid):
41 42
        print("mid: "+str(mid))

A
Alexis BRENON 已提交
43
    def on_subscribe(self, mqttc, obj, mid, granted_qos):
44 45
        print("Subscribed: "+str(mid)+" "+str(granted_qos))

A
Alexis BRENON 已提交
46
    def on_log(self, mqttc, obj, level, string):
47 48 49
        print(string)

    def run(self):
A
Alexis BRENON 已提交
50 51
        self.connect("m2m.eclipse.org", 1883, 60)
        self.subscribe("$SYS/#", 0)
52 53 54

        rc = 0
        while rc == 0:
A
Alexis BRENON 已提交
55
            rc = self.loop()
56 57 58 59 60 61 62 63 64 65 66
        return rc


# If you want to use a specific client id, use
# mqttc = MyMQTTClass("client-id")
# but note that the client id must be unique on the broker. Leaving the client
# id parameter empty will generate a random id for you.
mqttc = MyMQTTClass()
rc = mqttc.run()

print("rc: "+str(rc))