Reading HW9 (BNI) MQTT Data Via Python
1. Introduction
Provides instructions on how to use Python to subscribe and retrieve data from an MQTT topic, specifically targeting the BNI (Balluff HW9 IO-Link Master) device series.
2. Prerequisites
- Python installed on your system.
- Basic understanding of the MQTT protocol.
- Access to an installed and running MQTT broker.
3.1. Install Required Libraries
Ensure you have the `paho-mqtt` library installed. You can install it using the pip command below if it's not already installed:
pip install paho-mqtt
3.2. Python Code Setup
Create a Python script using the following code to connect to the MQTT broker and subscribe to the specified topic:
Enter the code below into your python IDE
import paho.mqtt.client as mqtt
import json
def on_connect(client, userdata, flags, rc):
if rc == 0:
print("Connected")
client.subscribe("balluff//iolink/devices/master1port8/processdata/in")
else:
print("Failed to connect, Error code", rc)
def on_message(client, userdata, msg):
payload = json.loads(msg.payload.decode())
item = payload.get("data", {}).get("items", {})
print(item)
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("192.168.10.200", 1883)
client.loop_forever()
3.3. Understanding the Code
on_connect: Handles connection to the MQTT broker and subscribes to the specified topic.
on_message: Processes incoming MQTT messages. It decodes the JSON payload and retrieves relevant data from the message.
3.4. Run the Script
Run the Python script. It will connect to the MQTT broker at `192.168.10.200` on port `1883` and start listening for messages on the specified topic.
4. Conclusion
This concludes the manual for reading MQTT data from the BNI device using Python. For further customization or integration into larger systems, refer to MQTT and Python documentation.
5. Troubleshooting
- Ensure the MQTT broker address (`192.168.10.200`) and port (`1883`) are correct and accessible from your network.
- Check for any firewall or network restrictions that might prevent connections.
- Confirm Broker Status: Ensure your MQTT broker is running by using debugging tools such as MQTT Explorer. Navigate to Services > Mosquitto to verify that it is active.
- Check BNI Device Connection: Confirm that your BNI device is properly configured and connected to the broker. If connected, you will see relevant status indicators, as shown in the image below.
- Setup Instructions: If you have not yet set up your broker or configured your BNI device, please refer to the following resources:
- Technical Application Notes
- Document: doc-18588303 - Install Mosquitto Broker and Connect MQTT on HW9 (BNI) Devices