============== 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, write_timeout=None, dsrdtr=False, inter_byte_timeout=None) :param port: Device name or :const:`None`. :param int 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 float timeout: Set a read timeout value. :param bool xonxoff: Enable software flow control. :param bool rtscts: Enable hardware (RTS/CTS) flow control. :param bool dsrdtr: Enable hardware (DSR/DTR) flow control. :param float write_timeout: Set a write timeout value. :param float inter_byte_timeout: 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` 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 :meth:`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. :meth:`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 :func:`serial_for_url` instead of creating Serial instances directly. .. versionchanged:: 2.5 *dsrdtr* now defaults to ``False`` (instead of *None*) .. versionchanged:: 3.0 numbers as *port* argument are no longer supported .. 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:`SerialException` when applied to a closed port. .. method:: read(size=1) :param size: Number of bytes to read. :return: Bytes read from the port. :rtype: 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. .. 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. :rtype: int :exception 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'``). .. 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:: flush() Flush of file like objects. In this case, wait until all data is written. .. attribute:: in_waiting :getter: Get the number of bytes in the input buffer :type: int Return the number of bytes in the receive buffer. .. versionchanged:: 3.0 changed to property from ``inWaiting()`` .. attribute:: 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. .. versionchanged:: 2.7 (Posix support added) .. versionchanged:: 3.0 changed to property from ``outWaiting()`` .. method:: reset_input_buffer() Flush input buffer, discarding all it's contents. .. versionchanged:: 3.0 renamed from ``flushInput()`` .. method:: reset_output_buffer() Clear output buffer, aborting the current output and discarding all that is in the buffer. .. versionchanged:: 3.0 renamed from ``flushOutput()`` .. method:: send_break(duration=0.25) :param float duration: Time to activate the BREAK condition. Send break condition. Timed, returns to idle state after given duration. .. attribute:: 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. .. attribute:: 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 :meth:`open`. .. attribute:: 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 :meth:`open`. Read-only attributes: .. attribute:: name :getter: Device name. :type: str .. versionadded:: 2.5 .. attribute:: cts :getter: Get the state of the CTS line :type: bool Return the state of the CTS line. .. attribute:: dsr :getter: Get the state of the DSR line :type: bool Return the state of the DSR line. .. attribute:: ri :getter: Get the state of the RI line :type: bool Return the state of the RI line. .. attribute:: cd :getter: Get the state of the CD line :type: bool Return the state of the CD line 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 :type: str Read or write port. When the port is already open, it will be closed and reopened with the new setting. .. attribute:: baudrate :getter: Get current baud rate :setter: Set new baud rate :type: int Read or write current baud rate setting. .. attribute:: bytesize :getter: Get current byte size :setter: Set new byte size. Possible values: :const:`FIVEBITS`, :const:`SIXBITS`, :const:`SEVENBITS`, :const:`EIGHTBITS` :type: int Read or write current data byte size setting. .. attribute:: parity :getter: Get current parity setting :setter: Set new parity mode. Possible values: :const:`PARITY_NONE`, :const:`PARITY_EVEN`, :const:`PARITY_ODD` :const:`PARITY_MARK`, :const:`PARITY_SPACE` Read or write current parity setting. .. attribute:: stopbits :getter: Get current stop bit setting :setter: Set new stop bit setting. Possible values: :const:`STOPBITS_ONE`, :const:`STOPBITS_ONE_POINT_FIVE`, :const:`STOPBITS_TWO` Read or write current stop bit width setting. .. attribute:: timeout :getter: Get current read timeout setting :setter: Set read timeout :type: float (seconds) Read or write current read timeout setting. .. attribute:: write_timeout :getter: Get current write timeout setting :setter: Set write timeout :type: float (seconds) Read or write current write timeout setting. .. versionchanged:: 3.0 renamed from ``writeTimeout`` .. attribute:: 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. .. versionchanged:: 3.0 renamed from ``interCharTimeout`` .. attribute:: 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. .. attribute:: 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. .. attribute:: 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. .. attribute:: rs485_mode :getter: Get the current RS485 settings :setter: Disable (``None``) or enable the RS485 settings :type: :class:`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 :class:`rs485.RS485Settings` and supported by OS, RTS will be active when data is sent and inactive otherwise (for reception). The :class:`rs485.RS485Settings` class provides additional settings supported on some platforms. .. versionadded:: 3.0 The following constants are also provided: .. attribute:: 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). .. 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. The following keys are supported: ``write_timeout``, ``inter_byte_timeout``, ``dsrdtr``, ``baudrate``, ``timeout``, ``parity``, ``bytesize``, ``rtscts``, ``stopbits``, ``xonxoff`` .. method:: get_settings() :return: a dictionary with current port settings. :rtype: 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 :meth:`apply_settings`. Note that control lines (RTS/DTR) are part of the settings. .. versionadded:: 2.5 .. versionchanged:: 3.0 renamed from ``getSettingsDict`` .. method:: apply_settings(d) :param dict d: a dictionary with port settings. Applies a dictionary that was created by :meth:`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. .. versionadded:: 2.5 .. versionchanged:: 3.0 renamed from ``applySettingsDict`` Platform specific methods. .. warning:: Programs using the following methods and attributes are not portable to other platforms! .. method:: nonblocking() :platform: Posix Configure the device for nonblocking operation. This can be useful if the port is used with :mod:`select`. Note that :attr:`timeout` must also be set to ``0`` .. method:: fileno() :platform: Posix :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:: set_input_flow_control(enable) :platform: Posix :param bool enable: 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. .. versionadded:: 2.7 (Posix support added) .. versionchanged:: 3.0 renamed from ``flowControlOut`` .. method:: set_output_flow_control(enable) :platform: Posix (HW and SW flow control) :platform: Windows (SW flow control only) :param bool 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``. .. versionchanged:: 2.7 (renamed on Posix, function was called ``flowControl``) .. versionchanged:: 3.0 renamed from ``setXON`` .. note:: The following members are deprecated and will be removed in a future release. .. attribute:: portstr .. deprecated:: 2.5 use :attr:`name` instead .. method:: inWaiting() .. deprecated:: 3.0 see :attr:`in_waiting` .. attribute:: writeTimeout .. deprecated:: 3.0 see :attr:`write_timeout` .. attribute:: interCharTimeout .. deprecated:: 3.0 see :attr:`inter_byte_timeout` .. method:: sendBreak(duration=0.25) .. deprecated:: 3.0 see :meth:`send_break` .. method:: flushInput() .. deprecated:: 3.0 see :meth:`reset_input_buffer` .. method:: flushOutput() .. deprecated:: 3.0 see :meth:`reset_output_buffer` .. method:: setBreak(level=True) .. deprecated:: 3.0 see :attr:`break_condition` .. method:: setRTS(level=True) .. deprecated:: 3.0 see :attr:`rts` .. method:: setDTR(level=True) .. deprecated:: 3.0 see :attr:`dtr` .. method:: getCTS() .. deprecated:: 3.0 see :attr:`cts` .. method:: getDSR() .. deprecated:: 3.0 see :attr:`dsr` .. method:: getRI() .. deprecated:: 3.0 see :attr:`ri` .. method:: getCD() .. deprecated:: 3.0 see :attr:`cd` .. method:: getSettingsDict() .. deprecated:: 3.0 see :meth:`get_settings` .. method:: applySettingsDict(d) .. deprecated:: 3.0 see :meth:`apply_settings` .. method:: outWaiting() .. deprecated:: 3.0 see :attr:`out_waiting` .. method:: setXON(level=True) .. deprecated:: 3.0 see :meth:`set_output_flow_control` .. method:: flowControlOut(enable) .. deprecated:: 3.0 see :meth:`set_input_flow_control` .. 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 .. versionchanged:: 3.0 (removed, see :attr:`rs485_mode` instead) 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. RS485 support ------------- The :class:`Serial` class has a :attr:`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. :attr:`Serial.rs485_mode` needs to be set to an instance of :class:`rs485.RS485Settings` to enable or to ``None`` to disable this feature. Usage:: ser = serial.Serial(...) ser.rs485_mode = serial.rs485.RS485Settings(...) ser.write(b'hello') There is a subclass :class:`rs485.RS485` available to emulate the RS485 support on regular serial ports. .. class:: rs485.RS485Settings A class that holds RS485 specific settings which are supported on some platforms. .. versionadded:: 3.0 .. method:: __init__(rts_level_for_tx=True, rts_level_for_rx=False, loopback=False, delay_before_tx=None, delay_before_rx=None): :param bool rts_level_for_tx: RTS level for transmission :param bool rts_level_for_rx: RTS level for reception :param bool loopback: When set to ``True`` transmitted data is also received. :param float delay_before_tx: Delay after setting RTS but before transmission starts :param float delay_before_rx: Delay after transmission ends and resetting RTS .. attribute:: rts_level_for_tx RTS level for transmission. .. attribute:: rts_level_for_rx RTS level for reception. .. attribute:: loopback When set to ``True`` transmitted data is also received. .. attribute:: delay_before_tx Delay after setting RTS but before transmission starts (seconds as float). .. attribute:: delay_before_rx Delay after transmission ends and resetting RTS (seconds as float). .. class:: rs485.RS485 A subclass that replaces the :meth:`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 :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 :ref:`URL ` in the form: ``rfc2217://:[?