import paho.mqtt.client as mqtt
def on_message(client, userdata, message):
print('Received message on topic : '.format(message.topic, message.payload.decode('utf-8')))
client = mqtt.Client()
client.on_message = on_message
client.connect('localhost', 1883)
client.subscribe('my_topic')
client.loop_forever()
```This Python script demonstrates how to use the `paho-mqtt` library to receive messages from an MQTT broker. Here's a step-by-step explanation of what the code does:
1. **Import `paho.mqtt.client`**: The script begins by importing the `mqtt` module from the `paho-mqtt` library. This module provides classes and functions for connecting to and interacting with MQTT brokers.
2. **Define the `on_message` callback**: The `on_message` function is defined as a callback to be executed whenever a message is received on a subscribed topic. It takes three arguments:
- `client`: The MQTT client that received the message.
- `userdata`: Optional user-defined data associated with the client.
- `message`: An object representing the received message, containing the topic and payload.
3. **Create an MQTT client**: An instance of the `mqtt.Client` class is created. This object will be used to connect to the MQTT broker and perform various operations, such as subscribing to topics and handling incoming messages.
4. **Register the `on_message` callback**: The `on_message` callback is registered with the MQTT client using the `client.on_message` attribute. This ensures that the `on_message` function will be called whenever a message arrives on a subscribed topic.
5. **Connect to the MQTT broker**: The `client.connect` method is used to establish a connection with the MQTT broker running on `localhost` at port `1883`.
6. **Subscribe to a topic**: The `client.subscribe` method is used to subscribe to the topic with the name `my_topic`. This means that the client will start receiving and processing messages published to this topic by other clients or devices.
7. **Start the loop**: The `client.loop_forever` method is used to start an infinite loop that handles incoming messages and other network events. This loop will continue running until the program is stopped (e.g., by pressing `Ctrl+C`).
8. **Handle incoming messages**: Whenever a subscribed topic receives a message from the broker, the `on_message` callback gets executed. In this callback:
- It prints the message's topic and payload as a UTF-8 decoded string. This allows you to see the content of the received messages.
In summary, this script sets up an MQTT client, connects it to a broker, subscribes to a specific topic, and handles incoming messages by printing their topic and payload information. It provides a basic example of receiving messages from an MQTT broker using the `paho-mqtt` library.
Image: alltradertips.blogspot.com
Image: bartunest.blogspot.com
Forex Trading Basics In Telugu