0% found this document useful (0 votes)
177 views

Pyserial

The Serial class in pySerial allows communication over serial ports. It can be initialized with parameters like the port name, baud rate, byte size, parity, and timeouts. Opening the port immediately establishes the connection. Methods then allow reading and writing bytes to the port, flushing buffers, and controlling the hardware flow. Exceptions may occur if the port is invalid or times out during reads/writes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
177 views

Pyserial

The Serial class in pySerial allows communication over serial ports. It can be initialized with parameters like the port name, baud rate, byte size, parity, and timeouts. Opening the port immediately establishes the connection. Methods then allow reading and writing bytes to the port, flushing buffers, and controlling the hardware flow. Exceptions may occur if the port is invalid or times out during reads/writes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 75

x

 index

 modules |

 next |

 previous |

 pySerial v2.6 documentation »

pySerial API
Classes
Native ports¶
class serial.Serial
__init__(port=None, baudrate=9600, bytesi
ze=EIGHTBITS, parity=PARITY_NONE, stopbits
=STOPBITS_ONE, timeout=None, xonxoff=Fals
e,rtscts=False, writeTimeout=None, dsrdtr=Fals
e, interCharTimeout=None)
 port – Device name or port number number or None.
 baudrate – 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
Paramete stopbits – Number of stop bits. Possible
rs: values: STOPBITS_ONE, STOPBITS_ONE_POINT_FIVE, STOPBITS_T
WO
 timeout – Set a read timeout value.
 xonxoff – Enable software flow control.
 rtscts – Enable hardware (RTS/CTS) flow control.
 dsrdtr – Enable hardware (DSR/DTR) flow control.
 writeTimeout – Set a write timeout value.
 interCharTimeout – Inter-character timeout, None to disable (default).
 ValueError – Will be raised when parameter are out of range, e.g. baud
rate, data bits.
Raises:  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() will be needed.

Possible values for the parameter port:

 Number: number of device, numbering


starts at zero.
 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.

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:

 timeout = None: wait forever


 timeout = 0: non-blocking mode (return
immediately on read)
 timeout = x: set timeout to x seconds
(float allowed)
Writes are blocking by default,
unless writeTimeout 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)

open()
Open port.

close()
Close port immediately.

__del__()
Destructor, close port when serial port instance is
freed.

The following methods may


raise ValueError when
applied to a closed port.

read(size=1)
 size – Number of bytes to read.
Parameters:

Returns: Bytes read from the port.


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)
 data – Data to send.
Parameters:

Returns: Number of bytes written.


Raises SerialTimeoutException:
In case a write timeout is configured for the port and the time is exceeded.
Write the string data to the port.

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.

inWaiting()
Return the number of chars in the receive buffer.

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

flushInpu
t()
Flush input buffer, discarding all it’s contents.

flushO
utput()
Clear output buffer, aborting the current output
and discarding all that is in the buffer.

sen
dBr
eak(
durati
on=0.
25)
 duration – Time (float) to activate the BREAK condition.
Parameters:

Send break condition. Timed, returns to idle state


after given duration.

s
e
t
B
r
e
a
k
(l
e
v
el
=
Tr
u
e)
 level – when true activate BREAK condition, else disable.
Parameters:

Set break: Controls TXD. When active, no


transmitting is possible.

s
e
t
R
T
S
(
l
e
v
e
l
=
T
r
u
e
)
 level – Set control line to logic level.
Parameters:

Set RTS line to specified logic level.

s
e
t
D
T
R
(
l
e
v
e
l
=
T
r
u
e
)
 level – Set control line to logic level.
Parameters:

Set DTR line to specified logic level.

g
e
t
C
T
S
(
)
Returns: Current state (boolean)
Return the state of the CTS line.
Returns: Current state (boolean)
Return the state of the DSR line.

Returns: Current state (boolean)


Return the state of the RI line.

Returns: Current state (boolean)


Return the state of the CD line
Device name. This is always the device name
even if the port was opened by a number. (Read
Only).

New in version 2.5.

Deprecated : use name instead


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

Read or write current baud rate setting.


Read or write current data byte size setting.

Read or write current parity setting.

Read or write current stop bit width setting.

Read or write current read timeout setting.


Read or write current write timeout setting.

Read or write current software flow control rate


setting.

Read or write current hardware flow control


setting.

Read or write current hardware flow control


setting.
Read or write current inter character timeout
setting.
A list of valid baud rates. The list may be
incomplete such that higher baud rates may be
supported by the device and that values in
between the standard baud rates are supported.
(Read Only).

A list of valid byte sizes for the device (Read


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

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


Only).
Returns: True
New in version 2.5.

Returns: True
New in version 2.5.

Returns: False
New in version 2.5.
 b – bytearray or array instance
Parameters:

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.


Returns: a dictionary with current port settings.
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
usingapplySettingsDict().

Note that control lines (RTS/DTR) are part of the


settings.
New in version 2.5.

 d – a dictionary with port settings.


Parameters:

Applies a dictionary that was created


by getSettingsDict(). 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.


Platform : Unix
Configure the device for nonblocking operation.
This can be useful if the port is used with select.

Platform : Unix
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.
Platform : Windows
 level – Set flow control state.
Parameters:
Set software flow control state.

Note

For systems that provide the io library (Python 2.6


and newer), the class Serial will derive
from io.RawIOBase. For all others from FileLike.

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.

class serial.FileLike
An abstract file like class. It is used as base class
for Serial when no io module is available.

This class
implements readline() and readlines() bas
ed on read() and writelines() based
on write().

Note that when the serial port was opened with


no timeout, that readline() blocks until it sees
a newline (or the specified size is reached) and
thatreadlines() would never return and
therefore refuses to work (it raises an exception
in this case)!

writelines(sequence)
Write a list of strings to the port.

The following three methods are overridden


in Serial.

flush()
Flush of file like objects. It’s a no-op in this class,
may be overridden.

read()
Raises NotImplementedError, needs to be
overridden by subclass.

write(data)
Raises NotImplementedError, needs to be
overridden by subclass.

The following functions are


implemented for compatibility
with other file-like objects,
however serial ports are not
seekable.

seek(pos, whence=0)
Raises IOError: always, as method is not supported on serial port
New in version 2.5.

tell()
Raises IOError: always, as method is not supported on serial port
New in version 2.5.

truncate(self, n=N
one)
Raises IOError: always, as method is not supported on serial port
New in version 2.5.
isatty()
Raises IOError: always, as method is not supported on serial port
New in version 2.5.

To be able to
use the file like
object as
iterator for
e.g. for line
in Serial(
0): ... usag
e:

next()
Return the next line by calling readline().

__iter
__()
Returns self.

Other
high
level
acces
s
functi
ons.

rea
dli
ne(si
ze=N
one, e
ol='\n'
)
 size – Max number of bytes to read, None -> no limit.
Parameters:
 eol – The end of line character.

Read a line which is terminated with end-of-line


(eol) character (\n by default) or until timeout.
r
e
a
d
l
i
n
e
s
(s
iz
e
hi
nt
=
N
o
n
e,
e
ol
='
\n
')
 sizehint – Ignored parameter.
Parameters:
 eol – The end of line character.

Read a list of lines, until timeout. sizehint is


ignored and only present for API compatibility
with built-in File objects.

Note that this function only returns on a timeout.

x
r
e
a
d
l
i
n
e
s
(
s
i
z
e
h
i
n
t
=
N
o
n
e
)
Read lines, implemented as generator.
Unlike readlines (that only returns on a timeout)
is this function yielding lines as they are received.

Deprecated since version


2.5: Use for line in Serial(...): ... in
stead. This method is not available in Python 2.6
and newer where the io library is available and
pySerial bases on it.

Changed in version 2.5: Implement as generator.

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 URLs in the
form: rfc2217://<host>:<port>[/<option>
[/<option>]]
This class API is compatible to Serial with a few
exceptions:

 numbers as port name are not allowed,


only URLs in the form described above.
 writeTimeout is not implemented
 The current implementation starts a thread
that keeps reading from the (internal)
socket. The thread is managed
automatically by
the rfc2217.Serialport 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(), flushInput() and flush
Output() may work with additional delay.
Likewise inWaiting()returns the size of
the data arrived at the object 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 every thing 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_out
put=False)
 serial_port – a Serial instance that is managed.
Parameters:
 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(data)() 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)
 data – data to be sent over the network.
Parameters:

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)
 data – data read from the network, including Telnet and RFC
Parameters: 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)
 force_notification – Set to false. Parameter is for internal use.
Parameters:

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.SerialExcep
tion
Base class for serial port exceptions.

Changed in version 2.5: Now derrives


from IOError instead of Exception

exception serial.SerialTim
eoutException
Exception that is raised on write timeouts.

Constants
Parity

serial.PARITY_NONE
serial.PARITY_EVE
N
serial.PARITY_
ODD
serial.PARIT
Y_MARK
serial.PA
RITY_SPA
CE

Stop bits

serial
.STOP
BITS_
ONE
ser
ial
.ST
OP
BI
TS
_O
NE
_P
OI
NT
_F
IV
E
s
e
r
i
a
l
.
S
T
O
P
B
I
T
S
_
T
W
O

N
o
t
e
t
h
a
t
1
.
5
s
t
o
p
b
i
t
s
a
r
e
n
o
t
s
u
p
p
o
r
t
e
d
o
n
P
O
S
I
X
.
I
t
w
i
l
l
f
a
l
l
b
a
c
k
t
o
2
s
t
o
p
b
i
t
s
.

B
y
t
e
s
i
z
e

s
e
r
i
a
l
.
F
I
V
E
B
I
T
S
s
e
r
i
a
l
.
S
I
X
B
I
T
S
s
e
r
i
a
l
.
S
E
V
E
N
B
I
T
S
A string indicating the pySerial version, such
as 2.5.

New in version 2.3.


Parameters: number – Port number.

Returns: String containing device name.


Deprecated : Use device names directly.
Convert a port number to a platform dependent
device name. Unfortunately this does not work
well for all platforms; e.g. some may miss USB-
Serial converters and enumerate only internal
serial ports.

The conversion may be made off-line, that is,


there is no guarantee that the returned device
name really exists on the system.
 url – Device name, number or URL
Parameters:
 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
below.

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.


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.


 sequence – String or list of integers
Parameters:

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.


Used to connect to RFC 2217 compatible
servers. All serial port functions are supported.
Implemented by rfc2217.Serial.
Supported options in the URL are:

 ign_set_control does not wait for


acknowledges to SET_CONTROL. This
option can be used for non compliant
servers (i.e. when getting
an remoterejected value for opti
on 'control' error when connecting).
 poll_modem: The client issues
NOTIFY_MODEMSTATE requests when
status lines are read (CTS/DTR/RI/CD).
Without this option it relies on the server
sending the notifications automatically
(that’s what the RFC suggests and most
servers do). Enable this option
when getCTS() does not work as
expected, i.e. for servers that do not send
notifications.
 timeout=<value>: Change network
timeout (default 3 seconds). This is useful
when the server takes a little more time to
send its answers. The timeout applies to
the initial Telnet / RFC 2271 negotiation as
well as changing port settings or control
line change commands.
 logging=[debug|info|warning|erro
r]: Prints diagnostic messages (not useful
for end users). It uses the logging module
and a logger
calledpySerial.rfc2217 so that the
application can setup up logging handlers
etc. It will
call logging.basicConfig() which
initializes for output on sys.stderr(if no
logging was set up already).
The purpose of this connection type is that
applications using pySerial can connect to
TCP/IP to serial port converters that do not
support RFC 2217.

Uses a TCP/IP socket. All serial port settings,


control and status lines are ignored. Only data is
transmitted and received.

Supported options in the URL are:

 logging=[debug|info|warning|erro
r]: Prints diagnostic messages (not useful
for end users). It uses the logging module
and a logger calledpySerial.socket so
that the application can setup up logging
handlers etc. It will
call logging.basicConfig() which
initializes for output on sys.stderr(if no
logging was set up already).

The least useful type. It simulates a loop back


connection (RX<->TX RTS<->CTS DTR<->DSR).
It could be used to test applications or run the unit
tests.

Supported options in the URL are:

 logging=[debug|info|warning|erro
r]: Prints diagnostic messages (not useful
for end users). It uses the logging module
and a logger calledpySerial.loop so
that the application can setup up logging
handlers etc. It will
call logging.basicConfig() which
initializes for output on sys.stderr (if no
logging was set up already).
Returns: an iterable.
The function returns an iterable that yields tuples
of three strings:

 port name as it can be passed


to serial.Serial or serial.serial_
for_url()
 description in human readable form
 sort of hardware ID. E.g. may contain
VID:PID of USB-serial adapters.

Items are returned in no particular order. It may


make sense to sort the items. Also note that the
reported strings are different across platforms
and operating systems, even for the same device.

Note

Support is limited to a number of operating


systems. On some systems description and
hardware ID will not be available (None).
Platform : Posix (/dev files)
Platform : Linux (/dev files, sysfs and lsusb)
Platform : Windows (setupapi, registry)
 regexp – regular expression (see stdlib re)
Parameters:

Returns: filtered sequence, see comports().


Search for ports using a regular expression. Port
name, description and hardware ID are searched
(case insensitive). The function returns an
iterable that contains the same tuples
that comport() generates but only those that
match the regexp.

You might also like