准备使用pyserial做一个小的串口助手,看了很久的pyserial文档,代码如下:

import sys,traceback  
import serial,serial.threaded  
from serial.tools import list_ports

LineReader = serial.threaded.LineReader  
ReaderThread = serial.threaded.ReaderThread

class PrintLines(LineReader):

    def connection_made(self, transport):
        super(PrintLines, self).connection_made(transport)
        print('port opened\n')

    def handle_line(self, data):
        print('line received: {!r}\n'.format(data))

    def data_received(self,data):
        super(PrintLines, self).data_received(data)
        sys.stdout.write(data)
        """data为串行口输出内容"""

    def connection_lost(self, exc):
        if exc:
            traceback.print_exc(exc)
        print('port closed\n')


class aserialPort:

    """serial functions include :
                    checkports()
                    openSerialPort()
                    closeSerialPort()
                    baudRateChanged()"""

    def __init__(self):
        self.threadOpenedOnce = False
        self.ser = serial.Serial()

    def checkPorts(self):
        list = list_ports.comports()
        ports = []
        for port in list:
            if not port[0].startswith("/dev/ttyS"):
                ports.append(port[0])
        return ports

    def openSerialPort(self, serialName, serialBaudRate):
        self.ser.baudrate = serialBaudRate
        self.ser.port = serialName
        self.ser.open()
        self.ReadThread = ReaderThread(self.ser, PrintLines)
        self.ReadThread.start()
        self.ReadThread.connect()
        self.transport, self.protocol = self.ReadThread.connect()
        self.protocol.write_line('Serial opened !')

    def closeSerialPort(self):
        self.ReadThread.stop()
        self.ser.close()
        print(b'Serialport closed!')

    def baudRatechanged(self, baudRate):
        serialconfdict = self.ser.get_settings()
        serialconfdict['baudrate'] = baudRate
        self.ser.apply_settings(serialconfdict)
        print("serial baudrate changed !")