Repository navigation
ser2net_gateway_setup
Prerequisite for using the Modbus devices library over TCP against a PetaLinux
gateway board (Zynq-7000). Configures ser2net to bridge on-board UARTs to TCP
sockets, so devices on RS485 buses can be reached as host:port from a remote
Python client using RTU-over-TCP framing.
Read this before deploying any board that will serve as a remote gateway.
Applies to boards that:
- Run PetaLinux with sysvinit (BusyBox userland, not systemd).
- Have Xilinx UART Lite cores wired to RS485 transceivers.
- Expose the devices as
/dev/ttyUL1,/dev/ttyUL2, etc. after PL setup runs (/etc/init.d/vdpp_set_hw.sh, symlinked asS95vdpp_set_hw.shin rcS.d).
If those assumptions don't hold, adapt paths, device names, and boot ordering accordingly. Everything else — the init script structure, the RTU-over-TCP client config — is portable.
| Layer | Component | Notes |
|---|---|---|
| Binary |
ser2net 4.3.4 at /usr/sbin/ser2net
|
Uses YAML config since 4.x |
| Config | /etc/ser2net/ser2net.yaml |
Default path, no -c needed at runtime |
| Init |
/etc/init.d/ser2net (sysvinit) |
sourced below |
| Autostart |
rc2.d–rc5.d/S99ser2net, rc0.d/rc1.d/rc6.d/K01ser2net
|
Starts after hardware setup |
| PID file | /var/run/ser2net.pid |
Owned by start-stop-daemon, not ser2net |
If /etc is on tmpfs/overlay, every step below evaporates on reboot. Verify:
touch /etc/.persist_test && sync && rebootAfter reboot:
ls /etc/.persist_test && echo "PERSISTENT — continue" || echo "VOLATILE — use bbappend"
rm -f /etc/.persist_testIf volatile, use the bbappend approach (see Appendix A). Do not proceed with the manual install below.
Create the config directory and file:
mkdir -p /etc/ser2net
cat > /etc/ser2net/ser2net.yaml << 'EOF'
connection: &bus1
accepter: tcp,5001
enable: on
options:
kickolduser: true
connector: serialdev,/dev/ttyUL1,9600n81,local,nobreak
connection: &bus2
accepter: tcp,5002
enable: on
options:
kickolduser: true
connector: serialdev,/dev/ttyUL2,9600n81,local,nobreak
EOF
chmod 644 /etc/ser2net/ser2net.yaml| Field | Meaning |
|---|---|
accepter: tcp,5001 |
Listen for incoming TCP on port 5001 |
connector: serialdev,/dev/ttyUL1,19200n81,local,nobreak |
Bridge to the UART at 19200 baud, 8N1, exclusive lock, no break signal |
options.kickolduser: true |
New TCP connection displaces any existing one |
enable: on |
Bring the bridge up at ser2net startup |
Baudrate is set here, not in the client. Change 19200n81 to match the
actual Modbus slave on the bus. The Python client no longer has any say once you
switch to TCP.
Add or remove connection: blocks per bus. Anchor names (&bus1, &bus2) must
be unique per file.
/etc/init.d/ser2net:
#!/bin/sh
### BEGIN INIT INFO
# Provides: ser2net
# Required-Start: $network $remote_fs vdpp_set_hw
# Required-Stop: $network $remote_fs
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Serial-to-network proxy (ser2net)
# Description: Bridges /dev/ttyUL* (Xilinx UART Lite, RS485) to TCP
# for use as a Modbus RTU-over-TCP gateway.
### END INIT INFO
DAEMON=/usr/sbin/ser2net
NAME=ser2net
CONFIG=/etc/ser2net/ser2net.yaml
PIDFILE=/var/run/ser2net.pid
DAEMON_ARGS="-n -c $CONFIG"
[ -x "$DAEMON" ] || exit 5
[ -r "$CONFIG" ] || exit 6
if [ "$(id -u)" -ne 0 ]; then
echo "$0: must be run as root" >&2
exit 4
fi
is_running() {
[ -f "$PIDFILE" ] || return 1
pid=$(cat "$PIDFILE" 2>/dev/null) || return 1
[ -n "$pid" ] && kill -0 "$pid" 2>/dev/null
}
start() {
printf "Starting %s: " "$NAME"
if is_running; then
echo "already running (pid $(cat $PIDFILE))"
return 0
fi
start-stop-daemon --start --background \
--make-pidfile --pidfile "$PIDFILE" \
--exec "$DAEMON" -- $DAEMON_ARGS
rc=$?
if [ $rc -eq 0 ]; then
echo "OK"
else
echo "FAIL ($rc)"
rm -f "$PIDFILE"
fi
return $rc
}
stop() {
printf "Stopping %s: " "$NAME"
if ! is_running; then
echo "not running"
rm -f "$PIDFILE"
return 0
fi
start-stop-daemon --stop --quiet \
--retry TERM/10/KILL/5 --pidfile "$PIDFILE"
rc=$?
rm -f "$PIDFILE"
if [ $rc -eq 0 ]; then echo "OK"; else echo "FAIL ($rc)"; fi
return $rc
}
status() {
if is_running; then
echo "$NAME running (pid $(cat $PIDFILE))"
return 0
elif [ -f "$PIDFILE" ]; then
echo "$NAME not running but pidfile exists"
return 1
else
echo "$NAME not running"
return 3
fi
}
case "$1" in
start) start ;;
stop) stop ;;
restart|force-reload) stop; sleep 1; start ;;
status) status ;;
*) echo "Usage: $0 {start|stop|restart|force-reload|status}"; exit 2 ;;
esacInstall and validate:
chmod 755 /etc/init.d/ser2net
sh -n /etc/init.d/ser2net # syntax check — no output means good-
-n+start-stop-daemon --background --make-pidfilerather than letting ser2net daemonize itself.start-stop-daemonwrites the pidfile before exec, eliminating the race window between fork and ser2net's own pidfile write. ser2net's manpage explicitly recommends-nfor use under init. -
Root check up front converts silent half-failures (pidfile write refused,
but the daemon still starts) into a clear error message. During interactive
debugging you will forget to
sudo -iat least once. -
No
/etc/init.d/functionssourced. Availability on Yocto/BusyBox is inconsistent. Script is self-contained. -
LSB
Required-Startincludingvdpp_set_hwis documentation only — sysvinit doesn't enforce facilities at runtime. Real ordering is theSNNnumber.
/etc/init.d/ser2net start
/etc/init.d/ser2net status # running (pid N)
netstat -ltn | grep -E ':500[12]\b' # both ports listening
/etc/init.d/ser2net stop
/etc/init.d/ser2net status # not running (exit 3)If any step fails, do not proceed. Debug with:
/usr/sbin/ser2net -d -c /etc/ser2net/ser2net.yamlThat runs ser2net in foreground with logs on stderr. Common causes: missing
/dev/ttyUL* (PL setup didn't run), YAML syntax error, port already in use.
Check for update-rc.d:
which update-rc.dIf present:
update-rc.d ser2net start 99 2 3 4 5 . stop 01 0 1 6 .If absent, manual symlinks:
for L in 2 3 4 5; do
ln -sf ../init.d/ser2net /etc/rc${L}.d/S99ser2net
done
for L in 0 1 6; do
ln -sf ../init.d/ser2net /etc/rc${L}.d/K01ser2net
doneVerify:
ls -l /etc/rc[0-6].d/[SK]??ser2net # 7 entries: 4× S99, 3× K01S99 places ser2net at the very end of userspace startup, after networking
(S01networking) and after the S98 hardware-related services. K01 on shutdown
runlevels stops ser2net first so it releases the UARTs before PL teardown.
To undo:
update-rc.d -f ser2net remove
# or manually:
rm -f /etc/rc[0-6].d/[SK]??ser2netrebootAfter the board comes back:
sudo -i
/etc/init.d/ser2net status # running
netstat -ltn | grep -E ':500[12]\b' # both listeners up
readlink /proc/$(cat /var/run/ser2net.pid)/fd/* | grep ttyUL # (see note)Note on fd inspection: ser2net opens /dev/ttyUL* lazily — only when a
TCP client connects. Before the first client, /proc/PID/fd shows only stdio,
epoll, self-pipe, and the two listening sockets. This is correct behaviour. To
verify serial-side opens, connect first:
# from any host that can reach the board:
nc <board-ip> 5001 # leave open
# on the board:
readlink /proc/$(cat /var/run/ser2net.pid)/fd/* | grep ttyUL
# → /dev/ttyUL1ser2net is a transparent byte pipe, not a Modbus TCP server. The client must
speak RTU (with CRC), just carried over a TCP socket instead of a UART. In
pymodbus this means ModbusTcpClient with the RTU framer, not the default
socket framer.
from pymodbus.client import ModbusTcpClient
from pymodbus.framer import FramerType
client = ModbusTcpClient(
host="192.168.10.134", # gateway board IP
port=5002, # ser2net accepter port for the target bus
framer=FramerType.RTU,
timeout=2.0,
)
client.connect()
try:
rr = client.read_holding_registers(address=0, count=10, slave=1)
if rr.isError():
raise RuntimeError(f"Modbus error: {rr}")
print(rr.registers)
finally:
client.close()from pymodbus.client import ModbusTcpClient
from pymodbus.framer import ModbusRtuFramer
client = ModbusTcpClient(host="192.168.10.134", port=5002,
framer=ModbusRtuFramer, timeout=2.0)Check installed version:
python -c "import pymodbus; print(pymodbus.__version__)"| Parameter | TCP-mode equivalent |
|---|---|
port="/dev/ttyUSB0" |
host=..., port=5001 |
baudrate= |
set in ser2net.yaml, not in client |
bytesize=, parity=, stopbits=
|
set in ser2net.yaml |
timeout= |
kept, now measures round-trip over TCP + serial |
slave= argument in requests |
kept — still needed for RTU addressing |
The slave/unit ID stays because it's part of the RTU frame the slave uses to decide whether to answer. Do not drop it thinking TCP transport replaces it.
-
kickolduser: truesilently disconnects the previous TCP client when a new one connects. Convenient during development, hazardous if two processes race for the same port. Set tofalseand handle "port busy" errors in the client if you need strict single-owner semantics. -
Baudrate is set once, on the gateway. Every client that talks to port 5001 gets whatever ser2net negotiated with the UART. If different slaves on the same bus need different rates, that's a bus design problem, not a configuration one.
-
RTU framing over TCP loses inter-frame timing. RTU normally relies on ≥3.5-char silence between frames; TCP buffering smears this. pymodbus's RTU framer validates by length + CRC instead of timing, which usually works but can produce spurious CRC errors under load. If you see these, look at ser2net's
chardelay-min/sendonoptions before blaming the bus. -
start-stop-daemon --retry TERM/10/KILL/5syntax works on modern BusyBox but has historically been quirky on older builds. Ifstoperrors out, fall back to--retry 10(bare timeout — sends TERM, then KILL after the timeout). -
UART must exist before ser2net starts. If
/dev/ttyUL*are created by PL setup, that setup must run inrcS.d(before rc2–5) or ser2net's serial opens will fail on the first client connection. Boot ordering matters even though ser2net won't crash without the device — it just returns errors to clients. -
Root required.
/var/run/ser2net.pidand low-numbered privileges make this a root-only script. The script exits 4 if run as a non-root user. Under normal init that's fine because PID 1 is UID 0.
-
/etc/.persist_testsurvives reboot (or bbappend used instead) -
/etc/ser2net/ser2net.yamlexists, has correct baudrate per bus -
/etc/init.d/ser2netexists, mode 0755,sh -nclean -
/etc/init.d/ser2net start && statusreports running -
netstat -ltnshows all expected ports listening -
rc[2-5].d/S99ser2netandrc[016].d/K01ser2netsymlinks in place - Reboot test: ser2net comes up automatically, listeners present
- Client can
nc <ip> <port>and see fd open in/proc/PID/fd - Python client with
ModbusTcpClient(framer=FramerType.RTU)gets valid responses
If /etc is not persistent, ship the files via a bbappend so they're baked into
the rootfs at build time.
Layout under <project>/project-spec/meta-user/recipes-connectivity/ser2net/:
ser2net_%.bbappend
└── files/
├── ser2net.init # the script from section 2
└── ser2net.yaml # the config from section 1
ser2net_%.bbappend:
FILESEXTRAPATHS:prepend := "${THISDIR}/files:"
SRC_URI += " \
file://ser2net.init \
file://ser2net.yaml \
"
inherit update-rc.d
INITSCRIPT_NAME = "ser2net"
INITSCRIPT_PARAMS = "start 99 2 3 4 5 . stop 01 0 1 6 ."
do_install:append() {
install -d ${D}${sysconfdir}/init.d
install -m 0755 ${WORKDIR}/ser2net.init ${D}${sysconfdir}/init.d/ser2net
install -d ${D}${sysconfdir}/ser2net
install -m 0644 ${WORKDIR}/ser2net.yaml ${D}${sysconfdir}/ser2net/ser2net.yaml
}
FILES:${PN} += " \
${sysconfdir}/init.d/ser2net \
${sysconfdir}/ser2net/ser2net.yaml \
"Override syntax note: :append / :prepend is Honister (Yocto 3.4, late
2021) and newer. Older PetaLinux trees (2020.x and earlier) need _append /
_prepend. Check with bitbake --version or match the style used by existing
bbappends in the tree.
Rebuild the image; the init script, symlinks (via update-rc.d.bbclass), and
YAML config are all present on first boot with no manual steps.
- ser2net(8) manpage: https://manpages.debian.org/testing/ser2net/ser2net.8.en.html
- pymodbus client docs: https://pymodbus.readthedocs.io/en/latest/source/client.html
- Yocto
update-rc.d.bbclass: shipped with poky; see localmeta/classes/