WaveshareCloud Wiki Help

Python SDK

This article mainly introduces how to use the paho-mqtt client library in a Python project to achieve functions such as connecting, subscribing, unsubscribing, and sending/receiving messages between the client and MQTT server.

paho-mqtt is currently a widely used MQTT client library in Python. It provides support for MQTT v5.0, v3.1, and v3.1.1 for client classes on Python 2.7.9+ or 3.6+. It also provides some utility functions, making it very easy to publish messages to an MQTT server.

Prerequisites

Get Connection Parameters

  • After creating a usable device through WaveshareCloud in the Device|Attribute List, click the yellow button on the right: View Address to obtain relevant information.

Example:

  • MqttPath: mqtt.waveshare.cloud

  • Port: 1883

  • Client ID: 052405b2

  • Pub Topic: Pub/10/16/052405b2

  • Sub Topic: Sub/10/16/052405b2

Confirm Python Version

This project is tested with Python 3.10.9:

→ ~ python -V Python 3.10.9

Install Paho-mqtt

  1. pip is a Python package management tool, which provides the function of finding, downloading, installing and uninstalling Python packages. Use the following command to install paho-mqtt.

pip install paho-mqtt
  1. Import Paho-mqtt

import paho.mqtt.client as mqtt

Connection Methods

  • Set MQTT connection address, port, topics, and client ID.

HOST = "mqtt.waveshare.cloud" PORT = 1883 Client_ID = "052405b2" # Fill in the client id Publish_Topic = 'Pub/10/16/052405b2' # Fill in the publishing topic Subscribe_Topic = 'Sub/10/16/052405b2' # Fill in the subscribing topic
  • Set MQTTS connection address, port, topics, and client ID.

  • Load the CA certificate in the code by copying it locally.

HOST = "mqtt.waveshare.cloud" PORT = 8883 Client_ID = "052405b2" # Fill in the client id Publish_Topic = 'Pub/10/16/052405b2' # Fill in the publishing topic Subscribe_Topic = 'Sub/10/16/052405b2' # Fill in the subscribing topic client = mqtt.Client(Client_ID) # SSL/TSL configuration client.tls_set(ca_certs=None, certfile=None, keyfile=None, cert_reqs=mqtt.ssl.CERT_NONE, tls_version=mqtt.ssl.PROTOCOL_TLS)
  • Set MQTTS connection address, port, topics, and client ID.

  • Load the CA certificate in the code by copying it locally.

HOST = "mqtt.waveshare.cloud" PORT = 8884 Client_ID = "052405b2" # Fill in the client id Publish_Topic = 'Pub/10/16/052405b2' # Fill in the publishing topic Subscribe_Topic = 'Sub/10/16/052405b2' # Fill in the subscribing topic client = mqtt.Client(Client_ID) # SSL/TSL certificate configuration ca_cert = "./cert/rootCA.crt" # Replace with your CA certificate path client_cert = "./cert/server.crt" # Replace with your client certificate path client_key = "./cert/server.key" # Replace with your client key path client.tls_set(ca_certs=ca_cert, certfile=client_cert, keyfile=client_key, cert_reqs=mqtt.ssl.CERT_REQUIRED, tls_version=mqtt.ssl.PROTOCOL_TLS)
  • Write a callback function on_connect. It will be called directly after the MQTT connection. In this function, you can use rc to determine whether the client connection is successful. When rc is 0, the connection is successful. At this point, call paho.mqtt.client.subscribe to subscribe to messages.

def on_connect(client, userdata, flags, rc): print("Connected with result code " + str(rc)) if rc == 0: client.subscribe(Subscribe_Topic)

Subscribe and Publish

Subscription topics have been implemented in the previous section.

Unsubscribe

Unsubscribe by using the following code. Specify the topic to unsubscribe at this time.

def unsubscribe(client: mqtt_client): client.on_message = None client.unsubscribe(topic)

Publish Topic

Use a while loop to publish the content of the message body.

while True: message = "Hello, MQTT!" client.publish(Publish_Topic, message) print("Published message: " + message) time.sleep(1)

Receive Messages

Specify that the client listens for message events through the following code. After receiving a message, execute the callback function to print the received message to the console.

def on_message(client, userdata, msg): print("Received message: " + msg.payload.decode())

Disconnect

def disconnect(client: mqtt_client): client.loop_stop() client.disconnect()

Complete code

Connect via a TCP port

import paho.mqtt.client as mqtt import time HOST = "mqtt.waveshare.cloud" PORT = 1883 Client_ID = "" Publish_Topic = '' Subscribe_Topic = '' client = mqtt.Client(Client_ID) def on_connect(client, userdata, flags, rc): print("Connected with result code " + str(rc)) if rc == 0: client.subscribe(Subscribe_Topic) def on_message(client, userdata, msg): print("Received message: " + msg.payload.decode()) def define(): client.on_connect = on_connect client.on_message = on_message client.connect(HOST, PORT, 60) client.loop_start() if __name__ == '__main__': define() try: while True: message = "Hello, MQTT!" client.publish(Publish_Topic, message) print("Published message: " + message) time.sleep(1) except KeyboardInterrupt: client.loop_stop() client.disconnect() print("MQTT client disconnected.")

Connect over SSL/TSL ports (certificateless)

import paho.mqtt.client as mqtt import time HOST = "mqtt.waveshare.cloud" PORT = 8884 Client_ID = "" Publish_Topic = '' Subscribe_Topic = '' client = mqtt.Client(Client_ID) client.tls_set(ca_certs=None, certfile=None, keyfile=None, cert_reqs=mqtt.ssl.CERT_NONE, tls_version=mqtt.ssl.PROTOCOL_TLS) connected = False def on_connect(client, userdata, flags, rc): global connected print("Connected with result code " + str(rc)) if rc == 0: client.subscribe(Subscribe_Topic) connected = True def on_message(client, userdata, msg): print("Received message: " + msg.payload.decode()) def define(): client.on_connect = on_connect client.on_message = on_message client.connect(HOST, PORT, 60) client.loop_start() if __name__ == '__main__': define() while not connected: time.sleep(1) try: while True: message = "Hello, MQTT!" client.publish(Publish_Topic, message) print("Published message: " + message) time.sleep(1) except KeyboardInterrupt: client.loop_stop() client.disconnect() print("MQTT client disconnected.")

Connect via SSL/TSL port (with certificate)

import paho.mqtt.client as mqtt import time HOST = "mqtt.waveshare.cloud" PORT = 8884 Client_ID = "" Publish_Topic = '' Subscribe_Topic = '' client = mqtt.Client(Client_ID) ca_cert = "Path/cert/rootCA.crt" client_cert = "Path/cert/server.crt" client_key = "Path/cert/server.key" client.tls_set(ca_certs=ca_cert, certfile=client_cert, keyfile=client_key, cert_reqs=mqtt.ssl.CERT_REQUIRED, tls_version=mqtt.ssl.PROTOCOL_TLS) connected = False def on_connect(client, userdata, flags, rc): global connected print("Connected with result code " + str(rc)) if rc == 0: client.subscribe(Subscribe_Topic) connected = True def on_message(client, userdata, msg): print("Received message: " + msg.payload.decode()) def define(): client.on_connect = on_connect client.on_message = on_message client.connect(HOST, PORT, 60) client.loop_start() if __name__ == '__main__': define() while not connected: time.sleep(1) try: while True: message = "Hello, MQTT!" client.publish(Publish_Topic, message) print("Published message: " + message) time.sleep(1) except KeyboardInterrupt: client.loop_stop() client.disconnect() print("MQTT client disconnected.")
Last modified: 12 一月 2024