Source code for RsLcx.RsLcx

from typing import ClassVar, List

from .Internal.Core import Core
from .Internal.InstrumentErrors import RsInstrException
from .Internal.CommandsGroup import CommandsGroup
from .Internal.VisaSession import VisaSession
from datetime import datetime, timedelta
from .Internal import Conversions
from . import enums


# noinspection PyPep8Naming,PyAttributeOutsideInit,SpellCheckingInspection
[docs]class RsLcx: """97 total commands, 18 Subgroups, 1 group commands""" _driver_options = "SupportedInstrModels = LCX, SupportedIdnPatterns = LCX, SimulationIdnString = 'Rohde&Schwarz,LCX,100001,2.7.0008'" _global_logging_relative_timestamp: ClassVar[datetime] = None _global_logging_target_stream: ClassVar = None def __init__(self, resource_name: str, id_query: bool = True, reset: bool = False, options: str = None, direct_session: object = None): """Initializes new RsLcx session. \n Parameter options tokens examples: - ``Simulate=True`` - starts the session in simulation mode. Default: ``False`` - ``SelectVisa=socket`` - uses no VISA implementation for socket connections - you do not need any VISA-C installation - ``SelectVisa=rs`` - forces usage of RohdeSchwarz Visa - ``SelectVisa=ivi`` - forces usage of National Instruments Visa - ``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 - ``OpcWaitMode = OpcQuery`` - mode for all the opc-synchronised write/reads. Other modes: StbPolling, StbPollingSlow, StbPollingSuperSlow. Default: ``StbPolling`` - ``AddTermCharToWriteBinBLock = True`` - Adds one additional LF to the end of the binary data (some instruments require that). Default: ``False`` - ``AssureWriteWithTermChar = True`` - Makes sure each command/query is terminated with termination character. Default: Interface dependent - ``TerminationCharacter = "\\r"`` - Sets the termination character for reading. Default: ``\\n`` (LineFeed or LF) - ``DataChunkSize = 10E3`` - Maximum size of one write/read segment. If transferred data is bigger, it is split to more segments. Default: ``1E6`` 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`` - ``StbInErrorCheck = False`` - if true, the driver checks errors with *STB? If false, it uses SYST:ERR?. Default: ``True`` - ``LoggingMode = On`` - Sets the logging status right from the start. 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 RsLcx.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 :param resource_name: VISA resource name, e.g. 'TCPIP::192.168.2.1::INSTR' :param id_query: if True, the instrument's model name is verified against the models supported by the driver and eventually throws an exception. :param reset: Resets the instrument (sends *RST command) and clears its status sybsystem. :param options: string tokens alternating the driver settings. :param direct_session: Another driver object or pyVisa object to reuse the session instead of opening a new session.""" self._core = Core(resource_name, id_query, reset, RsLcx._driver_options, options, direct_session) self._core.driver_version = '2.7.0008' self._options = options self._add_all_global_repcaps() self._custom_properties_init() self.utilities.default_instrument_setup() # noinspection PyTypeChecker self._cmd_group = CommandsGroup("ROOT", self._core, None)
[docs] @classmethod def from_existing_session(cls, session: object, options: str = None) -> 'RsLcx': """Creates a new RsLcx object with the entered 'session' reused. \n :param session: can be another driver or a direct pyvisa session. :param options: string tokens alternating the driver settings.""" # noinspection PyTypeChecker resource_name = None if hasattr(session, 'resource_name'): resource_name = getattr(session, 'resource_name') return cls(resource_name, False, False, options, session)
[docs] @classmethod def set_global_logging_target(cls, target) -> None: """Sets global common target stream that each instance can use. To use it, call the following: io.utilities.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.""" cls._global_logging_target_stream = target
[docs] @classmethod def get_global_logging_target(cls): """Returns global common target stream.""" return cls._global_logging_target_stream
[docs] @classmethod def set_global_logging_relative_timestamp(cls, timestamp: datetime) -> None: """Sets global common relative timestamp for log entries. To use it, call the following: io.utilities.logger.set_relative_timestamp_global()""" cls._global_logging_relative_timestamp = timestamp
[docs] @classmethod def set_global_logging_relative_timestamp_now(cls) -> None: """Sets global common relative timestamp for log entries to this moment. To use it, call the following: io.utilities.logger.set_relative_timestamp_global().""" cls._global_logging_relative_timestamp = datetime.now()
[docs] @classmethod def clear_global_logging_relative_timestamp(cls) -> None: """Clears the global relative timestamp. After this, all the instances using the global relative timestamp continue logging with the absolute timestamps.""" # noinspection PyTypeChecker cls._global_logging_relative_timestamp = None
[docs] @classmethod def get_global_logging_relative_timestamp(cls) -> datetime or None: """Returns global common relative timestamp for log entries.""" return cls._global_logging_relative_timestamp
def __str__(self) -> str: if self._core.io: return f"RsLcx session '{self._core.io.resource_name}'" else: return f"RsLcx with session closed"
[docs] def get_total_execution_time(self) -> timedelta: """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().""" return self._core.io.total_execution_time
[docs] def get_total_time(self) -> timedelta: """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().""" return datetime.now() - self._core.io.total_time_startpoint
[docs] def reset_time_statistics(self) -> None: """Resets all execution and total time counters. Affects the results of get_total_time() and get_total_execution_time()""" self._core.io.reset_time_statistics()
[docs] @staticmethod def assert_minimum_version(min_version: str) -> None: """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.""" min_version_list = min_version.split('.') curr_version_list = '2.7.0008'.split('.') count_min = len(min_version_list) count_curr = len(curr_version_list) count = count_min if count_min < count_curr else count_curr for i in range(count): minimum = int(min_version_list[i]) curr = int(curr_version_list[i]) if curr > minimum: break if curr < minimum: raise RsInstrException(f"Assertion for minimum RsLcx version failed. Current version: '2.7.0008', minimum required version: '{min_version}'")
[docs] @staticmethod def list_resources(expression: str = '?*::INSTR', visa_select: str = None) -> List[str]: """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 :param expression: see the examples in the function :param visa_select: optional parameter selecting a specific VISA. Examples: '@ivi', '@rs' """ rm = VisaSession.get_resource_manager(visa_select) resources = rm.list_resources(expression) rm.close() # noinspection PyTypeChecker return resources
[docs] def close(self) -> None: """Closes the active RsLcx session.""" self._core.io.close()
[docs] def get_session_handle(self) -> object: """Returns the underlying session handle.""" return self._core.get_session_handle()
def _add_all_global_repcaps(self) -> None: """Adds all the repcaps defined as global to the instrument's global repcaps dictionary.""" def _custom_properties_init(self) -> None: """Adds all the interfaces that are custom for the driver.""" from .CustomFiles.utilities import Utilities self.utilities = Utilities(self._core) from .CustomFiles.events import Events self.events = Events(self._core) def _sync_to_custom_properties(self, cloned: 'RsLcx') -> None: """Synchronises the state of all the custom properties to the entered object.""" cloned.utilities.sync_from(self.utilities) cloned.events.sync_from(self.events) @property def bias(self): """bias commands group. 3 Sub-classes, 1 commands.""" if not hasattr(self, '_bias'): from .Implementations.Bias import BiasCls self._bias = BiasCls(self._core, self._cmd_group) return self._bias @property def correction(self): """correction commands group. 4 Sub-classes, 1 commands.""" if not hasattr(self, '_correction'): from .Implementations.Correction import CorrectionCls self._correction = CorrectionCls(self._core, self._cmd_group) return self._correction @property def current(self): """current commands group. 0 Sub-classes, 1 commands.""" if not hasattr(self, '_current'): from .Implementations.Current import CurrentCls self._current = CurrentCls(self._core, self._cmd_group) return self._current @property def data(self): """data commands group. 2 Sub-classes, 2 commands.""" if not hasattr(self, '_data'): from .Implementations.Data import DataCls self._data = DataCls(self._core, self._cmd_group) return self._data @property def diMeasure(self): """diMeasure commands group. 3 Sub-classes, 1 commands.""" if not hasattr(self, '_diMeasure'): from .Implementations.DiMeasure import DiMeasureCls self._diMeasure = DiMeasureCls(self._core, self._cmd_group) return self._diMeasure @property def initiate(self): """initiate commands group. 1 Sub-classes, 0 commands.""" if not hasattr(self, '_initiate'): from .Implementations.Initiate import InitiateCls self._initiate = InitiateCls(self._core, self._cmd_group) return self._initiate @property def fetch(self): """fetch commands group. 0 Sub-classes, 2 commands.""" if not hasattr(self, '_fetch'): from .Implementations.Fetch import FetchCls self._fetch = FetchCls(self._core, self._cmd_group) return self._fetch @property def read(self): """read commands group. 0 Sub-classes, 2 commands.""" if not hasattr(self, '_read'): from .Implementations.Read import ReadCls self._read = ReadCls(self._core, self._cmd_group) return self._read @property def frequency(self): """frequency commands group. 0 Sub-classes, 1 commands.""" if not hasattr(self, '_frequency'): from .Implementations.Frequency import FrequencyCls self._frequency = FrequencyCls(self._core, self._cmd_group) return self._frequency @property def function(self): """function commands group. 3 Sub-classes, 0 commands.""" if not hasattr(self, '_function'): from .Implementations.Function import FunctionCls self._function = FunctionCls(self._core, self._cmd_group) return self._function @property def log(self): """log commands group. 3 Sub-classes, 4 commands.""" if not hasattr(self, '_log'): from .Implementations.Log import LogCls self._log = LogCls(self._core, self._cmd_group) return self._log @property def measure(self): """measure commands group. 1 Sub-classes, 4 commands.""" if not hasattr(self, '_measure'): from .Implementations.Measure import MeasureCls self._measure = MeasureCls(self._core, self._cmd_group) return self._measure @property def handler(self): """handler commands group. 2 Sub-classes, 1 commands.""" if not hasattr(self, '_handler'): from .Implementations.Handler import HandlerCls self._handler = HandlerCls(self._core, self._cmd_group) return self._handler @property def system(self): """system commands group. 11 Sub-classes, 1 commands.""" if not hasattr(self, '_system'): from .Implementations.System import SystemCls self._system = SystemCls(self._core, self._cmd_group) return self._system @property def voltage(self): """voltage commands group. 0 Sub-classes, 1 commands.""" if not hasattr(self, '_voltage'): from .Implementations.Voltage import VoltageCls self._voltage = VoltageCls(self._core, self._cmd_group) return self._voltage @property def display(self): """display commands group. 1 Sub-classes, 1 commands.""" if not hasattr(self, '_display'): from .Implementations.Display import DisplayCls self._display = DisplayCls(self._core, self._cmd_group) return self._display @property def hardCopy(self): """hardCopy commands group. 2 Sub-classes, 1 commands.""" if not hasattr(self, '_hardCopy'): from .Implementations.HardCopy import HardCopyCls self._hardCopy = HardCopyCls(self._core, self._cmd_group) return self._hardCopy @property def interfaces(self): """interfaces commands group. 1 Sub-classes, 0 commands.""" if not hasattr(self, '_interfaces'): from .Implementations.Interfaces import InterfacesCls self._interfaces = InterfacesCls(self._core, self._cmd_group) return self._interfaces # noinspection PyTypeChecker
[docs] def get_aperture(self) -> enums.MeasurementTimeMode: """SCPI: APERture \n Snippet: value: enums.MeasurementTimeMode = driver.get_aperture() \n Sets the measurement time mode and the acquisition time interval. \n :return: measurement_time_mode: Selects the basic measurement speed for one measurement. - SHORt: Sets the measurement time ≤.015 s. - MEDium: Sets the measurement time ≤0.100 s. - LONG: Sets the measurement time ≤0.500 s. - DEFault: Uses the default setting SHORt.""" response = self._core.io.query_str('APERture?') return Conversions.str_to_scalar_enum(response, enums.MeasurementTimeMode)
[docs] def set_aperture(self, measurement_time_mode: enums.MeasurementTimeMode) -> None: """SCPI: APERture \n Snippet: driver.set_aperture(measurement_time_mode = enums.MeasurementTimeMode.DEFault) \n Sets the measurement time mode and the acquisition time interval. \n :param measurement_time_mode: Selects the basic measurement speed for one measurement. - SHORt: Sets the measurement time ≤.015 s. - MEDium: Sets the measurement time ≤0.100 s. - LONG: Sets the measurement time ≤0.500 s. - DEFault: Uses the default setting SHORt.""" param = Conversions.enum_scalar_to_str(measurement_time_mode, enums.MeasurementTimeMode) self._core.io.write(f'APERture {param}')
def clone(self) -> 'RsLcx': """Creates a deep copy of the RsLcx object. After cloning, your new RsLcx object can be used separately, but shares the same instrument session. Calling close() on the new object does not close the original VISA session. This method is similar to calling RsLcx.from_existing_session()""" cloned = RsLcx.from_existing_session(self.get_session_handle(), self._options) self._cmd_group.synchronize_repcaps(cloned) self._sync_to_custom_properties(cloned) return cloned