3

I'm trying to write a serial 'proxy' that will sit between a process and a physical serial device and re-write some commands on the fly. I had it working in a crude manner but it was much slower than going straight to the physical device.

In an effort to speed it up, I've stripped out everything other than the bare read/write, but performance is much slower than expected.

Any ideas what I'm doing wrong? I am very new to this low level stuff, most of my limited experience is with parsing json / xml / etc and manipulating strings. Any thoughts or hints would be much appreciated.

Heres the simplified code-

def host_thread( host_port, dv_port ):

    while True:
        try:
            char = os.read(host_port, 1)
            os.write(dv_port, char)
        except OSError as err:
            if err.errno == errno.EAGAIN or err.errno == errno.EWOULDBLOCK:
                pass
            else:
                raise  # something else has happened -- better reraise


def dv_thread( host_port, dv_port ):

    while True:
        try:
            char = os.read(dv_port, 1)
            os.write(host_port, char)
        except OSError as err:
            if err.errno == errno.EAGAIN or err.errno == errno.EWOULDBLOCK:
                pass
            else:
                raise  # something else has happened -- better reraise

if __name__ == "__main__":

    host_port, slave = pty.openpty()
    print("Connect to port: %s" % os.ttyname(slave))


    fl = fcntl.fcntl(host_port, fcntl.F_GETFL)
    fcntl.fcntl(host_port, fcntl.F_SETFL, fl | os.O_NONBLOCK)

    dv_port = os.open("/dev/ttyUSB0", os.O_RDWR | os.O_NONBLOCK)

    host_thread = threading.Thread(target=host_thread, args=[host_port, dv_port])
    host_thread.start()

    dv_thread = threading.Thread(target=dv_thread, args=[host_port, dv_port])
    dv_thread.start()

    while True:
        time.sleep(.1)
marrold
  • 31
  • 2
  • Start by profiling your code: [How can you profile a script?](https://stackoverflow.com/questions/582336/how-can-you-profile-a-script) – Ortomala Lokni Sep 15 '17 at 07:58
  • 1
    the biggest issue i can see is that you are reading a single character at a time, because of the multiple levels of translation in and out of python space this is very slow, reading bigger chunks (with a timeout if possible) will be much faster than going character by character. – James Kent Sep 15 '17 at 08:27
  • also at the end, rather than a `while True` loop, call `.join()` on each thread, that should eliminate the busy loop maybe freeing more cpu for the useful parts of your script – James Kent Sep 15 '17 at 08:28

0 Answers0