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='auto', backend_defaults=None, failsafe=None, timeout=None, backend_params=None)[source]¶ Bases:
pylablib.core.devio.comm_backend.ICommBackendWrapper
A base class for a device controlled with the usual SCPI syntax.
- Implements two functions:
- deals with composing and parsing of standard SCPI commands and simplifying repetitive property access routines
- 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
comm_backend.IDeviceCommBackend
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 (e.g.,
'serial'
or'visa'
). - backend_defaults – if not
None
, specifies a dictionary{backend: params}
with default connection parameters (depending on the backend), which are added to conn - 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. IfNone
, use the class value _default_failsafe (False
by default). - timeout (float) – Default timeout (in seconds).
-
Error
¶ alias of
pylablib.core.devio.base.DeviceError
-
ReraiseError
= None¶
-
BackendError
¶ alias of
pylablib.core.devio.comm_backend.DeviceBackendError
-
reconnect
(new_instrument=True, ignore_error=True)[source]¶ Remake the connection.
If
new_instrument==True
, create a new backend instance. Ifignore_error==True
, ignore errors on closing.
-
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 theread()
/ask()
operation or at the end of the block.
-
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.
Note that the code execution is not paused.
-
wait
(wait_type='sync', timeout=None, wait_callback=None)[source]¶ Pause execution until device overlapped commands are complete.
wait_type is either
'sync'
(performwait_sync()
),'dev'
(performwait_dev()
) or'none'
(do nothing).
-
write
(msg, arg=None, arg_type=None, unit=None, bool_selector=None, wait_sync=None, 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. If a list of arguments is supplied, the result is joined with
","
. - arg_type (str) – Argument type. Can be
'raw'
(in which case data is sent raw),'string'
,'int'
,'float'
,'bool'
, a format string (such as'{:.3f}'
) or a list of argument types (for an iterable argument); if format string is used and the argument is a list or a tuple, then it is expanded as a list of arguments (e.g.,arg_type='{0};{1}'
witharg=[1,2]
will produce a string'1;2'
); if a list of types is used, each element of arg is converted using the corresponding type, and the result is joined with","
. - unit (str) – If not
None
, use it as a unit to append after the value. - bool_selector (tuple) – A tuple
(false_value, true_value)
of two strings to represent bool argument; by default, use._bool_selector
attribute. - wait_sync – if
True
, append the sync command (specified as._wait_sync_comm
attribute,"*OPC?"
by default) after the message and pause the execution command is complete; useful in long set operations, where the device might ignore later inputs until the current command is complete; ifNone
, use the class default._default_write_sync
attribute (False
by default). - 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'
(interprets0
or'off'
asFalse
, anything else asTrue
),'value'
(returns tuple(value, unit)
, where value is float), a callable (return the result of this callable applied to the string value), a dictionary (return the stored value corresponding to the string value, or to the value converted into integer if the string value is not present), or a list of data types (the result is treated as a list of values with the given types separated by commas). timeout overrides the default value.
-
class
NoParameterCaller
(device, kind)¶ Bases:
object
Class to simplify calling functions without a parameter
-
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()
. Ifread_echo==True
, assume that the device first echoes the input and skip it.
-
close
()¶ Close the backend
-
get_device_variable
(key)¶ Get the value of a settings, status, or full info parameter
-
get_full_info
(include=0)¶ Get dict
{name: value}
containing full device information (including status and settings).include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or
"all"
(all available variables). Since the lowest priority is -10, settinginclude=-10
queries all available variables, which is equivalent toinclude="all"
.
-
get_full_status
(include=0)¶ Get dict
{name: value}
containing the device status (including settings).include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or
"all"
(all available variables). Since the lowest priority is -10, settinginclude=-10
queries all available variables, which is equivalent toinclude="all"
.
-
get_settings
(include=0)¶ Get dict
{name: value}
containing all the device settings.include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or
"all"
(all available variables). Since the lowest priority is -10, settinginclude=-10
queries all available variables, which is equivalent toinclude="all"
.
-
is_opened
()¶ Check if the device is connected
-
lock
(timeout=None)¶ Lock the access to the device from other threads/processes (isn’t necessarily implemented)
-
locking
(timeout=None)¶ Context manager for lock & unlock
-
open
()¶ Open the backend
-
set_device_variable
(key, value)¶ Set the value of a settings parameter
-
unlock
()¶ Unlock the access to the device from other threads/processes (isn’t necessarily implemented)
-
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.
-
read_binary_array_data
(include_header=False, timeout=None, flush_term=True)[source]¶ Read a binary data in the from the device.
The data assumes the standard binary transfer header consisting of
"#"
symbol, then a single digit with the size of the length string, then the length string containing the length of the binary data (in bytes). Ifinclude_header==True
, return the data with the header; otherwise, return only the content. Ifflush_term==True
, flush the following line to skip terminator characters after the binary data, which are added by some devices. timeout overrides the default value.
-
static
parse_array_data
(data, fmt, include_header=False)[source]¶ Parse the data returned by the device. fmt is
DataFormat
description in numpy format (e.g.,"<u2"
).If
include_header==True
, the data is assumed to be in a (somewhat) standard SCPI format:b'#'
, then a single digits
denoting length of the size block, thens
digits denoting length of the data (in bytes) followed by the actual data. Otherwise (include_header==False
), assume that the header is already removed.
pylablib.core.devio.backend_logger module¶
pylablib.core.devio.base module¶
-
exception
pylablib.core.devio.base.
DeviceError
[source]¶ Bases:
RuntimeError
Generic device communication error
-
args
¶
-
with_traceback
()¶ Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
-
pylablib.core.devio.comm_backend module¶
Routines for defining a unified interface across multiple backends.
-
exception
pylablib.core.devio.comm_backend.
DeviceBackendError
(exc)[source]¶ Bases:
pylablib.core.devio.base.DeviceError
Generic exception relaying a backend error
-
args
¶
-
with_traceback
()¶ Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
-
-
pylablib.core.devio.comm_backend.
reraise
(func)[source]¶ Wrapper for a backend method which intercepts backend exceptions and re-emits them as a subclass of
DeviceBackendError
defined in the class
-
pylablib.core.devio.comm_backend.
logerror
(func)[source]¶ Wrapper for a backend method which logs if any errors escaped
-
class
pylablib.core.devio.comm_backend.
IDeviceCommBackend
(conn, timeout=None, term_write=None, term_read=None, datatype='auto', reraise_error=None)[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"
(returnbytes
object),"str"
(returnstr
object), or"auto"
(default Python result:str
in Python 2 andbytes
in Python 3) - reraise_error – if not
None
, specifies an error to be re-raised on any backend exception (by default, use backend-specific error); should be a subclass ofDeviceBackendError
.
-
BackendError
= None¶ Base class for the errors raised by the backend operations
-
Error
¶ alias of
DeviceBackendError
-
classmethod
combine_conn
(conn1, conn2)[source]¶ Combined two connection parameters into a single dictionary (conn1 overrides conn2)
-
classmethod
get_backend_name
()[source]¶ Get string representation of the backend (e.g.,
"serial"
,"visa"
, or"network"
)
-
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)
-
setup_cooldown
(**kwargs)[source]¶ Setup cooldown times for various operations.
The arguments are of the form
kind=value
, wherevalue
is the cooldown time (in seconds), andkind
is the operation kind (common kinds areopen
,close
,read
,write
,timeout
, andflush
).kind
can also bedefault
(default value for all kind), orall
(reset all cooldown values to this value). The cooldowns of the given kinds are usually called after the corresponding operation (it is necessary for some devices, otherwise the communication can freeze or crush). Default cooldown values are specified by_default_operation_cooldown
class attribute dictionary.
-
cooldown
(kind='default')[source]¶ Cooldown between the operations.
kind
specifies the operation kind (common kinds areopen
,close
,read
,write
,timeout
, andflush
);"default"
corresponds to the default cooldown (usually, specified as 0). Called automatically by various backend operations, so usually there is no need to call explicitly.
-
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:
-
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. Ifread_echo==True
, wait for read_echo_delay seconds and then performreadline()
(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 available resources for this backend.
If
desc==False
, return list of connections (usually strings or tuples), 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.comm_backend.
remove_longest_term
(msg, terms)[source]¶ Remove the longest terminator among terms from the end of the message.
-
exception
pylablib.core.devio.comm_backend.
DeviceVisaError
(exc)[source]¶ Bases:
pylablib.core.devio.comm_backend.DeviceBackendError
Visa backend operation error
-
args
¶
-
with_traceback
()¶ Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
-
-
class
pylablib.core.devio.comm_backend.
VisaDeviceBackend
(conn, timeout=10.0, term_write=None, term_read=None, do_lock=None, datatype='auto', reraise_error=None)[source]¶ Bases:
pylablib.core.devio.comm_backend.IDeviceCommBackend
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) - reraise_error – if not
None
, specifies an error to be re-raised on any backend exception (by default, use backend-specific error); should be a subclass ofDeviceBackendError
.
-
BackendError
¶ alias of
builtins.object
-
Error
¶ alias of
DeviceVisaError
-
static
list_resources
(desc=False)[source]¶ List all available resources for this backend.
If
desc==False
, return list of connections (usually strings or tuples), 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
.
-
readline
(remove_term=True, timeout=None, skip_empty=True)[source]¶ Read a single line from the device.
Parameters:
-
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
read_echo==True
, wait for read_echo_delay seconds and then performreadline()
(read_echo_lines times). flush parameter is ignored.
-
ask
(query, delay=0.0, read_all=False)¶ 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.
-
classmethod
combine_conn
(conn1, conn2)¶ Combined two connection parameters into a single dictionary (conn1 overrides conn2)
-
cooldown
(kind='default')¶ Cooldown between the operations.
kind
specifies the operation kind (common kinds areopen
,close
,read
,write
,timeout
, andflush
);"default"
corresponds to the default cooldown (usually, specified as 0). Called automatically by various backend operations, so usually there is no need to call explicitly.
-
flush_read
()¶ Flush the device output (read all the available data; return the number of bytes read)
-
classmethod
get_backend_name
()¶ Get string representation of the backend (e.g.,
"serial"
,"visa"
, or"network"
)
-
readlines
(lines_num, remove_term=True, timeout=None, skip_empty=True)¶ Read multiple lines from the device.
Parameters are the same as in
readline()
.
-
setup_cooldown
(**kwargs)¶ Setup cooldown times for various operations.
The arguments are of the form
kind=value
, wherevalue
is the cooldown time (in seconds), andkind
is the operation kind (common kinds areopen
,close
,read
,write
,timeout
, andflush
).kind
can also bedefault
(default value for all kind), orall
(reset all cooldown values to this value). The cooldowns of the given kinds are usually called after the corresponding operation (it is necessary for some devices, otherwise the communication can freeze or crush). Default cooldown values are specified by_default_operation_cooldown
class attribute dictionary.
-
using_timeout
(timeout=None)¶ Context manager for usage of a different timeout inside a block
-
exception
pylablib.core.devio.comm_backend.
DeviceSerialError
(exc)[source]¶ Bases:
pylablib.core.devio.comm_backend.DeviceBackendError
Serial backend operation error
-
args
¶
-
with_traceback
()¶ Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
-
-
class
pylablib.core.devio.comm_backend.
SerialDeviceBackend
(conn, timeout=10.0, term_write=None, term_read=None, connect_on_operation=False, open_retry_times=3, no_dtrrts=False, datatype='auto', reraise_error=None)[source]¶ Bases:
pylablib.core.devio.comm_backend.IDeviceCommBackend
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_dtrrts (bool) – If
True
, turn off DTR and RTS status lines 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) - reraise_error – if not
None
, specifies an error to be re-raised on any backend exception (by default, use backend-specific error); should be a subclass ofDeviceBackendError
.
-
BackendError
¶ alias of
builtins.object
-
Error
¶ alias of
DeviceSerialError
-
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).
-
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 forremove_term==True
). - error_on_timeout (bool) – If
False
, return an incomplete line instead of raising the error on timeout.
- remove_term (bool) – If
-
read
(size=None)[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. Ifread_echo==True
, wait for read_echo_delay seconds and then performreadline()
(read_echo_lines times).
-
static
list_resources
(desc=False)[source]¶ List all available resources for this backend.
If
desc==False
, return list of connections (usually strings or tuples), 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
.
-
ask
(query, delay=0.0, read_all=False)¶ 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.
-
classmethod
combine_conn
(conn1, conn2)¶ Combined two connection parameters into a single dictionary (conn1 overrides conn2)
-
cooldown
(kind='default')¶ Cooldown between the operations.
kind
specifies the operation kind (common kinds areopen
,close
,read
,write
,timeout
, andflush
);"default"
corresponds to the default cooldown (usually, specified as 0). Called automatically by various backend operations, so usually there is no need to call explicitly.
-
flush_read
()¶ Flush the device output (read all the available data; return the number of bytes read)
-
classmethod
get_backend_name
()¶ Get string representation of the backend (e.g.,
"serial"
,"visa"
, or"network"
)
-
lock
(timeout=None)¶ Lock the access to the device from other threads/processes (isn’t necessarily implemented)
-
locking
(timeout=None)¶ Context manager for lock & unlock
-
readlines
(lines_num, remove_term=True, timeout=None, skip_empty=True)¶ Read multiple lines from the device.
Parameters are the same as in
readline()
.
-
setup_cooldown
(**kwargs)¶ Setup cooldown times for various operations.
The arguments are of the form
kind=value
, wherevalue
is the cooldown time (in seconds), andkind
is the operation kind (common kinds areopen
,close
,read
,write
,timeout
, andflush
).kind
can also bedefault
(default value for all kind), orall
(reset all cooldown values to this value). The cooldowns of the given kinds are usually called after the corresponding operation (it is necessary for some devices, otherwise the communication can freeze or crush). Default cooldown values are specified by_default_operation_cooldown
class attribute dictionary.
-
unlock
()¶ Unlock the access to the device from other threads/processes (isn’t necessarily implemented)
-
using_timeout
(timeout=None)¶ Context manager for usage of a different timeout inside a block
- conn – Connection parameters. Can be either a string (for a port),
or a list/tuple
-
exception
pylablib.core.devio.comm_backend.
DeviceFT232Error
(exc)[source]¶ Bases:
pylablib.core.devio.comm_backend.DeviceBackendError
FT232 backend operation error
-
args
¶
-
with_traceback
()¶ Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
-
-
class
pylablib.core.devio.comm_backend.
FT232DeviceBackend
(conn, timeout=10.0, term_write=None, term_read=None, open_retry_times=3, datatype='auto', reraise_error=None)[source]¶ Bases:
pylablib.core.devio.comm_backend.IDeviceCommBackend
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)
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). - open_retry_times (int) – Number of times the connection is attempted before giving up.
- 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) - reraise_error – if not
None
, specifies an error to be re-raised on any backend exception (by default, use backend-specific error); should be a subclass ofDeviceBackendError
.
-
BackendError
¶ alias of
builtins.object
-
Error
¶ alias of
DeviceFT232Error
-
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 forremove_term==True
). - error_on_timeout (bool) – If
False
, return an incomplete line instead of raising the error on timeout.
- remove_term (bool) – If
-
read
(size=None)[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. Ifread_echo==True
, wait for read_echo_delay seconds and then performreadline()
(read_echo_lines times).
-
static
list_resources
(desc=False)[source]¶ List all available resources for this backend.
If
desc==False
, return list of connections (usually strings or tuples), 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
.
-
ask
(query, delay=0.0, read_all=False)¶ 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.
-
classmethod
combine_conn
(conn1, conn2)¶ Combined two connection parameters into a single dictionary (conn1 overrides conn2)
-
cooldown
(kind='default')¶ Cooldown between the operations.
kind
specifies the operation kind (common kinds areopen
,close
,read
,write
,timeout
, andflush
);"default"
corresponds to the default cooldown (usually, specified as 0). Called automatically by various backend operations, so usually there is no need to call explicitly.
-
flush_read
()¶ Flush the device output (read all the available data; return the number of bytes read)
-
classmethod
get_backend_name
()¶ Get string representation of the backend (e.g.,
"serial"
,"visa"
, or"network"
)
-
lock
(timeout=None)¶ Lock the access to the device from other threads/processes (isn’t necessarily implemented)
-
locking
(timeout=None)¶ Context manager for lock & unlock
-
readlines
(lines_num, remove_term=True, timeout=None, skip_empty=True)¶ Read multiple lines from the device.
Parameters are the same as in
readline()
.
-
setup_cooldown
(**kwargs)¶ Setup cooldown times for various operations.
The arguments are of the form
kind=value
, wherevalue
is the cooldown time (in seconds), andkind
is the operation kind (common kinds areopen
,close
,read
,write
,timeout
, andflush
).kind
can also bedefault
(default value for all kind), orall
(reset all cooldown values to this value). The cooldowns of the given kinds are usually called after the corresponding operation (it is necessary for some devices, otherwise the communication can freeze or crush). Default cooldown values are specified by_default_operation_cooldown
class attribute dictionary.
-
unlock
()¶ Unlock the access to the device from other threads/processes (isn’t necessarily implemented)
-
using_timeout
(timeout=None)¶ Context manager for usage of a different timeout inside a block
- conn – Connection parameters. Can be either a string (for a port),
or a list/tuple
-
exception
pylablib.core.devio.comm_backend.
DeviceNetworkError
(exc)[source]¶ Bases:
pylablib.core.devio.comm_backend.DeviceBackendError
Network backend operation error
-
args
¶
-
with_traceback
()¶ Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
-
-
class
pylablib.core.devio.comm_backend.
NetworkDeviceBackend
(conn, timeout=10.0, term_write=None, term_read=None, datatype='auto', reraise_error=None)[source]¶ Bases:
pylablib.core.devio.comm_backend.IDeviceCommBackend
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) - reraise_error – if not
None
, specifies an error to be re-raised on any backend exception (by default, use backend-specific error); should be a subclass ofDeviceBackendError
.
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.
-
BackendError
¶ alias of
builtins.OSError
-
Error
¶ alias of
DeviceNetworkError
-
readline
(remove_term=True, timeout=None, skip_empty=True)[source]¶ Read a single line from the device.
Parameters:
-
read
(size=None)[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)[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.
-
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 performreadline()
(read_echo_lines times). flush parameter is ignored.
-
ask
(query, delay=0.0, read_all=False)¶ 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.
-
classmethod
combine_conn
(conn1, conn2)¶ Combined two connection parameters into a single dictionary (conn1 overrides conn2)
-
cooldown
(kind='default')¶ Cooldown between the operations.
kind
specifies the operation kind (common kinds areopen
,close
,read
,write
,timeout
, andflush
);"default"
corresponds to the default cooldown (usually, specified as 0). Called automatically by various backend operations, so usually there is no need to call explicitly.
-
flush_read
()¶ Flush the device output (read all the available data; return the number of bytes read)
-
classmethod
get_backend_name
()¶ Get string representation of the backend (e.g.,
"serial"
,"visa"
, or"network"
)
-
static
list_resources
(desc=False)¶ List all available resources for this backend.
If
desc==False
, return list of connections (usually strings or tuples), 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
.
-
lock
(timeout=None)¶ Lock the access to the device from other threads/processes (isn’t necessarily implemented)
-
locking
(timeout=None)¶ Context manager for lock & unlock
-
readlines
(lines_num, remove_term=True, timeout=None, skip_empty=True)¶ Read multiple lines from the device.
Parameters are the same as in
readline()
.
-
setup_cooldown
(**kwargs)¶ Setup cooldown times for various operations.
The arguments are of the form
kind=value
, wherevalue
is the cooldown time (in seconds), andkind
is the operation kind (common kinds areopen
,close
,read
,write
,timeout
, andflush
).kind
can also bedefault
(default value for all kind), orall
(reset all cooldown values to this value). The cooldowns of the given kinds are usually called after the corresponding operation (it is necessary for some devices, otherwise the communication can freeze or crush). Default cooldown values are specified by_default_operation_cooldown
class attribute dictionary.
-
unlock
()¶ Unlock the access to the device from other threads/processes (isn’t necessarily implemented)
-
using_timeout
(timeout=None)¶ Context manager for usage of a different timeout inside a block
- conn – Connection parameters. Can be either a string
-
exception
pylablib.core.devio.comm_backend.
DeviceUSBError
(exc)[source]¶ Bases:
pylablib.core.devio.comm_backend.DeviceBackendError
USB backend operation error
-
args
¶
-
with_traceback
()¶ Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
-
-
class
pylablib.core.devio.comm_backend.
PyUSBDeviceBackend
(conn, timeout=10.0, term_write=None, term_read=None, check_read_size=True, datatype='auto', reraise_error=None)[source]¶ Bases:
pylablib.core.devio.comm_backend.IDeviceCommBackend
USB backend (via PyUSB package).
Connection is automatically opened on creation.
Parameters: - conn – Connection parameters. Can be either a string (for a port),
or a list/tuple
(vendorID, productID, index, endpoint_read, endpoint_write, backend)
supplied to the connection (default is(0x0000,0x0000,0,0x00,0x01,'libusb1')
, which is invalid for most devices), or a dict with the same parameters.vendorID
andproductID
specify device kind,index
is an integer index (starting from zero) of the device among several identical (i.e., with the same ids) ones, andendpoint_read
andendpoint_write
specify connection endpoints for the specific device. - 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) - reraise_error – if not
None
, specifies an error to be re-raised on any backend exception (by default, use backend-specific error); should be a subclass ofDeviceBackendError
.
-
BackendError
¶ alias of
usb.core.USBError
-
Error
¶ alias of
DeviceUSBError
-
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 forremove_term==True
). - error_on_timeout (bool) – If
False
, return an incomplete line instead of raising the error on timeout.
- remove_term (bool) – If
-
read
(size=None, max_read_size=65536)[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 performreadline()
(read_echo_lines times). flush parameter is ignored.
-
static
list_resources
(desc=False, **kwargs)[source]¶ List all available resources for this backend.
If
desc==False
, return list of connections (usually strings or tuples), 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
.
-
ask
(query, delay=0.0, read_all=False)¶ 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.
-
classmethod
combine_conn
(conn1, conn2)¶ Combined two connection parameters into a single dictionary (conn1 overrides conn2)
-
cooldown
(kind='default')¶ Cooldown between the operations.
kind
specifies the operation kind (common kinds areopen
,close
,read
,write
,timeout
, andflush
);"default"
corresponds to the default cooldown (usually, specified as 0). Called automatically by various backend operations, so usually there is no need to call explicitly.
-
flush_read
()¶ Flush the device output (read all the available data; return the number of bytes read)
-
classmethod
get_backend_name
()¶ Get string representation of the backend (e.g.,
"serial"
,"visa"
, or"network"
)
-
lock
(timeout=None)¶ Lock the access to the device from other threads/processes (isn’t necessarily implemented)
-
locking
(timeout=None)¶ Context manager for lock & unlock
-
readlines
(lines_num, remove_term=True, timeout=None, skip_empty=True)¶ Read multiple lines from the device.
Parameters are the same as in
readline()
.
-
setup_cooldown
(**kwargs)¶ Setup cooldown times for various operations.
The arguments are of the form
kind=value
, wherevalue
is the cooldown time (in seconds), andkind
is the operation kind (common kinds areopen
,close
,read
,write
,timeout
, andflush
).kind
can also bedefault
(default value for all kind), orall
(reset all cooldown values to this value). The cooldowns of the given kinds are usually called after the corresponding operation (it is necessary for some devices, otherwise the communication can freeze or crush). Default cooldown values are specified by_default_operation_cooldown
class attribute dictionary.
-
unlock
()¶ Unlock the access to the device from other threads/processes (isn’t necessarily implemented)
-
using_timeout
(timeout=None)¶ Context manager for usage of a different timeout inside a block
- conn – Connection parameters. Can be either a string (for a port),
or a list/tuple
-
exception
pylablib.core.devio.comm_backend.
DeviceRecordedError
(exc)[source]¶ Bases:
pylablib.core.devio.comm_backend.DeviceBackendError
Recorded backend operation error
-
args
¶
-
with_traceback
()¶ Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
-
-
class
pylablib.core.devio.comm_backend.
RecordedDeviceBackend
(conn, datatype='auto', reraise_error=None)[source]¶ Bases:
pylablib.core.devio.comm_backend.IDeviceCommBackend
Recorded backend.
Connection is automatically opened on creation.
Parameters: - conn – connection parameters (recorded log path)
- 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) - reraise_error – if not
None
, specifies an error to be re-raised on any backend exception (by default, use backend-specific error); should be a subclass ofDeviceBackendError
.
-
BackendError
¶ alias of
builtins.OSError
-
Error
¶ alias of
DeviceRecordedError
-
readline
(remove_term=True, timeout=None, skip_empty=True)[source]¶ Read a single line from the device.
Parameters:
-
read
(size=None)[source]¶ Read data from the device.
If size is not None, read size bytes (usual 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. Ifread_echo==True
, wait for read_echo_delay seconds and then performreadline()
(read_echo_lines times).
-
ask
(query, delay=0.0, read_all=False)¶ 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.
-
classmethod
combine_conn
(conn1, conn2)¶ Combined two connection parameters into a single dictionary (conn1 overrides conn2)
-
cooldown
(kind='default')¶ Cooldown between the operations.
kind
specifies the operation kind (common kinds areopen
,close
,read
,write
,timeout
, andflush
);"default"
corresponds to the default cooldown (usually, specified as 0). Called automatically by various backend operations, so usually there is no need to call explicitly.
-
flush_read
()¶ Flush the device output (read all the available data; return the number of bytes read)
-
classmethod
get_backend_name
()¶ Get string representation of the backend (e.g.,
"serial"
,"visa"
, or"network"
)
-
get_timeout
()¶ Get operations timeout (in seconds)
-
static
list_resources
(desc=False)¶ List all available resources for this backend.
If
desc==False
, return list of connections (usually strings or tuples), 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
.
-
lock
(timeout=None)¶ Lock the access to the device from other threads/processes (isn’t necessarily implemented)
-
locking
(timeout=None)¶ Context manager for lock & unlock
-
readlines
(lines_num, remove_term=True, timeout=None, skip_empty=True)¶ Read multiple lines from the device.
Parameters are the same as in
readline()
.
-
set_timeout
(timeout)¶ Set operations timeout (in seconds)
-
setup_cooldown
(**kwargs)¶ Setup cooldown times for various operations.
The arguments are of the form
kind=value
, wherevalue
is the cooldown time (in seconds), andkind
is the operation kind (common kinds areopen
,close
,read
,write
,timeout
, andflush
).kind
can also bedefault
(default value for all kind), orall
(reset all cooldown values to this value). The cooldowns of the given kinds are usually called after the corresponding operation (it is necessary for some devices, otherwise the communication can freeze or crush). Default cooldown values are specified by_default_operation_cooldown
class attribute dictionary.
-
unlock
()¶ Unlock the access to the device from other threads/processes (isn’t necessarily implemented)
-
using_timeout
(timeout=None)¶ Context manager for usage of a different timeout inside a block
-
pylablib.core.devio.comm_backend.
autodetect_backend
(conn, default='visa')[source]¶ Try to determine the backend by the connection.
default specifies the default backend which is returned if the backend is unclear.
-
pylablib.core.devio.comm_backend.
new_backend
(conn, backend='auto', defaults=None, **kwargs)[source]¶ Build new backend with the supplied parameters.
Parameters: - conn – Connection parameters (depend on the backend). Can be simply connection parameters (tuple or dict) for the given backend
(e.g.,
"192.168.0.1"
or("COM1",19200)
), a tuple(backend, conn)
which specifies both backend and connection (in which case it overrides the supplied backend), or an already opened backend (in which case it is returned as is) - backend (str) – Backend type. Available backends are
'auto'
(try to autodetect based on the connection),'visa'
,'serial'
,'ft232'
,'network'
, and"pyusb"
. Can also be directly a backend class (more appropriate for custom backends), or a tuple('auto', backend)
, which is analogous to'auto'
, but it returns the specifiedbackend
if the autodetection fails; by default, the fallback backend is'visa'
, so'auto'
is exactly the same as('auto', 'visa')
. - defaults – if not
None
, specifies a dictionary{backend: params}
with default connection parameters (depending on the backend), which are added to the connection parameters - **kwargs – parameters sent to the backend.
- conn – Connection parameters (depend on the backend). Can be simply connection parameters (tuple or dict) for the given backend
(e.g.,
-
pylablib.core.devio.comm_backend.
backend_error
(backend, conn=None)[source]¶ Return error class corresponding to the current backend.
Like
new_backend()
, allows settingbackend="auto"
, in which case conn is used to try and autodetect the backend kind (not completely reliable, should be avoided).
-
pylablib.core.devio.comm_backend.
list_backend_resources
(backend=None, desc=False)[source]¶ List all resources for the given backend.
If backend is
None
, return dictionary{backend: resources}
for all available backends. Ifdesc==False
, return list of connections (usually strings or tuples), which can be used to connect to the device. Otherwise, return a list of descriptions, which have more info, but can be backend-dependent.
-
class
pylablib.core.devio.comm_backend.
ICommBackendWrapper
(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). -
class
NoParameterCaller
(device, kind)¶ Bases:
object
Class to simplify calling functions without a parameter
-
apply_settings
(settings)¶ Apply the settings.
settings is the dict
{name: value}
of the device available settings. Non-applicable settings are ignored.
-
get_device_variable
(key)¶ Get the value of a settings, status, or full info parameter
-
get_full_info
(include=0)¶ Get dict
{name: value}
containing full device information (including status and settings).include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or
"all"
(all available variables). Since the lowest priority is -10, settinginclude=-10
queries all available variables, which is equivalent toinclude="all"
.
-
get_full_status
(include=0)¶ Get dict
{name: value}
containing the device status (including settings).include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or
"all"
(all available variables). Since the lowest priority is -10, settinginclude=-10
queries all available variables, which is equivalent toinclude="all"
.
-
get_settings
(include=0)¶ Get dict
{name: value}
containing all the device settings.include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or
"all"
(all available variables). Since the lowest priority is -10, settinginclude=-10
queries all available variables, which is equivalent toinclude="all"
.
-
set_device_variable
(key, value)¶ Set the value of a settings parameter
-
lock
(timeout=None)[source]¶ Lock the access to the device from other threads/processes (isn’t necessarily implemented)
-
class
pylablib.core.devio.data_format module¶
Library for binary data encoding/decoding for device communication and dealing with different data format representations in different contexts (numpy, SCPI, etc.).
-
class
pylablib.core.devio.data_format.
DataFormat
(size, kind, byteorder)[source]¶ Bases:
object
Describes data encoding for device communications.
Parameters: -
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_to_str
(data, ascii_format='.5f')[source]¶ Convert the array into a string data.
ascii_format is the
str.format()
string for textual representation.
-
static
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.
-
class
NoParameterCaller
(device, kind)[source]¶ Bases:
object
Class to simplify calling functions without a parameter
-
get_settings
(include=0)[source]¶ Get dict
{name: value}
containing all the device settings.include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or
"all"
(all available variables). Since the lowest priority is -10, settinginclude=-10
queries all available variables, which is equivalent toinclude="all"
.
-
get_full_status
(include=0)[source]¶ Get dict
{name: value}
containing the device status (including settings).include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or
"all"
(all available variables). Since the lowest priority is -10, settinginclude=-10
queries all available variables, which is equivalent toinclude="all"
.
-
get_full_info
(include=0)[source]¶ Get dict
{name: value}
containing full device information (including status and settings).include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or
"all"
(all available variables). Since the lowest priority is -10, settinginclude=-10
queries all available variables, which is equivalent toinclude="all"
.
-
class
-
class
pylablib.core.devio.interface.
IParameterClass
(name)[source]¶ Bases:
object
A generic parameter class.
Deals with converting device interface representation and the ‘internal’ representation (e.g., names used in SCPI commands or integer indices). Also responsible for validating the user-passed and device-returned parameters.
Needs to define to methods:
__call__
for converting user parameters (‘alias’) into the device parameters (‘value’) andi()
for the opposite conversion. In addition, it providesusing_device()
context manager to temporarily change thedevice
attribute, which can be used by some parameter classes for device-dependent conversions.Parameters: name – parameter class name; used to match method arguments with corresponding classes.
-
class
pylablib.core.devio.interface.
ICheckingParameterClass
(name)[source]¶ Bases:
pylablib.core.devio.interface.IParameterClass
Parameter class which separately handles checking and conversion.
Specifies six methods:
check_value()
,to_alias()
and_value_error_str
for handling value-to-alias conversion, andcheck_alias()
,to_value()
and_alias_error_str
for handling alias-to-value conversion.-
i
(value, device=None)[source]¶ Convert device parameter value into a corresponding use parameter value
If not
None
, device specifies the corresponding device instance for device-dependent conversion.
-
docstring
()¶ Get a parameter docstring
-
using_device
(device)¶ Context manager for temporarily changing the
device
attribute to the given device instance
-
-
class
pylablib.core.devio.interface.
RangeParameterClass
(name, minval=None, maxval=None, out_of_range='error')[source]¶ Bases:
pylablib.core.devio.interface.ICheckingParameterClass
Parameter class for numerical values constrained to a certain range.
Parameters: - name – parameter class name
- minval – minimal allowed value (inclusive);
None
means no lower limit - maxval – maximal allowed value (inclusive);
None
means no upper limit - out_of_range – action if an out-of-range value is supplied; can be either
"error"
(raise an error), or"truncate"
(truncate to the nearest limit).
-
i
(value, device=None)¶ Convert device parameter value into a corresponding use parameter value
If not
None
, device specifies the corresponding device instance for device-dependent conversion.
-
to_alias
(value)¶ Convert the device value into an alias
-
using_device
(device)¶ Context manager for temporarily changing the
device
attribute to the given device instance
-
class
pylablib.core.devio.interface.
IEnumParameterClass
(name, allowed_alias='device_values', allowed_value='exact', alias_case=None, value_case=None, match_prefix=False)[source]¶ Bases:
pylablib.core.devio.interface.ICheckingParameterClass
Parameter class for a generic enum (i.e., predefined values) parameter.
- Defines two methods for handling conversion:
_get_value_map
which returns a dictionary for converting device values into aliases,_get_alias_map
which returns a dictionary for converting aliases into device values.
These methods need to be redefined in subclasses.
Parameters: - name – parameter class name
- allowed_alias – specifies a range of allowed aliases; can be
"exact"
(only exact map matches are allowed),"device_value"
(exact map matches and raw device values are allowed), or"all"
(all values are allowed); in the latter two cases the value not in the map are passed as is. - allowed_value – specifies a range of allowed device values; can be
"exact"
(only exact map matches are allowed), or"all"
(all values are allowed); in the latter case the value not in the map is passed as is. - alias_case – default alias parameter case for string values; can be
None
(no case normalization), or"lower"
or"upper"
(any received or returned alias will be normalized into this case) - value_case – default value parameter case for string values; can be
None
(no case normalization), or"lower"
or"upper"
(any received or returned device value will be normalized into this case) - match_prefix – if
True
, then the keys in the value map (returned by_get_value_map
method) are interpreted as prefixes, so in the value-to-alias conversion the converted value matches the map value if it just starts with it; in the case of ambiguity (several map values are prefixes for the same converted value), the exact match takes priority; useful for some SCPI devices, where the shorter version of the value can sometimes be returned.
-
docstring
()¶ Get a parameter docstring
-
i
(value, device=None)¶ Convert device parameter value into a corresponding use parameter value
If not
None
, device specifies the corresponding device instance for device-dependent conversion.
-
using_device
(device)¶ Context manager for temporarily changing the
device
attribute to the given device instance
-
class
pylablib.core.devio.interface.
EnumParameterClass
(name, alias_map, value_map=None, allowed_alias='device_values', allowed_value='exact', alias_case=None, value_case=None, match_prefix=False)[source]¶ Bases:
pylablib.core.devio.interface.IEnumParameterClass
Parameter class for a enum (i.e., predefined values) parameter with the specified mapping.
Parameters: - name – parameter class name
- alias_map – mapping of aliases to device values; can be a dictionary, or a list of
(alias,value)
tuples (in the latter case non-tuple values are also allowed, indicating that value is the same as the alias); the list representation is useful in cases where the same alias maps to more than one value, so the map inversion is impossible - value_map – mapping of device values to aliases; can only be a dictionary or
None
, which means that the alias map is automatically inverted - allowed_alias – specifies a range of allowed aliases; can be
"exact"
(only exact map matches are allowed),"device_value"
(exact map matches and raw device values are allowed), or"all"
(all values are allowed); in the latter two cases the value not in the map are passed as is. - allowed_value – specifies a range of allowed device values; can be
"exact"
(only exact map matches are allowed), or"all"
(all values are allowed); in the latter case the value not in the map is passed as is. - alias_case – default alias parameter case for string values; can be
None
(no case normalization), or"lower"
or"upper"
(any received or returned alias will be normalized into this case) - value_case – default value parameter case for string values; can be
None
(no case normalization), or"lower"
or"upper"
(any received or returned device value will be normalized into this case) - match_prefix – if
True
, then the keys in the value map (or values in the alias map, if only it is provided) are assumed to br prefixes, so in the value-to-alias conversion the converted value matches the map value if it just starts with it; useful for some SCPI devices, where the shorter version of the value can sometimes be returned.
-
check_alias
(alias)¶ Check if the alias is valid
-
check_value
(value)¶ Check if the device value is valid
-
docstring
()¶ Get a parameter docstring
-
i
(value, device=None)¶ Convert device parameter value into a corresponding use parameter value
If not
None
, device specifies the corresponding device instance for device-dependent conversion.
-
to_alias
(value)¶ Convert the device value into an alias
-
to_value
(alias)¶ Convert the alias into a device value
-
using_device
(device)¶ Context manager for temporarily changing the
device
attribute to the given device instance
-
class
pylablib.core.devio.interface.
FunctionParameterClass
(name, to_alias=None, to_value=None, check_value=None, check_alias=None, alias_err=None, value_err=None)[source]¶ Bases:
pylablib.core.devio.interface.ICheckingParameterClass
Parameter class which uses supplied methods for checking, conversion, and generating error messages.
The arguments correspond to the parameter methods with the same names. When not supplied, checking methods always return
True
, conversion methods leave value intact, and error string methods generate the default error messages.-
docstring
()¶ Get a parameter docstring
-
i
(value, device=None)¶ Convert device parameter value into a corresponding use parameter value
If not
None
, device specifies the corresponding device instance for device-dependent conversion.
-
using_device
(device)¶ Context manager for temporarily changing the
device
attribute to the given device instance
-
-
class
pylablib.core.devio.interface.
CombinedParameterClass
(name, parameters)[source]¶ Bases:
pylablib.core.devio.interface.IParameterClass
A multi-stage combined parameter class, which performs several conversion/check stages.
Parameters: - name – parameter class name
- parameters – list of parameters classes which are combined; the order is from the ‘most alias’ to the ‘most device parameter’, i.e., when converting an alias to a device parameter, it is first passed to the first class, then the second, etc. (the reverse is done when converting device values into aliases)
-
docstring
()¶ Get a parameter docstring
-
i
(value, device=None)[source]¶ Convert device parameter value into a corresponding use parameter value
If not
None
, device specifies the corresponding device instance for device-dependent conversion.
-
using_device
(device)¶ Context manager for temporarily changing the
device
attribute to the given device instance
-
class
pylablib.core.devio.interface.
TRawParameterValue
(value)¶ Bases:
tuple
-
count
()¶ Return number of occurrences of value.
-
index
()¶ Return first index of value.
Raises ValueError if the value is not present.
-
value
¶
-
-
pylablib.core.devio.interface.
pval
(value)[source]¶ Mark that the value has already been treated by the parameter class
-
pylablib.core.devio.interface.
use_parameters
(*args, **kwargs)[source]¶ Wrapper to indicate that a device class method uses device parameter classes.
The corresponding parameters classes are automatically determined if the argument name matches the parameter class name. The parameters classes can also be defined explicitly using keywords arguments
arg=parameter
supplied to the wrapper, wherearg
is the argument, andparameter
is either a parameter class instance, or a parameter class name (the more preferable way). In addition, an argument_returns
can be used to define the parameter class for the return value; it can also be a list or a tuple of parameter classes, indicating that the returned value is also a list or a tuple.