In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly shows you "how to use MQTT on raspberry pie". The content is easy to understand and clear. I hope it can help you solve your doubts. Let me lead you to study and learn this article "how to use MQTT on raspberry pie".
Setting up the environment and installing Python3
This project is developed using Python3. In general, Python3 is built into the raspberry pie system. If you are not sure whether it has been installed in the system, you can use the following command to confirm it.
Python3-version
If Python 3.x.x is displayed (x represents a number), it is already installed, otherwise use the apt command to install (or follow the Python3 installation guide).
Sudo apt install python3 installs MQTT client libraries
In order to connect to the MQTT server, we need to install the paho-mqtt library. You can choose one of the following two methods to install.
Install using source code
Git clone https://github.com/eclipse/paho.mqtt.python cd paho.mqtt.python python3 setup.py install
Install using pip3
The use of pip3 install paho-mqttMQTT to connect to MQTT servers
This article will use the free public MQTT server provided by EMQ X, which is based on EMQ X's MQTT Internet of things cloud platform. The server access information is as follows:
Broker: broker.emqx.io
TCP Port: 1883
Websocket Port: 8083
If necessary, you can also use docker to quickly install the EMQ X server locally.
Docker run-d-- name emqx-p 1883 emqx/emqx 1883-p 8083 emqx/emqx
Connection sample code
# test_connect.py import paho.mqtt.client as mqtt # callback function. This function is triggered when an attempt is made to establish a connection with MQTT broker. # client is the client instance of this connection. # userdata is the user's information, which is generally empty. However, if necessary, you can also set it through the user_data_set function. # flags keeps a dictionary of server response flags. # rc is the response code. In general, we only need to pay attention to whether the rc response code is 0. Def on_connect (client, userdata, flags, rc): if rc = 0: print ("Connected success") else: print (f "Connected fail with code {rc}") client = mqtt.Client () client.on_connect = on_connect client.connect ("broker.emqx.io", 1883, 60) client.loop_forever ()
Save the above code as a test_connect.py file and run
Python3 test_connect.py
We judge the response code in the on_connect function. A value of 0 means that the output Connected success indicates a successful connection. If other numbers are returned, we need to judge against the response code below.
0: connection success 1: connection failure-incorrect protocol version 2: connection failure-invalid client identifier 3: connection failure-server unavailable 4: connection failure-incorrect user name or password 5: connection failure-unauthorized 6-255: undefined. If it is another problem, you can check the network condition or confirm whether `connection mqtt` is installed.
In the concept of MQTT protocol, messages are delivered through topics, such as device A sending messages to topic T, then only devices subscribed to topic T can receive them. So just accessing the MQTT server doesn't mean much. To fully use the MQTT service, we also need to know how to subscribe and publish messages.
Subscribe to messages
Open any editor, enter the following code, and save it as a subscriber.py file:
# subscriber.pyimport paho.mqtt.client as mqttdef on_connect (client, userdata, flags, rc): print (f "Connected with result code {rc}") # subscription, which needs to be placed in on_connect # if you lose your connection with broker and reconnect, you will continue to subscribe to the raspberry/topic topic client.subscribe ("raspberry/topic") # callback function when you receive a message Trigger the function def on_message (client, userdata, msg): print (f "{msg.topic} {msg.payload}") client = mqtt.Client () client.on_connect = on_connectclient.on_message = on_message# to set the testament message when the raspberry pie is powered off or the network is interrupted abnormally. Send a testamentary message to other clients client.will_set ('raspberry/status', {"status": "Off"}) # to create a connection. The three parameters are broker address, broker port number, client.connect ("broker.emqx.io", 1883, 60) # set network loop blocking, and will not actively end the program client.loop_forever () before calling disconnect () or the program crashes.
Call the subscribe () function to get the raspberry pie to subscribe to a topic. In the above code, we use it to subscribe to raspberry/topic topics and listen for messages.
In addition, we set up the testamentary message using will_set (). A testamentary message is a feature of MQTT that sends a message to a specific topic when the device is accidentally disconnected from the network. Through this feature, we can know whether the raspberry pie has a power outage or a network anomaly.
Publish a message
Open any editor, enter the following code, and save it as a publisher.py file:
Import paho.mqtt.client as mqttimport timedef on_connect (client, userdata, flags, rc): print (f "Connected with result code {rc}") client = mqtt.Client () client.on_connect = on_connectclient.connect ("broker.emqx.io", 1883, 60) # send a message to raspberry/topic every second, for i in range (5): # four parameters are: subject, send content QoS, whether to keep the message client.publish ('raspberry/topic', payload=i, qos=0, retain=False) print (f "send {I} to raspberry/topic") time.sleep (1) client.loop_forever ()
Call the publish () function to send a message to a topic. In the above code, we used it to send messages to the subject raspberry/topic. The parameter QoS is another MQTT feature. If you want to know more about QoS, you can see the introduction to MQTT QoS (quality of Service). Here we set it to 0.
test
We used the MQTT 5.0client tool-MQTT X for the following tests.
Test subscription messages
Run the Python code and proactively send a message.
Open the terminal, run the Python code, and listen for messages.
Python3 subscriber.py
Use the MQTT X client to establish a connection to the MQTT server and send a message to the subject raspberry/topic.
Check the raspberry pie terminal information and you will see that the message published by MQTT X has been successfully received.
Test release message
Subscribe to raspberry/topic topics in the MQTT X client.
Run the Python code on the terminal.
In the MQTT X client, view the message sent by the raspberry pie.
Test testament message
Next, test whether the will message is set successfully.
In the MQTT X client, subscribe to raspberry/status.
Interrupt the program, or disconnect the raspberry pie network.
In the MQTT X client, view the messages received by the raspberry/status topic.
The above is all the content of the article "how to use MQTT on raspberry pie". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.