Protocols and integration
Build a Modbus RTU to MQTT and Modbus TCP gateway on a Raspberry Pi
Updated
This page builds a gateway that polls Modbus RTU devices on an RS-485 bus, publishes every reading to an MQTT broker as JSON, and answers Modbus TCP reads from the same data. The whole thing is one Python file of about 200 lines, using pymodbus 3.16.2 and paho-mqtt 2.2.0, and it runs as a systemd service. Writes from the TCP side are refused on purpose: this gateway is for monitoring, not control.
What you need
| Item | Assumed here |
|---|---|
| Computer | Raspberry Pi 5 or Compute Module 5 (Pi 4 works with a different UART overlay) |
| OS | Raspberry Pi OS Bookworm (Python 3.11) or Trixie (Python 3.13), 64-bit |
| Libraries | pymodbus 3.16.2 (needs Python 3.10 or later), pyserial 3.5, paho-mqtt 2.2.0 |
| RS-485 | A 3.3 V transceiver on UART0 (GPIO 14/15), or a USB RS-485 adapter (/dev/ttyUSB0) |
| Broker | Mosquitto on the same Pi, or any MQTT 3.1.1/5 broker you can reach |
| Devices | One or more Modbus RTU slaves with a register map from their manual |
The code was run against a simulated RTU device over a virtual serial link and a local MQTT broker on 2026-11-19. It has not been run on Pi hardware by us; the serial settings below follow the Raspberry Pi documentation.
How the gateway works
- One loop owns the serial bus. Modbus RTU allows one master per bus, so every read goes through this loop in turn; nothing else should open the port.
- Every
poll_intervalseconds it reads each configured point, converts the registers to a number (int16,uint16,int32,uint32orfloat32, with a scale factor) and publishes it. - Each reading goes to
<topic_prefix>/<point name>as a retained JSON message, for example{"value": 21.5, "unit": "degC", "quality": "good", "error": null, "ts": "2026-11-19T14:53:15+00:00"}. A failed read publishes"value": null, "quality": "bad"with the reason, so subscribers can tell a dead sensor from a steady one. <topic_prefix>/statusholdsonlineoroffline. The broker setsofflineitself through MQTT’s last-will message if the gateway dies or loses its network.- The optional Modbus TCP server answers function 3 and 4 reads from the last good RTU values. The TCP unit ID is the RTU device ID. If a value is older than
stale_afterseconds, the read is answered with Modbus exception 11 (gateway target device failed to respond) rather than an old number. Writes get exception 2.
The TCP side is a cache, not a pass-through. A SCADA or HMI reading port 502 never touches the serial bus, so it cannot slow the poll cycle or collide with it. The cost is that TCP clients see data up to one poll interval old.
Wire the RS-485 bus
Connect the transceiver’s A and B to the bus pair, and its ground to the bus common. The Modbus serial line specification names the lines D0 and D1 and requires the common conductor; vendors’ A/B labels disagree, so if nothing answers, swapping the two data wires is safe and is the first thing to try. Terminate both ends of the trunk with 150 ohm resistors and bias the line in one place only. The RS-485 on a Raspberry Pi guide covers transceivers, termination, biasing and troubleshooting in detail.
On a Pi 5 or CM5, the primary UART goes to the debug header by default, so enable UART0 on GPIO 14/15 with an overlay in /boot/firmware/config.txt. If your transceiver has a DE/RE direction pin, the rs485 parameter of the uart0-pi5 overlay lets the kernel drive it from RTS on GPIO 17:
# /boot/firmware/config.txt, Pi 5 or CM5
dtoverlay=uart0-pi5,rs485
Then turn off the serial login console (sudo raspi-config, Interface Options, Serial Port: login shell No, hardware Yes, as the Raspberry Pi documentation describes) and reboot. The port is /dev/ttyAMA0. With a USB adapter, skip both steps and use /dev/ttyUSB0.
Install
sudo apt update
sudo apt install -y python3-venv mosquitto mosquitto-clients
sudo mkdir -p /opt/modbus-gateway /etc/modbus-gateway
sudo python3 -m venv /opt/modbus-gateway/venv
sudo /opt/modbus-gateway/venv/bin/pip install pymodbus==3.16.2 pyserial==3.5 paho-mqtt==2.2.0
Pin the versions. pymodbus is mid-transition: its upgrade notes say the old ModbusSequentialDataBlock datastores are replaced by SimData/SimDevice from 3.13 and removed in 4.0. The TCP side below uses the new SimDevice API, which the 3.16.2 source still marks experimental. Re-test before upgrading.
A fresh Mosquitto 2.x install with no listener lines accepts anonymous clients on the local machine only (mosquitto.conf), which suits a broker on the same Pi. To reach a remote broker, set host, port and tls = true, and put the credentials in /etc/modbus-gateway/env:
sudo install -m 600 /dev/null /etc/modbus-gateway/env
sudo tee /etc/modbus-gateway/env > /dev/null <<'EOF'
MQTT_USERNAME=gateway-site1
MQTT_PASSWORD=change-me
EOF
The gateway
Save as /opt/modbus-gateway/gateway.py:
"""Poll Modbus RTU devices, publish readings to MQTT and mirror them on a read-only Modbus TCP server."""
import asyncio
import json
import logging
import os
import signal
import sys
import time
import tomllib
from dataclasses import dataclass
from datetime import datetime, timezone
import paho.mqtt.client as mqtt
from pymodbus import ModbusException
from pymodbus.client import AsyncModbusSerialClient
from pymodbus.constants import ExcCodes
from pymodbus.server import ModbusTcpServer
from pymodbus.simulator import DataType, SimData, SimDevice
log = logging.getLogger("modbus-gateway")
DATATYPES = AsyncModbusSerialClient.DATATYPE
REGISTER_COUNT = {"int16": 1, "uint16": 1, "int32": 2, "uint32": 2, "float32": 2}
@dataclass
class Point:
name: str
device_id: int
table: str # "holding" (function 3) or "input" (function 4)
address: int
type: str
scale: float = 1.0
unit: str = ""
word_order: str = "big"
@property
def count(self) -> int:
return REGISTER_COUNT[self.type]
@dataclass
class Reading:
point: Point
registers: list[int] | None
value: float | None
error: str | None
timestamp: float
def load_points(raw_points: list[dict]) -> list[Point]:
points = [Point(**raw) for raw in raw_points]
occupied: dict[tuple[int, int], str] = {}
for p in points:
if p.type not in REGISTER_COUNT or p.table not in ("holding", "input"):
sys.exit(f"point {p.name}: unsupported type {p.type!r} or table {p.table!r}")
for address in range(p.address, p.address + p.count):
# The TCP mirror keeps one register map per device, so two points cannot share an address.
if (p.device_id, address) in occupied:
sys.exit(f"point {p.name} overlaps {occupied[(p.device_id, address)]} on device {p.device_id}")
occupied[(p.device_id, address)] = p.name
return points
async def read_point(client: AsyncModbusSerialClient, p: Point) -> Reading:
read = client.read_holding_registers if p.table == "holding" else client.read_input_registers
try:
response = await read(p.address, count=p.count, device_id=p.device_id)
except ModbusException as exc:
return Reading(p, None, None, f"no response: {exc}", time.time())
if response.isError():
return Reading(p, None, None, f"exception code {response.exception_code}", time.time())
raw = client.convert_from_registers(response.registers, DATATYPES[p.type.upper()], word_order=p.word_order)
return Reading(p, response.registers, round(raw * p.scale, 6), None, time.time())
class MqttPublisher:
def __init__(self, cfg: dict):
self.prefix = cfg["topic_prefix"].rstrip("/")
self.status_topic = f"{self.prefix}/status"
self.client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id=cfg["client_id"])
if os.environ.get("MQTT_USERNAME"):
self.client.username_pw_set(os.environ["MQTT_USERNAME"], os.environ.get("MQTT_PASSWORD"))
if cfg.get("tls", False):
self.client.tls_set()
# The broker publishes "offline" for us if the gateway dies or loses its connection.
self.client.will_set(self.status_topic, "offline", qos=1, retain=True)
self.client.on_connect = self.on_connect
self.client.on_disconnect = self.on_disconnect
self.client.connect_async(cfg["host"], cfg.get("port", 1883), keepalive=30)
self.client.loop_start()
def on_connect(self, client, userdata, flags, reason_code, properties):
if reason_code.is_failure:
log.error("MQTT connect refused: %s", reason_code)
return
log.info("MQTT connected")
client.publish(self.status_topic, "online", qos=1, retain=True)
def on_disconnect(self, client, userdata, flags, reason_code, properties):
log.warning("MQTT disconnected: %s (paho reconnects automatically)", reason_code)
def publish(self, reading: Reading) -> None:
payload = {
"value": reading.value,
"unit": reading.point.unit,
"quality": "good" if reading.error is None else "bad",
"error": reading.error,
"ts": datetime.fromtimestamp(reading.timestamp, timezone.utc).isoformat(timespec="seconds"),
}
self.client.publish(f"{self.prefix}/{reading.point.name}", json.dumps(payload), qos=1, retain=True)
def close(self) -> None:
self.client.publish(self.status_topic, "offline", qos=1, retain=True).wait_for_publish(timeout=2)
self.client.disconnect()
self.client.loop_stop()
class TcpMirror:
"""Answers Modbus TCP reads from the last good RTU readings; refuses writes and stale data."""
def __init__(self, points: list[Point], stale_after: float):
self.stale_after = stale_after
self.latest: dict[int, dict[int, tuple[int, float]]] = {p.device_id: {} for p in points}
self.devices = []
for device_id in self.latest:
blocks = [
SimData(address=p.address, count=p.count, datatype=DataType.REGISTERS, readonly=True)
for p in points
if p.device_id == device_id
]
self.devices.append(SimDevice(id=device_id, simdata=blocks, action=self.make_action(device_id)))
def update(self, reading: Reading) -> None:
if reading.registers is None:
return
for offset, register in enumerate(reading.registers):
self.latest[reading.point.device_id][reading.point.address + offset] = (register, reading.timestamp)
def make_action(self, device_id: int):
async def action(function_code, start_address, address, count, registers, set_values):
now = time.time()
for a in range(address, address + count):
register, timestamp = self.latest[device_id].get(a, (None, 0.0))
if register is None or now - timestamp > self.stale_after:
return ExcCodes.GATEWAY_NO_RESPONSE
registers[a - start_address] = register
return None
return action
async def poll_forever(client, points, publisher, mirror, interval, stop: asyncio.Event):
while not stop.is_set():
cycle_start = time.monotonic()
if not client.connected and not await client.connect():
log.error("cannot open the serial port; retrying next cycle")
readings = [Reading(p, None, None, "serial port unavailable", time.time()) for p in points]
else:
readings = [await read_point(client, p) for p in points]
for reading in readings:
if reading.error:
log.warning("%s: %s", reading.point.name, reading.error)
publisher.publish(reading)
if mirror:
mirror.update(reading)
remaining = interval - (time.monotonic() - cycle_start)
try:
await asyncio.wait_for(stop.wait(), timeout=max(remaining, 0.1))
except TimeoutError:
pass
async def main(config_path: str) -> None:
with open(config_path, "rb") as f:
cfg = tomllib.load(f)
logging.basicConfig(level=cfg.get("log_level", "INFO"), format="%(levelname)s %(message)s")
points = load_points(cfg["points"])
serial = cfg["serial"]
client = AsyncModbusSerialClient(
serial["port"],
baudrate=serial.get("baudrate", 19200),
parity=serial.get("parity", "E"),
stopbits=serial.get("stopbits", 1),
bytesize=8,
timeout=serial.get("timeout", 0.5),
retries=serial.get("retries", 1),
)
publisher = MqttPublisher(cfg["mqtt"])
stop = asyncio.Event()
loop = asyncio.get_running_loop()
for sig in (signal.SIGTERM, signal.SIGINT):
loop.add_signal_handler(sig, stop.set)
mirror, server = None, None
tcp = cfg.get("tcp", {})
if tcp.get("enabled", False):
mirror = TcpMirror(points, tcp.get("stale_after", 3 * serial.get("poll_interval", 5.0)))
server = ModbusTcpServer(mirror.devices, address=(tcp.get("bind", "0.0.0.0"), tcp.get("port", 502)))
await server.serve_forever(background=True)
log.info("Modbus TCP mirror listening on %s:%s", tcp.get("bind", "0.0.0.0"), tcp.get("port", 502))
try:
await poll_forever(client, points, publisher, mirror, serial.get("poll_interval", 5.0), stop)
finally:
log.info("stopping")
if server:
await server.shutdown()
client.close()
publisher.close()
if __name__ == "__main__":
asyncio.run(main(sys.argv[1] if len(sys.argv) > 1 else "/etc/modbus-gateway/config.toml"))
Notes on choices that are easy to get wrong:
- Addresses in the config are the zero-based numbers sent on the wire. A manual that says “40001” or “holding register 1” usually means address 0. Off-by-one is the most common reason a gateway reads plausible but wrong values.
float32and the 32-bit integers span two registers. Devices disagree on which comes first; if a value looks absurd, setword_order = "little"for that point.- The poll loop reads one point per request. At 19200 baud a two-register read takes roughly 15 to 25 ms including the device’s turnaround, so 50 points fit comfortably in a 5 s cycle. For hundreds of points, merge neighbouring registers into one read (up to 125 registers per request in the Modbus application protocol).
- When a read fails, pymodbus logs the last frames it sent and received. That hex dump is the quickest way to see whether the device answered at all.
Configure points
Save as /etc/modbus-gateway/config.toml and replace the points with your devices’ register maps:
log_level = "INFO"
[serial]
port = "/dev/ttyAMA0"
baudrate = 19200
parity = "E" # Modbus default; use "N" with stopbits = 2 if the devices say so
stopbits = 1
timeout = 0.5 # seconds to wait for each reply
retries = 1
poll_interval = 5.0 # seconds between the start of each polling cycle
[mqtt]
host = "localhost"
port = 1883
client_id = "modbus-gateway-site1"
topic_prefix = "site1/modbus"
tls = false
[tcp]
enabled = true
bind = "0.0.0.0"
port = 502
stale_after = 15 # seconds; older readings are refused with exception 11
[[points]]
name = "tank1_temperature"
device_id = 1
table = "input"
address = 0
type = "int16"
scale = 0.1
unit = "degC"
[[points]]
name = "pump1_status"
device_id = 1
table = "holding"
address = 10
type = "uint16"
[[points]]
name = "tank1_level"
device_id = 2
table = "holding"
address = 0
type = "float32"
word_order = "big"
unit = "m"
Two points on the same device may not share an address: the TCP side keeps one register map per device, readable with function 3 or 4, and the gateway refuses to start if points overlap.
Run it under systemd
Save as /etc/systemd/system/modbus-gateway.service:
[Unit]
Description=Modbus RTU to MQTT and Modbus TCP gateway
Wants=network-online.target
After=network-online.target
[Service]
ExecStart=/opt/modbus-gateway/venv/bin/python /opt/modbus-gateway/gateway.py /etc/modbus-gateway/config.toml
EnvironmentFile=-/etc/modbus-gateway/env
Restart=always
RestartSec=5
DynamicUser=yes
SupplementaryGroups=dialout
AmbientCapabilities=CAP_NET_BIND_SERVICE
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
NoNewPrivileges=yes
ProtectHome=yes
[Install]
WantedBy=multi-user.target
DynamicUser runs the service as a throwaway unprivileged user, SupplementaryGroups=dialout gives it the serial port, and CAP_NET_BIND_SERVICE lets it listen on port 502 without root (systemd.exec). If you set tcp.port to 1024 or higher, you can drop the two capability lines.
sudo systemctl daemon-reload
sudo systemctl enable --now modbus-gateway
journalctl -u modbus-gateway -f
Check it works
Watch the MQTT side:
mosquitto_sub -h localhost -t 'site1/modbus/#' -v
You should see site1/modbus/status online and one message per point every poll interval. Then read the TCP side from another machine with any Modbus TCP client; with pymodbus:
from pymodbus.client import ModbusTcpClient
client = ModbusTcpClient("192.168.1.50", port=502) # the gateway's address
client.connect()
print(client.read_input_registers(0, count=1, device_id=1).registers)
client.close()
Unplug a device and wait stale_after seconds: MQTT messages for its points turn "quality": "bad" and TCP reads return exception 11.
Security before you expose it
Modbus TCP has no authentication. Anyone who can reach port 502 can read every value, which is why this gateway refuses writes. Keep port 502 on the plant network or behind a firewall, never on the internet. For MQTT across the internet, use TLS and a username per gateway. To alarm on these values, see Modbus or MQTT value to alarm, end to end.
Sources
- pymodbus on PyPI (version 3.16.2), accessed 2026-11-19
- Pymodbus 4.0 upgrade procedure (SimData/SimDevice replace the old datastores), accessed 2026-11-19
- pymodbus client documentation, accessed 2026-11-19
- paho-mqtt on PyPI (version 2.2.0), accessed 2026-11-19
- paho-mqtt client documentation, accessed 2026-11-19
- paho-mqtt 2.0 migration guide (callback API versions), accessed 2026-11-19
- Raspberry Pi documentation, Configuration (UARTs), accessed 2026-11-19
- Raspberry Pi device tree overlays README (uart0-pi5 and rs485 parameters), accessed 2026-11-19
- Modbus Organization, specifications (Modbus over Serial Line V1.02, Application Protocol V1.1b3), accessed 2026-11-19
- Debian package python3 in bookworm (3.11), accessed 2026-11-19
- Debian package python3 in trixie (3.13), accessed 2026-11-19
- mosquitto.conf manual page, accessed 2026-11-19
- systemd.exec manual page, accessed 2026-11-19