[Xiao Mu learns Python] Python implements communication protocol (mqtt)

1 Introduction

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

The MQTT protocol is a machine-to-machine (M2M)/"Internet of Things" connectivity protocol. It is designed as an extremely lightweight publish/subscribe messaging transport, useful for connections to remote locations that require a small code footprint and/or where network bandwidth is at a premium.

MQTT is a lightweight publish/subscribe communication protocol that is particularly suitable for low-bandwidth, high-latency or unstable network environments. Because of its high efficiency and low consumption, MQTT has become the standard for IoT communication.

MQTT is a standard binary publish-subscribe messaging protocol designed for fast and reliable transfer of industrial asset, system and application data for predictive maintenance, especially under very constrained conditions. Limitations may include unreliable network connections, limited bandwidth, or limited battery power. MQTT is built on TCP/IP, the preferred communication protocol for connecting network devices on the Internet. Therefore, MQTT is very suitable for IIoT and supports event-driven architecture.

Insert image description here
MQTT technology is designed to push data to and obtain data from thousands of remote assets, systems and applications within the enterprise. MQTT Sparkplug is a framework that sits on top of MQTT to add more context to industrial data. It is an open source software specification that provides a framework for MQTT clients to integrate various industrial data and provide context by defining data models. It provides manufacturing equipment manufacturers and software providers with a consistent way to share contextual plant data, enriched with predictive maintenance data.
Insert image description here
MQTT allows for real-time tracking of vehicles, providing the latest location and status updates. This capability helps monitor and improve delivery schedules, optimize routes, and increase overall fleet efficiency.
Insert image description here
One of the biggest advantages of MQTT is the ability to have a unified namespace (UNS) as a single truth for all OEE data from different systems (such as factory machines, quality systems, MES, ERP, etc.) The source is then made available to applications that can use and act on it. (Supports different data types and data rates)
Insert image description here

2. Installation

pip install paho-mqtt
# pip3 install -i https://pypi.doubanio.com/simple paho-mqtt

# or
git clone https://github.com/eclipse/paho.mqtt.python
cd paho.mqtt.python
python setup.py install

Insert image description here

3. Basic code

3.1 Based on Apollo service

  • Server-side construction:
    https://archive.apache.org/dist/activemq/activemq-apollo/1.7.1/
  • Extract and open the target as follows:
    The pollo middleware is actually free of installation. We only need to download apache-apollo-1.7.1-windows-distro.zip, and then unzip it to A certain folder will do. Here I extracted it to D:\soft\apache-apollo-1.7.1.
    Insert image description here
    (1) First go to the apollo directory and cd D:\soft\apache-apollo-1.7.1
    (2) D:\soft\apache-apollo -1.7.1\bin
    (3) Execute the command apollo create myapollo

Insert image description here
The following error occurred Loading configuration file 'D:\phpStudy\apache-apollo-1.7.1\bin\mybroker\etc\apollo.xml'.
Startup failed: java. lang.NoClassDefFoundError: javax/xml/bind/ValidationEventHandler
Answer: Just change to jdk1.8 version.
Insert image description here

apollo-broker.cmd run

Insert image description here
Enter the background management, open the web page, enter ip +: 61680 to enter the background management, the default user name is admin and the password is password, for example, 127.0.0.1:61680

http://127.0.0.1:61680

Insert image description here
Insert image description here

  • Subscribe to topic
import time

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):
    if rc == 0:
        print("连接成功")
        print("Connected with result code " + str(rc))

def on_message(client, userdata, msg):
    print(msg.topic + " " + str(msg.payload))
client = mqtt.Client(protocol=3)
client.username_pw_set("admin", "password")
client.on_connect = on_connect
client.on_message = on_message
client.connect(host="127.0.0.1", port = 61613, keepalive=60)  # 订阅频道
time.sleep(1)
# client.subscribe("public")
client.subscribe([("public", 0), ("test", 2)])
client.loop_forever()
  • Post topic
import paho.mqtt.client as mqtt
import time
import sys
def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))
def on_subscribe(client,userdata,mid,granted_qos):
    print("消息发送成功")
client = mqtt.Client(protocol=3)
client.username_pw_set("admin", "password")
client.on_connect = on_connect
client.on_subscribe = on_subscribe
client.connect(host="127.0.0.1", port = 61613, keepalive=60)  # 订阅频道
time.sleep(1)
i = 0
while True:
    try:
        # 发布MQTT信息
        sensor_data = "test" + str(i)
        client.publish(topic="public", payload=sensor_data, qos=0)
        time.sleep(5)
        i += 1
    except KeyboardInterrupt:
        print("EXIT")
        client.disconnect()
        sys.exit(0)

After executing the above script:
Insert image description here

3.2 Based on public services

Here, we choose to use the free MQTT public server provided by EMQX, but you can also choose any other MQTT broker.

Broker: broker.emqx.io
TCP Port: 1883
Websocket Port: 8083
  • Message publishing code, pub.py
# python 3.6
 
import random
import time
 
from paho.mqtt import client as mqtt_client
 
 
broker = 'broker.emqx.io'
port = 1883
topic = "/python/mqtt"
# generate client ID with pub prefix randomly
client_id = f'python-mqtt-{
      
      random.randint(0, 1000)}'
 
 
def connect_mqtt():
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            print("Connected to MQTT Broker!")
        else:
            print("Failed to connect, return code %d\n", rc)
 
    client = mqtt_client.Client(client_id)
    client.on_connect = on_connect
    client.connect(broker, port)
    return client
 
 
def publish(client):
    msg_count = 0
    while True:
        time.sleep(1)
        msg = f"messages: {
      
      msg_count}"
        result = client.publish(topic, msg)
        # result: [0, 1]
        status = result[0]
        if status == 0:
            print(f"Send `{
      
      msg}` to topic `{
      
      topic}`")
        else:
            print(f"Failed to send message to topic {
      
      topic}")
        msg_count += 1
 
 
def run():
    client = connect_mqtt()
    client.loop_start()
    publish(client)
 
 
if __name__ == '__main__':
    run()
  • Message subscription code, sub.py
# python3.6
 
import random
 
from paho.mqtt import client as mqtt_client
 
 
broker = 'broker.emqx.io'
port = 1883
topic = "/python/mqtt"
# generate client ID with pub prefix randomly
client_id = f'python-mqtt-{
      
      random.randint(0, 100)}'
 
 
def connect_mqtt() -> mqtt_client:
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            print("Connected to MQTT Broker!")
        else:
            print("Failed to connect, return code %d\n", rc)
 
    client = mqtt_client.Client(client_id)
    client.on_connect = on_connect
    client.connect(broker, port)
    return client
 
 
def subscribe(client: mqtt_client):
    def on_message(client, userdata, msg):
        print(f"Received `{
      
      msg.payload.decode()}` from `{
      
      msg.topic}` topic")
 
    client.subscribe(topic)
    client.on_message = on_message
 
 
def run():
    client = connect_mqtt()
    subscribe(client)
    client.loop_forever()
 
 
if __name__ == '__main__':
    run()

4. More code (flask)

4.1 Install flask_mqtt library

pip install flask_mqtt

Insert image description here

4.2 Write flask_mqtt script

Write code:

from flask import Flask, request, jsonify
from flask_mqtt import Mqtt

app = Flask(__name__)

# 代理地址
app.config['MQTT_BROKER_URL'] = 'broker.emqx.io'
# 端口
app.config['MQTT_BROKER_PORT'] = 1883
# 当需要验证用户名和密码时,请设置该项
app.config['MQTT_USERNAME'] = 'user'
# 当需要验证用户名和密码时,请设置该项
app.config['MQTT_PASSWORD'] = '123456'
# 设置心跳时间,单位为秒
app.config['MQTT_KEEPALIVE'] = 60
# 如果服务器支持 TLS,则设置为 True
app.config['MQTT_TLS_ENABLED'] = False
# 主题
topic = '/flask/mqtt'
# 实例化
mqtt_client = Mqtt(app)

@app.route('/')
def index():
    # 初始路由
    return "Welcome mqtt_flask"

@mqtt_client.on_connect()
def handle_connect(client, userdata, flags, rc):
    """连接回调函数"""
    if rc == 0:
        print('Connected successfully')
        # 订阅主题
        mqtt_client.subscribe(topic)
    else:
        # 连接失败
        print('Bad connection. Code:', rc)

@mqtt_client.on_message()
def handle_mqtt_message(client, userdata, message):
    """ 消息回调函数 """
    # 定义接受到的消息
    data = dict(
        # 主题
        topic=message.topic,
        # 内容
        payload=message.payload.decode()
    )
    # 打印输出接收到的消息
    print('Received message on topic: {topic} with payload: {payload}'.format(**data))

@app.route('/publish', methods=['POST'])
def publish_message():
    """ 消息发布接口(实际应用中,该接口可能需要处理一些复杂业务逻辑) """
    # 格式化数据
    request_data = request.get_json()
    # 发布消息
    publish_result = mqtt_client.publish(request_data['topic'], request_data['msg'])

    return jsonify({
    
    'code': publish_result[0]})

if __name__ == '__main__':
    # app.run()
    app.run(host='127.0.0.1', port=5000)

When the Flask application is started, the MQTT client will connect to the server and subscribe to the topic /flask/mqtt.
Insert image description here

4.3 Install MQTTX (MQTT client)

https://mqttx.app/zh/downloads
Insert image description here
The main interface is displayed as follows:
Insert image description here

4.4 Test message reception

  • Create connection
Host:为代码中定义好的 broker.emqx.io
Port:为代码中定义好的 1883
用户名、密码根据需要添加

Insert image description here

  • Add subscription
    The topic is: /flask/mqtt
    Insert image description here
    Insert image description here
  • Publish message in MQTTX
    Insert image description here
    Message received in Flask console:
    Insert image description here

4.5 Test message release

  • Subscription using message reception
    The topic is: /flask/mqtt

Use Postman to call the /publish interface: send the message Hello from Flask to the /flask/mqtt topic.

Insert image description here
You will be able to see the message sent by Flask in MQTTX.
Insert image description here
You will be able to see the message sent by Flask in python.
Insert image description here

Conclusion

如果您觉得该方法或代码有一点点用处,可以给作者点个赞,或打赏杯咖啡;╮( ̄▽ ̄)╭
如果您感觉方法或代码不咋地//(ㄒoㄒ)//,就在评论处留言,作者继续改进;o_O???
如果您需要相关功能的代码定制化开发,可以留言私信作者;(✿◡‿◡)
感谢各位大佬童鞋们的支持!( ´ ▽´ )ノ ( ´ ▽´)! ! !

Guess you like

Origin blog.csdn.net/hhy321/article/details/134907922