mqtt publish and subscribe with Python

Assume you have read some introduction papers about MQTT(like here: https://pypi.org/project/paho-mqtt/)

I write 2 Python scripts with python2.7: mqtt_talk.py as publisher, mqtt_listen.py as subscriber, here are the details

mqtt_talker.py

#!/usr/bin/env python

import os.path
import paho.mqtt.client as mqtt

class mqtt_talker():
    def __init__(self, broker_ip):
        self.ip = broker_ip
        self.client = mqtt.Client(client_id = "test_mqtt_talker")
        self.client.on_connect = self.on_connect
        self.client.on_disconnect = self.on_disconnect
        self.client.on_publish = self.on_publish

    def connect(self):
        self.client.connect(self.ip, 1883, 60)

    def on_connect(self, client, userdata, flags, rc):
        self.connected = True
        print("Connected with broker ......")

    def disconnect(self):
        self.client.disconnect()

    def on_disconnect(self, client, userdata, rc):
        print("Disconnected with broker ......")

    def publish(self):
        data = "Hello Lily"
        self.client.publish("mqtt_talker", data, 2)

    def on_publish(self, client, userdata, mid):
        print("Data publish success ...")

    def loop_forever(self):
        self.client.loop_forever()

if __name__ == '__main__':
    broker_IP = "192.168.1.2"   # change broker ip same with mqtt server
    client = mqtt_talker(broker_IP)
    client.connect()
    client.publish()
    #client.disconnect()
    client.loop_forever()

mqtt_listen.py

#!/usr/bin/env python

import os.path
import paho.mqtt.client as mqtt

class mqtt_listener():
    def __init__(self, broker_ip):
        self.ip = broker_ip
        self.client = mqtt.Client(client_id = "test_mqtt_listener")
        self.client.on_connect = self.on_connect
        self.client.on_disconnect = self.on_disconnect
        self.client.on_message = self.on_message

    def connect(self):
        self.client.connect(self.ip, 1883, 60)

    def on_connect(self, client, userdata, flags, rx):
        print("Connected with broker ......")
        self.subscribe("mqtt_talker")
        return True

    def disconnect(self):
        self.client.disconnect()

    def on_disconnect(self, client, userdata, rc):
        print("Disconnected with broker ......")

    def subscribe(self, topic):
        self.client.subscribe(topic)

    def on_message(self, client, userdata, msg):
        print("topic:{} payload: {}".format(msg.topic, msg.payload))

    def loop_forever(self):
        self.client.loop_forever()

if __name__ == '__main__':
    broker_IP = "192.168.1.2"   # change broker ip same with mqtt server
    client = mqtt_listener(broker_IP)
    client.connect()
    client.subscribe("mqtt_talker")
    client.disconnect()
    client.loop_forever()

猜你喜欢

转载自blog.csdn.net/cutelily2014/article/details/82151755