Python MQTT client implementation

Python MQTT client implementation

If you need to reprint, please indicate the source: http://blog.csdn.net/itas109
QQ technology exchange group: 12951803

1. Install PAHO mqtt

Using Python Package Index (PyPi)

pip install paho-mqtt

Using virtualenv

virtualenv paho-mqtt
source paho-mqtt/bin/activate
pip install paho-mqtt

Or compile the source code

git clone https://github.com/eclipse/paho.mqtt.python

Install using source code

cd paho.mqtt.python
python setup.py install

2. Demo

receive data

import paho.mqtt.client as mqtt
import time

HOST = "127.0.0.1"
PORT = 61613

def client_loop():
    client_id = time.strftime('%Y%m%d%H%M%S',time.localtime(time.time()))
    client = mqtt.Client(client_id)    # ClientId cannot be duplicate, so the current time is used
    client.username_pw_set("admin", "123456")  # Must be set, otherwise it will return "Connected with result code 4"
    client.on_connect = on_connect
    client.on_message = on_message
    client.connect(HOST, PORT, 60)
    client.loop_forever()

def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    client.subscribe("test")

def on_message(client, userdata, msg):
    print(msg.topic+" "+msg.payload.decode("utf-8"))

if __name__ == '__main__':
    client_loop()

Note that the client? ID is required and unique. Otherwise, the following errors may occur:

[WinError 10054] the remote host forced an existing connection to be closed.

Publish data

# import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish
import time

HOST = "127.0.0.1"
PORT = 61613
def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    client.subscribe("test")

def on_message(client, userdata, msg):
    print(msg.topic+" "+msg.payload.decode("utf-8"))

if __name__ == '__main__':
    client_id = time.strftime('%Y%m%d%H%M%S',time.localtime(time.time()))
    # client = mqtt.Client(client_id)    # ClientId cannot be duplicate, so the current time is used
    # client.username_pw_set("admin", "123456")  # Must be set, otherwise it will return "Connected with result code 4"
    # client.on_connect = on_connect
    # client.on_message = on_message
    # client.connect(HOST, PORT, 60)
    # client.publish("test", "Hello MQTT", qos=0, retain=False)  # Publish message

    publish.single("test", "Hello MQTT", qos = 1,hostname=HOST,port=PORT, client_id=client_id,auth = {'username':"admin", 'password':"123456"})

3. Results

Receive

Send out

Reference
https://pypi.python.org/pypi/paho-mqtt

Think the article is helpful to you, you can use wechat scan QR code to donate to the blogger, thank you!

If you need to reprint, please indicate the source: http://blog.csdn.net/itas109
QQ technology exchange group: 12951803

Tags: Python pip git github

Posted on Mon, 04 May 2020 04:51:36 -0700 by jeffshead