Introduction to the use of MQTT Client paho.mqtt.python

Introduction

The MQTT protocol may currently be the most popular transmission protocol for the Internet of Things, so how to use Python as a client to interact with the MQTT server?

This article will use paho.mqtt.python ( https://github.com/eclipse/paho.mqtt.python ) as the client, and EMQ is the MQTT Broker to introduce the interaction between paho and EMQ.

Install MQTT Broker: EMQ

EMQ is currently the most popular MQTT Broker in the open source community. The blog of EMQ has already discussed how to install it on different operating systems. This article will not go into details.

To install EMQ on Ubuntu, please click here ; to install EMQ on Windows, please click here .

Prepare paho.mqtt.python

For Python installation, please refer to these three articles: Linux system python installation ; Windows system Python installation ; Mac system Python installation .

EMQ recommends that the Python version is python3.6 (paho recommends 2.7+ and 3.2+)

Unzip paho.mqtt.python-master.zip

Open the command line window, switch to the paho directory after decompression, install paho

python setup.py install

After the Windows installation is complete, the paho file is in the Python\Lib\site-packages\paho_mqtt-1.3.1-py3.6.egg\paho\mqtt directory.

 

After the Ubuntu installation is complete, the paho file is in the /usr/local/lib/python3.6/dist-packages/paho_mqtt-1.3.1-py3.6.egg/paho/mqtt/ directory.

 

The main client usage in the client.py file is as follows:

  • Use connect() / connect_async() to connect to Broker
  • Call loop() to maintain network connection with Broker
  • Use loop_start() to call a loop() process
  • Use loop_forever() to keep loop() calling
  • Use subscribe() to subscribe to topics and receive messages
  • Use publish() to publish messages
  • Use disconnect() to disconnect from Broker

Use the callback function to make Broker return data available, examples are as follows:

 

def on_connect(client, userdata, flags, rc):
  print("Connection returned " + str(rc))
client.on_connect = on_connect

All callbacks have a "client" and a "userdata" parameter. "client" is the client instance that calls the callback, and "userdata" is any type of user data, which can be set when creating a new client instance or use user_data_set( userdata)

on_connect(client, userdata, flags, rc)

Called when Broker responds to our request, "flags" is a dictionary containing Broker response parameters: flags['session present']-This flag is set to 0 only for clean sessions, and if session=0 is set, it is used for client reconnection Whether the Broker still saves the previous session information before, if it is set to 1, the session will always exist. The "rc" value is used to determine whether the connection is successful:

 

0: 连接成功
1: 连接失败-不正确的协议版本
2: 连接失败-无效的客户端标识符
3: 连接失败-服务器不可用
4: 连接失败-错误的用户名或密码
5: 连接失败-未授权
6-255: 未定义.

on_disconnect(client, userdata, rc)

Called when the client is disconnected from the Broker

on_message(client, userdata, message)

Called when a message is received on a topic subscribed by the client, the "message" variable is an MQTT message describing all message characteristics

on_publish(client, userdata, mid)

Called when the message sent using publish() has been transmitted to the agent. For messages with QoS levels 1 and 2, this means that the appropriate handshake has been completed. For QoS 0, this simply means that the message has left the client. The "mid" variable is the intermediate variable returned from the corresponding publish() call. This callback is important because even if the publish() call returns successfully, it does not always mean that the message has been sent

on_subscribe(client, userdata, mid, granted_qos)

Called when the Broker responds to a subscription request, the "mid" variable is an intermediate variable returned from the corresponding subscribe() call, and the "granted_qos" variable is a list of Qos levels of different subscription requests sent each time

on_unsubscribe(client, userdata, mid)

Called when the Broker responds to an unsubscribe request, the "mid" variable is an intermediate variable returned from the corresponding unsubscribe() call

on_log(client, userdata, level, buf)

Called when the client has log information, the definition allows debugging, the "level" variable is the message level including MQTT_LOG_INFO, MQTT_LOG_NOTICE, MQTT_LOG_WARNING, MQTT_LOG_ERR, MQTT_LOG_DEBUG, and the message itself is buf.

Examples of use

paho connect and subscribe to topics

Use paho to establish a connection, subscribe and publish topics. The information displayed on the EMQ console before connection is as follows.

 

Pub code is as follows:

 

import paho.mqtt.client as mqtt
 
def on_connect(client, userdata, flags, rc):
  print("Connected with result code "+str(rc))

def on_message(client, userdata, msg):
  print(msg.topic+" "+str(msg.payload))

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("127.0.0.1", 1883, 600)
client.publish('emqtt',payload='Hello,EMQ!',qos=0)
client.loop_start()

After running, it will display as shown in the figure below.

 

The Sub code is as follows,

 

import paho.mqtt.client as mqtt
 
def on_connect(client, userdata, flags, rc):
  print("Connected with result code "+str(rc))

def on_message(client, userdata, msg):
  print(msg.topic+" "+str(msg.payload))

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("127.0.0.1", 1883, 600)
client.subscribe('emqtt',qos=0)
client.loop_start()

After running, it will display as shown in the figure below.

 

EMQ console displays information after executing the code

 

to sum up

The related functions of paho client and MQTT interaction are introduced here. If readers continue to learn more, please follow EMQ's blog.


For more information, please visit our official website emqx.io , or follow us on open source projects github.com/emqx/emqx , detailed documentation, visit the official documentation .



Author: EMQ
link: https: //www.jianshu.com/p/b76dbc675141
Source: Jane books
are copyrighted by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.

Guess you like

Origin blog.csdn.net/qingzhuyuxian/article/details/106145631