### Standard Session Initialization Example Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/docs/source/Chapter_04_InitiateSession.rst Demonstrates the basic instantiation of an RsInstrument object to establish a remote-control session with an instrument. It shows how to connect using a resource string and highlights common identification properties accessible after connection. ```python from RsInstrument import * try: # Example for TCPIP connection using HiSLIP protocol instr = RsInstrument('TCPIP::192.168.56.101::hislip0') # Access identification properties print(f"IDN String: {instr.idn_string}") print(f"Driver Version: {instr.driver_version}") print(f"Visa Manufacturer: {instr.visa_manufacturer}") print(f"Instrument Model: {instr.full_instrument_model_name}") print(f"Serial Number: {instr.instrument_serial_number}") print(f"Firmware Version: {instr.instrument_firmware_version}") print(f"Instrument Options: {instr.instrument_options}") except Exception as e: print(f"An error occurred: {e}") finally: # Close the session if it was opened if 'instr' in locals() and instr.opened: instr.close() ``` -------------------------------- ### Selecting Specific VISA Implementation Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/docs/source/Chapter_04_InitiateSession.rst Illustrates how to specify a particular VISA library or implementation to be used by RsInstrument. This is useful when multiple VISA installations are present or a specific one is required. ```python from RsInstrument import * try: # Example: Specify a VISA library (e.g., 'rs') # Note: The actual VISA string might vary based on your installation instr = RsInstrument('TCPIP::192.168.56.101::hislip0', select_visa='rs') print("Instrument session initialized using a specific VISA.") except Exception as e: print(f"An error occurred: {e}") finally: if 'instr' in locals() and instr.opened: instr.close() ``` -------------------------------- ### Install RsInstrument using pip Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/docs/source/Chapter_02_Installation.rst Installs the RsInstrument Python package using the pip command-line tool. This method requires Python to be installed and accessible via the command console. ```shell cd c:\Users\John\AppData\Local\Programs\Python\Python310\Scripts ``` ```shell pip install RsInstrument ``` -------------------------------- ### Basic Hello-World Example Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/README.rst Demonstrates the fundamental usage of RsInstrument to connect to an instrument, query its identity, and print the response. Requires a valid instrument address. ```python from RsInstrument import * instr = RsInstrument('TCPIP::192.168.56.101::hislip0', id_query=True, reset=True) idn = instr.query_str('*IDN?') print('Hello, I am: ' + idn) ``` -------------------------------- ### Example: Minimal Logging Format Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/docs/source/Chapter_16_Logging.rst Demonstrates customizing the RsInstrument logging format to display only the start time, duration, and the SCPI command executed. This provides a concise log output. ```python import logging from RsInstrument import * # Define a minimal log format string # %START_TIME%, %DURATION%, %LOG_STRING% minimal_format = "%(START_TIME)s %(DURATION)s %(LOG_STRING)s" # Set the custom log format globally RsInstrument.set_log_format(minimal_format) # Configure logging level (e.g., to see commands) RsInstrument.set_log_level(logging.INFO) # Create an instrument session (replace with your instrument address) try: smw = RsInstrument("TCPIP::192.168.1.101::INSTR", True, True) print(f"Instrument connected: {smw.idn_string}") # Execute some commands smw.write("*RST") smw.query("*STB?") smw.query("*OPC?") smw.write("*CLS") smw.query("*STB?") except Exception as e: print(f"An error occurred: {e}") finally: if 'smw' in locals() and smw.opened: smw.close() print("Instrument session closed.") ``` -------------------------------- ### Offline RsInstrument Installation Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/docs/source/Chapter_02_Installation.rst Provides instructions for installing RsInstrument offline by downloading and executing a Python script. This method is useful for environments without internet access and requires Python 3.6 or newer. ```shell python rsinstrument_offline_install.py ``` -------------------------------- ### Simulating Session with Specific Options Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/docs/source/Chapter_04_InitiateSession.rst Shows how to initialize a simulated RsInstrument session with additional configuration options, such as selecting a specific VISA implementation alongside simulation. ```python from RsInstrument import * try: # Initialize with specific VISA and simulation enabled instr = RsInstrument('TCPIP::192.168.56.101::hislip0', True, True, "SelectVisa='rs', Simulate=True") print("Instrument session initialized with specific VISA and simulation.") except Exception as e: print(f"An error occurred: {e}") finally: if 'instr' in locals() and instr.opened: instr.close() ``` -------------------------------- ### Logger Methods: start() and stop() Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/README.rst Adds convenient `start()` and `stop()` methods to the logger for controlling logging operations, likely for starting and stopping log collection. ```APIDOC Added logger convenient methods start() and stop(). ``` -------------------------------- ### Simulating Instrument Session Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/docs/source/Chapter_04_InitiateSession.rst Demonstrates how to initialize RsInstrument in simulation mode. This is useful for development and testing without requiring a physical instrument, providing mock responses to commands. ```python from RsInstrument import * try: # Initialize in simulation mode instr = RsInstrument('TCPIP::192.168.56.101::hislip0', id_query=True, reset=True, simulate=True) print("Instrument session initialized in simulation mode.") # Example of simulated query idn_simulated = instr.query('*IDN?') print(f"Simulated *IDN?: {idn_simulated}") # Expected: 'Simulating' except Exception as e: print(f"An error occurred: {e}") finally: if 'instr' in locals() and instr.opened: instr.close() ``` -------------------------------- ### Example: Customizing Log String Info Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/docs/source/Chapter_16_Logging.rst Demonstrates how to customize the '%LOG_STRING_INFO%' part of the log format by providing custom strings, leading to more compact and specific log entries. ```python import logging from RsInstrument import * # Define a custom log format with a replacer for LOG_STRING_INFO # Example: 'W:' for Write, 'Q:' for Query, 'Cls:' for Close custom_format = "%(START_TIME)s %(DURATION)s %(LOG_STRING_INFO)s: %(LOG_STRING)s" # Configure logging level RsInstrument.set_log_level(logging.INFO) # Create an instrument session try: smw = RsInstrument("TCPIP::192.168.1.101::INSTR", True, True) print(f"Instrument connected: {smw.idn_string}") # Set custom log string info for different operations smw.set_log_string_info("Write", "W:") smw.set_log_string_info("Query", "Q:") smw.set_log_string_info("Close Session", "Close:") smw.set_log_string_info("Query Error", "Q_err:") # Example for error query smw.set_log_string_info("Query OPC", "Q_OPC:") smw.set_log_string_info("Write CLS", "Cls:") smw.set_log_string_info("Query Integer", "Q_integer:") # Execute commands with custom log string info smw.write("*RST") smw.query("*STB?") smw.query("*OPC?") smw.write("*CLS") smw.query("*STB?") smw.query("*STB?") # Example of repeated query smw.query("*STB?") # Example of repeated query except Exception as e: print(f"An error occurred: {e}") finally: if 'smw' in locals() and smw.opened: smw.close() print("Instrument session closed.") ``` -------------------------------- ### Session Initialization with id_query and reset Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/docs/source/Chapter_04_InitiateSession.rst Shows how to initialize an RsInstrument session with optional arguments for querying the instrument's identity and performing a reset. Setting `id_query=True` verifies compatibility, while `reset=True` performs a device reset. ```python from RsInstrument import * try: # Initialize with id_query=True and reset=True instr = RsInstrument('TCPIP::192.168.56.101::hislip0', id_query=True, reset=True) print("Instrument session initialized with ID query and reset.") except Exception as e: print(f"An error occurred: {e}") finally: if 'instr' in locals() and instr.opened: instr.close() ``` -------------------------------- ### Example: Logging Format via Constructor Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/docs/source/Chapter_16_Logging.rst Demonstrates setting a custom logging format directly within the RsInstrument constructor options string. This allows for immediate application of the desired log format upon session initialization. ```python import logging from RsInstrument import * # Define a minimal log format string minimal_format = "%(START_TIME)s %(DURATION)s %(LOG_STRING)s" # Configure logging level (e.g., to see commands) RsInstrument.set_log_level(logging.INFO) # Create an instrument session with custom log format in constructor try: # The format string is passed as part of the options string smw = RsInstrument("TCPIP::192.168.1.101::INSTR", True, True, f"LOG_FORMAT='{minimal_format}'") print(f"Instrument connected: {smw.idn_string}") # Execute some commands smw.write("*RST") smw.query("*STB?") smw.write("*CLS") except Exception as e: print(f"An error occurred: {e}") finally: if 'smw' in locals() and smw.opened: smw.close() print("Instrument session closed.") ``` -------------------------------- ### Console Output: Logging Format via Constructor Example Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/docs/source/Chapter_16_Logging.rst Shows the console output when the logging format is specified during the RsInstrument session initialization. Includes session initialization log entry. ```console 09:36:47.983 1210.274 ms @INIT_SESSION 09:36:49.193 81.984 ms *STB? 09:36:49.275 40.988 ms *RST 09:36:51.205 82.990 ms *CLS ``` -------------------------------- ### Console Output: Minimal Logging Format Example Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/docs/source/Chapter_16_Logging.rst Shows the console output when using a minimal logging format, displaying only the timestamp, duration, and the SCPI command for each operation. ```console 09:31:54.146 40.991 ms *RST 09:31:54.146 1939.319 ms *STB? 09:31:56.086 81.984 ms *OPC? 09:31:56.168 124.930 ms *CLS 09:31:56.293 82.015 ms *STB? ``` -------------------------------- ### Console Output Example Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/docs/source/Chapter_16_Logging.rst Illustrates typical console output from RsInstrument sessions, showing timestamps, instrument identifiers, communication times, and status messages. ```console 11:43:42.657 SMW 10.712 ms Session init: Device 'TCPIP::192.168.1.101::INSTR' IDN: Rohde&Schwarz,SMW200A,1412.0000K02/0,4.70.026 beta 11:43:42.668 SMW 2.928 ms Status check: OK 11:43:42.686 SMCV 1.952 ms Session init: Device 'TCPIP::192.168.1.102::INSTR' IDN: Rohde&Schwarz,SMCV100B,1432.7000K02/0,4.70.060.41 beta 11:43:42.688 SMCV 1.981 ms Status check: OK > Custom log from SMW session 11:43:42.690 SMW 0.973 ms Write: *RST 11:43:42.690 SMW 1874.658 ms Status check: OK 11:43:44.565 SMW 0.976 ms Query OPC: 1 11:43:44.566 SMW 1.952 ms Clear status: OK 11:43:44.568 SMW 2.928 ms Status check: OK > Custom log from SMCV session 11:43:44.571 SMCV 0.975 ms Query: *IDN? Rohde&Schwarz,SMCV100B,1432.7000K02/0,5.30.175.95 11:43:44.571 SMCV 1.951 ms Status check: OK 11:43:44.573 SMW 0.977 ms Close: Closing session 11:43:44.574 SMCV 0.976 ms Close: Closing session ``` -------------------------------- ### Global Logging Configuration Example Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/docs/source/Chapter_16_Logging.rst Demonstrates setting logging parameters as class variables to affect all RsInstrument instances globally, including relative timestamps. ```python import logging # Define a custom logger for global settings class GlobalInstrumentLogger(logging.Logger): def __init__(self, name, level=logging.NOTSET): super().__init__(name, level) # Example: Set a class variable for relative timestamp self.log_relative_time = True # You would typically integrate this with RsInstrument's logger setup # For demonstration, imagine RsInstrument uses this class or similar logic # Example of how the output might look with relative timestamps: # 00:00:00.000 SMW 117.739 ms Session init: Device 'TCPIP::192.168.1.101::hislip0' IDN: Rohde&Schwarz,SMW200A,1412.0000K02/0,5.30.305.44 # 00:00:00.119 SMW 0.982 ms Status check: OK # 00:00:00.120 SMCV 54.835 ms Session init: Device 'TCPIP::192.168.1.102::hislip0' IDN: Rohde&Schwarz,SMCV100B,1432.7000K02/0,5.30.175.95 ``` -------------------------------- ### Console Output: Customizing Log String Info Example Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/docs/source/Chapter_16_Logging.rst Displays console output with customized '%LOG_STRING_INFO%' fields, showing a more compact and user-defined prefix for each log entry. ```console 12:19:37.025 0.975 ms W: *RST 12:19:37.025 1879.123 ms Q_err: *STB? 12:19:38.905 0.976 ms Q_OPC: *OPC? 12:19:38.906 1.951 ms Cls: *CLS 12:19:38.908 0.000 ms Q_err: *STB? 12:19:38.908 1.007 ms Q: *IDN? 12:19:38.908 1.952 ms Q_err: *STB? 12:19:38.910 1.002 ms Q_integer: *STB? 12:19:38.910 1.984 ms Q_err: *STB? ``` -------------------------------- ### Simulated Session Response Behavior Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/docs/source/Chapter_04_InitiateSession.rst Explains the default return values for queries in a simulated RsInstrument session when no preceding set command has been issued. This behavior mimics instrument responses for development purposes. ```APIDOC Simulated Session Responses: When a command is written in simulation mode (e.g., **SENSe:FREQ 10MHz**), the subsequent query **SENSe:FREQ?** will return **10MHz**. For queries not preceded by set commands, RsInstrument returns default values: - String queries: **'Simulating'** - Integer queries: **0** - Float queries: **0.0** - Boolean queries: **False** ``` -------------------------------- ### Session Initialization using Context Manager Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/docs/source/Chapter_04_InitiateSession.rst Demonstrates using the RsInstrument session as a context manager with a `with` statement. This ensures the instrument session is automatically closed, even if errors occur within the block. ```python from RsInstrument import * try: with RsInstrument('TCPIP::192.168.56.101::hislip0') as instr: print("Instrument session opened within context manager.") # Perform instrument operations here print(f"IDN: {instr.idn_string}") # Session is automatically closed upon exiting the 'with' block print("Instrument session closed automatically.") except Exception as e: print(f"An error occurred: {e}") ``` -------------------------------- ### Instrument Identification Properties Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/docs/source/Chapter_04_InitiateSession.rst Lists common identification properties available on an RsInstrument object after a successful session initialization. These properties provide details about the connected instrument. ```python idn_string: str driver_version: str visa_manufacturer: str full_instrument_model_name: str instrument_serial_number: str instrument_firmware_version: str instrument_options: List[str] ``` -------------------------------- ### Shared Instrument Session Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/docs/source/Chapter_04_InitiateSession.rst Demonstrates how to share a single instrument session among multiple RsInstrument objects. This allows concurrent access to the same instrument without establishing redundant connections. ```python from RsInstrument import * try: # First instrument object holds the master session instr1 = RsInstrument('TCPIP::192.168.56.101::hislip0') print("instr1 session created.") # Second instrument object shares the same session instr2 = RsInstrument('TCPIP::192.168.56.101::hislip0', shared_session=instr1.session) print("instr2 session created, sharing session with instr1.") # Both objects can now interact with the instrument print(f"instr1 IDN: {instr1.idn_string}") print(f"instr2 IDN: {instr2.idn_string}") except Exception as e: print(f"An error occurred: {e}") finally: # Closing the master session (instr1) invalidates shared sessions if 'instr1' in locals() and instr1.opened: instr1.close() print("instr1 session closed.") # instr2 will likely fail if accessed after instr1.close() if 'instr2' in locals() and instr2.opened: instr2.close() print("instr2 session closed.") ``` -------------------------------- ### No VISA Session - Raw LAN Socket Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/docs/source/Chapter_04_InitiateSession.rst Shows how to establish a connection to an instrument using a raw LAN socket, bypassing the VISA layer. This method is an alternative for environments where VISA is not available or preferred. ```python from RsInstrument import * try: # Connect using raw socket (e.g., TCP/IP) instr = RsInstrument('TCPIP::192.168.56.101::hislip0', visa_library='') # Empty visa_library bypasses VISA print("Instrument session initialized using raw LAN socket.") except Exception as e: print(f"An error occurred: {e}") finally: if 'instr' in locals() and instr.opened: instr.close() ``` -------------------------------- ### RsInstrument Logging Configuration Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/docs/source/Chapter_16_Logging.rst API methods and options for configuring the logging behavior of RsInstrument. This includes starting logging, setting output targets, customizing formats, and managing time offsets. ```APIDOC RsInstrument.logger.start() - Starts the logger to capture SCPI communication. RsInstrument(..., stream_output=None, file_output=None) - stream_output: A stream-like object (e.g., sys.stdout) for logging. - file_output: A file-like object for logging. RsInstrument(..., options="LoggingMode=On") - Equivalent to calling instr.logger.start() after initialization. RsInstrument.set_time_offset_zero_on_first_entry() - Sets the time of the first log entry to 00:00:00.000, enabling relative time logging. - Equivalent to using the constructor option "LoggingRelativeTimeOfFirstEntry=True". RsInstrument.set_format_string(format_string) - Customizes the log message format. - Example format specifiers: %(asctime)s, %(name)s, %(levelname)s, %(message)s. RsInstrument.abbreviated_max_len_ascii RsInstrument.abbreviated_max_len_bin RsInstrument.abbreviated_max_len_list - Properties to set the maximum length for abbreviated ASCII, binary, and list data in log messages. ``` -------------------------------- ### VISA Timeout Suppression Example Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/README.rst Demonstrates how to use the `visa_tout_suppressor` context manager to ignore VISA timeout errors. It checks for suppressed timeouts after the block. ```python import io # Any Timeout error in the context is ignored with io.visa_tout_suppressor(500) as supp: io.write("*IDaN") if supp.get_timeout_occurred(): print("VISA Timeout suppressed") ``` -------------------------------- ### Example: Errors-Only Logging Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/docs/source/Chapter_16_Logging.rst Demonstrates the 'Errors-only' logging mode in RsInstrument. This mode logs entire segments of operations only if an error occurs within that segment, providing context for troubleshooting. ```python import logging from RsInstrument import * # Configure logging to show errors and context # Assuming RsInstrument is configured to log to console or a file # Example: RsInstrument.set_log_level(logging.DEBUG) # Create an instrument session (replace with your instrument address) try: smw = RsInstrument("TCPIP::192.168.1.101::INSTR", True, True) print(f"Instrument connected: {smw.idn_string}") # Deliberately misspell a SCPI command to trigger an error smw.write("*CLaS") # Incorrect command except Exception as e: print(f"An error occurred: {e}") finally: if 'smw' in locals() and smw.opened: smw.close() print("Instrument session closed.") ``` -------------------------------- ### Console Output: Errors-Only Logging Example Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/docs/source/Chapter_16_Logging.rst Illustrates the console output when an error occurs during an operation in 'Errors-only' logging mode. It shows the operation that led to the error and the subsequent status check error. ```console 12:11:02.879 TCPIP::192.168.1.101::INSTR 0.976 ms Write: *CLaS 12:11:02.879 TCPIP::192.168.1.101::INSTR 6.833 ms Status check: StatusException: Instrument error detected: Undefined header;*CLaS ``` -------------------------------- ### Settings: FirstCmds and EachCmdPrefix Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/README.rst Introduces two new settings: 'FirstCmds' for sending commands immediately after initialization, and 'EachCmdPrefix' for adding a prefix to every command sent to the instrument. ```APIDOC Added settings 'FirstCmds': - Allows sending defined commands right after the init. - Supports multiple commands separated by ';;'. Added settings 'EachCmdPrefix': - Adds a prefix to each command sent to the instrument. - Supported values include 'lf', 'cr', 'tab'. ``` -------------------------------- ### RsInstrument Session-Specific Time Statistics Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/docs/source/Chapter_16_Logging.rst Access and manage time-related statistics for an RsInstrument session. This includes retrieving total execution times, start points, and resetting the statistics. ```APIDOC InstrumentSession: get_total_execution_time() -> timedelta Returns the total time spent executing operations within the session. get_total_time() -> timedelta Returns the total duration of the session, from initialization to the current point. get_total_time_startpoint() -> datetime Returns the datetime object representing the start of the session. reset_time_statistics() Resets all accumulated time statistics for the session. ``` -------------------------------- ### Instrument Error Suppression Example Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/README.rst Demonstrates how to use the `instr_err_suppressor` context manager to ignore instrument errors during write operations. It checks for suppressed errors after the block. ```python import io # Any Instrument error in the context is ignored with io.instr_err_suppressor() as supp: io.write("*RSaT") if supp.get_errors_occurred(): print("Error(s) suppressed") ``` -------------------------------- ### Basic Write and Query with RsInstrument Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/docs/source/Chapter_06_BasicIOcommunication.rst Demonstrates the fundamental methods for interacting with an instrument. Use `write()` for commands that do not expect a response, and `query()` for commands that require a response, such as identification queries. ```python # Example of writing a command without expecting a response # instr.write("*RST") # Example of querying an instrument for information # instrument_id = instr.query("*IDN?") ``` -------------------------------- ### SCPI Logger Configuration Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/README.rst Introduces the SCPI Logger functionality and simplifies the constructor's options string format by removing the DriverSetup=() syntax for termination characters. ```Python # Old format: DriverSetup=(TerminationCharacter='\n') # New format: TerminationCharacter='\n' # The original format is still supported. ``` -------------------------------- ### RsInstrument API - Version and Compatibility Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/README.rst Includes methods for checking library version compatibility and managing instrument connection details. ```APIDOC RsInstrument: assert_minimum_version(required_version: str) -> None Raises an assertion error if the RsInstrument version is below the required version. SelectVisa (option in constructor) Specifies the VISA library location, e.g., 'SelectVisa=rs' for Linux. TerminationCharacter (option in constructor) Sets the termination character for reading and writing, e.g., 'TerminationCharacter="\r"'. Default is '\n'. ``` -------------------------------- ### Constructor Option: VxiCapable Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/README.rst Introduces a constructor option `VxiCapable` (boolean) to control VXI capability, with a default of True, which is later coerced based on session type. ```APIDOC Added constructor options boolean token VxiCapable. Example: VxiCapable=False. Default: True (coerced later to false based on a session type). ``` -------------------------------- ### Log SCPI Communication to Console Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/docs/source/Chapter_16_Logging.rst Demonstrates basic logging of SCPI communication to the console. The output includes timestamps, device resource names, operation duration, and log entries. Columns are aligned for readability. ```python from RsInstrument import * try: # Example_LoggingBasic.py instr = RsInstrument("TCPIP::192.168.1.101::INSTR") instr.logger.start() instr.reset() idn = instr.query("*IDN?") print(f"Instrument IDN: {idn}") instr.close() except Exception as e: print(f"An error occurred: {e}") ``` ```console 10:29:10.819 TCPIP::192.168.1.101::INSTR 0.976 ms Write: *RST 10:29:10.819 TCPIP::192.168.1.101::INSTR 1884.985 ms Status check: OK 10:29:12.704 TCPIP::192.168.1.101::INSTR 0.983 ms Query OPC: 1 10:29:12.705 TCPIP::192.168.1.101::INSTR 2.892 ms Clear status: OK 10:29:12.708 TCPIP::192.168.1.101::INSTR 3.905 ms Status check: OK 10:29:12.712 TCPIP::192.168.1.101::INSTR 1.952 ms Close: Closing session ``` -------------------------------- ### Settings Profile 'Minimal' Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/README.rst Adds a new 'Minimal' options profile designed for instruments that do not adhere to SCPI-99 standards, providing a simplified configuration. ```APIDOC Added new options profile 'Minimal' for non-SCPI-99 instruments. ``` -------------------------------- ### RsInstrument Context Manager Usage Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/README.rst Shows how to use the `RsInstrument` class as a context manager for automatic resource management. This simplifies instrument connection and disconnection. ```python from RsInstrument import RsInstrument with RsInstrument("TCPIP::192.168.1.101::hislip0") as io: io.reset() ``` -------------------------------- ### Settings: OpcSyncQueryMechanism Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/README.rst Introduces the 'OpcSyncQueryMechanism' setting with multiple values to control the synchronization mechanism for OPC queries, including a changed default value. ```APIDOC Added settings 'OpcSyncQueryMechanism'. Changed default value to 'only_check_mav_err_queue'. Supported values: Standard, AlsoCheckMav, ClsOnlyCheckMavErrQueue, OnlyCheckMavErrQueue. ``` -------------------------------- ### RsInstrument API - Core Functionality Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/README.rst Provides core methods for interacting with R&S instruments, including writing commands, querying responses, and handling operation complete signals. ```APIDOC RsInstrument: write_str(command: str) -> None Writes a string command to the instrument. query_str(query: str) -> str Sends a query command and returns the string response. write_str_with_opc(command: str) -> None Writes a string command and waits for the OPC signal. query_str_with_opc(query: str) -> str Sends a query command, waits for OPC, and returns the string response. query_opc(timeout: float = None) -> None Waits for the OPC signal with an optional timeout. resource_name: str (read-only) The VISA resource name of the connected instrument. str_to_str_list(input_str: str, clear_one_empty_item: bool = False) -> list[str] Converts a delimited string into a list of strings, with an option to clear empty items. ``` -------------------------------- ### Settings Profile XK41 Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/README.rst Introduces a new settings profile named 'XK41' specifically for R&S Software Defined Radios, enabling specialized configurations. ```APIDOC Added settings profile 'XK41' for R&S Software Defined Radios. ``` -------------------------------- ### Logging from Multiple Sessions Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/docs/source/Chapter_16_Logging.rst Shows how to direct logs from multiple RsInstrument sessions to a single file, ensuring all instrument activities are captured in one place. ```python import logging import sys # Configure a file handler for logging log_file = "instrument_session.log" file_handler = logging.FileHandler(log_file) file_handler.setLevel(logging.INFO) # Create a formatter (optional, but good practice) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') file_handler.setFormatter(formatter) # Get the root logger and add the file handler root_logger = logging.getLogger() root_logger.addHandler(file_handler) root_logger.setLevel(logging.INFO) # Assuming 'smw1' and 'smw2' are initialized RsInstrument sessions # smw1 = RsInstrument("TCPIP::192.168.1.101::hislip0", reset=True) # smw2 = RsInstrument("TCPIP::192.168.1.102::hislip0", reset=True) # Both smw1 and smw2 will now log to 'instrument_session.log' # smw1.logger.info("Log from SMW1") # smw2.logger.info("Log from SMW2") ``` -------------------------------- ### Resource Locking Methods Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/README.rst Introduces `lock_resource()` and `unlock_resource()` methods for managing device-site locking, providing explicit control over resource access. ```APIDOC Added lock_resource() and unlock_resource() methods for device-site locking. ``` -------------------------------- ### Synchronize with RsInstrument using query_opc Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/docs/source/Chapter_06_BasicIOcommunication.rst Ensures synchronization by sending the '*OPC?' command. The instrument waits until all pending tasks are completed before responding, allowing your program to wait for instrument readiness. ```python instr.visa_timeout = 3000 instr.write("INIT") # Wait for the instrument to finish its tasks before proceeding instr.query_opc() # Now it's safe to fetch results results = instr.query('FETCH:MEASUREMENT?') ``` -------------------------------- ### go_to_local() / go_to_remote() Fix Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/README.rst Fixes the behavior of `go_to_local()` and `go_to_remote()` methods when used with VXI-capable sessions. ```APIDOC Fixed go_to_local() / go_to_remote() for VXI-capable sessions. ``` -------------------------------- ### Settings: EachCmdAsQuery Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/README.rst Introduces a boolean setting `EachCmdAsQuery` which, when true, treats each command sent as a query. The default value is False. ```APIDOC Added settings boolean token EachCmdAsQuery. Example: EachCmdAsQuery=True. Default: False. ``` -------------------------------- ### Write Binary Data from File Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/docs/source/Chapter_12_Writing_BinaryData.rst Writes binary data from a specified file on the PC to the instrument. The `write_bin_block_from_file()` method takes the SCPI command string and the source PC file path as parameters. This simplifies sending large binary files. ```python smw.write_bin_block_from_file("SOUR:BB:ARB:WAV:DATA 'MyWaveform.wv',", r"c:\\temp\\wform_data.wv") ``` -------------------------------- ### RsInstrument LogInfoReplacer API Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/docs/source/logger.rst API documentation for the LogInfoReplacer class, used to customize message content within the ScpiLogger. It supports setting full string replacements and regular expression-based replacements for specific string patterns. -------------------------------- ### File Management Methods Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/README.rst Adds `file_exists()` and `get_file_size()` methods for interacting with files on the instrument, allowing checks for file existence and retrieval of file sizes. ```APIDOC Added methods file_exists() and get_file_size(). ``` -------------------------------- ### Query List Methods Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/README.rst Adds new methods for querying lists of string or boolean values from the instrument, with options for including OPC (Operation Complete) status. ```Python def query_str_list(self, query: str) -> list[str]: """Queries a list of strings from the instrument. Args: query: The SCPI query command. Returns: A list of string responses. """ pass def query_str_list_with_opc(self, query: str) -> list[str]: """Queries a list of strings with OPC. Args: query: The SCPI query command. Returns: A list of string responses. """ pass def query_bool_list(self, query: str) -> list[bool]: """Queries a list of boolean values from the instrument. Args: query: The SCPI query command. Returns: A list of boolean responses. """ pass def query_bool_list_with_opc(self, query: str) -> list[bool]: """Queries a list of boolean values with OPC. Args: query: The SCPI query command. Returns: A list of boolean responses. """ pass ``` -------------------------------- ### Method Aliases for String Operations Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/README.rst Introduces convenient aliases for common string writing and querying methods, simplifying common operations. ```Python # Aliases: # write() = write_str() # query() = query_str() # write_with_opc() = write_str_with_opc() # query_with_opc() = query_str_with_opc() ``` -------------------------------- ### RsInstrument ScpiLogger API Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/docs/source/logger.rst API documentation for the ScpiLogger class, which handles SCPI command logging. It allows configuration of logging modes, targets (console, UDP), timestamp handling, message formatting, and provides methods for logging information and errors. ```APIDOC ScpiLogger: __init__() Initializes the SCPI logger. Attributes: mode (str): The current logging mode. default_mode (str): The default logging mode. device_name (str): The name of the device being logged. log_to_console (bool): Enables or disables logging to the console. log_to_udp (bool): Enables or disables logging to UDP. log_to_console_and_udp (bool): Enables logging to both console and UDP. log_status_check_ok (bool): Controls logging of status check OK messages. abbreviated_max_len_ascii (int): Maximum length for abbreviated ASCII strings. abbreviated_max_len_bin (int): Maximum length for abbreviated binary strings. abbreviated_max_len_list (int): Maximum length for abbreviated list strings. bin_line_block_size (int): Block size for binary data lines. udp_port (int): The UDP port for logging. target_auto_flushing (bool): Enables automatic flushing of log targets. log_info_replacer (LogInfoReplacer): An instance of LogInfoReplacer for custom message replacement. Methods: stop(): Stops the logger. start(): Starts the logger. set_logging_target(target: str, enable: bool): Sets a specific logging target (e.g., 'console', 'udp') to enabled or disabled. get_logging_target(target: str) -> bool: Gets the status of a specific logging target. set_logging_target_global(target: str, enable: bool): Sets a global logging target. info_raw(message: str): Logs a raw information message. info(message: str): Logs an information message. error(message: str): Logs an error message. set_relative_timestamp(): Sets the logger to use relative timestamps. set_relative_timestamp_now(): Sets the logger to use relative timestamps starting from now. get_relative_timestamp() -> float: Gets the current relative timestamp. clear_relative_timestamp(): Clears the relative timestamp. set_time_offset_zero_on_first_entry(enable: bool): Configures whether to set time offset to zero on the first log entry. flush(): Flushes all pending log entries. sync_from(other_logger): Synchronizes logging state from another logger instance. clear_cached_entries(): Clears any cached log entries. set_format_string(format_string: str): Sets a custom format string for log messages. restore_format_string(): Restores the default format string. ``` -------------------------------- ### Configure Non-Standard Instruments Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/README.rst Allows setting specific profiles for non-standard instruments via the constructor's options string. ```Python # Example usage in constructor: # rs_instrument = RsInstrument(resource_name='TCPIP::192.168.1.100::INSTR', options='Profile=hm8123') ``` -------------------------------- ### Enable OPC Query After Write in RsInstrument Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/docs/source/Chapter_06_BasicIOcommunication.rst Automatically sends an '*OPC?' query after every `write_xxx()` command. This simplifies synchronization by ensuring the instrument has completed the previous write operation before the next command is sent. ```python # Set the flag to True to enable automatic OPC queries after writes # Default value after initialization is False instr.opc_query_after_write = True ``` -------------------------------- ### Constructor Option: OpenTimeout Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/README.rst Introduces a constructor option `OpenTimeout` (integer) to specify the timeout for opening a connection, with a default value of 0. ```APIDOC Added constructor options integer token OpenTimeout. Example: OpenTimeout=5000. Default: 0. ``` -------------------------------- ### Log SCPI Communication to File Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/docs/source/Chapter_16_Logging.rst Shows how to log SCPI communication to a file by treating the file as a stream. This allows for persistent logging of instrument interactions. ```python from RsInstrument import * import sys try: # Example_LoggingFile.py with open("log_file.txt", "w") as log_file: instr = RsInstrument("TCPIP::192.168.1.101::INSTR", sys.stdout, log_file) instr.logger.start() instr.reset() instr.close() except Exception as e: print(f"An error occurred: {e}") ``` -------------------------------- ### Settings: DisableOpcQuery Fix Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/README.rst Corrects the effect of the `DisableOpcQuery=True` setting, ensuring it functions as intended to disable OPC queries. ```APIDOC Fixed DisableOpcQuery=True settings effect. ``` -------------------------------- ### Log with Relative Time and Statistics Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/docs/source/Chapter_16_Logging.rst Configures logging to display relative timestamps from the first entry and tracks instrument execution time versus program time. This aids in performance analysis. ```python from RsInstrument import * try: # Example_LoggingRelativeAndStats.py instr = RsInstrument("TCPIP::192.168.1.101::hislip0", options="LoggingRelativeTimeOfFirstEntry=True") # Alternatively: instr.set_time_offset_zero_on_first_entry() instr.logger.start() instr.reset() idn = instr.query("*IDN?") print(f"Instrument IDN: {idn}") instr.close() except Exception as e: print(f"An error occurred: {e}") ``` ```console 00:00:00.000 TCPIP::192.168.1.101::hislip0 137.704 ms Session init: Device 'TCPIP::192.168.1.101::hislip0' IDN: Rohde&Schwarz,SMA100B,1419.8888K02/0,5.30.132.68 00:00:00.137 TCPIP::192.168.1.101::hislip0 2.002 ms Status check: OK Entries above come from the constructor. 00:00:00.139 TCPIP::192.168.1.101::hislip0 2.922 ms Query: *IDN? Rohde&Schwarz,SMA100B,1419.8888K02/0,5.30.132.68 00:00:00.142 TCPIP::192.168.1.101::hislip0 1.510 ms Status check: OK 00:00:01.145 TCPIP::192.168.1.101::hislip0 32.979 ms Write: *RST 00:00:01.178 TCPIP::192.168.1.101::hislip0 1879.281 ms Status check: OK 00:00:03.057 TCPIP::192.168.1.101::hislip0 129.349 ms Query OPC: 1 00:00:03.186 TCPIP::192.168.1.101::hislip0 5.432 ms Clear status: OK 00:00:03.192 TCPIP::192.168.1.101::hislip0 1.982 ms Status check: OK Communication time spent: 0:00:02.191159 Program time spent: 0:00:03.194408 ``` -------------------------------- ### RsInstrument Key Features Overview Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/docs/source/Chapter_01_Introduction.rst RsInstrument provides a comprehensive set of features for instrument control, including type-safe APIs, flexible VISA management, and robust data handling capabilities. ```Python # RsInstrument Key Features: # - Type-safe API using typing module # - Select which VISA to use or not use any VISA # - Straight-forward session initialization # - Implemented features: reset, self-test, opc-synchronization, error checking, option checking # - Binary data blocks transfer (both directions) # - Transfer of arrays of numbers (binary or ASCII format) # - File transfers (both directions) # - Events generation (error, sent data, received data, chunk data) # - Multithreading session locking # - Logging feature tailored for SCPI communication ``` -------------------------------- ### Python Logging Integration Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/docs/source/Chapter_16_Logging.rst Demonstrates how to integrate RsInstrument with Python's standard logging module for capturing instrument communication details. ```python import logging # Assuming 'smw' is an initialized RsInstrument session # smw = RsInstrument("TCPIP::192.168.1.101::hislip0", reset=True) # Configure Python's root logger or a specific logger logging.basicConfig(level=logging.INFO) # RsInstrument automatically uses the root logger if not specified # You can also set a specific logger for RsInstrument: # smw.logger.set_logger(logging.getLogger('my_instrument_logger')) # Example of logging a custom message # smw.logger.info("This is a custom log message from RsInstrument.") ``` -------------------------------- ### Read File from Instrument to PC Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/docs/source/Chapter_13_TransferringFiles.rst Transfers a file from the instrument's storage to the local PC. Requires the source path on the instrument and the destination path on the PC. ```python instr.read_file_from_instrument_to_pc( r'/var/user/instr_screenshot.png', r'c:\temp\pc_screenshot.png') ``` -------------------------------- ### Resource Manager Fallback Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/README.rst Enhances the Resource Manager's behavior by falling back to R&S VISA if no default VISA implementation is found, crucial for Linux and macOS environments. ```APIDOC If the Resource Manager does not find any default VISA implementation, it falls back to R&S VISA - relevant for LINUX and MacOS. ``` -------------------------------- ### Utility Functions Added Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/README.rst Lists new utility functions added to the Utilities interface and as standalone utility functions. These enhance data querying and formatting capabilities. ```APIDOC Added to Utilities interface: - query_str_list() - query_str_list_with_opc() - query_bool_list() - query_bool_list_with_opc() Added Utility functions: - value_to_si_string() - size_to_kb_mb_gb_string() ``` -------------------------------- ### RsInstrument API - Error Handling Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/README.rst Provides methods for querying instrument errors and managing error logging. ```APIDOC RsInstrument: SYST:ERR? parsing Tolerates '+0,"No Error"' responses. query_all_errors_with_codes() -> list[tuple[str, int]] Retrieves all instrument errors as a list of (message, code) tuples. logger.log_status_check_ok (property) Allows skipping log lines with 'Status check: OK'. ``` -------------------------------- ### Connection Management Methods Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/README.rst Adds methods for managing instrument connections, including reconnecting to a device and checking if the current connection is active. ```Python def reconnect(self): """Attempts to re-establish the connection to the instrument.""" pass def is_connection_active(self) -> bool: """Checks if the instrument connection is currently active.""" pass ``` -------------------------------- ### Settings Profile CMQ Source: https://github.com/rohde-schwarz/rsinstrument/blob/main/README.rst Introduces a new options profile named 'CMQ' for the CMQ500 instrument, enabling specific configurations for this device. ```APIDOC Added new options profile for CMQ500: 'Profile=CMQ'. ```