Py Serial
Py Serial
Py Serial
Release 2.6
Chris Liechti
CONTENTS
pySerial 1.1 Overview . . . 1.2 Features . . . . 1.3 Requirements . 1.4 Installation . . 1.5 References . . 1.6 Older Versions
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
3 3 3 4 4 5 5 7 7 7 8 8 9 9 10 11 12 13 13 13 15 15 23 23 24 26 29 29 30 30 30 31 33 33 33 i
Short introduction 2.1 Opening serial ports . 2.2 Conguring ports later 2.3 Readline . . . . . . . 2.4 Testing ports . . . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
Examples 3.1 Miniterm . . . . . . . . . . . . . . . . . . . . 3.2 TCP/IP - serial bridge . . . . . . . . . . . . . 3.3 Single-port TCP/IP - serial bridge (RFC 2217) 3.4 Multi-port TCP/IP - serial bridge (RFC 2217) . 3.5 wxPython examples . . . . . . . . . . . . . . 3.6 Wrapper class . . . . . . . . . . . . . . . . . 3.7 Unit tests . . . . . . . . . . . . . . . . . . . . pySerial API 4.1 Classes . . . . . . . . . . . . . 4.2 Exceptions . . . . . . . . . . . 4.3 Constants . . . . . . . . . . . . 4.4 Module functions and attributes 4.5 Tools . . . . . . . . . . . . . . pyParallel 5.1 Overview . . . . . 5.2 Short introduction 5.3 API . . . . . . . . 5.4 Notes . . . . . . . 5.5 Misc . . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
6.3 6.4 7
34 34 37 39 41
ii
This module encapsulates the access for the serial port. It provides backends for Python running on Windows, Linux, BSD (possibly any POSIX compliant system), Jython and IronPython (.NET and Mono). The module named serial automatically selects the appropriate backend. Other pages (online) project page on SourceForge SVN repository Download Page with releases This page, when viewed online, is at http://pyserial.sf.net. Contents:
CONTENTS
CONTENTS
CHAPTER
ONE
PYSERIAL
1.1 Overview
This module encapsulates the access for the serial port. It provides backends for Python running on Windows, Linux, BSD (possibly any POSIX compliant system), Jython and IronPython (.NET and Mono). The module named serial automatically selects the appropriate backend. It is released under a free software license, see LICENSE for more details. Copyright (C) 2001-2010 Chris Liechti <cliechti(at)gmx.net> Other pages (online) project page on SourceForge SVN repository Download Page with releases This page, when viewed online is at http://pyserial.sf.net.
1.2 Features
Same class based interface on all supported platforms. Access to the port settings through Python properties. Support for different byte sizes, stop bits, parity and ow control with RTS/CTS and/or Xon/Xoff. Working with or without receive timeout. File like API with read and write (readline etc. also supported). The les in this package are 100% pure Python. The port is set up for binary transmission. No NULL byte stripping, CR-LF translation etc. (which are many times enabled for POSIX.) This makes this module universally useful. Compatible with io library (Python 2.6+) RFC 2217 client (experimental), server provided in the examples.
1.3 Requirements
Python 2.3 or newer, including Python 3.x ctypes extensions on Windows (is in standard library since Python 2.5+) Java Communications (JavaComm) or compatible extension for Java/Jython
1.4 Installation
1.4.1 pyserial
This installs a package that can be used from Python (import serial). To install the module for all users on the system, administrator rights (root) is required.. From source (tar.gz or checkout) Download the archive from http://pypi.python.org/pypi/pyserial. Unpack the archive, enter the pyserial-x.y directory and run:
python setup.py install
From PyPI Alternatively it can be installed from PyPI, either manually downloading the les and installing as described above or using:
pip pyserial
or:
easy_install -U pyserial
Packages There are also packaged versions for some Linux distributions and Windows: Debian/Ubuntu A package is available under the name python-serial. Note that some distributions package an older version of pySerial. Windows There is also a Windows installer for end users. It is located in the PyPi. Developers may be interested to get the source archive, because it contains examples and the readme.
Chapter 1. pySerial
1.5 References
Python: http://www.python.org/ Jython: http://www.jython.org/ Java@IBM: http://www-106.ibm.com/developerworks/java/jdk/ (JavaComm links are on the download page for the respective platform JDK) Java@SUN: http://java.sun.com/products/ IronPython: http://www.codeplex.com/IronPython setuptools: http://peak.telecommunity.com/DevCenter/setuptools
1.5. References
Chapter 1. pySerial
CHAPTER
TWO
SHORT INTRODUCTION
2.1 Opening serial ports
Open port 0 at 9600,8,N,1, no timeout:
>>> >>> >>> >>> >>> import serial ser = serial.Serial(0) print ser.portstr ser.write("hello") ser.close() # # # # open first serial port check which port was really used write a string close port
>>> ser = serial.Serial() >>> ser.baudrate = 19200 >>> ser.port = 0 >>> ser Serial<id=0xa81c10, open=False>(port=COM1, baudrate=19200, bytesize=8, parity=N, stopbits=1, time >>> ser.open() >>> ser.isOpen() True >>> ser.close() >>> ser.isOpen() False
2.3 Readline
Be carefully when using readline(). Do specify a timeout when opening the serial port otherwise it could block forever if no newline character is received. Also note that readlines() only works with a timeout. readlines() depends on having a timeout and interprets that as EOF (end of le). It raises an exception if the port is not opened correctly. Do also have a look at the example les in the examples directory in the source distribution or online. Note: The eol parameter for readline() is no longer supported when pySerial is run with newer Python versions (V2.6+) where the module io is available.
2.3.1 EOL
To specify the EOL character for readline() or to use universal newline mode, it is advised to use io.TextIOWrapper:
import serial import io ser = serial.serial_for_url(loop://, timeout=1) sio = io.TextIOWrapper(io.BufferedRWPair(ser, ser)) sio.write(unicode("hello\n")) sio.flush() # it is buffering. required to get the data out *now* hello = sio.readline() print hello == unicode("hello\n")
CHAPTER
THREE
EXAMPLES
3.1 Miniterm
This is a console application that provides a small terminal application. Miniterm itself does not implement any terminal features such as VT102 compatibility. However it inherits these features from the terminal it is run. For example on GNU/Linux running from an xterm it will support the escape sequences of the xterm. On Windows the typical console window is dumb and does not support any escapes. When ANSI.sys is loaded it supports some escapes. Miniterm:
--- Miniterm on /dev/ttyS0: 9600,8,N,1 ----- Quit: Ctrl+] | Menu: Ctrl+T | Help: Ctrl+T followed by Ctrl+H ---
Command line options can be given so that binary data including escapes for terminals are escaped or output as hex. Miniterm supports RFC 2217 remote serial ports and raw sockets using URLs such as rfc2217:://<host>:<port> respectively socket://<host>:<port> as port argument when invoking. Command line options python -m serial.tools.miniterm -h:
Usage: miniterm.py [options] [port [baudrate]] Miniterm - A simple terminal program for the serial port. Options: -h, --help -p PORT, --port=PORT
show this help message and exit port, a number (default 0) or a device name (deprecated option) -b BAUDRATE, --baud=BAUDRATE set baud rate, default 9600 --parity=PARITY set parity, one of [N, E, O, S, M], default=N -e, --echo enable local echo (default off) --rtscts enable RTS/CTS flow control (default off) --xonxoff enable software flow control (default off) --cr do not send CR+LF, send CR only --lf do not send CR+LF, send LF only -D, --debug debug received data (escape non-printable chars) --debug can be given multiple times: 0: just print what is received 1: escape non-printable characters, do newlines as unusual 2: escape non-printable characters, newlines too 3: hex dump everything --rts=RTS_STATE set initial RTS line state (possible values: 0, 1) --dtr=DTR_STATE set initial DTR line state (possible values: 0, 1) -q, --quiet suppress non error messages
--exit-char=EXIT_CHAR ASCII code of special character that is used to exit the application --menu-char=MENU_CHAR ASCII code of special character that is used to control miniterm (menu)
Miniterm supports some control functions. Typing Ctrl+T Ctrl+H when it is running shows the help text:
--------------------------------------------pySerial - miniterm - help Ctrl+] Exit Ctrl+T Menu Menu keys: Ctrl+T Ctrl+] Ctrl+I Ctrl+U Toggles: Ctrl+R Ctrl+D Ctrl+L Port settings p 7 8 n e o s m 1 2 3 b x X r R program escape key, followed by: Send the menu character itself to remote Send the exit character to remote Show info Upload file (prompt will be shown) RTS DTR line feed Ctrl+E Ctrl+B Ctrl+A local echo BREAK Cycle repr mode
(Ctrl+T followed by the following): change port set data bits change parity (None, Even, Odd, Space, Mark) set stop bits (1, 2, 1.5) change baud rate disable/enable software flow control disable/enable hardware flow control
Changed in version 2.5: Added Ctrl+T menu and added support for opening URLs.Changed in version 2.6: File moved from the examples to serial.tools.miniterm. miniterm.py The miniterm program. setup-miniterm-py2exe.py This is a py2exe setup script for Windows. It can be used to create a standalone miniterm.exe.
10
Chapter 3. Examples
show this help message and exit suppress non error messages peek at the communication and print all data to the console
Serial Port: Serial port settings -p PORT, --port=PORT port, a number (default 0) or a device name -b BAUDRATE, --baud=BAUDRATE set baud rate, default: 9600 --parity=PARITY set parity, one of [N, E, O], default=N --rtscts enable RTS/CTS flow control (default off) --xonxoff enable software flow control (default off) --rts=RTS_STATE set initial RTS line state (possible values: 0, 1) --dtr=DTR_STATE set initial DTR line state (possible values: 0, 1) Network settings: Network configuration. -P LOCAL_PORT, --localport=LOCAL_PORT local TCP port --rfc2217 allow control commands with Telnet extension RFC-2217 Newline Settings: Convert newlines between network and serial port. Conversion is normally disabled and can be enabled by --convert. -c, --convert enable newline conversion (default off) --net-nl=NET_NEWLINE type of newlines that are expected on the network (default: LF) --ser-nl=SER_NEWLINE type of newlines that are expected on the serial port (default: CR+LF) NOTE: no security measures are implemented. Anyone can remotely connect to this service over the network. Only one connection at once is supported. When the connection is terminated it waits for the next connect.
11
New in version 2.5. rfc2217_server.py Main program. setup-rfc2217_server-py2exe.py This is a py2exe setup script for Windows. It can be used to create a standalone rfc2217_server.exe.
12
Chapter 3. Examples
Add links to the runlevels using update-rc.d port_publisher.sh defaults 99 Thats it :-) the service will be started on next reboot. port_publisher.sh start as root. New in version 2.5: new example port_publisher.py Multi-port TCP/IP-serial converter (RFC 2217) for POSIX environments. port_publisher.sh Example init.d script. Alternatively run invoke-rc.d
13
14
Chapter 3. Examples
CHAPTER
FOUR
PYSERIAL API
4.1 Classes
4.1.1 Native ports
class serial.Serial __init__(port=None, baudrate=9600, bytesize=EIGHTBITS, parity=PARITY_NONE, stopbits=STOPBITS_ONE, timeout=None, xonxoff=False, rtscts=False, writeTimeout=None, dsrdtr=False, interCharTimeout=None) Parameters 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 stopbits Number of stop bits. Possible STOPBITS_ONE_POINT_FIVE, STOPBITS_TWO timeout Set a read timeout value. xonxoff Enable software ow control. rtscts Enable hardware (RTS/CTS) ow control. dsrdtr Enable hardware (DSR/DTR) ow control. writeTimeout Set a write timeout value. interCharTimeout Inter-character timeout, None to disable (default). 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 congured. 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: values: STOPBITS_ONE,
15
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 (oat allowed) Writes are blocking by default, unless writeTimeout is set. For possible values refer to the list for timeout above. Note that enabling both ow 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) Parameters size Number of bytes to read. 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) Parameters data Data to send. Returns Number of bytes written. Raises SerialTimeoutException In case a write timeout is congured 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.
16
inWaiting() Return the number of chars in the receive buffer. flush() Flush of le like objects. In this case, wait until all data is written. flushInput() Flush input buffer, discarding all its contents. flushOutput() Clear output buffer, aborting the current output and discarding all that is in the buffer. sendBreak(duration=0.25) Parameters duration Time (oat) to activate the BREAK condition. Send break condition. Timed, returns to idle state after given duration. setBreak(level=True) Parameters level when true activate BREAK condition, else disable. Set break: Controls TXD. When active, no transmitting is possible. setRTS(level=True) Parameters level Set control line to logic level. Set RTS line to specied logic level. setDTR(level=True) Parameters level Set control line to logic level. Set DTR line to specied logic level. getCTS() Returns Current state (boolean) Return the state of the CTS line. getDSR() Returns Current state (boolean) Return the state of the DSR line. getRI() Returns Current state (boolean) Return the state of the RI line. getCD() Returns Current state (boolean) Return the state of the CD line Read-only attributes: name Device name. This is always the device name even if the port was opened by a number. (Read Only). New in version 2.5. portstr Deprecated use name instead
4.1. Classes
17
New values can be assigned to the following attributes (properties), the port will be recongured, even if its opened at that time: port Read or write port. When the port is already open, it will be closed and reopened with the new setting. baudrate Read or write current baud rate setting. bytesize Read or write current data byte size setting. parity Read or write current parity setting. stopbits Read or write current stop bit width setting. timeout Read or write current read timeout setting. writeTimeout Read or write current write timeout setting. xonxoff Read or write current software ow control rate setting. rtscts Read or write current hardware ow control setting. dsrdtr Read or write current hardware ow control setting. interCharTimeout Read or write current inter character timeout setting. The following constants are also provided: BAUDRATES 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). 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()
18
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. getSettingsDict() 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 using applySettingsDict(). Note that control lines (RTS/DTR) are part of the settings. New in version 2.5. applySettingsDict(d) Parameters d a dictionary with port settings. 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 specic methods. Warning: Programs using the following methods are not portable to other platforms! nonblocking() Platform Unix Congure the device for nonblocking operation. This can be useful if the port is used with select. fileno() Platform Unix Returns File descriptor. Return le descriptor number for the port that is opened by this object. It is useful when serial ports are used with select. setXON(level=True) Platform Windows Parameters level Set ow control state. Set software ow 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 specic class and others by the base class mentioned above.
4.1. Classes
19
class serial.FileLike An abstract le like class. It is used as base class for Serial when no io module is available. This class implements readline() and readlines() based 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 specied size is reached) and that readlines() 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 le like objects. Its 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 le-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=None) 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 le like object as iterator for e.g. for line in Serial(0): next() Return the next line by calling readline(). __iter__() Returns self. Other high level access functions. readline(size=None, eol=\n) Parameters size Max number of bytes to read, None -> no limit. eol The end of line character. ... usage:
20
Read a line which is terminated with end-of-line (eol) character (\n by default) or until timeout. readlines(sizehint=None, eol=\n) Parameters sizehint Ignored parameter. 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. xreadlines(sizehint=None) 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(...): ... instead. 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.
names
are
URLs
in
the
form:
4.1. Classes
21
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_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(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 congure 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.
22
A generator that lters 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_notication=False) Parameters force_notication 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 notications automatically. New in version 2.5. See Also: RFC 2217 - Telnet Com Port Control Option
4.2 Exceptions
exception serial.SerialException Base class for serial port exceptions. Changed in version 2.5: Now derrives from IOError instead of Exception exception serial.SerialTimeoutException Exception that is raised on write timeouts.
4.3 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
4.2. Exceptions
23
serial.EIGHTBITS Others Default control characters (instances of bytes for Python 3.0+) for software ow control: serial.XON serial.XOFF Module version: serial.VERSION A string indicating the pySerial version, such as 2.5. New in version 2.3.
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 String or list of integers
24
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) doesnt work for all versions of Python. This function is used internally and in the unit tests. New in version 2.5.
4.4.1 URLs
The function serial_for_url() accepts the following types of URLs: rfc2217://<host>:<port>[/<option>[/<option>]] socket://<host>:<port>[/<option>[/<option>]] loop://[<option>[/<option>]] Device names are also supported, e.g.: /dev/ttyUSB0 (Linux) COM3 (Windows) Future releases of pySerial might add more types. Since pySerial 2.6 it is also possible for the user to add protocol handlers using protocol_handler_packages. rfc2217:// 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 remote rejected value for option 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 notications automatically (thats 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 notications. 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|error]: Prints diagnostic messages (not useful for end users). It uses the logging module and a logger called pySerial.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). socket:// 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|error]: Prints diagnostic messages (not useful for end users). It uses the logging module and a logger called pySerial.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).
25
loop:// 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|error]: Prints diagnostic messages (not useful for end users). It uses the logging module and a logger called pySerial.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). Examples: rfc2217://localhost:7000 rfc2217://localhost:7000/poll_modem rfc2217://localhost:7000/ign_set_control/timeout=5.5 socket://localhost:7777 loop://logging=debug
4.5 Tools
4.5.1 serial.tools.list_ports
New in version 2.6. This module can be executed to get serial.tools.list_ports). It also contains the following functions. serial.tools.list_ports.comports() 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 les) Platform Linux (/dev les, sysfs and lsusb) Platform Windows (setupapi, registry) serial.tools.list_ports.grep(regexp) Parameters regexp regular expression (see stdlib re) Returns ltered sequence, see comports(). a list of ports (python -m
26
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.
4.5.2 serial.tools.miniterm
New in version 2.6. Miniterm is now available as module instead of example. see Miniterm for details.
4.5. Tools
27
28
CHAPTER
FIVE
PYPARALLEL
Note: This module is in development (since years ;-)
5.1 Overview
This module encapsulates the access for the parallel port. It provides backends for Python running on Windows and Linux. Other platforms are possible too but not yet integrated. This module is still under development. But it may be useful for developers. Copyright (C) 2001-2003 Chris Liechti <cliechti(at)gmx.net> Here is the project page on SourceForge and here is the SVN repository.
5.1.1 Features
same class based interface on all supported platforms port numbering starts at zero, no need to know the port name in the user program port string (device name) can be specied if access through numbering is inappropriate
5.1.2 Requirements
Python 2.2 or newer Java Communications (JavaComm) extension for Java/Jython
5.1.3 Installation
Extract les from the archive, open a shell/console in that directory and let Distutils do the rest: python setup.py install The les get installed in the Lib/site-packages directory in newer Python versions. The windows version needs a compiled extension and the giveio.sys driver for Windows NT/2k/XP. The extension module can be compiled with Distutils with either MSVC or GCC/mingw32. It is released under a free software license, see LICENSE.txt for more details.
29
5.2.1 Examples
Please look in the SVN Repository. There is an example directory where you can nd a simple terminal and more. http://pyserial.svn.sourceforge.net/viewvc/pyserial/trunk/pyparallel/examples/
5.3 API
class parallel.Parallel __init__(port) Open given parallel port. setData(value) Apply the given byte to the data pins of the parallel port. setDataStrobe(level) Set the data strobe line to the given state. setAutoFeed(level) Set auto feed line to given state. setInitOut(level) Set initialize line to given state. getInSelected() Read level of select line. getInPaperOut() Read level of paper out line. getInAcknowledge() Read level of Acknowledge line. class parallel.parallelutil.BitaccessMeta This mix-in class adds a few properties that allow easier bit access to the data lines. (D0 .. D7) e.g. p.D0 refers to the rst bit of the data lines. class parallel.parallelutil.VirtualParallelPort This class provides a virtual parallel port implementation, useful for tests and simulations without real hardware.
5.4 Notes
5.4.1 Linux
1. The lp(4) module must be unloaded, rmmod lp. lp claims exclusive access to the port and other programs wont be able to use it.
30
Chapter 5. pyParallel
2. The ppdev(4) module needs to be loaded, modprobe ppdev. When udev is in use, (default with 2.6 kernels) this will create a /dev/parport0. 3. The user needs to have write permissions to /dev/parport0. Many distributions have an lp group that owns the device; the simplest is to add the user account to this group. Simply changing permissions on the device is not the best strategy as they will be reverted to their defaults next time the driver is loaded.
5.4.2 Windows
The giveio driver must be installed as the module needs direct access to the hardware. This also means that USB parallel port adapters wont be supported.
5.5 Misc
5.5.1 References
Python: http://www.python.org/ Jython: http://www.jython.org/ Java@IBM: http://www-106.ibm.com/developerworks/java/jdk/ (JavaComm links are on the download page for the respective platform JDK) Java@SUN: http://java.sun.com/products/
5.5. Misc
31
32
Chapter 5. pyParallel
CHAPTER
SIX
APPENDIX
6.1 How To
Enable RFC 2217 in programs using pySerial. Patch the code where the serial.Serial is instantiated. Replace it with:
try: s = serial.serial_for_url(...) except AttributeError: s = serial.Serial(...)
Assuming the application already stores port names as strings thats all that is required. The user just needs a way to change the port setting of your application to an rfc2217:// URL (e.g. by editing a conguration le, GUI dialog etc.). Please note that this enables all URL types supported by pySerial and that those involving the network are unencrypted and not protected against eavesdropping. Test your setup. Is the device not working as expected? Maybe its time to check the connection before proceeding. Miniterm from the Examples can be used to open the serial port and do some basic tests. To test cables, connecting RX to TX (loop back) and typing some characters in Miniterm is a simple test. When the characters are displayed on the screen, then at least RX and TX work (they still could be swapped though).
6.2 FAQ
Example works in Miniterm but not in script. The RTS and DTR lines are switched when the port is opened. This may cause some processing or reset on the connected device. In such a cases an immediately following call to write() may not be received by the device. A delay after opening the port, before the rst write(), is recommended in this situation. time.sleep(1) E.g. a
Application works when .py le is run, but fails when packaged (py2exe etc.) py2exe and similar packaging programs scan the sources for import statements and create a list of modules that they package. pySerial may create two issues with that: implementations for other modules are found. On Windows, its safe to exclude serialposix, serialjava and serialcli as these are not used. serial.serial_for_url() does a dynamic lookup of protocol handlers at runtime. If this function is used, the desired handlers have to be included manually (e.g. serial.urlhandler.protocol_socket, se-
33
rial.urlhandler.protocol_rfc2217, etc.). This can be done either with the includes option in setup.py or by a dummy import in one of the packaged modules. User supplied URL handlers serial.serial_for_url() can be used to access virtual serial ports identied by an URL scheme. E.g. for the RFC 2217: rfc2217:://. Custom URL handlers can be added by extending the module search serial.protocol_handler_packages. This is possible starting from pySerial V2.6. path in
6.4 License
Copyright (C) 2001-2011 Chris Liechti <cliechti(at)gmx.net>; All Rights Reserved. This is the Python license. In short, you can use this product in commercial and non-commercial applications, modify it, redistribute it. A notication to the author when you use and/or modify it is welcome. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING THIS SOFTWARE LICENSE AGREEMENT 1. This LICENSE AGREEMENT is between the copyright holder of this product, and the Individual or Organization (Licensee) accessing and otherwise using this product in source or binary form and its associated documentation. 2. Subject to the terms and conditions of this License Agreement, the copyright holder hereby grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use this product alone or in any derivative version, provided, however, that copyright holders License Agreement and copyright holders notice of copyright are retained in this product alone or in any derivative version prepared by Licensee. 3. In the event Licensee prepares a derivative work that is based on or incorporates this product or any part thereof, and wants to make the derivative work available to others as provided herein, then Licensee hereby agrees to include in any such work a brief summary of the changes made to this product. 4. The copyright holder is making this product available to Licensee on an AS IS basis. THE COPYRIGHT HOLDER MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, THE COPYRIGHT HOLDER MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THIS PRODUCT WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. 5. THE COPYRIGHT HOLDER SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THIS PRODUCT FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING THIS PRODUCT, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. 6. This License Agreement will automatically terminate upon a material breach of its terms and conditions. 7. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between the copyright holder and Licensee. This License Agreement does not grant permission to use trademarks or trade names from the copyright holder in a trademark sense to endorse or promote products or services of Licensee, or any third party.
34
Chapter 6. Appendix
8. By copying, installing or otherwise using this product, Licensee agrees to be bound by the terms and conditions of this License Agreement.
6.4. License
35
36
Chapter 6. Appendix
CHAPTER
SEVEN
37
38
p
parallel, 30 parallel.parallelutil, 30
s
serial, 15 serial.tools.list_ports, 26 serial.tools.miniterm, 27
39
40
INDEX
Symbols
__del__() (serial.Serial method), 16 __init__() (parallel.Parallel method), 30 __init__() (serial.Serial method), 15 __init__() (serial.rfc2217.PortManager method), 22 __iter__() (serial.FileLike method), 20
G
getCD() (serial.Serial method), 17 getCTS() (serial.Serial method), 17 getDSR() (serial.Serial method), 17 getInAcknowledge() (parallel.Parallel method), 30 getInPaperOut() (parallel.Parallel method), 30 getInSelected() (parallel.Parallel method), 30 getRI() (serial.Serial method), 17 getSettingsDict() (serial.Serial method), 19 grep() (in module serial.tools.list_ports), 26
A
applySettingsDict() (serial.Serial method), 19
B
baudrate (serial.Serial attribute), 18 BAUDRATES (serial.Serial attribute), 18 BitaccessMeta (class in parallel.parallelutil), 30 bytesize (serial.Serial attribute), 18 BYTESIZES (serial.Serial attribute), 18
I
interCharTimeout (serial.Serial attribute), 18 inWaiting() (serial.Serial method), 16 isatty() (serial.FileLike method), 20
name (serial.Serial attribute), 17 check_modem_lines() (serial.rfc2217.PortManager next() (serial.FileLike method), 20 nonblocking() (serial.Serial method), 19 method), 23 close() (serial.Serial method), 16 O comports() (in module serial.tools.list_ports), 26 open() (serial.Serial method), 16
P
Parallel (class in parallel), 30 parallel (module), 30 parallel.parallelutil (module), 30 PARITIES (serial.Serial attribute), 18 parity (serial.Serial attribute), 18 PARITY_EVEN (in module serial), 23 PARITY_MARK (in module serial), 23 PARITY_NONE (in module serial), 23 PARITY_ODD (in module serial), 23 PARITY_SPACE (in module serial), 23 port (serial.Serial attribute), 18 portstr (serial.Serial attribute), 17 protocol_handler_packages (in module serial), 24
E
EIGHTBITS (in module serial), 23 escape() (serial.rfc2217.PortManager method), 22
F
FileLike (class in serial), 19 leno() (serial.Serial method), 19 lter() (serial.rfc2217.PortManager method), 22 FIVEBITS (in module serial), 23 ush() (serial.FileLike method), 20 ush() (serial.Serial method), 17 ushInput() (serial.Serial method), 17 ushOutput() (serial.Serial method), 17
R
read() (serial.FileLike method), 20 41
read() (serial.Serial method), 16 readable() (serial.Serial method), 18 readinto() (serial.Serial method), 19 readline() (serial.FileLike method), 20 readlines() (serial.FileLike method), 21 RFC RFC 2217, 9, 11, 12, 2125, 33, 34 RFC 2271, 25 rfc2217.PortManager (class in serial), 22 rfc2217.Serial (class in serial), 21 rtscts (serial.Serial attribute), 18
X
XOFF (in module serial), 24 XON (in module serial), 24 xonxoff (serial.Serial attribute), 18 xreadlines() (serial.FileLike method), 21
S
seek() (serial.FileLike method), 20 seekable() (serial.Serial method), 18 sendBreak() (serial.Serial method), 17 Serial (class in serial), 15 serial (module), 15 serial.tools.list_ports (module), 26 serial.tools.miniterm (module), 27 serial_for_url() (in module serial), 24 SerialException, 23 SerialTimeoutException, 23 setAutoFeed() (parallel.Parallel method), 30 setBreak() (serial.Serial method), 17 setData() (parallel.Parallel method), 30 setDataStrobe() (parallel.Parallel method), 30 setDTR() (serial.Serial method), 17 setInitOut() (parallel.Parallel method), 30 setRTS() (serial.Serial method), 17 setXON() (serial.Serial method), 19 SEVENBITS (in module serial), 23 SIXBITS (in module serial), 23 STOPBITS (serial.Serial attribute), 18 stopbits (serial.Serial attribute), 18 STOPBITS_ONE (in module serial), 23 STOPBITS_ONE_POINT_FIVE (in module serial), 23 STOPBITS_TWO (in module serial), 23
T
tell() (serial.FileLike method), 20 timeout (serial.Serial attribute), 18 to_bytes() (in module serial), 24 truncate() (serial.FileLike method), 20
V
VERSION (in module serial), 24 VirtualParallelPort (class in parallel.parallelutil), 30
W
writable() (serial.Serial method), 18 write() (serial.FileLike method), 20 write() (serial.Serial method), 16
42
Index