0

I have a FTDI device which connects to ttyUSB0. After unplugging and re-inserting the device always connects to ttyUSB1. I have to detect the change and act accordingly to keep my send and recv functions running. I tried to detect it within the send and recv functions. Here is what I did:

`
def recv_serial_data(n):
    global serial_port
    try:
        if not serial_port.isOpen():
            serial_port = serial.Serial('/dev/ttyUSB1', 115200, 0.05)

        data = serial_port.read(n)
        tmp = []

        for c in data:
            tmp.append(ord(c))
        print data

        return tmp
    except Exception, e:
        raise Exception("recv_serial_data: " + str(e))

def send_serial_data(data):
    print data,type(data)
    global serial_port
    try:
        if not serial_port.isOpen():
            serial_port.close()
            serial_port = serial.Serial('/dev/ttyUSB1', 115200, 0.05)


        if not isinstance(data, basestring):
            data = array.array("B",data).tostring()
            serial_port.write(data)
        elif isinstance(data, basestring):
            serial_port.write(data)
    except Exception, e:
        raise Exception("send_serial_data: " + str(e))

    return



    def main():

    #[Doing stuff]

    global serial_port

    #options.serial_port is '/dev/ttyUSB0'        
    serial_port = serial.Serial(options.serial_port, options.baudrate, timeout=options.tty_timeout)

    #[Doing stuff]

    serial_port.close()

if __name__ == "__main__":
    main()
`

What I get now are messages like "recv_serial_data: device reports readiness to read but returned no data" (device disconnected or multiple access on port?)" or "send_serial_data: write failed: [Errno 5] Input/Output error" As long as i don't unplug the device everything runs smoothly.

  • but it's always possible to connect (open) both serial ports ? -> you should get an error when try to open the serial port => serial.Serial(...). – twooBeers Aug 30 '17 at 07:02
  • 1
    I'd say you should configure udev properly. It should put that device on the same device name (maybe its own) every time. – Klaus D. Aug 30 '17 at 07:12
  • @user3336433 As far as I can see right now I just don't get any data – Arlecchino12 Aug 30 '17 at 07:23
  • @KlausD. Yes, I tried that already and replaced "ttyUSB0" by the symlink name. Didn't work, but I wil give it another try definitely. – Arlecchino12 Aug 30 '17 at 07:26
  • Read, for example, [this](http://hintshop.ludvig.co.nz/show/persistent-names-usb-serial-devices/) or [this](https://www.element14.com/community/community/design-challenges/sci-fi-your-pi/blog/2015/07/15/persistent-names-for-usb-devices) about persistent names for USB devices. – Michael O. Aug 30 '17 at 12:02

0 Answers0