### Install niveristand from source Source: https://github.com/ni/niveristand-python/blob/master/docs/getting_started.md Install the niveristand package by downloading the source code and running the setup script. This is useful for development or custom installations. ```bash $ python setup.py install ``` -------------------------------- ### Install niveristand using easy_install Source: https://github.com/ni/niveristand-python/blob/master/docs/getting_started.md Install the niveristand package using easy_install from setuptools. This method is an alternative to pip. ```bash $ python -m easy_install niveristand ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/ni/niveristand-python/blob/master/CONTRIBUTING.md Installs all necessary development dependencies from the requirements file. Ensure you are in the project's root directory. ```bash $ pip install -r .\requirements.txt ``` -------------------------------- ### Workspace2.StartDataLogging() Source: https://github.com/ni/niveristand-python/blob/master/docs/api_reference.md Starts data logging in the NI VeriStand system. ```APIDOC ## Workspace2.StartDataLogging() ### Description Starts data logging in the NI VeriStand system. ### Method Not specified (assumed to be a method call within the Python API) ### Endpoint Not applicable (Python API call) ### Parameters None ### Request Example ```python niv.Workspace2.StartDataLogging() ``` ### Response #### Success Response None ``` -------------------------------- ### Install niveristand using pip Source: https://github.com/ni/niveristand-python/blob/master/docs/getting_started.md Use this command to install the niveristand package via pip. Ensure you have pip installed. ```bash $ python -m pip install niveristand ``` -------------------------------- ### Initialize ChannelReference Source: https://github.com/ni/niveristand-python/blob/master/docs/api_reference/datatypes.md Provides examples of initializing a ChannelReference with a channel path or alias. ```python a = ChannelReference('Aliases/DesiredRPM') a = ChannelReference('Targets/Controller/Simulation Models/Models/Engine Demo/Inports/command_RPM') ``` -------------------------------- ### Install Tox for Testing Source: https://github.com/ni/niveristand-python/blob/master/CONTRIBUTING.md Installs the tox package, which is used for running tests across multiple Python environments. This command should be run before using tox to manage virtual environments. ```bash $ pip install tox ``` -------------------------------- ### Initialize VectorChannelReference Source: https://github.com/ni/niveristand-python/blob/master/docs/api_reference/datatypes.md Provides an example of initializing a VectorChannelReference with a channel path or alias. ```python a = VectorChannelReference('engine/a') ``` -------------------------------- ### Stimulus2.RunStimulusProfile Source: https://github.com/ni/niveristand-python/blob/master/docs/api_reference/legacy.md Starts stimulus generation defined in a test file, with optional parameter files. ```APIDOC ## Stimulus2.RunStimulusProfile(testfile, baselogpath, timeout, autostart, stopondisconnect, parameterfiles=()) ### Description Starts the stimulus generation you defined in the test file. ### Method N/A (Method call) ### Parameters #### Path Parameters - **testfile** (string) - Required - Path to the test file defining the stimulus generation. - **baselogpath** (string) - Required - Base path for log files. - **timeout** (float) - Required - Timeout duration for the stimulus generation. - **autostart** (boolean) - Required - Whether to automatically start the stimulus generation. - **stopondisconnect** (boolean) - Required - Whether to stop stimulus generation on disconnect. - **parameterfiles** (tuple) - Optional - A tuple of paths to parameter files. ``` -------------------------------- ### Data Logging Source: https://context7.com/ni/niveristand-python/llms.txt Starts and stops data logging for a specified configuration. The configuration name and logging settings should be defined. ```python # Data logging workspace.StartDataLogging("my_config", {}) # ... run tests ... workspace.StopDataLogging("my_config") ``` -------------------------------- ### Mix Legacy API with Real-time Sequences Source: https://github.com/ni/niveristand-python/blob/master/docs/basic_rt_sequence_examples.md Combines the Niveristand Legacy API with Python real-time sequences to create an automated test environment. This example deploys a system definition and runs a test sequence. ```python import os from examples.engine_demo.engine_demo_basic import run_engine_demo from niveristand import run_py_as_rtseq from niveristand.errors import RunError from niveristand.legacy import NIVeriStand def mix_legacy_and_rtseq_run(): """Combines the legacy API with Python real-time sequences to run a deterministic test.""" # Ensures NI VeriStand is running. NIVeriStand.LaunchNIVeriStand() NIVeriStand.WaitForNIVeriStandReady() # Uses the ClientAPI interface to get a reference to Workspace2 workspace = NIVeriStand.Workspace2("localhost") engine_demo_path = os.path.join( os.path.expanduser("~public"), "Documents", "National Instruments", "NI VeriStand 2019", "Examples", "Stimulus Profile", "Engine Demo", "Engine Demo.nivssdf", ) # Deploys the system definition. workspace.ConnectToSystem(engine_demo_path, True, 120000) try: # Uses Python real-time sequences to run a test. run_py_as_rtseq(run_engine_demo) print("Test Success") except RunError as e: print("Test Failed: %d - %s" % (int(e.error.error_code), e.error.message)) finally: # You can now disconnect from the system, so the next test can run. workspace.DisconnectFromSystem("", True) if __name__ == "__main__": mix_legacy_and_rtseq_run() ``` -------------------------------- ### Real-Time Sequence State Machine Example Source: https://github.com/ni/niveristand-python/blob/master/docs/basic_rt_sequence_examples.md Implements a state machine within a real-time sequence. The state machine transitions between different states, executing various waveform generation functions or waiting for a specified duration. The loop terminates after a set number of iterations or if an invalid state is encountered. ```python import nivs from nivs.values import DoubleValue, I64Value, BooleanValue, I32Value from nivs.channels import ChannelReference from nivs.timing import seqtime, seqtimeus, tickcountms, tickcountus from nivs.random import rand from nivs.waveforms import sine_wave, square_wave, triangle_wave, uniform_white_noise_wave, ramp, sawtooth_wave @nivs_rt_sequence def state_machine_example(): state = I32Value(0) iters = I32Value(0) amplitude = DoubleValue(1000) stop = BooleanValue(False) output = ChannelReference("Aliases/DesiredRPM") while ( stop.value != True # noqa: E712 NI recommends you use comparison instead of identity. and iters.value < 10 ): state.value = rand(7) if state.value == 0: wait(2) elif state.value == 1: sine_wave(output, amplitude, 1, 0, 0, 2) elif state.value == 2: square_wave(output, amplitude, 5, 0, 0, 50, 2) elif state.value == 3: triangle_wave(output, amplitude, 1, 0, 0, 2) elif state.value == 4: uniform_white_noise_wave(output, amplitude, tickcountus(), 2) elif state.value == 5: ramp(output, -amplitude.value, amplitude, 2) elif state.value == 6: sawtooth_wave(output, amplitude, 1, 0, 0, 2) else: stop.value = True iters.value += 1 state.value = rand(7) ``` -------------------------------- ### RunStimulusProfile Source: https://github.com/ni/niveristand-python/blob/master/docs/api_reference/legacy.md Starts stimulus generation defined in a test file. ```APIDOC ## RunStimulusProfile(testfile, baselogpath, timeout, autostart, stopondisconnect) ### Description Starts the stimulus generation you defined in the test file. ### Method N/A (Function call) ### Parameters #### Path Parameters - **testfile** (string) - Required - Path to the test file defining the stimulus generation. - **baselogpath** (string) - Required - Base path for log files. - **timeout** (float) - Required - Timeout duration for the stimulus generation. - **autostart** (boolean) - Required - Whether to automatically start the stimulus generation. - **stopondisconnect** (boolean) - Required - Whether to stop stimulus generation on disconnect. ``` -------------------------------- ### Configure NI-XNET CAN and LIN Interfaces Source: https://context7.com/ni/niveristand-python/llms.txt Adds NI-XNET CAN and LIN interfaces to a VeriStand system definition, configuring signal-based frames. Ensure NI-XNET drivers are installed. ```python from niveristand.systemdefinitionapi.hardware.xnet import ( Database, CANPort, XNETTermination, SignalBasedFrame, DataLoggingFile, FileType, DataFileReplay, LINPort, ) chassis = target.get_hardware().get_chassis_list()[0] chassis.get_xnet().enable_xnet() # --- CAN --- can = chassis.get_xnet().get_can() can_db = Database("NIXNET_example") target.get_xnet_databases().add_database(can_db) can_port = CANPort("CAN 1", 1, can_db, "CAN_Cluster", 125000) can_port.termination = XNETTermination.ON can.add_can_port(can_port) for frame_name, frame_id, signals in [ ("CANCyclicFrame1", 64, ["CANCyclicSignal1", "CANCyclicSignal2"]), ]: frame = SignalBasedFrame(frame_name, frame_id, can_db, "CAN_Cluster", 8, 0.1, False, signals) can_port.get_incoming().get_single_point().add_signal_based_frame(frame) for sig in signals: frame.create_signal_based_signal(sig, "", "volts", 0.0) # --- LIN --- lin = chassis.get_xnet().get_lin() lin_db = Database("NIXNET_exampleLDF") target.get_xnet_databases().add_database(lin_db) lin_port = LINPort("LIN 1", 1, lin_db, "Cluster", 125000, "SlowSchedule") lin.add_lin_port(lin_port) lin_frame = SignalBasedFrame("Slave1Frame2", 5, lin_db, "Cluster", 8, 0.1, False, ["SlaveSignal3_U8"]) lin_port.get_incoming().get_single_point().add_signal_based_frame(lin_frame) lin_frame.create_signal_based_signal("SlaveSignal3_U8", "", "volts", 0.0) system_definition.save_system_definition_file() ``` -------------------------------- ### Concurrent Task Execution with multitask() and task() Source: https://context7.com/ni/niveristand-python/llms.txt Demonstrates how to use `multitask()` to create a concurrent execution context and `@task(mt)` to define asynchronous tasks within that context. Includes examples of yielding execution with `nivs_yield()` and stopping tasks with `stop_task()`. ```APIDOC ## `multitask()` and `task()` — Concurrent Task Execution `multitask()` creates a concurrent execution context inside an RT sequence. Each nested function decorated with `@task(mt)` runs asynchronously (cooperatively, not in parallel). Use `nivs_yield()` to yield execution to the next task and `stop_task()` to terminate a running task. ```python from niveristand import nivs_rt_sequence, NivsParam from niveristand.clientapi import BooleanValue, ChannelReference, DoubleValue from niveristand.library import multitask, nivs_yield, stop_task, task, wait_until_settled @NivsParam("desired_rpm", DoubleValue(0), NivsParam.BY_REF) @NivsParam("actual_rpm", DoubleValue(0), NivsParam.BY_REF) @NivsParam("engine_temp", DoubleValue(0), NivsParam.BY_REF) @nivs_rt_sequence def engine_demo_advanced(desired_rpm, actual_rpm, engine_temp): warmup_complete = BooleanValue(False) warmup_succeeded = BooleanValue(False) with multitask() as mt: @task(mt) def engine_warmup(): desired_rpm.value = 2500 wait_until_settled(actual_rpm, 9999999, 2450, 25, 120) desired_rpm.value = 8000 wait_until_settled(actual_rpm, 9999999, 7800, 25, 120) warmup_complete.value = True @task(mt) def monitor_temp(): while warmup_complete.value is False: if engine_temp.value > 110: stop_task(engine_warmup) warmup_complete.value = True warmup_succeeded.value = False nivs_yield() return warmup_succeeded.value @nivs_rt_sequence def run_demo(): try: warmup_succeeded = BooleanValue(False) engine_power = ChannelReference("Aliases/EnginePower") desired_rpm = ChannelReference("Aliases/DesiredRPM") actual_rpm = ChannelReference("Aliases/ActualRPM") engine_temp = ChannelReference("Aliases/EngineTemp") engine_power.value = True warmup_succeeded.value = engine_demo_advanced(desired_rpm, actual_rpm, engine_temp) finally: engine_power.value = False desired_rpm.value = 0 return warmup_succeeded.value ``` ``` -------------------------------- ### Perform Array Operations in Real-time Sequence Source: https://github.com/ni/niveristand-python/blob/master/docs/basic_rt_sequence_examples.md Demonstrates various operations on array data types within a real-time sequence, including indexing, updating, getting array size, and iterating over elements. Arrays cannot contain other arrays. ```python import niveristand from niveristand.realtime import DoubleValue, I64Value, DoubleValueArray, arraysize @niveristand.nivs_rt_sequence def array_operations(): """ Shows operations you can perform with array data types in a real-time sequence. An array can hold multiple values of the same data type. You cannot have arrays of arrays. Use arrays to pass buffers of data for playback or storage. Returns: float: sum of all values in the array. """ var = DoubleValue(0) arr_size = I64Value(0) array = DoubleValueArray([0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]) # Indexes a value out of an array. var.value = array[4].value + 100 # Updates a value in an array. array[2].value = 6.0 # Gets the size of an array. arr_size.value = arraysize(array) # Loops over each element of an array. Each time the loop iterates a value from the array is copied into x. var.value = 0.0 for x in array: var.value += x return var.value ``` -------------------------------- ### Create Basic System Definition Source: https://github.com/ni/niveristand-python/blob/master/docs/sysdef_examples.md Initializes a SystemDefinition object with basic properties. Sets the target operating system based on the IP address. Requires the SystemDefinition class to be imported. ```python is_local = ip_address == "localhost" or ip_address == "127.0.0.1" target_type = "Windows" if is_local else "Linux_x64" system_definition = SystemDefinition( filename, "This is an example System Definition file created using the System Definition API", "System Definition API", "1.0.0.0", "Controller", target_type, filepath, ) target = system_definition.root.get_targets().get_target_list()[0] if not is_local: target.ip_address = ip_address ``` -------------------------------- ### Launch VeriStand and Connect to System Source: https://context7.com/ni/niveristand-python/llms.txt Launches NI VeriStand and connects to a specified system definition. Ensure the system definition path is correct for your environment. ```python import os import NIVeriStand NIVeriStand.LaunchNIVeriStand() NIVeriStand.WaitForNIVeriStandReady() workspace = NIVeriStand.Workspace2("localhost") sysdef_path = os.path.join( os.path.expanduser("~public"), "Documents", "National Instruments", "NI VeriStand 2019", "Examples", "Stimulus Profile", "Engine Demo", "Engine Demo.nivssdf" ) workspace.ConnectToSystem(sysdef_path, True, 120000) ``` -------------------------------- ### Initialize I32ValueArray Source: https://github.com/ni/niveristand-python/blob/master/docs/api_reference/datatypes.md Demonstrates initializing an I32ValueArray with a list of valid I32Value initializers. ```python a = I32ValueArray([3, 3.1415, 0x7FFFFFFF, True]) ``` -------------------------------- ### Stimulus.GetStimulusProfileManagerState Source: https://github.com/ni/niveristand-python/blob/master/docs/api_reference.md Gets the state of the stimulus profile manager. ```APIDOC ## Stimulus.GetStimulusProfileManagerState() ### Description Gets the current state of the stimulus profile manager. ### Method `GetStimulusProfileManagerState` ### Response #### Success Response (string) Returns the state of the stimulus profile manager (e.g., 'Idle', 'Running', 'Paused'). #### Response Example ```json "Running" ``` ``` -------------------------------- ### Initialize I64ValueArray Source: https://github.com/ni/niveristand-python/blob/master/docs/api_reference/datatypes.md Demonstrates initializing an I64ValueArray with a list of valid I64Value initializers. ```python a = I64ValueArray([3, 3.1415, 0x7FFFFFFFFFFFFFFF, -9.2e18, True]) ``` -------------------------------- ### niveristand.library.iteration() Source: https://github.com/ni/niveristand-python/blob/master/docs/api_reference/library.md Returns the number of iterations since the current top-level sequence started. ```APIDOC ## iteration() ### Description Returns the number of iterations since the current top-level sequence started. ### Returns - int: The iteration count. ``` -------------------------------- ### Initialize U64ValueArray Source: https://github.com/ni/niveristand-python/blob/master/docs/api_reference/datatypes.md Demonstrates initializing a U64ValueArray with a list of valid U64Value initializers. ```python a = U64ValueArray([3, 3.1415, 0xFFFFFFFFFFFFFFFF, 18.4e18, True]) ``` -------------------------------- ### Initialize U32ValueArray Source: https://github.com/ni/niveristand-python/blob/master/docs/api_reference/datatypes.md Demonstrates initializing a U32ValueArray with a list of valid U32Value initializers. ```python a = U32ValueArray([3, 3.1415, 0xFFFFFFFF, True]) ``` -------------------------------- ### Programmatically Create System Definition Files Source: https://context7.com/ni/niveristand-python/llms.txt Use the `SystemDefinition` API to create NI VeriStand system definition files (`.nivssdf`). This includes adding targets, user channels, calculated channels, aliases, alarms, procedures, and models. ```python import os from niveristand.systemdefinitionapi import ( SystemDefinition, Alias, AliasFolder, Procedure, SetVariableStepFunction, AlarmMode, AlarmState, AlarmPriority, Model, ) from niveristand.systemdefinitionapi.calculatedchannels import LowpassFilter filepath = os.path.join(os.path.expanduser("~"), "Documents", "test_system.nivssdf") filename = "test_system" system_definition = SystemDefinition( filename, "Example system definition created with the Python API", "System Definition API", "1.0.0.0", "Controller", "Windows", filepath, ) target = system_definition.root.get_targets().get_target_list()[0] # Add user channel target.get_user_channels().add_new_user_channel("MyUserChannel", "", "", 1.0) user_channel = target.get_user_channels().get_user_channel_list()[1] # Add calculated (lowpass filter) channel lpf = LowpassFilter("MyLPFChannel", "", user_channel, 50, 1) target.get_calculated_channels().add_calculated_channel(lpf) # Add alias alias = Alias("MyAlias", "", user_channel) folder = AliasFolder("MyAliasFolder", "") system_definition.root.get_aliases().add_alias_folder(folder) system_definition.root.get_aliases().get_alias_folder_list()[0].add_alias(alias) # Add procedure with dwell and set-variable steps procedure = Procedure("MyProcedure", "") procedure.add_new_dwell("Dwell 3s", "", 3) procedure.add_new_set_variable("Count", "", user_channel, SetVariableStepFunction.ADD, user_channel, 1) target.get_procedures().add_procedure(procedure) # Add alarm target.get_alarms().add_new_alarm( "OverspeedAlarm", "", user_channel, 2, 1, procedure, AlarmMode.NORMAL, AlarmState.ENABLED, AlarmPriority.LOW, 0, "" ) ``` -------------------------------- ### Initialize DoubleValueArray Source: https://github.com/ni/niveristand-python/blob/master/docs/api_reference/datatypes.md Demonstrates initializing a DoubleValueArray with a list of valid DoubleValue initializers. ```python a = DoubleValueArray([1, 2.0, 0.3, 0x40]) ``` -------------------------------- ### Main Execution Block Source: https://github.com/ni/niveristand-python/blob/master/docs/engine_demo.md This block demonstrates how to execute both deterministic and non-deterministic versions of the engine demo. It prints the results, indicating whether each test passed or failed, with an expectation of failure for the non-deterministic test due to temperature limits. ```python if __name__ == "__main__": # Run the tests. # Note: We expect the tests to fail because the engine temperature rises above 110 degrees (C), # but the cleanup code at the end turns the engine off. print("Non-Deterministic test:") print("Test Passed!" if run_non_deterministic() else "Test Failed (expected)!") print("Deterministic test:") print("Test Passed!" if run_deterministic() else "Test Failed (expected)!") ``` -------------------------------- ### Bitwise Operator Restrictions with Float or Boolean Types in Python Source: https://github.com/ni/niveristand-python/blob/master/docs/restrictions.md Bitwise operations are not supported on float or boolean values in Python. The code examples provided only work when run deterministically. ```python bool_var = BooleanValue(False) double_var = DoubleValue(1.0) # The following statements only work when the code is run deterministically. bool_var.value = BooleanValue(True) & BooleanValue(True) double_var.value = 3.5 | 2.5 double_var.value = DoubleValue(3.5) ^ DoubleValue(2.5) ``` -------------------------------- ### Unsupported For Loop Constructs in Python Source: https://github.com/ni/niveristand-python/blob/master/docs/restrictions.md For loops in NI VeriStand Python do not support else blocks, ranges with start or step values, channel references in ranges, or array constants in ranges. ```python # The following statements are invalid: for x in range(5): pass else: pass for x in range(2, 5): for x in range(2, 5, 2): channel_ref = ChannelReference('Aliases/DesiredRPM') for x in range(channel_ref.value): for x in [1, 2, 3]: ``` -------------------------------- ### Workspace2.GetSystemState() Source: https://github.com/ni/niveristand-python/blob/master/docs/api_reference.md Retrieves the current system state of NI VeriStand. ```APIDOC ## Workspace2.GetSystemState() ### Description Retrieves the current system state of NI VeriStand. ### Method Not specified (assumed to be a method call within the Python API) ### Endpoint Not applicable (Python API call) ### Parameters None ### Request Example ```python returnValue = niv.Workspace2.GetSystemState() ``` ### Response #### Success Response - **returnValue** (object) - The current system state. ``` -------------------------------- ### Arithmetic Shift Restrictions with Double Types in Python Source: https://github.com/ni/niveristand-python/blob/master/docs/restrictions.md Double data types cannot be used to the left of an arithmetic shift operation in Python. The code examples provided only work when run deterministically. ```python double_var = DoubleValue(5.0) # The following statements only work when the code is run deterministically. double_var.value = DoubleValue(3.0) << 5 double_var.value = 3.0 >> 5 double_var.value = double_var.value >> 5 ``` -------------------------------- ### run Method Source: https://github.com/ni/niveristand-python/blob/master/docs/api_reference/realtimesequence.md Runs the sequence on the globally configured VeriStand Engine. It deploys and runs the sequence without waiting for it to finish. ```APIDOC #### run(rtseq_params={}) Runs the sequence on the globally configured VeriStand Engine. * **Parameters:** **rtseq_params** (*Dict* *[**str* *,* [*niveristand.clientapi._datatypes.rtprimitives.DoubleValue*](datatypes.md#niveristand.clientapi.DoubleValue) *]*) – the parameters to be passed to the RT sequence. * **Returns:** Stimulus profile session state. * **Return type:** [niveristand.clientapi.stimulusprofileapi.StimulusProfileState](stimulusprofileapi.md#niveristand.clientapi.StimulusProfileState) Deploys and runs the sequence without waiting for the sequence to finish. Use the returned [`StimulusProfileState`](stimulusprofileapi.md#niveristand.clientapi.StimulusProfileState) to wait for the sequence to complete and obtain the return value. For a simpler use case, refer to [`niveristand.realtimesequencetools.run_py_as_rtseq()`](realtimesequencetools.md#niveristand.realtimesequencetools.run_py_as_rtseq) ``` -------------------------------- ### Define a Basic Real-time Sequence Source: https://github.com/ni/niveristand-python/blob/master/docs/basic_rt_sequence_examples.md Defines a Python function as a real-time sequence using the @nivs_rt_sequence decorator. This example calls another function and checks its result, generating an error if it's unexpected. ```python import niveristand from niveristand.exceptions import RunError from niveristand.realtime import DoubleValue, ErrorAction # Assume add_two_numbers and generate_error are defined elsewhere def add_two_numbers(a, b): # This is a placeholder for the actual function return a + b def generate_error(code, message, action): # This is a placeholder for the actual function print(f"Error: {code} - {message}") @niveristand.nivs_rt_sequence def call_add_two_numbers_test(): result = DoubleValue(0) result.value = add_two_numbers(1, 2) if result.value != 3: generate_error(-100, "Unexpected result", ErrorAction.ContinueSequenceExecution) ``` -------------------------------- ### Initialize BooleanValueArray Source: https://github.com/ni/niveristand-python/blob/master/docs/api_reference/datatypes.md Shows how to initialize a BooleanValueArray using lists of valid BooleanValue initializers. ```python a = BooleanValueArray([True, False]) a = BooleanValueArray([1.0, 0.0]) ``` -------------------------------- ### save Method Source: https://github.com/ni/niveristand-python/blob/master/docs/api_reference/realtimesequence.md Saves this sequence to disk, including all its dependencies. ```APIDOC #### save(path=None) Saves this sequence to disk. * **Parameters:** **path** (*Optional* *[**str* *]*) – path to the location you want to save the sequence file. * **Returns:** path you specify in **path**. All dependencies required for deployment of this sequence save to the same path. If you do not specify a path in **path**, this sequence saves to the location where you last saved the object. If you did not previously save the object, it saves to a temporary folder. For a simpler use case, refer to [`niveristand.realtimesequencetools.save_py_as_rtseq()`](realtimesequencetools.md#niveristand.realtimesequencetools.save_py_as_rtseq) ``` -------------------------------- ### Run Real-time Sequence Non-deterministically Source: https://github.com/ni/niveristand-python/blob/master/docs/basic_rt_sequence_examples.md Demonstrates how to execute a real-time sequence in a non-deterministic manner, similar to running a standard Python function. Includes basic error handling for potential runtime issues. ```python from niveristand.exceptions import RunError # Assume call_add_two_numbers_test is defined elsewhere def call_add_two_numbers_test(): pass # Placeholder try: call_add_two_numbers_test() except RunError as run_error: print("Something Non-deterministic went wrong:" + str(run_error)) ``` -------------------------------- ### Configure LIN Interface and Database Source: https://github.com/ni/niveristand-python/blob/master/docs/sysdef_examples.md Enables the XNET interface and configures a LIN database, cluster, and port. Ensure the database name matches your LDF file. ```python target = system_definition.root.get_targets().get_target_list()[0] chassis = target.get_hardware().get_chassis_list()[0] chassis.get_xnet().enable_xnet() # enable XNET if we haven't already # LIN Database lin = chassis.get_xnet().get_lin() lin_database = Database("NIXNET_exampleLDF") target.get_xnet_databases().add_database(lin_database) # LIN Cluster lin_cluster = "Cluster" lin_port = LINPort("LIN 1", 1, lin_database, lin_cluster, 125000, "SlowSchedule") lin.add_lin_port(lin_port) ``` -------------------------------- ### Read and Write Individual Channels Source: https://context7.com/ni/niveristand-python/llms.txt Demonstrates reading a single channel's value and setting a single channel's value. Use channel aliases for easier access. ```python # Read and write individual channels rpm = workspace.GetSingleChannelValue("Aliases/ActualRPM") print(f"ActualRPM: {rpm}") workspace.SetSingleChannelValue("Aliases/DesiredRPM", 3000.0) ``` -------------------------------- ### System Definition API Source: https://context7.com/ni/niveristand-python/llms.txt Programmatically create NI VeriStand system definition (`.nivssdf`) files, adding targets, user channels, calculated channels, aliases, alarms, procedures, FMU models, and hardware. ```APIDOC ## System Definition API — `SystemDefinition`, Channels, Alarms, Models Programmatically create NI VeriStand system definition (`.nivssdf`) files, adding targets, user channels, calculated channels, aliases, alarms, procedures, FMU models, and hardware. ```python import os from niveristand.systemdefinitionapi import ( SystemDefinition, Alias, AliasFolder, Procedure, SetVariableStepFunction, AlarmMode, AlarmState, AlarmPriority, Model, ) from niveristand.systemdefinitionapi.calculatedchannels import LowpassFilter filepath = os.path.join(os.path.expanduser("~"), "Documents", "test_system.nivssdf") filename = "test_system" system_definition = SystemDefinition( filename, "Example system definition created with the Python API", "System Definition API", "1.0.0.0", "Controller", "Windows", filepath, ) target = system_definition.root.get_targets().get_target_list()[0] # Add user channel target.get_user_channels().add_new_user_channel("MyUserChannel", "", "", 1.0) user_channel = target.get_user_channels().get_user_channel_list()[1] # Add calculated (lowpass filter) channel lpf = LowpassFilter("MyLPFChannel", "", user_channel, 50, 1) target.get_calculated_channels().add_calculated_channel(lpf) # Add alias alias = Alias("MyAlias", "", user_channel) folder = AliasFolder("MyAliasFolder", "") system_definition.root.get_aliases().add_alias_folder(folder) system_definition.root.get_aliases().get_alias_folder_list()[0].add_alias(alias) # Add procedure with dwell and set-variable steps procedure = Procedure("MyProcedure", "") procedure.add_new_dwell("Dwell 3s", "", 3) procedure.add_new_set_variable("Count", "", user_channel, SetVariableStepFunction.ADD, user_channel, 1) target.get_procedures().add_procedure(procedure) # Add alarm target.get_alarms().add_new_alarm( "OverspeedAlarm", "", user_channel, 2, 1, procedure, AlarmMode.NORMAL, AlarmState.ENABLED, AlarmPriority.LOW, 0, "" ) ``` ``` -------------------------------- ### Configure DAQ Device and Channels Source: https://github.com/ni/niveristand-python/blob/master/docs/sysdef_examples.md This snippet demonstrates how to add a DAQ device and configure its analog input, analog output, digital input, digital output, counter, and internal channels. It also shows how to set up a waveform task and apply a polynomial scale. ```python daq_device = DAQDevice( "Dev1", "This is a DAQ Device created using the System Definition Offline API.", DAQDeviceInputConfiguration.DEFAULT, ) target = system_definition.root.get_targets().get_target_list()[0] chassis = target.get_hardware().get_chassis_list()[0] chassis.get_daq().add_device(daq_device) # Analog Input Channels analog_inputs = daq_device.create_analog_inputs() analog_inputs.add_analog_input( DAQAnalogInput("AI0", 1, DAQMeasurementType.ANALOG_INPUT_TEMPERATURE_THERMOCOUPLE) ) analog_inputs.add_analog_input( DAQAnalogInput("AI1", 0, DAQMeasurementType.ANALOG_INPUT_VOLTAGE) ) # Analog Output Channels analog_outputs = daq_device.create_analog_outputs() analog_outputs.add_analog_output( DAQAnalogOutput("AO0", 0, DAQMeasurementType.ANALOG_OUTPUT_VOLTAGE) ) # Digital Input Channels digital_inputs = daq_device.create_digital_inputs() daq_input_port = DAQDIOPort(0, False) digital_inputs.add_dio_port(daq_input_port) daq_input_port.add_digital_input(DAQDigitalInput("DI0", False, 0, 0)) daq_input_port.add_digital_input(DAQDigitalInput("DI1", False, 1, 0)) # Digital Output Channels digital_outputs = daq_device.create_digital_outputs() daq_output_port = DAQDIOPort(1, False) digital_outputs.add_dio_port(daq_output_port) daq_output_port.add_digital_output(DAQDigitalOutput("DO4", False, 4, 1)) # Counter Channels counters = daq_device.create_counters() counters.add_counter( DAQFrequencyMeasurement("FreqIn", "", 0, 0.0, 1.0, 0.0, DAQCounterEdge.FALLING) ) counters.add_counter_output(DAQPulseGeneration("PWMOut", "", 1)) # Internal Channels internal_channels = daq_device.create_internal_channels() internal_channels.add_internal_channel(DAQInternalChannel("Channel 0", 0.0)) # Waveform Tasks daq_device_waveform = DAQDevice("Dev2", "", DAQDeviceInputConfiguration.DEFAULT) chassis.get_daq().add_device(daq_device_waveform) daq_tasks = chassis.get_daq().get_tasks() waveform_task = DAQTaskAI("Task1", 1000, AcquisitionMode.CONTINUOUS) waveform_task.get_triggers().start_trigger = DAQTriggerDigitalEdge( "PFI0", DirectionType.FALLING ) daq_tasks.add_task(waveform_task) analog_waveform_input = DAQWaveformAnalogInput( "AI2", 0, DAQMeasurementType.ANALOG_INPUT_CURRENT ) waveform_analog_inputs = daq_device_waveform.create_analog_inputs() waveform_analog_inputs.sample_mode = SampleMode.WAVEFORM waveform_analog_inputs.add_waveform_analog_input(analog_waveform_input) waveform_analog_inputs.waveform_analog_input_task = waveform_task # Polynomial Scale coefficients = [1.0] reverse_coefficients = [] scale = PolynomialScale("MyScale", coefficients, reverse_coefficients, "") system_definition.root.get_scales().add_scale(scale) daq_device.get_analog_input_section().get_analog_input_list()[0].scale = scale ``` -------------------------------- ### Initialize I64Value Source: https://github.com/ni/niveristand-python/blob/master/docs/api_reference/datatypes.md Illustrates initializing an I64Value with int, float, or boolean values. Floating-point values are rounded down. ```python a = I64Value(3) a = I64Value(3.1415) a = I64Value(0x7FFFFFFFFFFFFFFF) a = I64Value(-9.2e18) a = I64Value(True) ``` -------------------------------- ### RealTimeSequence.run() Source: https://github.com/ni/niveristand-python/blob/master/docs/api_reference.md Executes the current VeriStand real-time sequence. ```APIDOC ## RealTimeSequence.run() ### Description Executes the current VeriStand real-time sequence. ### Method `run()` ### Parameters None ### Request Example ```python sequence.run() ``` ### Response None ``` -------------------------------- ### Workspace2.ReconnectToSystem() Source: https://github.com/ni/niveristand-python/blob/master/docs/api_reference.md Re-establishes the connection to the NI VeriStand system. ```APIDOC ## Workspace2.ReconnectToSystem() ### Description Re-establishes the connection to the NI VeriStand system. ### Method Not specified (assumed to be a method call within the Python API) ### Endpoint Not applicable (Python API call) ### Parameters None ### Request Example ```python niv.Workspace2.ReconnectToSystem() ``` ### Response #### Success Response None ``` -------------------------------- ### Initialize BooleanValue Source: https://github.com/ni/niveristand-python/blob/master/docs/api_reference/datatypes.md Demonstrates initializing a BooleanValue with different valid types: bool, string, and int/float. ```python a = BooleanValue(True) a = BooleanValue(1.0) a = BooleanValue(1) ``` -------------------------------- ### Initialize U64Value Source: https://github.com/ni/niveristand-python/blob/master/docs/api_reference/datatypes.md Illustrates initializing a U64Value with int, float, or boolean values. Floating-point values are rounded down. ```python a = U64Value(3) a = U64Value(3.1415) a = U64Value(0x7FFFFFFFFFFFFFFF) a = U64Value(18.4e18) a = U64Value(True) ``` -------------------------------- ### MacroPlayer.LoadMacro Source: https://github.com/ni/niveristand-python/blob/master/docs/api_reference/legacy.md Loads a workspace macro for playback. ```APIDOC ## MacroPlayer.LoadMacro(file) ### Description Loads a workspace macro. ### Method N/A (Method call) ### Parameters #### Path Parameters - **file** (string) - Required - The path to the workspace macro file. ``` -------------------------------- ### Run Real-time Sequence Deterministically Source: https://github.com/ni/niveristand-python/blob/master/docs/basic_rt_sequence_examples.md Shows how to execute a real-time sequence deterministically on the VeriStand engine. This method requires a connection to the VeriStand system and includes error handling. ```python import niveristand from niveristand.exceptions import RunError # Assume call_add_two_numbers_test is defined elsewhere def call_add_two_numbers_test(): pass # Placeholder try: niveristand.realtimesequencetools.run_py_as_rtseq(call_add_two_numbers_test) except RunError as run_error: print("Something Deterministic went wrong:" + str(run_error)) ``` -------------------------------- ### Run Advanced Engine Demo Sequence Source: https://github.com/ni/niveristand-python/blob/master/docs/engine_demo.md This function executes the advanced engine demonstration sequence. It includes a try/finally block to ensure the engine is safely shut down, even if an error occurs during the demonstration. Use this to run the main engine simulation. ```python @nivs_rt_sequence def run_engine_demo_advanced(): """Run the engine_demo_advanced example. To handle a condition that stops a task (such as, the engine temperature rising above a safe value), use a try/finally block. Regardless of the result of the execution, the finally block can be used to safely shut down the engine. """ try: warmup_succeeded = BooleanValue(False) engine_power = ChannelReference("Aliases/EnginePower") desired_rpm = ChannelReference("Aliases/DesiredRPM") actual_rpm = ChannelReference("Aliases/ActualRPM") engine_temp = ChannelReference("Aliases/EngineTemp") engine_power.value = True warmup_succeeded.value = engine_demo_advanced(desired_rpm, actual_rpm, engine_temp) finally: engine_power.value = False desired_rpm.value = 0 return warmup_succeeded.value ``` -------------------------------- ### Initialize I32Value Source: https://github.com/ni/niveristand-python/blob/master/docs/api_reference/datatypes.md Shows initializing an I32Value with int, float, or boolean values. Floating-point values are rounded down. ```python a = I32Value(3) a = I32Value(3.1415) a = I32Value(0x7FFFFFFF) a = I32Value(True) ``` -------------------------------- ### Legacy Workspace2 API Source: https://github.com/ni/niveristand-python/blob/master/docs/api_reference.md Advanced methods for connecting to and managing VeriStand systems. ```APIDOC ## Workspace2.ConnectToSystem() ### Description Connects to a VeriStand system. ### Method `Workspace2.ConnectToSystem()` ### Parameters None ``` ```APIDOC ## Workspace2.DisconnectFromSystem() ### Description Disconnects from the VeriStand system. ### Method `Workspace2.DisconnectFromSystem()` ### Parameters None ``` -------------------------------- ### niveristand.library.multitask() Source: https://github.com/ni/niveristand-python/blob/master/docs/api_reference/library.md Creates a multitask context for branching execution. ```APIDOC ## multitask() ### Description Creates a multitask context for branching execution. Refer to `niveristand.library.multitask()` for more details on branching execution. ``` -------------------------------- ### MacroPlayer.PlayMacro Source: https://github.com/ni/niveristand-python/blob/master/docs/api_reference.md Plays the currently loaded macro. ```APIDOC ## MacroPlayer.PlayMacro() ### Description Executes the macro that is currently loaded in the Macro Player. ### Method `PlayMacro` ### Response #### Success Response This method does not return a value upon success. ``` -------------------------------- ### Run All Tests with Tox Source: https://github.com/ni/niveristand-python/blob/master/CONTRIBUTING.md Executes all tests defined in the project using tox. This command creates virtual environments and runs tests on all supported Python versions. ```bash $ tox ``` -------------------------------- ### Legacy API - Workspace2, AlarmManager2, ModelManager2 Source: https://context7.com/ni/niveristand-python/llms.txt The `niveristand.legacy` module provides the IronPython-compatible Gateway API for connecting to a running VeriStand system, reading/writing channels, managing alarms, controlling models, and running stimulus profiles. ```APIDOC ## Legacy API — `Workspace2`, `AlarmManager2`, `ModelManager2` The `niveristand.legacy` module provides the IronPython-compatible Gateway API for connecting to a running VeriStand system, reading/writing channels, managing alarms, controlling models, and running stimulus profiles. ```python import os from niveristand import run_py_as_rtseq from niveristand.errors import RunError from niveristand.legacy import NIVeriStand ``` ``` -------------------------------- ### Configure NI-XNET CAN Interface Source: https://github.com/ni/niveristand-python/blob/master/docs/sysdef_examples.md Enables XNET, adds a user channel, and configures CAN databases, clusters, ports, and frames for both incoming and outgoing communication. Includes settings for data logging and frame faulting. ```python target = system_definition.root.get_targets().get_target_list()[0] chassis = target.get_hardware().get_chassis_list()[0] chassis.get_xnet().enable_xnet() # enable XNET if we haven't already target.get_user_channels().add_new_user_channel("MyXnetUserChannel", "", "", 1.0) user_channel = target.get_user_channels().get_user_channel_list()[0] # CAN Database can = chassis.get_xnet().get_can() can_database = Database("NIXNET_example") target.get_xnet_databases().add_database(can_database) # CAN Cluster can_cluster = "CAN_Cluster" can_port = CANPort("CAN 1", 1, can_database, can_cluster, 125000) can_port.termination = XNETTermination.ON can.add_can_port(can_port) # Frame Variables cyclic_frame = "CANCyclicFrame1" cyclic_frame_signals = ["CANCyclicSignal1", "CANCyclicSignal2"] event_frame = "CANEventFrame1" event_frame_signals = ["CANEventSignal1", "CANEventSignal2"] # CAN Incoming Frames incoming_cyclic_frame = SignalBasedFrame( cyclic_frame, 64, can_database, can_cluster, 8, 0.1, False, cyclic_frame_signals ) can_port.get_incoming().get_single_point().add_signal_based_frame(incoming_cyclic_frame) for signal in cyclic_frame_signals: incoming_cyclic_frame.create_signal_based_signal(signal, "", "volts", 0.0) incoming_event_frame = SignalBasedFrame( event_frame, 66, can_database, can_cluster, 8, 0.1, False, event_frame_signals ) can_port.get_incoming().get_single_point().add_signal_based_frame(incoming_event_frame) for signal in event_frame_signals: incoming_event_frame.create_signal_based_signal(signal, "", "volts", 0.0) incoming_cyclic_frame.create_frame_information() incoming_data_logging = DataLoggingFile( "log", "file", os.path.dirname(system_definition.document_type.document_file_path) ) incoming_data_logging.data_logging_file_type = FileType.TDMS can_port.get_incoming().get_raw_frame_data_logging().add_data_logging_file( incoming_data_logging ) can_port.get_incoming().get_raw_frame_data_logging().get_data_logging_file_list()[0].trigger_channel = user_channel # CAN Outgoing Frames outgoing_cyclic_frame = SignalBasedFrame( cyclic_frame, 64, can_database, can_cluster, 8, 0.1, False, cyclic_frame_signals ) can_port.get_outgoing().get_cyclic().add_signal_based_frame(outgoing_cyclic_frame) for signal in cyclic_frame_signals: outgoing_cyclic_frame.create_signal_based_signal(signal, "", "volts", 0.0) outgoing_event_frame = SignalBasedFrame( event_frame, 64, can_database, can_cluster, 8, 0.1, False, event_frame_signals ) can_port.get_outgoing().get_event_triggered().add_signal_based_frame(outgoing_event_frame) for signal in event_frame_signals: outgoing_event_frame.create_signal_based_signal(signal, "", "volts", 0.0) outgoing_cyclic_frame.create_frame_faulting(True, True) outgoing_cyclic_frame.get_frame_faulting().get_skip_cyclic_frames().trigger_channel = ( user_channel ) outgoing_cyclic_frame.get_frame_faulting().get_transmit_time().set_trigger_channel(user_channel) outgoing_data_replay = DataFileReplay("replay", get_asset("fake.tdms")) can_port.get_outgoing().get_data_replay().add_data_file_replay(outgoing_data_replay) can_port.get_outgoing().get_data_replay().get_data_file_replay_list()[ 0 ].trigger_channel = user_channel ```