Using udev rules to run a python script when inserting USB to serial dongle
- plug your USB to serial cable in the SBC’s USB port.
- Check the device’s name:
$ dmesg | tail
…
…
Usb 1-2.1: FTDI USB Serial Device converter now attached to ttyUSB0
- We need more information about this device:
$ udevadm info -a -n /dev/ttyUSB0 | grep ‘{serial}’ | head -n1
ATTRS{serial}==”A40111OG”
$ udevadm info -a -n /dev/ttyUSB0 | grep ‘{idVendor}’ | head -n1
ATTRS{idVendor}==”0403″
$ udevadm info -a -n /dev/ttyUSB0 | grep ‘{idProduct}’ | head -n1
ATTRS{idProduct}==”6001″
- Create the udev rules file :
$ echo ‘SUBSYSTEM==”tty”, ATTRS{serial}==”A40111OG”, ATTRS{idVendor}==”0403″, ATTRS{idProduct}==”6001″, RUN+=”/opt/hello.py %k”’ > /etc/udev/rules.d/99-usbserial.rules
- Reload udev:
$ /etc/init.d/udev reload
- Create the python script :
$ cat <<EOF > /opt/hello.py
#!/usr/bin/python
import serial
import sys
serial_port = sys.argv[1]
ser = serial.Serial(port="/dev/"+serial_port, baudrate=115200)
ser.open()
try:
while 1:
ser.read()
ser.write("hello\n\r")
except:
ser.close()
EOF
(make sure indentation is respected)
- Install python-serial package
$ apt-get install python-serial
- Connect a null modem cable between the usb2serial cable and a PC, then open a terminal emulator (picocom under linux / putty or hyper terminal under windows) and press enter, you should receive “hello”)
Note: If more than one identical USB to serial cable are in use, the ATTRS{serial} attribute ensures that the right application is ran for the right cable.