RsInstrument package

Modules

RsInstrument.RsInstrument

Root class for remote-controlling instrument with SCPI commands.

class RsInstrument(resource_name: str, id_query: bool = True, reset: bool = False, options: str = None, direct_session: object = None)[source]

Bases: object

Root class for remote-controlling instrument with SCPI commands.

Initializes new RsInstrument session.

Parameters:
  • resource_name – VISA resource name, e.g. ‘TCPIP::192.168.2.1::INSTR’

  • id_query – if True, the instrument’s model name is verified against the models supported by the driver and eventually throws an exception

  • reset – Resets the instrument (sends *RST) command and clears its status syb-system

  • direct_session – Another driver object or pyVisa object to reuse the session instead of opening a new session

  • options – string tokens alternating the driver settings

Parameter options tokens examples:
  • Simulate=True - starts the session in simulation mode. Default: False

  • SelectVisa=socketio - uses no VISA implementation for socket connections - you do not need any VISA-C installation

  • SelectVisa=rs - forces usage of RohdeSchwarz Visa

  • SelectVisa=ni - forces usage of National Instruments Visa

  • Profile = HM8123 - setting profile fitting the specific non-standard instruments. Available values: HM8123, CMQ, ATS, Minimal. Default: none

  • OpenTimeout=5000 - sets timeout used at the session opening. Default: 0

  • ExclusiveLock=True - opens the session with exclusive lock on the VISA level. Default: False

  • QueryInstrumentStatus = False - same as driver.utilities.instrument_status_checking = False. Default: True

  • WriteDelay = 20, ReadDelay = 5 - introduces delay of 20ms before each write and 5ms before each read. Default: 0ms for both

  • TerminationCharacter = "\r" - sets the termination character for reading. Default: \n (LineFeed or LF)

  • AssureWriteWithTermChar = True - makes sure each command/query is terminated with termination character. Default: Interface dependent

  • AddTermCharToWriteBinBlock = True - adds one additional LF to the end of the binary data (some instruments require that). Default: False

  • DataChunkSize = 10E3 - maximum size of one write/read segment. If transferred data is bigger, it is split to more segments. Default: 1E7 bytes

  • OpcTimeout = 10000 - same as driver.utilities.opc_timeout = 10000. Default: 30000ms

  • VisaTimeout = 5000 - same as driver.utilities.visa_timeout = 5000. Default: 10000ms

  • ViClearExeMode = Disabled - viClear() execution mode. Default: execute_on_all

  • OpcQueryAfterWrite = True - same as driver.utilities.opc_query_after_write = True. Default: False

  • OpcWaitMode = OpcQuery - mode for all the opc-synchronised write/reads. Other modes: StbPolling, StbPollingSlow, StbPollingSuperSlow. Default: StbPolling

  • StbInErrorCheck = False - if true, the driver checks errors with *STB? If false, it uses SYST:ERR?. Default: True

  • SkipStatusSystemSettings = False - some instruments do not support full status system commands. In such case, set this value to True. Default: False

  • SkipClearStatus = True - set to True for instruments that do not support *CLS command. Default: False

  • DisableOpcQuery = True - set to True for instruments that do not support *OPC? query. Default: False

  • EachCmdAsQuery = True, set to True, for instruments that always return answer. Default: false

  • CmdIdn = ID? - defines which SCPI command to use for identification query. Default: \*IDN?

  • CmdReset = RT - defines which SCPI command to use for reset. Default: \*RST

  • VxiCapable = false - you can force a session to a VXI-incapable. Default: <interface-dependent>

  • Encoding = utf-8 - setting of encoding for strings into bytes and vice-versa. Default: charmap

  • OpcSyncQueryMechanism = AlsoCheckMav - setting of mechanism for OPC-synchronised queries. Default: OnlyCheckMavErrQueue

  • LoggingMode = On - sets the logging status right from the start. Possible values: On | Off | Error. Default: Off

  • LoggingName = 'MyDevice' - sets the name to represent the session in the log entries. Default: <resource_name>

  • LogToGlobalTarget = True - sets the logging target to the class-property previously set with RsInstrument.set_global_logging_target() Default: False

  • LoggingToConsole = True - immediately starts logging to the console. Default: False

  • LoggingToUdp = True - immediately starts logging to the UDP port. Default: False

  • LoggingUdpPort = 49200 - UDP port to log to. Default: 49200

static assert_minimum_version(min_version: str) None[source]

Asserts that the driver version fulfills the minimum required version you have entered. This way you make sure your installed driver is of the entered version or newer.

assign_lock(lock: RLock) None[source]

Assigns the provided thread lock.

property bin_float_numbers_format: BinFloatFormat

Sets / returns format of float numbers when transferred as binary data

property bin_int_numbers_format: BinIntFormat

Sets / returns format of integer numbers when transferred as binary data

classmethod clear_global_logging_relative_timestamp() None[source]

Clears the global relative timestamp. After this, all the instances using the global relative timestamp continue logging with the absolute timestamps.

clear_lock() None[source]

Clears the existing thread lock, making the current session thread-independent from others that might share the current thread lock.

clear_status() None[source]

Clears instrument’s status system, the session’s I/O buffers and the instrument’s error queue

close() None[source]

Closes the active RsInstrument session

property data_chunk_size: int

Returns max chunk size of one data block.

property driver_version: str

Returns the instrument driver version

property encoding: str

Returns string<=>bytes encoding of the session.

property events: Events

Interface for event handlers, see here

file_exists(instr_file: str) bool[source]

Returns true, if the instrument file exist.

classmethod from_existing_session(session: object, options: str = None) RsInstrument[source]

Creates a new RsInstrument object with the entered ‘session’ reused. :param session: can be another driver or a direct pyvisa session :param options: string tokens alternating the driver settings

property full_instrument_model_name: str

Returns the current instrument’s full name e.g. ‘FSW26’

get_file_size(instr_file: str) int[source]

Return size of the instrument file, or None if the file does not exist.

classmethod get_global_logging_relative_timestamp() datetime[source]

Returns global common relative timestamp for log entries.

classmethod get_global_logging_target()[source]

Returns global common target stream.

get_last_sent_cmd() str[source]

Returns the last commands sent to the instrument. Only works in simulation mode.

get_lock() RLock[source]

Returns the thread lock for the current session.

By default:

  • If you create a new RsInstrument instance with new VISA session, the session gets a new thread lock. You can assign it to another RsInstrument sessions in order to share one physical instrument with a multi-thread access.

  • If you create a new RsInstrument from an existing session, the thread lock is shared automatically making both instances multi-thread safe.

You can always assign new thread lock by calling driver.utilities.assign_lock()

get_session_handle()[source]

Returns the underlying pyvisa session

get_total_execution_time() timedelta[source]

Returns total time spent by the library on communicating with the instrument. This time is always shorter than get_total_time(), since it does not include gaps between the communication. You can reset this counter with reset_time_statistics().

get_total_time() timedelta[source]

Returns total time spent by the library on communicating with the instrument. This time is always shorter than get_total_time(), since it does not include gaps between the communication. You can reset this counter with reset_time_statistics().

get_total_time_startpoint() datetime[source]

Returns time from which the execution started. This is the value that the get_total_time() calculates as its reference. Calling the reset_time_statistics() sets this time to now.

go_to_local() None[source]

Puts the instrument into local state.

go_to_remote() None[source]

Puts the instrument into remote state.

property idn_string: str

Returns instrument’s identification string - the response on the SCPI command *IDN?

property instrument_firmware_version: str

Returns instrument’s firmware version

property instrument_model_name: str

Returns the current instrument’s family name e.g. ‘FSW’

property instrument_options: List[str]

Returns all the instrument options. The options are sorted in the ascending order starting with K-options and continuing with B-options

property instrument_serial_number: str

Returns instrument’s serial_number

property instrument_status_checking: bool

Sets / returns Instrument Status Checking. When True (default is True), all the driver methods and properties are sending “SYSTem:ERRor?” at the end to immediately react on error that might have occurred. We recommend keeping the state checking ON all the time. Switch it OFF only in rare cases when you require maximum speed. The default state after initializing the session is ON.

is_connection_active() bool[source]

Returns true, if the VISA connection is active and the communication with the instrument still works.

static list_resources(expression: str = '?*::INSTR', visa_select: str = None) List[str][source]

Finds all the resources defined by the expression.

  • ‘?*’ - matches all the available instruments

  • ‘USB::?*’ - matches all the USB instruments

  • ‘TCPIP::192?*’ - matches all the LAN instruments with the IP address starting with 192

Parameters:
  • expression – see the examples in the function

  • visa_select – optional parameter selecting a specific VISA. Examples: @ivi’, @rs

lock_resource(timeout: int, requested_key: str = None) bytes[source]

Locks the instrument to prevent it from communicating with other clients.

property logger: ScpiLogger

Scpi Logger interface, see here

property manufacturer: str

Returns manufacturer of the instrument

property opc_query_after_write: bool

Sets / returns Instrument *OPC? query sending after each command write. When True, (default is False) the driver sends *OPC? every time a write command is performed. Use this if you want to make sure your sequence is performed command-after-command.

property opc_sync_query_mechanism: OpcSyncQueryMechanism

Returns the current setting of the OPC-Sync query mechanism.

property opc_timeout: int

Sets / returns timeout in milliseconds for all the operations that use OPC synchronization.

process_all_commands() None[source]

SCPI command: *WAI Stops further commands processing until all commands sent before *WAI have been executed.

query(query: str) str[source]

Sends the string query to the instrument and returns the response as string. The response is trimmed of any trailing LF characters and has no length limit. This method is an alias to the query_str() method.

query_all_errors() List[str][source]

Queries and clears all the errors from the instrument’s error queue. The method returns list of strings as error messages. If no error is detected, the return value is None. The process is: querying ‘SYSTem:ERRor?’ in a loop until the error queue is empty. If you want to include the error codes, call the query_all_errors_with_codes()

query_all_errors_with_codes() List[Tuple[int, str]][source]

Queries and clears all the errors from the instrument’s error queue. The method returns list of tuples (code: int, message: str). If no error is detected, the return value is None. The process is: querying ‘SYSTem:ERRor?’ in a loop until the error queue is empty.

query_bin_block(query: str) bytes[source]

Queries binary data block to bytes. Throws an exception if the returned data was not a binary data. Returns data:bytes

query_bin_block_to_file(query: str, file_path: str, append: bool = False) None[source]

Queries binary data block to the provided file. If append is False, any existing file content is discarded. If append is True, the new content is added to the end of the existing file, or if the file does not exit, it is created. Throws an exception if the returned data was not a binary data. Example for transferring a file from Instrument -> PC: query = f”MMEM:DATA? ‘{INSTR_FILE_PATH}’”.

Alternatively, use the dedicated methods for this purpose:

  • send_file_from_pc_to_instrument()

  • read_file_from_instrument_to_pc()

query_bin_block_to_file_with_opc(query: str, file_path: str, append: bool = False, timeout: int = None) None[source]

Sends a OPC-synced query and writes the returned data to the provided file. If append is False, any existing file content is discarded. If append is True, the new content is added to the end of the existing file, or if the file does not exit, it is created. Throws an exception if the returned data was not a binary data.

query_bin_block_with_opc(query: str, timeout: int = None) bytes[source]

Sends a OPC-synced query and returns binary data block to bytes. If you do not provide timeout, the method uses current opc_timeout.

query_bin_or_ascii_float_list(query: str) List[float][source]

Queries a list of floating-point numbers that can be returned as ASCII or binary format.

  • For ASCII format, the list numbers are decoded as comma-separated values.

  • For Binary Format, the numbers are decoded based on the property BinFloatFormat, usually float 32-bit (FORM REAL,32).

query_bin_or_ascii_float_list_with_opc(query: str, timeout: int = None) List[float][source]

Sends a OPC-synced query and reads a list of floating-point numbers that can be returned as ASCII or binary format.

  • For ASCII format, the list numbers are decoded as comma-separated values.

  • For Binary Format, the numbers are decoded based on the property BinFloatFormat, usually float 32-bit (FORM REAL,32).

If you do not provide timeout, the method uses current opc_timeout.

query_bin_or_ascii_int_list(query: str) List[int][source]

Queries a list of floating-point numbers that can be returned as ASCII or binary format.

  • For ASCII format, the list numbers are decoded as comma-separated values.

  • For Binary Format, the numbers are decoded based on the property BinFloatFormat, usually float 32-bit (FORM REAL,32).

query_bin_or_ascii_int_list_with_opc(query: str, timeout: int = None) List[int][source]

Sends a OPC-synced query and reads a list of floating-point numbers that can be returned as ASCII or binary format.

  • For ASCII format, the list numbers are decoded as comma-separated values.

  • For Binary Format, the numbers are decoded based on the property BinFloatFormat, usually float 32-bit (FORM REAL,32).

If you do not provide timeout, the method uses current opc_timeout.

query_bool(query: str) bool[source]

Sends the query to the instrument and returns the response as boolean.

query_bool_list(query: str) List[bool][source]

Sends the string query to the instrument and returns the response as List of booleans, where the delimiter is comma (‘,’).

query_bool_list_with_opc(query: str, timeout: int = None) List[bool][source]

Sends a OPC-synced query and reads response from the instrument as csv-list of booleans. If you do not provide timeout, the method uses current opc_timeout.

query_bool_with_opc(query: str, timeout: int = None) bool[source]

Sends the opc-synced query to the instrument and returns the response as boolean. If you do not provide timeout, the method uses current opc_timeout.

query_float(query: str) float[source]

Sends the query to the instrument and returns the response as float.

query_float_with_opc(query: str, timeout: int = None) float[source]

Sends the opc-synced query to the instrument and returns the response as float. If you do not provide timeout, the method uses current opc_timeout.

query_int(query: str) int[source]

Sends the query to the instrument and returns the response as integer.

query_int_with_opc(query: str, timeout: int = None) int[source]

Sends the opc-synced query to the instrument and returns the response as integer. If you do not provide timeout, the method uses current opc_timeout.

query_opc(timeout: int = 0) int[source]

SCPI command: *OPC? Queries the instrument’s OPC bit and hence it waits until the instrument reports operation complete. If you define timeout > 0, the VISA timeout is set to that value just for this method call.

query_str(query: str) str[source]

Sends the string query to the instrument and returns the response as string. The response is trimmed of any trailing LF characters and has no length limit. This method is an alias to the query() method.

query_str_list(query: str) List[str][source]

Sends the string query to the instrument and returns the response as List of strings, where the delimiter is comma (‘,’). Each element of the list is trimmed for leading and trailing quotes.

query_str_list_with_opc(query: str, timeout: int = None) List[str][source]

Sends a OPC-synced query and reads response from the instrument as csv-list. If you do not provide timeout, the method uses current opc_timeout.

query_str_stripped(query: str) str[source]

Sends the string query to the instrument and returns the response as string stripped of the trailing LF and leading/trailing single/double quotes. The stripping of the leading/trailing quotes is blocked, if the string contains the quotes in the middle. This method is an alias to the query_stripped() method.

query_str_with_opc(query: str, timeout: int = None) str[source]

Sends the opc-synced query to the instrument and returns the response as string. The response is trimmed of any trailing LF characters and has no length limit. If you do not provide timeout, the method uses current opc_timeout.

query_stripped(query: str) str[source]

Sends the string query to the instrument and returns the response as string stripped of the trailing LF and leading/trailing single/double quotes. The stripping of the leading/trailing quotes is blocked, if the string contains the quotes in the middle.

query_with_opc(query: str, timeout: int = None) str[source]

This method is an alias to the write_str_with_opc(). Sends the opc-synced query to the instrument and returns the response as string. The response is trimmed of any trailing LF characters and has no length limit. If you do not provide timeout, the method uses current opc_timeout.

read_file_from_instrument_to_pc(source_instr_file: str, target_pc_file: str, append_to_pc_file: bool = False) None[source]

SCPI Command: MMEM:DATA?

Reads file from instrument to the PC.

Set the append_to_pc_file to True if you want to append the read content to the end of the existing PC file.

reconnect(force_close: bool = False) bool[source]

If the connection is not active, the method tries to reconnect to the device. If the connection is active, and force_close is False, the method does nothing. If the connection is active, and force_close is True, the method closes, and opens the session again. Returns True, if the reconnection has been performed.

reset(timeout: int = 0) None[source]

SCPI command: *RST Sends *RST command + calls the clear_status(). If you define timeout > 0, the VISA timeout is set to that value just for this method call.

reset_time_statistics() None[source]

Resets all execution and total time counters. Affects the results of get_total_time(), get_total_execution_time() and get_total_time_startpoint()

property resource_name: str

Returns the resource name used in the constructor.

self_test(timeout: int = None) Tuple[int, str][source]

SCPI command: *TST? Performs instrument’s self-test. Returns tuple (code:int, message: str). Code 0 means the self-test passed. You can define the custom timeout in milliseconds. If you do not define it, the method uses default self-test timeout (usually 60 secs).

send_file_from_pc_to_instrument(source_pc_file: str, target_instr_file: str) None[source]

SCPI Command: MMEM:DATA

Sends file from PC to the instrument.

classmethod set_global_logging_relative_timestamp(timestamp: datetime) None[source]

Sets global common relative timestamp for log entries. To use it, call the following: io.logger.set_relative_timestamp_global()

classmethod set_global_logging_relative_timestamp_now() None[source]

Sets global common relative timestamp for log entries to this moment. To use it, call the following: io.logger.set_relative_timestamp_global().

classmethod set_global_logging_target(target) None[source]

Sets global common target stream that each instance can use. To use it, call the following: io.logger.set_logging_target_global(). If an instance uses global logging target, it automatically uses the global relative timestamp (if set). You can set the target to None to invalidate it.

property supported_models: List[str]

Returns a list of the instrument models supported by this instrument driver

unlock_resource() None[source]

Unlocks the instrument to other clients.

property visa_manufacturer: str

Returns the manufacturer of the current VISA session.

property visa_timeout: int

Sets / returns visa IO timeout in milliseconds.

write(cmd: str) None[source]

Writes the command to the instrument as string. This method is an alias to the write_str() method.

write_bin_block(cmd: str, payload: bytes) None[source]

Writes all the payload as binary data block to the instrument. The binary data header is added at the beginning of the transmission automatically, do not include it in the payload!!!

write_bin_block_from_file(cmd: str, file_path: str) None[source]

Writes data from the file as binary data block to the instrument using the provided command. Example for transferring a file from PC -> Instrument: cmd = f”MMEM:DATA ‘{INSTR_FILE_PATH}’,”.

Alternatively, use the dedicated methods for this purpose:

  • send_file_from_pc_to_instrument()

  • read_file_from_instrument_to_pc()

write_bool(cmd: str, param: bool) None[source]

Writes the command to the instrument followed by the boolean parameter: e.g.: cmd = ‘OUTPUT’ param = ‘True’, result command = ‘OUTPUT ON’

write_bool_with_opc(cmd: str, param: bool, timeout: int = None) None[source]

Writes the command with OPC to the instrument followed by the boolean parameter: e.g.: cmd = ‘OUTPUT’ param = ‘True’, result command = ‘OUTPUT ON’ If you do not provide timeout, the method uses current opc_timeout.

write_float(cmd: str, param: float) None[source]

Writes the command to the instrument followed by the boolean parameter: e.g.: cmd = ‘CENTER:FREQ’ param = ‘10E6’, result command = ‘CENTER:FREQ 10E6’

write_float_with_opc(cmd: str, param: float, timeout: int = None) None[source]

Writes the command with OPC to the instrument followed by the boolean parameter: e.g.: cmd = ‘CENTER:FREQ’ param = ‘10E6’, result command = ‘CENTER:FREQ 10E6’ If you do not provide timeout, the method uses current opc_timeout.

write_int(cmd: str, param: int) None[source]

Writes the command to the instrument followed by the integer parameter: e.g.: cmd = ‘SELECT:INPUT’ param = ‘2’, result command = ‘SELECT:INPUT 2’

write_int_with_opc(cmd: str, param: int, timeout: int = None) None[source]

Writes the command with OPC to the instrument followed by the integer parameter: e.g.: cmd = ‘SELECT:INPUT’ param = ‘2’, result command = ‘SELECT:INPUT 2’ If you do not provide timeout, the method uses current opc_timeout.

write_str(cmd: str) None[source]

Writes the command to the instrument as string. This method is an alias to write() method.

write_str_with_opc(cmd: str, timeout: int = None) None[source]

Writes the opc-synced command to the instrument. If you do not provide timeout, the method uses current opc_timeout.

write_with_opc(cmd: str, timeout: int = None) None[source]

This method is an alias to the write_str_with_opc(). Writes the opc-synced command to the instrument. If you do not provide timeout, the method uses current opc_timeout.

Module contents

VISA communication interface for SCPI-based instrument remote control. :version: 1.60.0 :copyright: 2020 by Rohde & Schwarz GMBH & Co. KG :license: MIT, see LICENSE for more details.