Skip to content
d00dz edited this page Apr 11, 2025 · 1 revision

MQTT Environment for PLC and HMI Simulation

This repository demonstrates a simple MQTT-based simulation environment consisting of three main components:

  • Mosquitto Broker: Acts as the central MQTT broker that routes messages between clients.
  • PLC (Publisher): A Python script that simulates a PLC by publishing sensor values (randomly generated) to an MQTT topic.
  • HMI (Subscriber): A Python script that simulates an HMI by subscribing to that MQTT topic and displaying the received sensor values.

How It Works

  1. Mosquitto Broker
    Mosquitto is a lightweight MQTT broker that listens on the default MQTT port (1883). It handles connections from both the PLC and the HMI. When the PLC publishes a sensor value to the MQTT topic (in this case, plc/sensor), Mosquitto forwards that message to all clients subscribed to that topic.

  2. PLC (Publisher)
    The PLC script (plc_mqtt.py) simulates a real PLC by publishing a new random sensor value (an integer between 0 and 100) every 2 seconds to the MQTT topic plc/sensor. This mimics a PLC sending periodic sensor readings.

  3. HMI (Subscriber)
    The HMI script (hmi_mqtt.py) acts as an MQTT subscriber. It connects to the broker, subscribes to the topic plc/sensor, and displays the sensor values it receives on the console.


Installing Mosquitto

  1. Update your package lists and install Mosquitto along with its client tools:
    sudo apt update
    sudo apt install mosquitto mosquitto-clients
  2. Start the Mosquitto service:
    sudo systemctl start mosquitto

Running the Python Scripts

  1. Running the PLC (Publisher) Open a terminal and navigate to the directory containing plc_mqtt.py.

Run the script:

python3 plc_mqtt.py
  • The PLC script connects to the MQTT broker at localhost:1883 and publishes a random sensor value (0–100) to the topic plc/sensor every 2 seconds.
  1. Running the HMI (Subscriber) Open another terminal and navigate to the directory containing hmi_mqtt.py.

Run the script:

python3 hmi_mqtt.py
  • The HMI script connects to the broker, subscribes to the topic plc/sensor, and prints the sensor values as they are received.

Monitoring MQTT Traffic with Wireshark

To verify that MQTT messages are transmitted correctly:

  1. Open Wireshark.
  2. Set a display filter to capture MQTT traffic on port 1883:
tcp.port == 1883
  1. You should see MQTT packets with proper MQTT headers (including message types, topics, etc.), confirming that the PLC and HMI are correctly using the MQTT protocol.