USB serial ports by serial number

O'Connor, Daniel darius at dons.net.au
Thu Oct 3 02:56:20 UTC 2019


Hi,
I have several USB serial ports on a machine and I don't want to rely on attach order to get various programs to talk to the correct serial port.

I wrote the following devd script and shell script to create symlinks from cu.${sernum}/tty.${sernum} to the real device nodes.

I post it here in the hope other people find it useful.

[maarsytest 2:49] ~> cat /usr/local/etc/devd/usbserialsn.conf
attach 100 {
	device-name		".*";
	match "ttyname"		".+";
	match "ugen"		".+";
	match "sernum"		".+";
	action "/usr/local/libexec/usbserialsn attach $device-name $sernum $ttyname";
};

detach 100 {
	device-name		".*";
	action "/usr/local/libexec/usbserialsn detach $device-name";
};
[maarsytest 2:49] ~> cat /usr/local/libexec/usbserialsn
#!/bin/sh

if [ $# -lt 2 ]; then
  echo "Bad usage"
  exit 1
fi

mode=$1
devname=$2
sernum=$3
ttyname=$4

case "$mode" in
  attach)
    if [ $# -ne 4 ]; then
      echo "Bad usage"
      exit 1
    fi
    ln -sf cua${ttyname} /dev/cu.${sernum}
    ln -sf tty${ttyname} /dev/tty.${sernum}
    echo ${sernum} >/var/run/usbserialsn.${devname}
    ;;

  detach)
    if [ $# -ne 2 ]; then
      echo "Bad usage"
      exit 1
    fi
    if [ ! -e /var/run/usbserialsn.${devname} ]; then
      exit 0
    fi
    sernum=$(cat /var/run/usbserialsn.${devname})
    rm -f /dev/cu.${sernum} /dev/tty.${sernum} /var/run/usbserialsn.${devname}
    ;;

  *)
    echo "Unknown mode"
    exit 1
    ;;
esac

It would be a lot simpler if devd reported the same things on detach as it does on attach but I am not sure how difficult that would be to achieve (presumably it would require caching them).

--
Daniel O'Connor
"The nice thing about standards is that there
are so many of them to choose from."
 -- Andrew Tanenbaum




More information about the freebsd-usb mailing list