Skip to content

Instantly share code, notes, and snippets.

@marcsello
Created July 18, 2025 14:24
Show Gist options
  • Save marcsello/f18b20c89b184d8b980c0d96556245f1 to your computer and use it in GitHub Desktop.
Save marcsello/f18b20c89b184d8b980c0d96556245f1 to your computer and use it in GitHub Desktop.
Simple script to expose /dev/ttyUSB* on a TCP socket using socat with some hacks
#!/bin/ash
trap "trap - SIGTERM && kill -- -$$" SIGINT SIGTERM EXIT
while sleep 1; do
# search for a sutiable device
# this is a bit lame match, it tries to find the last device,
# but if that last device is not suitable, it will not step back to the previous ones
echo "Found devices:"
for dev in /dev/ttyUSB?; do
if [[ "${dev}" != "/dev/ttyUSB\?" ]] && [[ -c "${dev}" ]]; then # ash has no nullglob support
echo "- $dev"
else
dev=""
fi
done
if [[ -z "${dev}" ]]; then
echo "nothing :("
continue # restart loop if nothing found
fi
echo "selecting ${dev}"
# start socat
socat -d -d GOPEN:$dev,b9600,rawer,echo=0,creat=0 TCP4-LISTEN:3333,keepalive &
socatpid=$!
echo "socat pid: ${socatpid}"
sleep 0.5 # make sure socat starts up (or fails) before we start checking stuff
# monitor for device presence
while [ -d "/proc/${socatpid}" ]; do
if ! [ -c "${dev}" ]; then
echo "device disappeared, restarting socat..."
kill "${socatpid}"
wait ${socatpid}
else
sleep 1
fi
done
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment