1

I have written a small COM Redirection and cloning python script that will take the input of a physical serial port, and then output them to a two virtual serial ports (one of which is a read-only).

Problem is that I been noticing that using this script utilizes alot of CPU, about 50% and that the only other application I launched is socat to make the virtual ports.

Is there anything I could be missing or looked over, that could bring that CPU usage down, without introducing any sort of timeout.

I am using a Raspberry Pi, with the debian-based Raspian OS.

Code:

import serial, threading, sys



def transferData(serialIn, serialOutA, serialOutB):
    data = serialIn.read(1024)
    if data:
        serialOutA.write(data)
        serialOutB.write(data)



def main():
    serialIn = serial.Serial(port = sys.argv[1], timeout=0, baudrate = 19200, parity=serial.PARITY_NONE, bytesize=serial.EIGHTBITS, stopbits=serial.STOPBITS_ONE)
    serialOutA = serial.Serial(port = sys.argv[2], timeout=0, baudrate = 19200, parity=serial.PARITY_NONE, bytesize=serial.EIGHTBITS, stopbits=serial.STOPBITS_ONE)
    serialOutB = serial.Serial(port = sys.argv[3], timeout=0, baudrate = 19200,  parity=serial.PARITY_NONE, bytesize=serial.EIGHTBITS, stopbits=serial.STOPBITS_ONE)




    while True:
        transferData(serialIn, serialOutA, serialOutB)
        transferData(serialOutA, serialIn,  serialOutB)

if __name__ == '__main__':
    main()
needoriginalname
  • 703
  • 3
  • 9
  • 27
  • Why are you redirecting the serial port instead of directly connecting them? Are you planning on parsing or injecting data? – John Oct 05 '15 at 17:40

1 Answers1

0

The code you have written is constantly reading the serial ports. There is no need to occupy the cpu with this constant read task. Add a sleep according to your latency requirements in your while loop to allow other processes to grab the cpu.

import serial, threading, sys, time



def transferData(serialIn, serialOutA, serialOutB):
    data = serialIn.read(1024)
    if data:
        serialOutA.write(data)
        serialOutB.write(data)



def main():
    serialIn = serial.Serial(port = sys.argv[1], timeout=0, baudrate = 19200,     parity=serial.PARITY_NONE, bytesize=serial.EIGHTBITS, stopbits=serial.STOPBITS_ONE)
    serialOutA = serial.Serial(port = sys.argv[2], timeout=0, baudrate = 19200, parity=serial.PARITY_NONE, bytesize=serial.EIGHTBITS, stopbits=serial.STOPBITS_ONE)
    serialOutB = serial.Serial(port = sys.argv[3], timeout=0, baudrate = 19200,  parity=serial.PARITY_NONE, bytesize=serial.EIGHTBITS, stopbits=serial.STOPBITS_ONE)

    while True:
        transferData(serialIn, serialOutA, serialOutB)
        transferData(serialOutA, serialIn,  serialOutB)
        time.sleep(1)

if __name__ == '__main__':
    main()
John
  • 2,410
  • 1
  • 19
  • 33