fg71
Lets make a example in Python to prototype a Gateway or Bridge between Modbus TCP and MQTT.
In OpenPLC we will use the blink example and use Modbus TCP Server. We use the LED_BUILTIN and use the location address to point to pin 13. ex. %QX0.3 but it could be something else if you have other I/O configuration. Make sure you have the modules installed for your system python.
 
We will create 2 python script. modbus_mqtt.py and sub_mqtt.py and make both running on your local computer.
 
So what will happen: Your Arduino compatible board will blink the built-in LED. The modbus_mqtt.py script will read the state bit address 3 and publish its state to MQTT on the localhost. The script sub_mqtt.py will subscript for topic and print the payload in the terminal.
 
In the modbus_mqtt.py we include:
import time
import paho.mqtt.client as mqtt
from pymodbus.client import ModbusTcpClient

# Configuration for Modbus device
MODBUS_IP = 'YOUR_IP'  # IP address of the Modbus device
MODBUS_PORT = 502      # Port of the Modbus device

# Configuration for MQTT broker
MQTT_BROKER = 'localhost'   # IP address of the MQTT broker
MQTT_PORT = 1883            # Port of the MQTT broker
MQTT_TOPIC_SUBSCRIBE = 'mqtt/to/modbus'  # MQTT topic to subscribe for incoming data
MQTT_TOPIC_PUBLISH = 'modbus/to/mqtt'    # MQTT topic to publish data from Modbus

# Create Modbus client
modbus_client = ModbusTcpClient(MODBUS_IP, port=MODBUS_PORT)

# Create MQTT client
mqtt_client = mqtt.Client()

# Callback when the client receives a CONNACK response from the server
def on_connect(client, userdata, flags, rc):
    print("Connected to MQTT broker with result code " + str(rc))
    # Subscribing to a topic
    client.subscribe(MQTT_TOPIC_SUBSCRIBE)

# Callback when a PUBLISH message is received from the server
def on_message(client, userdata, msg):
    print(f"Received message from MQTT: {msg.topic} {msg.payload.decode()}")
    # Write received data to Modbus device as a coil
    data = bool(int(msg.payload.decode()))
    modbus_client.write_coil(0, data, unit=1)

# Assign the on_connect and on_message callbacks
mqtt_client.on_connect = on_connect
mqtt_client.on_message = on_message

# Connect to the MQTT broker
mqtt_client.connect(MQTT_BROKER, MQTT_PORT, 60)

# Function to read coils from Modbus and publish to MQTT
def modbus_to_mqtt():
    while True:
        try:
            # Read coils from Modbus device
            response = modbus_client.read_coils(address=0, count=10)
            if response.isError():
                print("Error reading coils from Modbus device")
            else:
                # Get the data from the response
                data = response.bits[3] # %QX0.3
                print(f"Read coil LED from Modbus: {data}")

                # Publish data to MQTT
                mqtt_client.publish(MQTT_TOPIC_PUBLISH, str(data))

            # Wait for a short interval before the next read/write cycle
            time.sleep(5)
        except Exception as e:
            print(f"Exception: {e}")

# Start the Modbus to MQTT publishing in the background
import threading
modbus_thread = threading.Thread(target=modbus_to_mqtt)
modbus_thread.start()

# Blocking call to process network traffic, callbacks, and reconnecting
mqtt_client.loop_forever()

# Close the Modbus client when done
modbus_client.close()
 
in the sub_mqtt.py we include
import sys
import time

import paho.mqtt.client as paho

def on_message(client, userdata, message):
    print("Response: ", str(message.payload.decode("utf-8")))

client = paho.Client(paho.CallbackAPIVersion.VERSION2)

if client.connect("localhost", 1883, 60) != 0:
    print("Couldn't connect to the mqtt broker")
    sys.exit(1)

client.loop_start()
client.subscribe("modbus/to/mqtt")
client.on_message = on_message
time.sleep(60)
client.loop_stop()
client.disconnect()
 
Reply 0 0
fg71
[203128%2F9234157%2Fmceclip0]
Reply 0 0
Reply