Automatically resetting an USB-to-serial adapter

I read the temperatures and other data from my heating controller using a python script. The heating controller is connected via a serial line to a raspberry pi, using an FTDI USB-to-serial adapter. From time to time, the adapter stops working. Plugging it out and in again helps, but eventually I found out how to restart it automatically.

You need to find out the device number of your adapter (here it is device 4):

$ lsusb
Bus 001 Device 004: ID 0403:6001 Future Technology Devices International, Ltd FT232 USB-Serial (UART) IC
Bus 001 Device 003: ID 0424:ec00 Standard Microsystems Corp. SMSC9512/9514 Fast Ethernet Adapter
Bus 001 Device 002: ID 0424:9514 Standard Microsystems Corp. SMC9514 Hub
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

You need to find out the name of the driver module (here it is ftdi_sio):

$ lsusb -t
/:  Bus 01.Port 1: Dev 1, Class=root_hub, Driver=dwc_otg/1p, 480M
    |__ Port 1: Dev 2, If 0, Class=Hub, Driver=hub/5p, 480M
        |__ Port 1: Dev 3, If 0, Class=Vendor Specific Class, Driver=smsc95xx, 480M
        |__ Port 3: Dev 4, If 0, Class=Vendor Specific Class, Driver=ftdi_sio, 12M

You need to find out the identifier (here it is 1-1.3:1.0):

$ ls -l /sys/bus/usb/drivers/ftdi_sio/
lrwxrwxrwx 1 root root    0 Sep 12 20:51 1-1.3:1.0 -> ../../../../devices/platform/soc/20980000.usb/usb1/1-1/1-1.3/1-1.3:1.0
--w------- 1 root root 4096 Sep 12 20:51 bind
lrwxrwxrwx 1 root root    0 Sep 12 20:51 module -> ../../../../module/usbserial
--w------- 1 root root 4096 Sep 12 20:50 uevent
--w------- 1 root root 4096 Sep 12 20:51 unbind

With all this information, execute the following script:

# !/bin/sh
sudo sh -c "echo -n '1-1.3:1.0' > /sys/bus/usb/drivers/ftdi_sio/unbind"
sudo modprobe -r ftdi_sio modprobe
sudo modprobe ftdi_sio

(Of course you need to replace the ftdi_sio and 1-1.3:1.0 with the things you found out in steps 1-3)

Now the USB-to-serial adpater is working again.