Smart Cities - Python MQTT class library: Difference between revisions
No edit summary |
|||
| Line 51: | Line 51: | ||
This imports the Paho MQTT library, which provides tools for creating and managing MQTT clients. MQTT (Message Queuing Telemetry Transport) is a lightweight messaging protocol often used for IoT and home automation systems. | This imports the Paho MQTT library, which provides tools for creating and managing MQTT clients. MQTT (Message Queuing Telemetry Transport) is a lightweight messaging protocol often used for IoT and home automation systems. | ||
= The Mqtt Class = | |||
This class encapsulates the MQTT functionality, allowing you to create an MQTT client, subscribe to topics, and publish messages. | |||
== Constructor: __init__(self, host, port, callback) == | |||
<syntaxhighlight lang="python"> | |||
def __init__(self, host, port, callback): | |||
self.client = mqtt.Client() # Create an mqtt client | |||
self.client.on_message = callback # Assign a message handler | |||
if (self.client.connect(host, port, 60) == 0): # Connect to the mqtt broker | |||
print('Connected to MQTT broker') | |||
self.client.loop_start() # Start handling mqtt messages | |||
print('MQTT client started') | |||
</syntaxhighlight> | |||
* '''self.client = mqtt.Client()''': Creates an instance of the MQTT client. | |||
* '''self.client.on_message = callback''': Assigns a callback function to handle incoming messages. The callback function is passed as a parameter when creating an instance of the Mqtt class. | |||
* '''self.client.connect(host, port, 60)''': Connects the MQTT client to the MQTT broker, using the specified host (IP address or domain name) and port (commonly 1883 for unencrypted MQTT). | |||
* '''60''' refers to the keep-alive interval in seconds, which helps maintain the connection to the broker. | |||
If the connection is successful (returns 0), it prints a success message. | |||
* '''self.client.loop_start()''': Starts a background thread that handles the sending and receiving of MQTT messages, so you don't have to block the main thread. | |||
= subscribe(self, topic) = | |||
<syntaxhighlight lang="python"> | |||
def subscribe(self, topic): | |||
self.client.subscribe(topic) | |||
</syntaxhighlight> | |||
This method allows the client to subscribe to a specific MQTT topic. When subscribed, the client will receive all messages published to this topic. | |||
= publish(self, topic, message) = | |||
<syntaxhighlight lang="python"> | |||
def publish(self, topic, message): | |||
self.client.publish(topic, message) | |||
</syntaxhighlight> | |||
This method allows the client to publish a message to a specific MQTT topic. Any subscribers to that topic will receive the message. | |||
Revision as of 08:58, 29 September 2024
MQTT Class library
This Python program implements an MQTT client using the Paho MQTT library. It creates a simple class called Mqtt that can subscribe to and publish messages on MQTT topics, typically used in home automation systems. Let’s break down the program step by step.
#Home automation system MQTT class library
#Copyright (c) 2024, Julie VK3FOWL and Joe VK3YSP.
#For The School Amater Radio Club Network (r) VK3SRC.
#This program:
# Implements a Message Queuing Telemetry Transport (MQTT) client
# Subscribes to MQTT topics
# Publishes MQTT messages
import paho.mqtt.client as mqtt
class Mqtt(object):
def __init__(self, host, port, callback):
#Constructor
self.client = mqtt.Client() #Create an mqtt client
self.client.on_message = callback #Assign a message handler
if (self.client.connect(host, port, 60) == 0): #Connect to the mqtt broker
print('Connected to MQTT broker')
self.client.loop_start() #Start handling mqtt messages
print('MQTT client started')
def subscribe(self, topic):
#Subscribe to an mqtt topic
self.client.subscribe(topic)
def publish(self, topic, message):
#Subscribe to an mqtt topic
self.client.publish(topic, message)
if __name__ == '__main__': #Run this code stand-alone
#Test script - This script creates a MQTT object and demonstrates subscribing and publishing messages
def mqttCallback(client, userdata, message):
#This function handles received MQTT messages
print(f'MQTT: {message.topic}: {message.payload.decode()}') #Print the topic and message
mqttIP = 'localhost' #Assume the MQTT broker is running on this machine
mqttPort = 1883 #The standard MQTT port
mqtt = Mqtt(mqttIP, mqttPort, mqttCallback) #Create an MQTT object
mqtt.subscribe('Test1') #Subscribe to the Test1 topic
mqtt.subscribe('Test2') #Subscribe to the Test2 topic
mqtt.publish('Test1','Message1') #Publish a message to the Test1 topic
mqtt.publish('Test2','message2') #Publish a message to the Test2 topic
Imports
import paho.mqtt.client as mqtt
This imports the Paho MQTT library, which provides tools for creating and managing MQTT clients. MQTT (Message Queuing Telemetry Transport) is a lightweight messaging protocol often used for IoT and home automation systems.
The Mqtt Class
This class encapsulates the MQTT functionality, allowing you to create an MQTT client, subscribe to topics, and publish messages.
Constructor: __init__(self, host, port, callback)
def __init__(self, host, port, callback):
self.client = mqtt.Client() # Create an mqtt client
self.client.on_message = callback # Assign a message handler
if (self.client.connect(host, port, 60) == 0): # Connect to the mqtt broker
print('Connected to MQTT broker')
self.client.loop_start() # Start handling mqtt messages
print('MQTT client started')
- self.client = mqtt.Client(): Creates an instance of the MQTT client.
- self.client.on_message = callback: Assigns a callback function to handle incoming messages. The callback function is passed as a parameter when creating an instance of the Mqtt class.
- self.client.connect(host, port, 60): Connects the MQTT client to the MQTT broker, using the specified host (IP address or domain name) and port (commonly 1883 for unencrypted MQTT).
- 60 refers to the keep-alive interval in seconds, which helps maintain the connection to the broker.
If the connection is successful (returns 0), it prints a success message.
- self.client.loop_start(): Starts a background thread that handles the sending and receiving of MQTT messages, so you don't have to block the main thread.
subscribe(self, topic)
def subscribe(self, topic):
self.client.subscribe(topic)
This method allows the client to subscribe to a specific MQTT topic. When subscribed, the client will receive all messages published to this topic.
publish(self, topic, message)
def publish(self, topic, message):
self.client.publish(topic, message)
This method allows the client to publish a message to a specific MQTT topic. Any subscribers to that topic will receive the message.