============== pySerial API ============== .. module:: serial Classes ======= Native ports ------------ .. class:: Serial .. method:: __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) :param port: Device name or port number number or :const:`None`. :param baudrate: Baud rate such as 9600 or 115200 etc. :param bytesize: Number of data bits. Possible values: :const:`FIVEBITS`, :const:`SIXBITS`, :const:`SEVENBITS`, :const:`EIGHTBITS` :param parity: Enable parity checking. Possible values: :const:`PARITY_NONE`, :const:`PARITY_EVEN`, :const:`PARITY_ODD` :const:`PARITY_MARK`, :const:`PARITY_SPACE` :param stopbits: Number of stop bits. Possible values: :const:`STOPBITS_ONE`, :const:`STOPBITS_ONE_POINT_FIVE`, :const:`STOPBITS_TWO` :param timeout: Set a read timeout value. :param xonxoff: Enable software flow control. :param rtscts: Enable hardware (RTS/CTS) flow control. :param dsrdtr: Enable hardware (DSR/DTR) flow control. :param writeTimeout: Set a write timeout value. :param interCharTimeout: Inter-character timeout, :const:`None` to disable (default). :exception ValueError: Will be raised when parameter are out of range, e.g. baud rate, data bits. :exception 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 :const:`None` and a successive call to :meth:`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 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*: - ``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 :func:`serial_for_url` instead of creating Serial instances directly. .. versionchanged:: 2.5 *dsrdtr* now defaults to ``False`` (instead of *None*) .. method:: open() Open port. .. method:: close() Close port immediately. .. method:: __del__() Destructor, close port when serial port instance is freed. The following methods may raise :exc:`ValueError` when applied to a closed port. .. method:: read(size=1) :param size: Number of bytes to read. :return: 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. .. versionchanged:: 2.5 Returns an instance of :class:`bytes` when available (Python 2.6 and newer) and :class:`str` otherwise. .. method:: write(data) :param data: Data to send. :return: Number of bytes written. :exception SerialTimeoutException: In case a write timeout is configured for the port and the time is exceeded. Write the string *data* to the port. .. versionchanged:: 2.5 Accepts instances of :class:`bytes` and :class:`bytearray` when available (Python 2.6 and newer) and :class:`str` otherwise. .. versionchanged:: 2.5 Write returned ``None`` in previous versions. .. method:: inWaiting() Return the number of chars in the receive buffer. .. method:: flush() Flush of file like objects. In this case, wait until all data is written. .. method:: flushInput() Flush input buffer, discarding all it's contents. .. method:: flushOutput() Clear output buffer, aborting the current output and discarding all that is in the buffer. .. method:: sendBreak(duration=0.25) :param duration: Time (float) to activate the BREAK condition. Send break condition. Timed, returns to idle state after given duration. .. method:: setBreak(level=True) :param level: when true activate BREAK condition, else disable. Set break: Controls TXD. When active, no transmitting is possible. .. method:: setRTS(level=True) :param level: Set control line to logic level. Set RTS line to specified logic level. .. method:: setDTR(level=True) :param level: Set control line to logic level. Set DTR line to specified logic level. .. method:: getCTS() :return: Current state (boolean) Return the state of the CTS line. .. method:: getDSR() :return: Current state (boolean) Return the state of the DSR line. .. method:: getRI() :return: Current state (boolean) Return the state of the RI line. .. method:: getCD() :return: Current state (boolean) Return the state of the CD line Read-only attributes: .. attribute:: name Device name. This is always the device name even if the port was opened by a number. (Read Only). .. versionadded:: 2.5 .. attribute:: portstr :deprecated: use :attr:`name` instead New values can be assigned to the following attributes (properties), the port will be reconfigured, even if it's opened at that time: .. attribute:: port Read or write port. When the port is already open, it will be closed and reopened with the new setting. .. attribute:: baudrate Read or write current baud rate setting. .. attribute:: bytesize Read or write current data byte size setting. .. attribute:: parity Read or write current parity setting. .. attribute:: stopbits Read or write current stop bit width setting. .. attribute:: timeout Read or write current read timeout setting. .. attribute:: writeTimeout Read or write current write timeout setting. .. attribute:: xonxoff Read or write current software flow control rate setting. .. attribute:: rtscts Read or write current hardware flow control setting. .. attribute:: dsrdtr Read or write current hardware flow control setting. .. attribute:: interCharTimeout Read or write current inter character timeout setting. The following constants are also provided: .. attribute:: 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). .. attribute:: BYTESIZES A list of valid byte sizes for the device (Read Only). .. attribute:: PARITIES A list of valid parities for the device (Read Only). .. attribute:: STOPBITS A list of valid stop bit widths for the device (Read Only). The following methods are for compatibility with the :mod:`io` library. .. method:: readable() :return: True .. versionadded:: 2.5 .. method:: writable() :return: True .. versionadded:: 2.5 .. method:: seekable() :return: False .. versionadded:: 2.5 .. method:: readinto(b) :param b: bytearray or array instance :return: Number of byte read Read up to len(b) bytes into :class:`bytearray` *b* and return the number of bytes read. .. versionadded:: 2.5 The port settings can be read and written as dictionary. .. method:: getSettingsDict() :return: 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 :meth:`applySettingsDict`. Note that control lines (RTS/DTR) are part of the settings. .. versionadded:: 2.5 .. method:: applySettingsDict(d) :param d: a dictionary with port settings. Applies a dictionary that was created by :meth:`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. .. versionadded:: 2.5 Platform specific methods. .. warning:: Programs using the following methods and attributes are not portable to other platforms! .. method:: outWaiting() :platform: Unix :platform: Windows Return the number of bytes in the output buffer. .. versionchanged:: 2.7 (Posix support added) .. method:: nonblocking() :platform: Unix Configure the device for nonblocking operation. This can be useful if the port is used with :mod:`select`. .. method:: fileno() :platform: Unix :return: File descriptor. Return file descriptor number for the port that is opened by this object. It is useful when serial ports are used with :mod:`select`. .. method:: setXON(level=True) :platform: Windows :platform: Posix :param level: 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. .. versionchanged:: 2.7 (renamed on Posix, function was called ``flowControl``) .. method:: flowControlOut(enable) :platform: Posix :param enable: 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``. .. versionadded:: 2.7 (Posix support added) .. attribute:: 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. .. versionadded:: 2.6 .. note:: For systems that provide the :py:mod:`io` library (Python 2.6 and newer), the class :class:`Serial` will derive from :py:class:`io.RawIOBase`. For all others from :class:`FileLike`. Implementation detail: some attributes and functions are provided by the class :class:`SerialBase` and some by the platform specific class and others by the base class mentioned above. .. class:: FileLike An abstract file like class. It is used as base class for :class:`Serial` when no :py:mod:`io` module is available. This class implements :meth:`readline` and :meth:`readlines` based on :meth:`read` and :meth:`writelines` based on :meth:`write`. Note that when the serial port was opened with no timeout, that :meth:`readline` blocks until it sees a newline (or the specified size is reached) and that :meth:`readlines` would never return and therefore refuses to work (it raises an exception in this case)! .. method:: writelines(sequence) Write a list of strings to the port. The following three methods are overridden in :class:`Serial`. .. method:: flush() Flush of file like objects. It's a no-op in this class, may be overridden. .. method:: read() Raises NotImplementedError, needs to be overridden by subclass. .. method:: 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. .. method:: seek(pos, whence=0) :exception IOError: always, as method is not supported on serial port .. versionadded:: 2.5 .. method:: tell() :exception IOError: always, as method is not supported on serial port .. versionadded:: 2.5 .. method:: truncate(self, n=None) :exception IOError: always, as method is not supported on serial port .. versionadded:: 2.5 .. method:: isatty() :exception IOError: always, as method is not supported on serial port .. versionadded:: 2.5 To be able to use the file like object as iterator for e.g. ``for line in Serial(0): ...`` usage: .. method:: next() Return the next line by calling :meth:`readline`. .. method:: __iter__() Returns self. Other high level access functions. .. method:: readline(size=None, eol='\\n') :param size: Max number of bytes to read, ``None`` -> no limit. :param eol: The end of line character. Read a line which is terminated with end-of-line (*eol*) character (``\n`` by default) or until timeout. .. method:: readlines(sizehint=None, eol='\\n') :param sizehint: Ignored parameter. :param 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. .. method:: 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:: 2.5 Use ``for line in Serial(...): ...`` instead. This method is not available in Python 2.6 and newer where the :mod:`io` library is available and pySerial bases on it. .. versionchanged:: 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://:[/