pySerial API

Classes

Native ports

class serial.Serial
__init__(port=None, baudrate=9600, bytesize=EIGHTBITS, parity=PARITY_NONE, stopbits=STOPBITS_ONE, timeout=None, xonxoff=False, rtscts=False, write_timeout=None, dsrdtr=False, inter_byte_timeout=None, exclusive=None)
Parameters:
  • port – Device name or None.
  • baudrate (int) – Baud rate such as 9600 or 115200 etc.
  • bytesize – Number of data bits. Possible values: FIVEBITS, SIXBITS, SEVENBITS, EIGHTBITS
  • parity – Enable parity checking. Possible values: PARITY_NONE, PARITY_EVEN, PARITY_ODD PARITY_MARK, PARITY_SPACE
  • stopbits – Number of stop bits. Possible values: STOPBITS_ONE, STOPBITS_ONE_POINT_FIVE, STOPBITS_TWO
  • timeout (float) – Set a read timeout value.
  • xonxoff (bool) – Enable software flow control.
  • rtscts (bool) – Enable hardware (RTS/CTS) flow control.
  • dsrdtr (bool) – Enable hardware (DSR/DTR) flow control.
  • write_timeout (float) – Set a write timeout value.
  • inter_byte_timeout (float) – Inter-character timeout, None to disable (default).
  • exclusive (bool) – Set exclusive access mode (POSIX only). A port cannot be opened in exclusive access mode if it is already open in exclusive access mode.
Raises:
  • ValueError – Will be raised when parameter are out of range, e.g. baud rate, data bits.
  • SerialException – In case the device can not be found or can not be configured.

The port is immediately opened on object creation, when a port is given. It is not opened when port is None and a successive call to open() is required.

port is a device name: depending on operating system. e.g. /dev/ttyUSB0 on GNU/Linux or COM3 on Windows.

The parameter baudrate can be one of the standard values: 50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800, 9600, 19200, 38400, 57600, 115200. These are well supported on all platforms.

Standard values above 115200, such as: 230400, 460800, 500000, 576000, 921600, 1000000, 1152000, 1500000, 2000000, 2500000, 3000000, 3500000, 4000000 also work on many platforms and devices.

Non-standard values are also supported on some platforms (GNU/Linux, MAC OSX >= Tiger, Windows). Though, even on these platforms some serial ports may reject non-standard values.

Possible values for the parameter timeout which controls the behavior of read():

  • timeout = None: wait forever / until requested number of bytes are received
  • timeout = 0: non-blocking mode, return immediately in any case, returning zero or more, up to the requested number of bytes
  • timeout = x: set timeout to x seconds (float allowed) returns immediately when the requested number of bytes are available, otherwise wait until the timeout expires and return all bytes that were received until then.

write() is blocking by default, unless write_timeout is set. For possible values refer to the list for timeout above.

Note that enabling both flow control methods (xonxoff and rtscts) together may not be supported. It is common to use one of the methods at once, not both.

dsrdtr is not supported by all platforms (silently ignored). Setting it to None has the effect that its state follows rtscts.

Also consider using the function serial_for_url() instead of creating Serial instances directly.

Changed in version 2.5: dsrdtr now defaults to False (instead of None)

Changed in version 3.0: numbers as port argument are no longer supported

New in version 3.3: exclusive flag

open()

Open port. The state of rts and dtr is applied.

Note

Some OS and/or drivers may activate RTS and or DTR automatically, as soon as the port is opened. There may be a glitch on RTS/DTR when rts` or dtr are set differently from their default value (True / active).

Note

For compatibility reasons, no error is reported when applying rts or dtr fails on POSIX due to EINVAL (22) or ENOTTY (25).

close()

Close port immediately.

__del__()

Destructor, close port when serial port instance is freed.

The following methods may raise SerialException when applied to a closed port.

read(size=1)
Parameters:size – Number of bytes to read.
Returns:Bytes read from the port.
Return type:bytes

Read size bytes from the serial port. If a timeout is set it may return less characters as requested. With no timeout it will block until the requested number of bytes is read.

Changed in version 2.5: Returns an instance of bytes when available (Python 2.6 and newer) and str otherwise.

write(data)
Parameters:data – Data to send.
Returns:Number of bytes written.
Return type:int
Raises:SerialTimeoutException – In case a write timeout is configured for the port and the time is exceeded.

Write the bytes data to the port. This should be of type bytes (or compatible such as bytearray or memoryview). Unicode strings must be encoded (e.g. 'hello'.encode('utf-8').

Changed in version 2.5: Accepts instances of bytes and bytearray when available (Python 2.6 and newer) and str otherwise.

Changed in version 2.5: Write returned None in previous versions.

flush()

Flush of file like objects. In this case, wait until all data is written.

in_waiting
Getter:Get the number of bytes in the input buffer
Type:int

Return the number of bytes in the receive buffer.

Changed in version 3.0: changed to property from inWaiting()

out_waiting
Getter:Get the number of bytes in the output buffer
Type:int
Platform:Posix
Platform:Windows

Return the number of bytes in the output buffer.

Changed in version 2.7: (Posix support added)

Changed in version 3.0: changed to property from outWaiting()

reset_input_buffer()

Flush input buffer, discarding all its contents.

Changed in version 3.0: renamed from flushInput()

reset_output_buffer()

Clear output buffer, aborting the current output and discarding all that is in the buffer.

Note, for some USB serial adapters, this may only flush the buffer of the OS and not all the data that may be present in the USB part.

Changed in version 3.0: renamed from flushOutput()

send_break(duration=0.25)
Parameters:duration (float) – Time to activate the BREAK condition.

Send break condition. Timed, returns to idle state after given duration.

break_condition
Getter:Get the current BREAK state
Setter:Control the BREAK state
Type:bool

When set to True activate BREAK condition, else disable. Controls TXD. When active, no transmitting is possible.

rts
Setter:Set the state of the RTS line
Getter:Return the state of the RTS line
Type:bool

Set RTS line to specified logic level. It is possible to assign this value before opening the serial port, then the value is applied uppon open() (with restrictions, see open()).

dtr
Setter:Set the state of the DTR line
Getter:Return the state of the DTR line
Type:bool

Set DTR line to specified logic level. It is possible to assign this value before opening the serial port, then the value is applied uppon open() (with restrictions, see open()).

Read-only attributes:

name
Getter:Device name.
Type:str

New in version 2.5.

cts
Getter:Get the state of the CTS line
Type:bool

Return the state of the CTS line.

dsr
Getter:Get the state of the DSR line
Type:bool

Return the state of the DSR line.

ri
Getter:Get the state of the RI line
Type:bool

Return the state of the RI line.

cd
Getter:Get the state of the CD line
Type:bool

Return the state of the CD line

is_open
Getter:Get the state of the serial port, whether it’s open.
Type:bool

New values can be assigned to the following attributes (properties), the port will be reconfigured, even if it’s opened at that time:

port
Type:str

Read or write port. When the port is already open, it will be closed and reopened with the new setting.

baudrate
Getter:Get current baud rate
Setter:Set new baud rate
Type:int

Read or write current baud rate setting.

bytesize
Getter:Get current byte size
Setter:Set new byte size. Possible values: FIVEBITS, SIXBITS, SEVENBITS, EIGHTBITS
Type:int

Read or write current data byte size setting.

parity
Getter:Get current parity setting
Setter:Set new parity mode. Possible values: PARITY_NONE, PARITY_EVEN, PARITY_ODD PARITY_MARK, PARITY_SPACE

Read or write current parity setting.

stopbits
Getter:Get current stop bit setting
Setter:Set new stop bit setting. Possible values: STOPBITS_ONE, STOPBITS_ONE_POINT_FIVE, STOPBITS_TWO

Read or write current stop bit width setting.

timeout
Getter:Get current read timeout setting
Setter:Set read timeout
Type:float (seconds)

Read or write current read timeout setting.

write_timeout
Getter:Get current write timeout setting
Setter:Set write timeout
Type:float (seconds)

Read or write current write timeout setting.

Changed in version 3.0: renamed from writeTimeout

inter_byte_timeout
Getter:Get current inter byte timeout setting
Setter:Disable (None) or enable the inter byte timeout
Type:float or None

Read or write current inter byte timeout setting.

Changed in version 3.0: renamed from interCharTimeout

xonxoff
Getter:Get current software flow control setting
Setter:Enable or disable software flow control
Type:bool

Read or write current software flow control rate setting.

rtscts
Getter:Get current hardware flow control setting
Setter:Enable or disable hardware flow control
Type:bool

Read or write current hardware flow control setting.

dsrdtr
Getter:Get current hardware flow control setting
Setter:Enable or disable hardware flow control
Type:bool

Read or write current hardware flow control setting.

rs485_mode
Getter:Get the current RS485 settings
Setter:Disable (None) or enable the RS485 settings
Type:rs485.RS485Settings or None
Platform:Posix (Linux, limited set of hardware)
Platform:Windows (only RTS on TX possible)

Attribute to configure RS485 support. When set to an instance of rs485.RS485Settings and supported by OS, RTS will be active when data is sent and inactive otherwise (for reception). The rs485.RS485Settings class provides additional settings supported on some platforms.

New in version 3.0.

The following constants are also provided:

BAUDRATES

A list of valid baud rates. The list may be incomplete, such that higher and/or intermediate baud rates may also be supported by the device (Read Only).

BYTESIZES

A list of valid byte sizes for the device (Read Only).

PARITIES

A list of valid parities for the device (Read Only).

STOPBITS

A list of valid stop bit widths for the device (Read Only).

The following methods are for compatibility with the io library.

readable()
Returns:True

New in version 2.5.

writable()
Returns:True

New in version 2.5.

seekable()
Returns:False

New in version 2.5.

readinto(b)
Parameters:b – bytearray or array instance
Returns:Number of byte read

Read up to len(b) bytes into bytearray b and return the number of bytes read.

New in version 2.5.

The port settings can be read and written as dictionary. The following keys are supported: write_timeout, inter_byte_timeout, dsrdtr, baudrate, timeout, parity, bytesize, rtscts, stopbits, xonxoff

get_settings()
Returns:a dictionary with current port settings.
Return type:dict

Get a dictionary with port settings. This is useful to backup the current settings so that a later point in time they can be restored using apply_settings().

Note that the state of control lines (RTS/DTR) are not part of the settings.

New in version 2.5.

Changed in version 3.0: renamed from getSettingsDict

apply_settings(d)
Parameters:d (dict) – a dictionary with port settings.

Applies a dictionary that was created by get_settings(). Only changes are applied and when a key is missing, it means that the setting stays unchanged.

Note that control lines (RTS/DTR) are not changed.

New in version 2.5.

Changed in version 3.0: renamed from applySettingsDict

This class can be used as context manager. The serial port is closed when the context is left.

__enter__()
Returns:Serial instance

Returns the instance that was used in the with statement.

Example:

>>> with serial.serial_for_url(port) as s:
...     s.write(b'hello')

Here no port argument is given, so it is not opened automatically:

>>> with serial.Serial() as s:
...     s.port = ...
...     s.open()
...     s.write(b'hello')
__exit__(exc_type, exc_val, exc_tb)

Closes serial port (exceptions are not handled by __exit__).

Platform specific methods.

Warning

Programs using the following methods and attributes are not portable to other platforms!

nonblocking()
Platform:Posix

Deprecated since version 3.2: The serial port is already opened in this mode. This method is not needed and going away.

fileno()
Platform:Posix
Returns:File descriptor.

Return file descriptor number for the port that is opened by this object. It is useful when serial ports are used with select.

set_input_flow_control(enable)
Platform:Posix
Parameters:enable (bool) – Set flow control state.

Manually control flow - when software flow control is enabled.

This will send XON (true) and XOFF (false) to the other device.

New in version 2.7: (Posix support added)

Changed in version 3.0: renamed from flowControlOut

set_output_flow_control(enable)
Platform:Posix (HW and SW flow control)
Platform:Windows (SW flow control only)
Parameters:enable (bool) – Set flow control state.

Manually control flow of outgoing data - when hardware or software flow control is enabled.

Sending will be suspended when called with False and enabled when called with True.

Changed in version 2.7: (renamed on Posix, function was called flowControl)

Changed in version 3.0: renamed from setXON

cancel_read()
Platform:Posix
Platform:Windows

Cancel a pending read operation from another thread. A blocking read() call is aborted immediately. read() will not report any error but return all data received up to that point (similar to a timeout).

On Posix a call to cancel_read() may cancel a future read() call.

New in version 3.1.

cancel_write()
Platform:Posix
Platform:Windows

Cancel a pending write operation from another thread. The write() method will return immediately (no error indicated). However the OS may still be sending from the buffer, a separate call to reset_output_buffer() may be needed.

On Posix a call to cancel_write() may cancel a future write() call.

New in version 3.1.

Note

The following members are deprecated and will be removed in a future release.

portstr

Deprecated since version 2.5: use name instead

inWaiting()

Deprecated since version 3.0: see in_waiting

isOpen()

Deprecated since version 3.0: see is_open

writeTimeout

Deprecated since version 3.0: see write_timeout

interCharTimeout

Deprecated since version 3.0: see inter_byte_timeout

sendBreak(duration=0.25)

Deprecated since version 3.0: see send_break()

flushInput()

Deprecated since version 3.0: see reset_input_buffer()

flushOutput()

Deprecated since version 3.0: see reset_output_buffer()

setBreak(level=True)

Deprecated since version 3.0: see break_condition

setRTS(level=True)

Deprecated since version 3.0: see rts

setDTR(level=True)

Deprecated since version 3.0: see dtr

getCTS()

Deprecated since version 3.0: see cts

getDSR()

Deprecated since version 3.0: see dsr

getRI()

Deprecated since version 3.0: see ri

getCD()

Deprecated since version 3.0: see cd

getSettingsDict()

Deprecated since version 3.0: see get_settings()

applySettingsDict(d)

Deprecated since version 3.0: see apply_settings()

outWaiting()

Deprecated since version 3.0: see out_waiting

setXON(level=True)

Deprecated since version 3.0: see set_output_flow_control()

flowControlOut(enable)

Deprecated since version 3.0: see set_input_flow_control()

rtsToggle
Platform:Windows

Attribute to configure RTS toggle control setting. When enabled and supported by OS, RTS will be active when data is available and inactive if no data is available.

New in version 2.6.

Changed in version 3.0: (removed, see rs485_mode instead)

Implementation detail: some attributes and functions are provided by the class SerialBase and some by the platform specific class and others by the base class mentioned above.

RS485 support

The Serial class has a Serial.rs485_mode attribute which allows to enable RS485 specific support on some platforms. Currently Windows and Linux (only a small number of devices) are supported.

Serial.rs485_mode needs to be set to an instance of rs485.RS485Settings to enable or to None to disable this feature.

Usage:

import serial
import serial.rs485
ser = serial.Serial(...)
ser.rs485_mode = serial.rs485.RS485Settings(...)
ser.write(b'hello')

There is a subclass rs485.RS485 available to emulate the RS485 support on regular serial ports (serial.rs485 needs to be imported).

class rs485.RS485Settings

A class that holds RS485 specific settings which are supported on some platforms.

New in version 3.0.

__init__(rts_level_for_tx=True, rts_level_for_rx=False, loopback=False, delay_before_tx=None, delay_before_rx=None):
Parameters:
  • rts_level_for_tx (bool) – RTS level for transmission
  • rts_level_for_rx (bool) – RTS level for reception
  • loopback (bool) – When set to True transmitted data is also received.
  • delay_before_tx (float) – Delay after setting RTS but before transmission starts
  • delay_before_rx (float) – Delay after transmission ends and resetting RTS
rts_level_for_tx

RTS level for transmission.

rts_level_for_rx

RTS level for reception.

loopback

When set to True transmitted data is also received.

delay_before_tx

Delay after setting RTS but before transmission starts (seconds as float).

delay_before_rx

Delay after transmission ends and resetting RTS (seconds as float).

class rs485.RS485

A subclass that replaces the Serial.write() method with one that toggles RTS according to the RS485 settings.

Usage:

ser = serial.rs485.RS485(...)
ser.rs485_mode = serial.rs485.RS485Settings(...)
ser.write(b'hello')

Warning

This may work unreliably on some serial ports (control signals not synchronized or delayed compared to data). Using delays may be unreliable (varying times, larger than expected) as the OS may not support very fine grained delays (no smaller than in the order of tens of milliseconds).

Note

Some implementations support this natively in the class Serial. Better performance can be expected when the native version is used.

Note

The loopback property is ignored by this implementation. The actual behavior depends on the used hardware.

RFC 2217 Network ports

Warning

This implementation is currently in an experimental state. Use at your own risk.

class rfc2217.Serial

This implements a RFC 2217 compatible client. Port names are URL in the form: rfc2217://<host>:<port>[?<option>[&<option>]]

This class API is compatible to Serial with a few exceptions:

  • write_timeout is not implemented
  • The current implementation starts a thread that keeps reading from the (internal) socket. The thread is managed automatically by the rfc2217.Serial port object on open()/close(). However it may be a problem for user applications that like to use select instead of threads.

Due to the nature of the network and protocol involved there are a few extra points to keep in mind:

  • All operations have an additional latency time.
  • Setting control lines (RTS/CTS) needs more time.
  • Reading the status lines (DSR/DTR etc.) returns a cached value. When that cache is updated depends entirely on the server. The server itself may implement a polling at a certain rate and quick changes may be invisible.
  • The network layer also has buffers. This means that flush(), reset_input_buffer() and reset_output_buffer() may work with additional delay. Likewise in_waiting returns the size of the data arrived at the objects internal buffer and excludes any bytes in the network buffers or any server side buffer.
  • Closing and immediately reopening the same port may fail due to time needed by the server to get ready again.

Not implemented yet / Possible problems with the implementation:

  • RFC 2217 flow control between client and server (objects internal buffer may eat all your memory when never read).
  • No authentication support (servers may not prompt for a password etc.)
  • No encryption.

Due to lack of authentication and encryption it is not suitable to use this client for connections across the internet and should only be used in controlled environments.

New in version 2.5.

class rfc2217.PortManager

This class provides helper functions for implementing RFC 2217 compatible servers.

Basically, it implements everything needed for the RFC 2217 protocol. It just does not open sockets and read/write to serial ports (though it changes other port settings). The user of this class must take care of the data transmission itself. The reason for that is, that this way, this class supports all programming models such as threads and select.

Usage examples can be found in the examples where two TCP/IP - serial converters are shown, one using threads (the single port server) and an other using select (the multi port server).

Note

Each new client connection must create a new instance as this object (and the RFC 2217 protocol) has internal state.

__init__(serial_port, connection, debug_output=False)
Parameters:
  • serial_port – a Serial instance that is managed.
  • connection – an object implementing write(), used to write to the network.
  • debug_output – enables debug messages: a logging.Logger instance or None.

Initializes the Manager and starts negotiating with client in Telnet and RFC 2217 protocol. The negotiation starts immediately so that the class should be instantiated in the moment the client connects.

The serial_port can be controlled by RFC 2217 commands. This object will modify the port settings (baud rate etc.) and control lines (RTS/DTR) send BREAK etc. when the corresponding commands are found by the filter() method.

The connection object must implement a write() function. This function must ensure that data is written at once (no user data mixed in, i.e. it must be thread-safe). All data must be sent in its raw form (escape() must not be used) as it is used to send Telnet and RFC 2217 control commands.

For diagnostics of the connection or the implementation, debug_output can be set to an instance of a logging.Logger (e.g. logging.getLogger('rfc2217.server')). The caller should configure the logger using setLevel for the desired detail level of the logs.

escape(data)
Parameters:data – data to be sent over the network.
Returns:data, escaped for Telnet/RFC 2217

A generator that escapes all data to be compatible with RFC 2217. Implementors of servers should use this function to process all data sent over the network.

The function returns a generator which can be used in for loops. It can be converted to bytes using serial.to_bytes().

filter(data)
Parameters:data – data read from the network, including Telnet and RFC 2217 controls.
Returns:data, free from Telnet and RFC 2217 controls.

A generator that filters and processes all data related to RFC 2217. Implementors of servers should use this function to process all data received from the network.

The function returns a generator which can be used in for loops. It can be converted to bytes using serial.to_bytes().

check_modem_lines(force_notification=False)
Parameters:force_notification – Set to false. Parameter is for internal use.

This function needs to be called periodically (e.g. every second) when the server wants to send NOTIFY_MODEMSTATE messages. This is required to support the client for reading CTS/DSR/RI/CD status lines.

The function reads the status line and issues the notifications automatically.

New in version 2.5.

See also

RFC 2217 - Telnet Com Port Control Option

Exceptions

exception serial.SerialException

Base class for serial port exceptions.

Changed in version 2.5: Now derives from IOError instead of Exception

exception serial.SerialTimeoutException

Exception that is raised on write timeouts.

Constants

Parity

serial.PARITY_NONE
serial.PARITY_EVEN
serial.PARITY_ODD
serial.PARITY_MARK
serial.PARITY_SPACE

Stop bits

serial.STOPBITS_ONE
serial.STOPBITS_ONE_POINT_FIVE
serial.STOPBITS_TWO

Note that 1.5 stop bits are not supported on POSIX. It will fall back to 2 stop bits.

Byte size

serial.FIVEBITS
serial.SIXBITS
serial.SEVENBITS
serial.EIGHTBITS

Others

Default control characters (instances of bytes for Python 3.0+) for software flow control:

serial.XON
serial.XOFF

Module version:

serial.VERSION

A string indicating the pySerial version, such as 3.0.

New in version 2.3.

Module functions and attributes

serial.device(number)

Changed in version 3.0: removed, use serial.tools.list_ports instead

serial.serial_for_url(url, *args, **kwargs)
Parameters:
  • url – Device name, number or URL
  • do_not_open – When set to true, the serial port is not opened.
Returns:

an instance of Serial or a compatible object.

Get a native or a RFC 2217 implementation of the Serial class, depending on port/url. This factory function is useful when an application wants to support both, local ports and remote ports. There is also support for other types, see URL section.

The port is not opened when a keyword parameter called do_not_open is given and true, by default it is opened.

New in version 2.5.

serial.protocol_handler_packages

This attribute is a list of package names (strings) that is searched for protocol handlers.

e.g. we want to support a URL foobar://. A module my_handlers.protocol_foobar is provided by the user:

serial.protocol_handler_packages.append("my_handlers")
s = serial.serial_for_url("foobar://")

For an URL starting with XY:// is the function serial_for_url() attempts to import PACKAGE.protocol_XY with each candidate for PACKAGE from this list.

New in version 2.6.

serial.to_bytes(sequence)
Parameters:sequence – bytes, bytearray or memoryview
Returns:an instance of bytes

Convert a sequence to a bytes type. This is used to write code that is compatible to Python 2.x and 3.x.

In Python versions prior 3.x, bytes is a subclass of str. They convert str([17]) to '[17]' instead of '\x11' so a simple bytes(sequence) doesn’t work for all versions of Python.

This function is used internally and in the unit tests.

New in version 2.5.

serial.iterbytes(sequence)
Parameters:sequence – bytes, bytearray or memoryview
Returns:a generator that yields bytes

Some versions of Python (3.x) would return integers instead of bytes when looping over an instance of bytes. This helper function ensures that bytes are returned.

New in version 3.0.

Threading

New in version 3.0.

Warning

This implementation is currently in an experimental state. Use at your own risk.

This module provides classes to simplify working with threads and protocols.

class serial.threaded.Protocol

Protocol as used by the ReaderThread. This base class provides empty implementations of all methods.

connection_made(transport)
Parameters:transport – instance used to write to serial port.

Called when reader thread is started.

data_received(data)
Parameters:data (bytes) – received bytes

Called with snippets received from the serial port.

connection_lost(exc)
Parameters:exc – Exception if connection was terminated by error else None

Called when the serial port is closed or the reader loop terminated otherwise.

class serial.threaded.Packetizer(Protocol)

Read binary packets from serial port. Packets are expected to be terminated with a TERMINATOR byte (null byte by default).

The class also keeps track of the transport.

TERMINATOR = b'\0'
__init__()
connection_made(transport)

Stores transport.

connection_lost(exc)

Forgets transport.

data_received(data)
Parameters:data (bytes) – partial received data

Buffer received data and search for TERMINATOR, when found, call handle_packet().

handle_packet(packet)
Parameters:packet (bytes) – a packet as defined by TERMINATOR

Process packets - to be overridden by subclassing.

class serial.threaded.LineReader(Packetizer)

Read and write (Unicode) lines from/to serial port. The encoding is applied.

TERMINATOR = b'\r\n'

Line ending.

ENCODING = 'utf-8'

Encoding of the send and received data.

UNICODE_HANDLING = 'replace'

Unicode error handly policy.

handle_packet(packet)
Parameters:packet (bytes) – a packet as defined by TERMINATOR

In this case it will be a line, calls handle_line() after applying the ENCODING.

handle_line(line)
Parameters:line (str) – Unicode string with one line (excluding line terminator)

Process one line - to be overridden by subclassing.

write_line(text)
Parameters:text (str) – Unicode string with one line (excluding line terminator)

Write text to the transport. text is expected to be a Unicode string and the encoding is applied before sending and also the TERMINATOR (new line) is appended.

class serial.threaded.ReaderThread(threading.Thread)

Implement a serial port read loop and dispatch to a Protocol instance (like the asyncio.Protocol) but do it with threads.

Calls to close() will close the serial port but it is also possible to just stop() this thread and continue to use the serial port instance otherwise.

__init__(serial_instance, protocol_factory)
Parameters:
  • serial_instance – serial port instance (opened) to be used.
  • protocol_factory – a callable that returns a Protocol instance

Initialize thread.

Note that the serial_instance ‘s timeout is set to one second! Other settings are not changed.

stop()

Stop the reader thread.

run()

The actual reader loop driven by the thread. It calls Protocol.connection_made(), reads from the serial port calling Protocol.data_received() and finally calls Protocol.connection_lost() when close() is called or an error occurs.

write(data)
Parameters:data (bytes) – data to write

Thread safe writing (uses lock).

close()

Close the serial port and exit reader thread, calls stop() (uses lock).

connect()

Wait until connection is set up and return the transport and protocol instances.

This class can be used as context manager, in this case it starts the thread and connects automatically. The serial port is closed when the context is left.

__enter__()
Returns:protocol

Connect and return protocol instance.

__exit__(exc_type, exc_val, exc_tb)

Closes serial port.

Example:

class PrintLines(LineReader):
    def connection_made(self, transport):
        super(PrintLines, self).connection_made(transport)
        sys.stdout.write('port opened\n')
        self.write_line('hello world')

    def handle_line(self, data):
        sys.stdout.write('line received: {}\n'.format(repr(data)))

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

ser = serial.serial_for_url('loop://', baudrate=115200, timeout=1)
with ReaderThread(ser, PrintLines) as protocol:
    protocol.write_line('hello')
    time.sleep(2)

asyncio

asyncio was introduced with Python 3.4. Experimental support for pySerial is provided via a separate distribution pyserial-asyncio.

It is currently under development, see: