欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python中如何使用mqtt的简易教程

程序员文章站 2022-05-25 08:49:37
...

学习新知识最好的方法就是去看源码,看官方示例!!!

https://pypi.org/project/paho-mqtt/

1.安装mqtt开源库paho-mqtt:

pip install paho-mqtt

 2.官方订阅代码示例:

 

创建一个客户端只需要6步,如下:

Client

You can use the client class as an instance, within a class or by subclassing. The general usage flow is as follows:

  • Create a client instance
  • Connect to a broker using one of the connect*() functions
  • Call one of the loop*() functions to maintain network traffic flow with the broker
  • Use subscribe() to subscribe to a topic and receive messages
  • Use publish() to publish messages to the broker
  • Use disconnect() to disconnect from the broker
import paho.mqtt.client as mqtt

# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))    #rc的值很重要,为0代表连接成功。

    # Subscribing in on_connect() means that if we lose the connection and
    # reconnect then subscriptions will be renewed.
    client.subscribe("$SYS/#")    #订阅$SYS/下的所有主题

# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))

client = mqtt.Client()
client.on_connect = on_connect    #连接broker时broker响应的回调
client.on_message = on_message    #接收到订阅消息时的回调

client.connect("mqtt.eclipse.org", 1883, 60)    #连接到broker

# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
client.loop_forever()    #保持永久连接

结果如下:

python中如何使用mqtt的简易教程

在paho/mqtt/client.py中有详细的解释各个函数的具体含义。例如:

def on_connect(client, userdata, flags, rc, properties=None): called when the broker responds to our connection
  request.
  flags is a dict that contains response flags from the broker:
    flags['session present'] - this flag is useful for clients that are
        using clean session set to 0 only. If a client with clean
        session=0, that reconnects to a broker that it has previously
        connected to, this flag indicates whether the broker still has the
        session information for the client. If 1, the session still exists.
  The value of rc determines success or not:
    0: Connection successful
    1: Connection refused - incorrect protocol version
    2: Connection refused - invalid client identifier
    3: Connection refused - server unavailable
    4: Connection refused - bad username or password
    5: Connection refused - not authorised
    6-255: Currently unused.
def on_message(client, userdata, message): called when a message has been received on a
  topic that the client subscribes to. The message variable is a
  MQTTMessage that describes all of the message parameters.
def connect(self, host, port=1883, keepalive=60, bind_address="", bind_port=0,
            clean_start=MQTT_CLEAN_START_FIRST_ONLY, properties=None):
    """Connect to a remote broker.

    host is the hostname or IP address of the remote broker.
    port is the network port of the server host to connect to. Defaults to
    1883. Note that the default port for MQTT over SSL/TLS is 8883 so if you
    are using tls_set() the port may need providing.
    keepalive: Maximum period in seconds between communications with the
    broker. If no other messages are being exchanged, this controls the
    rate at which the client will send ping messages to the broker.
    clean_start: (MQTT v5.0 only) True, False or MQTT_CLEAN_START_FIRST_ONLY.  
    Sets the MQTT v5.0 clean_start flag always, never or on the first successful connect only,
    respectively.  MQTT session data (such as outstanding messages and subscriptions)
    is cleared on successful connect when the clean_start flag is set.
    properties: (MQTT v5.0 only) the MQTT v5.0 properties to be sent in the
    MQTT connect packet.
    """

3.发布主题示例:

使用client.publish()即可。

PUBLISH()

publish(topic, payload=None, qos=0, retain=False)

This causes a message to be sent to the broker and subsequently from the broker to any clients subscribing to matching topics. It takes the following arguments:

topic

the topic that the message should be published on

payload

the actual message to send. If not given, or set to None a zero length message will be used. Passing an int or float will result in the payload being converted to a string representing that number. If you wish to send a true int/float, use struct.pack() to create the payload you require

qos

the quality of service level to use

retain

if set to True, the message will be set as the “last known good”/retained message for the topic.

例如:

client.publish("test", "你好".encode(), 2)

 

 

 

相关标签: python3 mqtt