程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[Python] use the PAHO mqtt library to realize mqtt listening and sending / receiving

編輯:Python

Reprinted from :

How to be in Python Use in MQTT - You know Python It's a widely used interpretive type 、 Advanced programming 、 Universal programming language .Python The philosophy of design emphasizes the readability of code and concise syntax ( In particular, use space indentation to divide code blocks , Instead of using braces or keywords ).Python Allow developers to express with less code …https://zhuanlan.zhihu.com/p/187481769

Python  It's a widely used interpretive type 、 Advanced programming 、 Universal programming language .Python The philosophy of design emphasizes the readability of code and concise syntax ( In particular, use space indentation to divide code blocks , Instead of using braces or keywords ).Python Let developers express their ideas in less code , Whether it's a small or a large program , The language tries to make the structure of the program clear .

MQTT  It's based on publishing / Subscription mode   Lightweight Internet of things message transmission protocol  , It can provide real-time and reliable message services for networked devices with very little code and bandwidth , It is widely used in the Internet of things 、 Mobile Internet 、 Smart hardware 、 Car networking 、 Power, energy and other industries .

This article mainly introduces how to do it in Python Project use  paho-mqtt  Client library , Implement client and MQTT Server connection 、 subscribe 、 Unsubscribe 、 Send and receive messages and other functions .

Project initialization

This project uses Python 3.6 Conduct development testing , The reader can confirm with the following command Python Version of .

* ~ python3 --version
Python 3.6.7

choice MQTT Client library

paho-mqtt  Is currently the Python It's more used in MQTT Client library , It's in Python 2.7 or 3.x For client classes, the MQTT v3.1 and v3.1.1 Support for . It also provides some helper functions , To publish a message to MQTT The server becomes very simple .

Pip install Paho MQTT client

Pip yes Python Package management tools , The tool provides the right Python Bag search 、 download 、 install 、 Uninstalled features .

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

Python MQTT Use

Connect MQTT The server

This article will use EMQ X Provided   Free public MQTT The server , The service is based on EMQ X Of  MQTT Internet of things cloud platform   establish . The server access information is as follows :

  • Broker: http://broker.emqx.io
  • TCP Port: 1883
  • Websocket Port: 8083

Import Paho MQTT client

from paho.mqtt import client as mqtt_client

Set up MQTT Broker Connection parameters

Set up MQTT Broker Connection address , Ports and topic, At the same time, we call Python random.randint  Functions are randomly generated MQTT client id.

broker = 'broker.emqx.io'
port = 1883
topic = "/python/mqtt"
client_id = f'python-mqtt-{random.randint(0, 1000)}'

To write MQTT Join function

Write the connection callback function  on_connect, This function will be called after the client connects , In this function, you can use  rc  To determine whether the client is successfully connected . Usually at the same time we will create a MQTT client , The client will connect to  broker.emqx.io.

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)
# Set Connecting Client ID
client = mqtt_client.Client(client_id)
client.on_connect = on_connect
client.connect(broker, port)
return client

Release the news

So let's define a while Loop statement , In the loop we will set the call per second MQTT client  publish  Functional direction  /python/mqtt  Subject send message .

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

Subscribe to news

Write a message callback function  on_message, This function will be used on the client side from MQTT Broker Called after receiving the message , In this function, we will print out the subscribed topic Name and received message content .

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

Complete code

Message release code

# 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

# 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()

test

News release

function MQTT Message release code , We'll see the client connect successfully , And successfully publish the message .

python3 pub.py

News subscription

function MQTT Message subscription code , We'll see the client connect successfully , And successfully received the published message .

python3 sub.py

summary

thus , We finished using  paho-mqtt  The client connects to   public MQTT The server , And realized the test client and MQTT Server connection 、 Message publishing and subscription .

And C ++ or Java And other high-level languages ,Python It is more suitable for the business logic implementation on the device side , Use Python You can reduce the logical complexity of your code , Reduce the cost of interacting with the device . We believe in the Internet of things Python There will be a wider range of applications .

Next, we will release more about the Internet of things development and Python Related articles of , Stay tuned .


Postscript :

This article uses  EMQ  Provided by the company   Free public    MQTT service , Used for testing . The content of this article is also EMQ Official articles of the company , The code is simple and practical , To prevent quality content from being swallowed , Redeposit .

In this paper, the Python The code uses the latest (python3.6 And later )f-string Format String Syntax , Than %s  and  format  Of   More intuitive syntax .

name = 'apple'
print(f"I eat an `{name}` ")
# The output is I eat an apple

Copyright notice : This paper is about  EMQ  original , Reprint please indicate the source .
Link to the original text :https://www.emqx.io/cn/blog/how-to-


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved