pylibftdi Package

pylibftdi Package

pylibftdi - python wrapper for libftdi

Copyright (c) 2010-2020 Ben Bass <benbass@codedstructure.net> See LICENSE file for details and (absence of) warranty

pylibftdi: https://github.com/codedstructure/pylibftdi

libftdi can be found at: http://www.intra2net.com/en/developer/libftdi/

Neither libftdi nor Intra2net are associated with this project; if something goes wrong here, it’s almost definitely my fault rather than a problem with the libftdi library.

exception pylibftdi.__init__.FtdiError[source]

Bases: Exception

class pylibftdi.__init__.Driver(libftdi_search: str | list[str] | None[str, list, None] = None, **kwargs)[source]

Bases: object

This is where it all happens… We load the libftdi library, and use it.

__init__(libftdi_search: str | list[str] | None[str, list, None] = None, **kwargs) → None[source]
Parameters:libftdi_search (string or a list of strings) – force a particular version of libftdi to be used can specify either library name(s) or path(s)
libftdi_version() → pylibftdi.driver.libftdi_version[source]
Returns:the version of the underlying library being used
Return type:tuple (major, minor, micro, version_string, snapshot_string)
libusb_version() → pylibftdi.driver.libusb_version[source]
Returns:namedtuple containing version info on libusb
list_devices() → list[source]
Returns:(manufacturer, description, serial#) for each attached device, e.g.:

[(‘FTDI’, ‘UM232R USB <-> Serial’, ‘FTE4FFVQ’), (‘FTDI’, ‘UM245R’, ‘FTE00P4L’)]

Return type:a list of string triples

the serial number can be used to open specific devices

fdll

ctypes DLL referencing the libftdi library

This is the main interface to FTDI functionality.

class pylibftdi.__init__.Device(device_id: str | None[str, None] = None, mode: str = 'b', encoding: str = 'latin1', interface_select: int | None[int, None] = None, device_index: int = 0, **kwargs)[source]

Bases: object

Represents a connection to a single FTDI device

__init__(device_id: str | None[str, None] = None, mode: str = 'b', encoding: str = 'latin1', interface_select: int | None[int, None] = None, device_index: int = 0, **kwargs) → None[source]

Device([device_id[, mode, [OPTIONS …]]) -> Device instance

represents a single FTDI device accessible via the libftdi driver. Supports a basic file-like interface (open/close/read/write, context manager support).

Parameters:
  • device_id – an optional serial number of the device to open. if omitted, this refers to the first device found, which is convenient if only one device is attached, but otherwise fairly useless.
  • mode – either ‘b’ (binary) or ‘t’ (text). This primarily affects Python 3 calls to read() and write(), which will accept/return unicode strings which will be encoded/decoded according to the given…
  • encoding – the codec name to be used for text operations.
  • interface_select – select interface to use on multi-interface devices
  • device_index – optional index of the device to open, in the event of multiple matches for other parameters (PID, VID, device_id). Defaults to zero (the first device found).

The following parameters are only available as keyword parameters and override class attributes, so may be specified in subclasses.

Parameters:
  • lazy_open – if True, then the device will not be opened immediately - the user must perform an explicit open() call prior to other operations.
  • chunk_size – if non-zero, split read and write operations into chunks of this size. With large or slow accesses, interruptions (i.e. KeyboardInterrupt) may not happen in a timely fashion.
  • auto_detach – default True, whether to automatically re-attach the kernel driver on device close.
  • index – optional index into list_devices() to open. Useful in the event that multiple devices of differing VID/PID are attached, where device_index is insufficient to select as device indexing restarts at 0 for each VID/PID combination.
close() → None[source]

close our connection, free resources

flush(flush_what: int = 1) → None[source]

Instruct the FTDI device to flush its FIFO buffers

By default both the input and output buffers will be flushed, but the caller can selectively chose to only flush the input or output buffers using flush_what:

Parameters:flush_what – select what to flush: FLUSH_BOTH (default); FLUSH_INPUT (just the rx buffer); FLUSH_OUTPUT (just the tx buffer)
flush_input() → None[source]

flush the device input buffer

flush_output() → None[source]

flush the device output buffer

get_error_string() → str[source]
Returns:error string from libftdi driver
handle_open_error(errcode: int) → str[source]

return a (hopefully helpful) error message on a failed open()

next() → str
open() → None[source]

open connection to a FTDI device

read(length) → bytes/string of up to `length` bytes.[source]

read upto length bytes from the FTDI device :param length: maximum number of bytes to read :return: value read from device :rtype: bytes if self.mode is ‘b’, else decode with self.encoding

readline(size: int = 0) → str[source]

readline() for file-like compatibility.

Parameters:size – maximum amount of data to read looking for a line
Returns:a line of text, or size bytes if no line-ending found

This only works for mode=’t’ on Python3

readlines(sizehint: int | None[int, None] = None) → list[source]

readlines() for file-like compatibility.

write(data) → count of bytes actually written[source]

write given data string to the FTDI device

Parameters:data (string or bytes) – string to be written
Returns:count of bytes written, which may be less than len(data)
writelines(lines: list) → None[source]

writelines for file-like compatibility.

Parameters:lines – sequence of lines to write
auto_detach = True
baudrate

get or set the baudrate of the FTDI device. Re-read after setting to ensure baudrate was accepted by the driver.

chunk_size = 0
closed

The Python file API defines a read-only ‘closed’ attribute

ftdi_fn

this allows the vast majority of libftdi functions which are called with a pointer to a ftdi_context struct as the first parameter to be called here preventing the need to leak self.ctx into the user code (and import byref from ctypes):

>>> with Device() as dev:
...     # set 8 bit data, 2 stop bits, no parity
...     dev.ftdi_fn.ftdi_set_line_property(8, 2, 0)
...
lazy_open = False
softspace = 0
class pylibftdi.__init__.BitBangDevice(device_id=None, direction=255, lazy_open=False, sync=True, bitbang_mode=1, interface_select=None, **kwargs)[source]

Bases: pylibftdi.device.Device

simple subclass to support bit-bang mode

Internally uses async mode at the moment, but provides a ‘sync’ flag (defaulting to True) which controls the behaviour of port reading and writing - if set, the FIFOs are ignored (read) or cleared (write) so operations will appear synchronous

Adds three read/write properties to the base class:

direction: 8 bit input(0)/output(1) direction control. port: 8 bit IO port, as defined by direction. latch: 8 bit output value, allowing e.g. bb.latch += 1 to make sense

when there is a mix of input and output lines
__init__(device_id=None, direction=255, lazy_open=False, sync=True, bitbang_mode=1, interface_select=None, **kwargs)[source]

Device([device_id[, mode, [OPTIONS …]]) -> Device instance

represents a single FTDI device accessible via the libftdi driver. Supports a basic file-like interface (open/close/read/write, context manager support).

Parameters:
  • device_id – an optional serial number of the device to open. if omitted, this refers to the first device found, which is convenient if only one device is attached, but otherwise fairly useless.
  • mode – either ‘b’ (binary) or ‘t’ (text). This primarily affects Python 3 calls to read() and write(), which will accept/return unicode strings which will be encoded/decoded according to the given…
  • encoding – the codec name to be used for text operations.
  • interface_select – select interface to use on multi-interface devices
  • device_index – optional index of the device to open, in the event of multiple matches for other parameters (PID, VID, device_id). Defaults to zero (the first device found).

The following parameters are only available as keyword parameters and override class attributes, so may be specified in subclasses.

Parameters:
  • lazy_open – if True, then the device will not be opened immediately - the user must perform an explicit open() call prior to other operations.
  • chunk_size – if non-zero, split read and write operations into chunks of this size. With large or slow accesses, interruptions (i.e. KeyboardInterrupt) may not happen in a timely fashion.
  • auto_detach – default True, whether to automatically re-attach the kernel driver on device close.
  • index – optional index into list_devices() to open. Useful in the event that multiple devices of differing VID/PID are attached, where device_index is insufficient to select as device indexing restarts at 0 for each VID/PID combination.
open()[source]

open connection to a FTDI device

read_pins()[source]

read the current ‘actual’ state of the pins

Returns:8-bit binary representation of pin state
Return type:int
direction

get or set the direction of each of the IO lines. LSB=D0, MSB=D7 1 for output, 0 for input

latch

latch property - the output latch (in-memory representation of output pin state)

Note _latch is not masked by direction (except on initialisation), as otherwise a loop incrementing a mixed input/output port would not work, as it would ‘stop’ on input pins. This is the primary use case for ‘latch’. It’s basically a port which ignores input.

Returns:the state of the output latch
port

get or set the state of the IO lines. The value of output lines is persisted in this object for the purposes of reading, so read-modify-write operations (e.g. drv.port+=1) are valid.

class pylibftdi.__init__.Bus(offset, width=1)[source]

Bases: object

This class is a descriptor for a bus of a given width starting at a given offset (0 = LSB). The device which does the actual reading and writing is assumed to be a BitBangDevice instance in the ‘device’ attribute of the object to which this is attached.

__init__(offset, width=1)[source]

Initialize self. See help(type(self)) for accurate signature.

_base Module

pylibftdi - python wrapper for libftdi

Copyright (c) 2010-2020 Ben Bass <benbass@codedstructure.net> See LICENSE file for details and (absence of) warranty

pylibftdi: https://github.com/codedstructure/pylibftdi

exception pylibftdi._base.FtdiError[source]

Bases: Exception

exception pylibftdi._base.LibraryMissingError[source]

Bases: pylibftdi._base.FtdiError

device Module

pylibftdi.device - access to individual FTDI devices

Copyright (c) 2010-2020 Ben Bass <benbass@codedstructure.net> See LICENSE file for details and (absence of) warranty

pylibftdi: https://github.com/codedstructure/pylibftdi

class pylibftdi.device.Device(device_id: str | None[str, None] = None, mode: str = 'b', encoding: str = 'latin1', interface_select: int | None[int, None] = None, device_index: int = 0, **kwargs)[source]

Bases: object

Represents a connection to a single FTDI device

__init__(device_id: str | None[str, None] = None, mode: str = 'b', encoding: str = 'latin1', interface_select: int | None[int, None] = None, device_index: int = 0, **kwargs) → None[source]

Device([device_id[, mode, [OPTIONS …]]) -> Device instance

represents a single FTDI device accessible via the libftdi driver. Supports a basic file-like interface (open/close/read/write, context manager support).

Parameters:
  • device_id – an optional serial number of the device to open. if omitted, this refers to the first device found, which is convenient if only one device is attached, but otherwise fairly useless.
  • mode – either ‘b’ (binary) or ‘t’ (text). This primarily affects Python 3 calls to read() and write(), which will accept/return unicode strings which will be encoded/decoded according to the given…
  • encoding – the codec name to be used for text operations.
  • interface_select – select interface to use on multi-interface devices
  • device_index – optional index of the device to open, in the event of multiple matches for other parameters (PID, VID, device_id). Defaults to zero (the first device found).

The following parameters are only available as keyword parameters and override class attributes, so may be specified in subclasses.

Parameters:
  • lazy_open – if True, then the device will not be opened immediately - the user must perform an explicit open() call prior to other operations.
  • chunk_size – if non-zero, split read and write operations into chunks of this size. With large or slow accesses, interruptions (i.e. KeyboardInterrupt) may not happen in a timely fashion.
  • auto_detach – default True, whether to automatically re-attach the kernel driver on device close.
  • index – optional index into list_devices() to open. Useful in the event that multiple devices of differing VID/PID are attached, where device_index is insufficient to select as device indexing restarts at 0 for each VID/PID combination.
close() → None[source]

close our connection, free resources

flush(flush_what: int = 1) → None[source]

Instruct the FTDI device to flush its FIFO buffers

By default both the input and output buffers will be flushed, but the caller can selectively chose to only flush the input or output buffers using flush_what:

Parameters:flush_what – select what to flush: FLUSH_BOTH (default); FLUSH_INPUT (just the rx buffer); FLUSH_OUTPUT (just the tx buffer)
flush_input() → None[source]

flush the device input buffer

flush_output() → None[source]

flush the device output buffer

get_error_string() → str[source]
Returns:error string from libftdi driver
handle_open_error(errcode: int) → str[source]

return a (hopefully helpful) error message on a failed open()

next() → str
open() → None[source]

open connection to a FTDI device

read(length) → bytes/string of up to `length` bytes.[source]

read upto length bytes from the FTDI device :param length: maximum number of bytes to read :return: value read from device :rtype: bytes if self.mode is ‘b’, else decode with self.encoding

readline(size: int = 0) → str[source]

readline() for file-like compatibility.

Parameters:size – maximum amount of data to read looking for a line
Returns:a line of text, or size bytes if no line-ending found

This only works for mode=’t’ on Python3

readlines(sizehint: int | None[int, None] = None) → list[source]

readlines() for file-like compatibility.

write(data) → count of bytes actually written[source]

write given data string to the FTDI device

Parameters:data (string or bytes) – string to be written
Returns:count of bytes written, which may be less than len(data)
writelines(lines: list) → None[source]

writelines for file-like compatibility.

Parameters:lines – sequence of lines to write
auto_detach = True
baudrate

get or set the baudrate of the FTDI device. Re-read after setting to ensure baudrate was accepted by the driver.

chunk_size = 0
closed

The Python file API defines a read-only ‘closed’ attribute

ftdi_fn

this allows the vast majority of libftdi functions which are called with a pointer to a ftdi_context struct as the first parameter to be called here preventing the need to leak self.ctx into the user code (and import byref from ctypes):

>>> with Device() as dev:
...     # set 8 bit data, 2 stop bits, no parity
...     dev.ftdi_fn.ftdi_set_line_property(8, 2, 0)
...
lazy_open = False
softspace = 0
class pylibftdi.device.ftdi_context_partial[source]

Bases: _ctypes.Structure

libusb_context

Structure/Union member

libusb_device_handle

Structure/Union member

driver Module

pylibftdi.driver - interface to the libftdi library

Copyright (c) 2010-2014 Ben Bass <benbass@codedstructure.net> See LICENSE file for details and (absence of) warranty

pylibftdi: https://github.com/codedstructure/pylibftdi

class pylibftdi.driver.Driver(libftdi_search: str | list[str] | None[str, list, None] = None, **kwargs)[source]

Bases: object

This is where it all happens… We load the libftdi library, and use it.

__init__(libftdi_search: str | list[str] | None[str, list, None] = None, **kwargs) → None[source]
Parameters:libftdi_search (string or a list of strings) – force a particular version of libftdi to be used can specify either library name(s) or path(s)
libftdi_version() → pylibftdi.driver.libftdi_version[source]
Returns:the version of the underlying library being used
Return type:tuple (major, minor, micro, version_string, snapshot_string)
libusb_version() → pylibftdi.driver.libusb_version[source]
Returns:namedtuple containing version info on libusb
list_devices() → list[source]
Returns:(manufacturer, description, serial#) for each attached device, e.g.:

[(‘FTDI’, ‘UM232R USB <-> Serial’, ‘FTE4FFVQ’), (‘FTDI’, ‘UM245R’, ‘FTE00P4L’)]

Return type:a list of string triples

the serial number can be used to open specific devices

fdll

ctypes DLL referencing the libftdi library

This is the main interface to FTDI functionality.

class pylibftdi.driver.ftdi_device_list[source]

Bases: _ctypes.Structure

dev

Structure/Union member

next

Structure/Union member

class pylibftdi.driver.ftdi_version_info[source]

Bases: _ctypes.Structure

major

Structure/Union member

micro

Structure/Union member

minor

Structure/Union member

snapshot_str

Structure/Union member

version_str

Structure/Union member

class pylibftdi.driver.libftdi_version(major, minor, micro, version_str, snapshot_str)

Bases: tuple

major

Alias for field number 0

micro

Alias for field number 2

minor

Alias for field number 1

snapshot_str

Alias for field number 4

version_str

Alias for field number 3

class pylibftdi.driver.libusb_version(major, minor, micro, nano, rc, describe)

Bases: tuple

describe

Alias for field number 5

major

Alias for field number 0

micro

Alias for field number 2

minor

Alias for field number 1

nano

Alias for field number 3

rc

Alias for field number 4

class pylibftdi.driver.libusb_version_struct[source]

Bases: _ctypes.Structure

describe

Structure/Union member

major

Structure/Union member

micro

Structure/Union member

minor

Structure/Union member

nano

Structure/Union member

rc

Structure/Union member

bitbang Module

pylibftdi - python wrapper for libftdi

Copyright (c) 2010-2014 Ben Bass <benbass@codedstructure.net> See LICENSE file for details and (absence of) warranty

pylibftdi: https://github.com/codedstructure/pylibftdi

class pylibftdi.bitbang.BitBangDevice(device_id=None, direction=255, lazy_open=False, sync=True, bitbang_mode=1, interface_select=None, **kwargs)[source]

Bases: pylibftdi.device.Device

simple subclass to support bit-bang mode

Internally uses async mode at the moment, but provides a ‘sync’ flag (defaulting to True) which controls the behaviour of port reading and writing - if set, the FIFOs are ignored (read) or cleared (write) so operations will appear synchronous

Adds three read/write properties to the base class:

direction: 8 bit input(0)/output(1) direction control. port: 8 bit IO port, as defined by direction. latch: 8 bit output value, allowing e.g. bb.latch += 1 to make sense

when there is a mix of input and output lines
__init__(device_id=None, direction=255, lazy_open=False, sync=True, bitbang_mode=1, interface_select=None, **kwargs)[source]

Device([device_id[, mode, [OPTIONS …]]) -> Device instance

represents a single FTDI device accessible via the libftdi driver. Supports a basic file-like interface (open/close/read/write, context manager support).

Parameters:
  • device_id – an optional serial number of the device to open. if omitted, this refers to the first device found, which is convenient if only one device is attached, but otherwise fairly useless.
  • mode – either ‘b’ (binary) or ‘t’ (text). This primarily affects Python 3 calls to read() and write(), which will accept/return unicode strings which will be encoded/decoded according to the given…
  • encoding – the codec name to be used for text operations.
  • interface_select – select interface to use on multi-interface devices
  • device_index – optional index of the device to open, in the event of multiple matches for other parameters (PID, VID, device_id). Defaults to zero (the first device found).

The following parameters are only available as keyword parameters and override class attributes, so may be specified in subclasses.

Parameters:
  • lazy_open – if True, then the device will not be opened immediately - the user must perform an explicit open() call prior to other operations.
  • chunk_size – if non-zero, split read and write operations into chunks of this size. With large or slow accesses, interruptions (i.e. KeyboardInterrupt) may not happen in a timely fashion.
  • auto_detach – default True, whether to automatically re-attach the kernel driver on device close.
  • index – optional index into list_devices() to open. Useful in the event that multiple devices of differing VID/PID are attached, where device_index is insufficient to select as device indexing restarts at 0 for each VID/PID combination.
open()[source]

open connection to a FTDI device

read_pins()[source]

read the current ‘actual’ state of the pins

Returns:8-bit binary representation of pin state
Return type:int
direction

get or set the direction of each of the IO lines. LSB=D0, MSB=D7 1 for output, 0 for input

latch

latch property - the output latch (in-memory representation of output pin state)

Note _latch is not masked by direction (except on initialisation), as otherwise a loop incrementing a mixed input/output port would not work, as it would ‘stop’ on input pins. This is the primary use case for ‘latch’. It’s basically a port which ignores input.

Returns:the state of the output latch
port

get or set the state of the IO lines. The value of output lines is persisted in this object for the purposes of reading, so read-modify-write operations (e.g. drv.port+=1) are valid.

serial_device Module

pylibftdi - python wrapper for libftdi

Copyright (c) 2010-2014 Ben Bass <benbass@codedstructure.net> See LICENSE file for details and (absence of) warranty

pylibftdi: https://github.com/codedstructure/pylibftdi

class pylibftdi.serial_device.SerialDevice(device_id: str | None[str, None] = None, mode: str = 'b', encoding: str = 'latin1', interface_select: int | None[int, None] = None, device_index: int = 0, **kwargs)[source]

Bases: pylibftdi.device.Device

simple subclass to support serial(rs232) lines

cts, dsr, ri - input dtr, rts - output modem_status - return a two byte bitfield of various values

Note: These lines are all active-low by default, though this can be changed in the EEPROM settings. pylibftdi does not attempt to hide these settings, and simply writes out the given values (i.e. ‘1’ will typically make an output line ‘active’ - and therefore low)

cts

get the state of CTS (1 = ‘active’)

dsr

get the state of DSR (1 = ‘active’)

dtr

set (or get the previous set) state of the DTR line

Returns:the state of the DTR line; None if not previously set
modem_status

Layout of the first byte: B0..B3 - must be 0 B4 Clear to send (CTS) 0 = inactive 1 = active B5 Data set ready (DTS) 0 = inactive 1 = active B6 Ring indicator (RI) 0 = inactive 1 = active B7 Receive line signal detect (RLSD) 0 = inactive 1 = active

Layout of the second byte: B0 Data ready (DR) B1 Overrun error (OE) B2 Parity error (PE) B3 Framing error (FE) B4 Break interrupt (BI) B5 Transmitter holding register (THRE) B6 Transmitter empty (TEMT) B7 Error in RCVR FIFO

‘{:016b}’.format(d.modem_status) ‘0110000000000001’ - b5,b6 set in MSB (‘2nd byte’), b0 set in first byte (despite the libftdi docs saying this shouldn’t be set)

ri

get the state of RI (1 = ‘active’)

rts

set (or get the previous set) state of the RTS line

Returns:the state of the RTS line; None if not previously set

util Module

pylibftdi - python wrapper for libftdi

Copyright (c) 2010-2014 Ben Bass <benbass@codedstructure.net> See LICENSE file for details and (absence of) warranty

pylibftdi: https://github.com/codedstructure/pylibftdi

class pylibftdi.util.Bus(offset, width=1)[source]

Bases: object

This class is a descriptor for a bus of a given width starting at a given offset (0 = LSB). The device which does the actual reading and writing is assumed to be a BitBangDevice instance in the ‘device’ attribute of the object to which this is attached.

__init__(offset, width=1)[source]

Initialize self. See help(type(self)) for accurate signature.