pylablib.core.devio package

Submodules

pylablib.core.devio.SCPI module

class pylablib.core.devio.SCPI.SCPIDevice(conn, term_write=None, term_read=None, wait_callback=None, backend='visa', failsafe=None, timeout=None, backend_params=None)[source]

Bases: pylablib.core.devio.backend.IBackendWrapper

A base class for a device controlled with the usual SCPI syntax.

Implements two functions:
  • deals with composing and parsing of standard SCPI commands.
  • implements automatic re-sending and reconnecting on communication failures (fail-safe mode)
Parameters:
  • conn – Connection parameters (depend on the backend). Can also be an opened backend.IDeviceBackend class for a custom backend.
  • term_write (str) – Line terminator for writing operations.
  • wait_callback (callable) – A function to be called periodically (every 300ms by default) while waiting for operations to complete.
  • backend (str) – Connection backend ('serial' or 'visa').
  • failsafe (bool) – If True, the device is working in a fail-safe mode: if an operation times out, attempt to repeat it several times before raising error. If None, use the class value _default_failsafe (False by default).
  • timeout (float) – Default timeout (in seconds).
reconnect(new_instrument=True)[source]

Remake the connection.

If new_instrument==True, create a new backend instance.

sleep(delay)[source]

Wait for delay seconds.

using_write_buffer()[source]

Context manager for using a write buffer.

While it’s active, all the consecutive write() operations are bundled together with ; delimiter. The actual write is performed at the read()/ask() operation or at the end of the block.

get_id(timeout=None)[source]

Get the device IDN. (query SCPI '*IDN?' command).

reset()[source]

Reset the device (by default, "*RST" command)

get_esr(timeout=None)[source]

Get the device status register (by default, "*ESR?" command)

wait_sync(timeout=None, wait_callback=None)[source]

Pause execution of the script until device overlapped commands (e.g., taking sweeps) are complete.

timeout and wait_callback override default constructor parameters.

wait_dev()[source]

Pause execution of the device commands until device overlapped commands (e.g., taking sweeps) are complete.

wait(wait_type='sync', timeout=None, wait_callback=None)[source]

Pause execution until device overlapped commands are complete.

wait_type is either 'sync' (perform wait_sync()), 'dev' (perform wait_dev()) or 'none' (do nothing).

static get_arg_type(arg)[source]
write(msg, arg=None, arg_type=None, unit=None, fmt=None, bool_selector=('OFF', 'ON'), read_echo=False, read_echo_delay=0.0)[source]

Send a command.

Parameters:
  • msg (str) – Text message.
  • arg – Optional argument to append in the end.
  • arg_type (str) – Argument type. Can be 'raw' (in which case data is sent raw), 'string', 'int', 'float', 'bool' or 'value'.
  • unit (str) – If arg_type=='value', use it as a unit to append after the value.
  • fmt (str) – If not None, is a str.format() string to convert arg.
  • bool_selector (tuple) – A tuple (false_value, true_value) of two strings to represent bool argument.
  • read_echo (bool) – If True, read a single line after write.
  • read_echo_delay (float) – The delay between write and read if read_echo==True.
read(data_type='string', timeout=None)[source]

Read data from the device.

data_type determines the type of the data. Can be 'raw' (just raw data), 'string' (with trailing and leading spaces stripped), 'int', 'float', 'bool' (interprets 0 or 'off' as False, anything else as True), or 'value' (returns tuple (value, unit), where value is float). timeout overrides the default value.

ask(msg, data_type='string', delay=0.0, timeout=None, read_echo=False)[source]

Write a message and read a reply.

msg is the query message, delay is the delay between write and read. Other parameters are the same as in read(). If read_echo==True, assume that the device first echoes the input and skip it.

flush(one_line=False)[source]

Flush the read buffer (read all the available data and return the number of bytes read).

If one_line==True, read only a single line.

static parse_trace_data(data, fmt)[source]

Parse the data returned by the device. fmt is DataFormat description.

The data is assumed to be in a (somewhat) standard SCPI format: b'#', then a single digit s denoting length of the size block, then s digits denoting length of the data (in bytes) followed by the actual data.

apply_settings(settings)[source]

Apply the settings.

settings is a dict {name: value} of the available device settings. Non-applicable settings are ignored.

pylablib.core.devio.backend module

Routines for defining a unified interface across multiple backends.

class pylablib.core.devio.backend.IDeviceBackend(conn, timeout=None, term_write=None, term_read=None, datatype='auto')[source]

Bases: object

An abstract class for a device communication backend.

Connection is automatically opened on creation.

Parameters:
  • conn – Connection parameters (depend on the backend).
  • timeout (float) – Default timeout (in seconds).
  • term_write (str) – Line terminator for writing operations.
  • term_read (str) – Line terminator for reading operations.
  • datatype (str) – Type of the returned data; can be "bytes" (return bytes object), "str" (return str object), or "auto" (default Python result: str in Python 2 and bytes in Python 3)
Error

alias of builtins.RuntimeError

classmethod combine_conn(conn1, conn2)[source]
open()[source]

Open the connection.

close()[source]

Close the connection.

is_opened()[source]

Check if the device is connected

lock(timeout=None)[source]

Lock the access to the device from other threads/processes (isn’t necessarily implemented).

unlock()[source]

Unlock the access to the device from other threads/processes (isn’t necessarily implemented).

locking(timeout=None)[source]

Context manager for lock & unlock.

cooldown()[source]

Cooldown between the operations (usually, some short time delay).

set_timeout(timeout)[source]

Set operations timeout (in seconds).

get_timeout()[source]

Get operations timeout (in seconds).

using_timeout(timeout=None)[source]

Context manager for usage of a different timeout inside a block.

readline(remove_term=True, timeout=None, skip_empty=True)[source]

Read a single line from the device.

Parameters:
  • remove_term (bool) – If True, remove terminal characters from the result.
  • timeout – Operation timeout. If None, use the default device timeout.
  • skip_empty (bool) – If True, ignore empty lines (works only for remove_term==True).
readlines(lines_num, remove_term=True, timeout=None, skip_empty=True)[source]

Read multiple lines from the device.

Parameters are the same as in readline().

read(size=None)[source]

Read data from the device.

If size is not None, read size bytes (the standard timeout applies); otherwise, read all available data (return immediately).

flush_read()[source]

Flush the device output (read all the available data; return the number of bytes read).

write(data, flush=True, read_echo=False, read_echo_delay=0, read_echo_lines=1)[source]

Write data to the device.

If flush==True, flush the write buffer. If read_echo==True, wait for read_echo_delay seconds and then perform readline() (read_echo_lines times).

ask(query, delay=0.0, read_all=False)[source]

Perform a write followed by a read, with delay in between.

If read_all==True, read all the available data; otherwise, read a single line.

static list_resources(desc=False)[source]

List all availabe resources for this backend.

If desc==False, return list of connections (usually strings), which can be used to connect to the device. Otherwise, return a list of descriptions, which have more info, but can be backend-dependent.

Might not be implemented (depending on the backend), in which case returns None.

pylablib.core.devio.backend.remove_longest_term(msg, terms)[source]

Remove the longest terminator among terms from the end of the message.

exception pylablib.core.devio.backend.IBackendOpenError[source]

Bases: OSError

exception pylablib.core.devio.backend.VisaBackendOpenError(e)[source]

Bases: pylablib.core.devio.backend.IBackendOpenError, object

Visa backend opening error

class pylablib.core.devio.backend.VisaDeviceBackend(conn, timeout=10.0, term_write=None, term_read=None, do_lock=None, datatype='auto')[source]

Bases: pylablib.core.devio.backend.IDeviceBackend

NIVisa backend (via pyVISA).

Connection is automatically opened on creation.

Parameters:
  • conn (str) – Connection string.
  • timeout (float) – Default timeout (in seconds).
  • term_write (str) – Line terminator for writing operations; appended to the data
  • term_read (str) – Line terminator for reading operations (specifies when readline() stops).
  • do_lock (bool) – If True, employ locking operations; otherwise, locking function does nothing.
  • datatype (str) – Type of the returned data; can be "bytes" (return bytes object), "str" (return str object), or "auto" (default Python result: str in Python 2 and bytes in Python 3)
Error

alias of builtins.object

BackendOpenError

alias of VisaBackendOpenError

static list_resources(desc=False)[source]

List all availabe resources for this backend.

If desc==False, return list of connections (usually strings), which can be used to connect to the device. Otherwise, return a list of descriptions, which have more info, but can be backend-dependent.

Might not be implemented (depending on the backend), in which case returns None.

open()[source]

Open the connection.

close()[source]

Close the connection.

is_opened()[source]

Check if the device is connected

lock(timeout=None)[source]

Lock the access to the device from other threads/processes.

unlock()[source]

Unlock the access to the device from other threads/processes.

locking(timeout=None)[source]

Context manager for lock & unlock.

cooldown()[source]

Cooldown between the operations.

Sleeping for a short time defined by _operation_cooldown attribute (30 ms by default). Also can be defined class-wide by _default_operation_cooldown class attribute.

set_timeout(timeout)[source]

Set operations timeout (in seconds).

get_timeout()[source]

Get operations timeout (in seconds).

readline(remove_term=True, timeout=None, skip_empty=True)[source]

Read a single line from the device.

Parameters:
  • remove_term (bool) – If True, remove terminal characters from the result.
  • timeout – Operation timeout. If None, use the default device timeout.
  • skip_empty (bool) – If True, ignore empty lines (works only for remove_term==True).
read(size=None)[source]

Read data from the device.

If size is not None, read size bytes (the standard timeout applies); otherwise, read all available data (return immediately).

write(data, flush=True, read_echo=False, read_echo_delay=0, read_echo_lines=1)[source]

Write data to the device.

If flush==True, flush the write buffer. If read_echo==True, wait for read_echo_delay seconds and then perform readline() (read_echo_lines times).

exception pylablib.core.devio.backend.SerialBackendOpenError(e)[source]

Bases: pylablib.core.devio.backend.IBackendOpenError, object

Serial backend opening error

class pylablib.core.devio.backend.SerialDeviceBackend(conn, timeout=10.0, term_write=None, term_read=None, connect_on_operation=False, open_retry_times=3, no_dtr=False, datatype='auto')[source]

Bases: pylablib.core.devio.backend.IDeviceBackend

Serial backend (via pySerial).

Connection is automatically opened on creation.

Parameters:
  • conn – Connection parameters. Can be either a string (for a port), or a list/tuple (port, baudrate, bytesize, parity, stopbits, xonxoff, rtscts, dsrdtr) supplied to the serial connection (default is ('COM1',19200,8,'N',1,0,0,0)), or a dict with the same parameters.
  • timeout (float) – Default timeout (in seconds).
  • term_write (str) – Line terminator for writing operations; appended to the data
  • term_read (str) – List of possible single-char terminator for reading operations (specifies when readline() stops).
  • connect_on_operation (bool) – If True, the connection is normally closed, and is opened only on the operations (normally two processes can’t be simultaneously connected to the same device).
  • open_retry_times (int) – Number of times the connection is attempted before giving up.
  • no_dtr (bool) – If True, turn off DTR status line before opening (e.g., turns off reset-on-connection for Arduino controllers).
  • datatype (str) – Type of the returned data; can be "bytes" (return bytes object), "str" (return str object), or "auto" (default Python result: str in Python 2 and bytes in Python 3)
Error

alias of builtins.object

BackendOpenError

alias of SerialBackendOpenError

open()[source]

Open the connection.

close()[source]

Close the connection.

is_opened()[source]

Check if the device is connected

single_op()[source]

Context manager for a single operation.

If connect_on_operation==True during creation, wrapping several command in single_op prevents the connection from being closed and reopened between the operations (only opened in the beginning and closed in the end).

cooldown()[source]

Cooldown between the operations.

Sleeping for a short time defined by _operation_cooldown attribute (no cooldown by default). Also defined class-wide by _default_operation_cooldown class attribute.

set_timeout(timeout)[source]

Set operations timeout (in seconds).

get_timeout()[source]

Get operations timeout (in seconds).

readline(remove_term=True, timeout=None, skip_empty=True, error_on_timeout=True)[source]

Read a single line from the device.

Parameters:
  • remove_term (bool) – If True, remove terminal characters from the result.
  • timeout – Operation timeout. If None, use the default device timeout.
  • skip_empty (bool) – If True, ignore empty lines (works only for remove_term==True).
  • error_on_timeout (bool) – If False, return an incomplete line instead of raising the error on timeout.
read(size=None, error_on_timeout=True)[source]

Read data from the device.

If size is not None, read size bytes (usual timeout applies); otherwise, read all available data (return immediately).

read_multichar_term(term, remove_term=True, timeout=None, error_on_timeout=True)[source]

Read a single line with multiple possible terminators.

Parameters:
  • term – Either a string (single multi-char terminator) or a list of strings (multiple terminators).
  • remove_term (bool) – If True, remove terminal characters from the result.
  • timeout – Operation timeout. If None, use the default device timeout.
  • error_on_timeout (bool) – If False, return an incomplete line instead of raising the error on timeout.
write(data, flush=True, read_echo=False, read_echo_delay=0, read_echo_lines=1)[source]

Write data to the device.

If flush==True, flush the write buffer. If read_echo==True, wait for read_echo_delay seconds and then perform readline() (read_echo_lines times).

static list_resources(desc=False)[source]

List all availabe resources for this backend.

If desc==False, return list of connections (usually strings), which can be used to connect to the device. Otherwise, return a list of descriptions, which have more info, but can be backend-dependent.

Might not be implemented (depending on the backend), in which case returns None.

exception pylablib.core.devio.backend.FT232BackendOpenError(e)[source]

Bases: pylablib.core.devio.backend.IBackendOpenError, object

FT232 backend opening error

class pylablib.core.devio.backend.FT232DeviceBackend(conn, timeout=10.0, term_write=None, term_read=None, open_retry_times=3, datatype='auto')[source]

Bases: pylablib.core.devio.backend.IDeviceBackend

FT232 backend (via pyft232).

Connection is automatically opened on creation.

Parameters:
  • conn – Connection parameters. Can be either a string (for a port), or a list/tuple (port, baudrate, bytesize, parity, stopbits, xonxoff, rtscts, dsrdtr) supplied to the serial connection (default is ('COM1',19200,8,'N',1,0,0,0)), or a dict with the same parameters.
  • timeout (float) – Default timeout (in seconds).
  • term_write (str) – Line terminator for writing operations; appended to the data
  • term_read (str) – List of possible single-char terminator for reading operations (specifies when readline() stops).
  • connect_on_operation (bool) – If True, the connection is normally closed, and is opened only on the operations (normally two processes can’t be simultaneously connected to the same device).
  • open_retry_times (int) – Number of times the connection is attempted before giving up.
  • no_dtr (bool) – If True, turn off DTR status line before opening (e.g., turns off reset-on-connection for Arduino controllers).
  • datatype (str) – Type of the returned data; can be "bytes" (return bytes object), "str" (return str object), or "auto" (default Python result: str in Python 2 and bytes in Python 3)
Error

alias of builtins.object

BackendOpenError

alias of FT232BackendOpenError

open()[source]

Open the connection.

close()[source]

Close the connection.

is_opened()[source]

Check if the device is connected

single_op()[source]

Context manager for a single operation.

Does nothing.

cooldown()[source]

Cooldown between the operations.

Sleeping for a short time defined by _operation_cooldown attribute (no cooldown by default). Also defined class-wide by _default_operation_cooldown class attribute.

set_timeout(timeout)[source]

Set operations timeout (in seconds).

get_timeout()[source]

Get operations timeout (in seconds).

readline(remove_term=True, timeout=None, skip_empty=True, error_on_timeout=True)[source]

Read a single line from the device.

Parameters:
  • remove_term (bool) – If True, remove terminal characters from the result.
  • timeout – Operation timeout. If None, use the default device timeout.
  • skip_empty (bool) – If True, ignore empty lines (works only for remove_term==True).
  • error_on_timeout (bool) – If False, return an incomplete line instead of raising the error on timeout.
read(size=None, error_on_timeout=True)[source]

Read data from the device.

If size is not None, read size bytes (usual timeout applies); otherwise, read all available data (return immediately).

read_multichar_term(term, remove_term=True, timeout=None, error_on_timeout=True)[source]

Read a single line with multiple possible terminators.

Parameters:
  • term – Either a string (single multi-char terminator) or a list of strings (multiple terminators).
  • remove_term (bool) – If True, remove terminal characters from the result.
  • timeout – Operation timeout. If None, use the default device timeout.
  • error_on_timeout (bool) – If False, return an incomplete line instead of raising the error on timeout.
write(data, flush=True, read_echo=False, read_echo_delay=0, read_echo_lines=1)[source]

Write data to the device.

If flush==True, flush the write buffer. If read_echo==True, wait for read_echo_delay seconds and then perform readline() (read_echo_lines times).

static list_resources(desc=False)[source]

List all availabe resources for this backend.

If desc==False, return list of connections (usually strings), which can be used to connect to the device. Otherwise, return a list of descriptions, which have more info, but can be backend-dependent.

Might not be implemented (depending on the backend), in which case returns None.

exception pylablib.core.devio.backend.NetworkBackendOpenError(e)[source]

Bases: pylablib.core.devio.backend.IBackendOpenError, OSError

Network backend opening error

class pylablib.core.devio.backend.NetworkDeviceBackend(conn, timeout=10.0, term_write=None, term_read=None, datatype='auto')[source]

Bases: pylablib.core.devio.backend.IDeviceBackend

Serial backend (via pySerial).

Connection is automatically opened on creation.

Parameters:
  • conn – Connection parameters. Can be either a string "IP:port" (e.g., "127.0.0.1:80"), or a tuple (IP,port), where IP is a string and port is a number.
  • timeout (float) – Default timeout (in seconds).
  • term_write (str) – Line terminator for writing operations; appended to the data
  • term_read (str) – List of possible single-char terminator for reading operations (specifies when readline() stops).
  • datatype (str) – Type of the returned data; can be "bytes" (return bytes object), "str" (return str object), or "auto" (default Python result: str in Python 2 and bytes in Python 3)

Note

If term_read is a string, its behavior is different from the VISA backend: instead of being a multi-char terminator it is assumed to be a set of single-char terminators. If multi-char terminator is required, term_read should be a single-element list instead of a string.

Error

alias of builtins.OSError

BackendOpenError

alias of NetworkBackendOpenError

open()[source]

Open the connection.

close()[source]

Close the connection.

is_opened()[source]

Check if the device is connected

cooldown()[source]

Cooldown between the operations.

Sleeping for a short time defined by _operation_cooldown attribute (no cooldown by default). Also defined class-wide by _default_operation_cooldown class attribute.

set_timeout(timeout)[source]

Set operations timeout (in seconds).

get_timeout()[source]

Get operations timeout (in seconds).

readline(remove_term=True, timeout=None, skip_empty=True, error_on_timeout=True)[source]

Read a single line from the device.

Parameters:
  • remove_term (bool) – If True, remove terminal characters from the result.
  • timeout – Operation timeout. If None, use the default device timeout.
  • skip_empty (bool) – If True, ignore empty lines (works only for remove_term==True).
  • error_on_timeout (bool) – If False, return an incomplete line instead of raising the error on timeout.
read(size=None, error_on_timeout=True)[source]

Read data from the device.

If size is not None, read size bytes (usual timeout applies); otherwise, read all available data (return immediately).

read_multichar_term(term, remove_term=True, timeout=None, error_on_timeout=True)[source]

Read a single line with multiple possible terminators.

Parameters:
  • term – Either a string (single multi-char terminator) or a list of strings (multiple terminators).
  • remove_term (bool) – If True, remove terminal characters from the result.
  • timeout – Operation timeout. If None, use the default device timeout.
  • error_on_timeout (bool) – If False, return an incomplete line instead of raising the error on timeout.
write(data, flush=True, read_echo=False, read_echo_delay=0, read_echo_lines=1)[source]

Write data to the device.

If read_echo==True, wait for read_echo_delay seconds and then perform readline() (read_echo_lines times). flush parameter is ignored.

pylablib.core.devio.backend.autodetect_backend(conn)[source]

Try to determine the backend by the connection.

The assumed default backend is 'visa'.

pylablib.core.devio.backend.new_backend(conn, timeout=None, backend='auto', **kwargs)[source]

Build new backend with the supplied parameters.

Parameters:
  • conn – Connection parameters (depend on the backend).
  • timeout (float) – Default timeout (in seconds).
  • backend (str) – Backend type. Available backends are 'auto' (try to autodetect), 'visa', 'serial', 'ft232', and 'network'.
  • **kwargs – parameters sent to the backend.
class pylablib.core.devio.backend.IBackendWrapper(instr)[source]

Bases: pylablib.core.devio.interface.IDevice

A base class for an instrument using a communication backend.

Parameters:instr – Backend (assumed to be already opened).
open()[source]

Open the backend.

close()[source]

Close the backend.

is_opened()[source]

Check if the device is connected

lock(timeout=None)[source]

Lock the access to the device from other threads/processes (isn’t necessarily implemented).

unlock()[source]

Unlock the access to the device from other threads/processes (isn’t necessarily implemented).

locking(timeout=None)[source]

Context manager for lock & unlock.

pylablib.core.devio.data_format module

Library for binary data encoding/decoding for device communication.

class pylablib.core.devio.data_format.DataFormat(size, kind, byteorder)[source]

Bases: object

Describes data encoding for device communications.

Parameters:
  • size (int) – Size of a single element (in bytes).
  • kind (str) – Kind of the element. Can be 'i' (integer), 'u' (unsigned integer), 'f' (floating point) or 'ascii' (text representation).
  • byteorder (str) – Byte order: '>' is big-endian (MSB first), '>' is little-endian (LSB first).
flip_byteorder()[source]

Flip byteorder of the description.

is_ascii()[source]

Check of the format is textual.

static from_desc(desc, str_type='numpy')[source]

Build the format from the string description.

str_type is the description format. Can be 'numpy' (numpy dtype description), 'struct' (struct description) or 'SCPI' (the standard SCPI description).

static from_desc_SCPI(desc, border='norm')[source]

Build the format from the string SCPI description.

border describes byte order (either 'norm' or 'swap').

to_desc(str_type='auto')[source]

Build a description string of this format.

str_type can be 'auto' (similar to 'numpy', but also accepts 'ascii'), 'numpy', 'struct' or 'SCPI' (return tuple (desc, border)).

convert_from_str(data)[source]

Convert the string data into an array.

convert_to_str(data, ascii_format='.5f')[source]

Convert the array into a string data.

ascii_format is the str.format() string for textual representation.

pylablib.core.devio.interface module

class pylablib.core.devio.interface.IDevice[source]

Bases: object

A base class for an instrument.

Contains some useful functions for dealing with device settings.

open()[source]

Open the connection

close()[source]

Close the connection

is_opened()[source]

Check if the device is connected

get_settings(nodes=None)[source]

Get dict {name: value} containing all the device settings.

nodes specifies nodes to acquire.

get_full_status(nodes=None)[source]

Get dict {name: value} containing the device status (including settings).

nodes specifies nodes to acquire.

get_full_info(nodes=None)[source]

Get dict {name: value} containing full device information (including status and settings).

nodes specifies nodes to acquire.

apply_settings(settings)[source]

Apply the settings.

settings is the dict {name: value} of the device available settings. Non-applicable settings are ignored.

pylablib.core.devio.units module

Routines for conversion of physical units.

pylablib.core.devio.units.split_units(value)[source]

Split string dimensionful value.

Return tuple (val, unit), where val is the float part of the value, and unit is the string representing units.

pylablib.core.devio.units.convert_length_units(value, value_unit='m', result_unit='m', case_sensitive=True)[source]

Convert value from value_unit to result_unit.

The possible length units are 'm',``’mm’, ``'um', 'nm', 'pm', 'fm'. If case_sensitive==True, matching units is case sensitive.

pylablib.core.devio.units.convert_time_units(value, value_unit='s', result_unit='s', case_sensitive=True)[source]

Convert value from value_unit to result_unit.

The possible time units are 's',``’ms’, ``'us', 'ns', 'ps', 'fs', 'as'. If case_sensitive==True, matching units is case sensitive.

pylablib.core.devio.units.convert_frequency_units(value, value_unit='Hz', result_unit='Hz', case_sensitive=True)[source]

Convert value from value_unit to result_unit.

The possible frequency units are 'Hz',``’kHz’, ``'MHz', 'GHz'. If case_sensitive==True, matching units is case sensitive.

pylablib.core.devio.units.convert_power_units(value, value_unit='dBm', result_unit='dBm', case_sensitive=True, impedance=50.0)[source]

Convert value from value_unit to result_unit.

For conversion between voltage and power, assume RMS voltage and the given impedance. The possible power units are 'dBm', 'dBmV', 'dBuV', 'W', 'mW', 'uW', 'nW', 'mV', 'nV'. If case_sensitive==True, matching units is case sensitive.

Module contents