def launch_veristand(): NIVeriStand.LaunchNIVeriStand() print('wait for Veristand Launching') time.sleep(10) print('Wait end') workspace = NIVeriStand.Workspace2('localhost') return workspace
def test_stimulus_steps_legacy(): #Every test should have a user variable that have a test ID number to ensure that you are running the correct test configuration. TEST_ID = 12000 wks = NIVeriStand.Workspace2() #print(statement take a string and it is piped out to a single trace file in the background, for your tracing needs.) print("") SYSDEFFILE = os.path.join(configutilities.get_autotest_projects_path(), "ProfileTest", "Profile Test.nivssdf") print("Deploying %s" % SYSDEFFILE) wks.ConnectToSystem(SYSDEFFILE, 1, 60000) print("System Definition deployed") try: #Verify the TEST_ID var on test file. test_ID = wks.GetSingleChannelValue("TEST_ID") assert (test_ID == TEST_ID), "Deployed wrong test file" stm = NIVeriStand.Stimulus() assert run_test(wks, stm, "Ramp Test.nivstest", 120) sleep() assert run_test(wks, stm, "Conditional Test.nivstest", 120) sleep() assert run_test(wks, stm, "Dwell Test.nivstest", 120) finally: #Always stop the engine. wks.DisconnectFromSystem("", 0)
def test_expected_profile_failures_legacy(): #Every test should have a user variable that have a test ID number to ensure that you are running the correct test configuration. TEST_ID = 12000 #Getting a handle to the workspace API #Other API: Model, Alarm, AlarmManager, SoftwareForcing, ModelManager wks = NIVeriStand.Workspace2() try: #print(statement take a string and it is piped out to a single trace file in the background, for your tracing needs.) print("") #standard way of running a configuration file. VSTANDPROJECTDIR is configured to the location where test project files get sync. So just append your folder and rig file. SYSDEFFILE = os.path.join(configutilities.get_autotest_projects_path(), "ProfileTest", "Profile Test.nivssdf") print("Deploying %s" % SYSDEFFILE ) wks.ConnectToSystem(SYSDEFFILE,1,60000) print("System Definition deployed") #Verify the TEST_ID var on test file. test_ID = wks.GetSingleChannelValue("TEST_ID") assert(test_ID == TEST_ID), "Deployed wrong test file" stm = NIVeriStand.Stimulus() with pytest.raises(NIVeriStandException): gens_error = run_test(wks, stm, "Too Many Gens.nivstest", 120) assert (gens_error == 4294659383) with pytest.raises(NIVeriStandException): steps_error = run_test(wks, stm, "Too Many Steps.nivstest", 120) assert (steps_error == 4294659395) with pytest.raises(NIVeriStandException): aux_error = run_test(wks, stm, "Aux Buffer Overflow.nivstest", 120) assert (aux_error == 4294659393) with pytest.raises(NIVeriStandException): chan_error = run_test(wks, stm, "Invalid Channel.nivstest", 120) assert (chan_error == 4294659387) finally: #Always stop the engine. wks.DisconnectFromSystem("", 0)
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() # Uses the ClientAPI interface to get a reference to Workspace2 workspace = NIVeriStand.Workspace2("localhost") engine_demo_path = os.path.join(os.path.expanduser("~"), 'Documents', 'National Instruments', 'VeriStand 2018', 'Examples', 'Stimulus Profile', 'Engine Demo', 'Engine Demo.nivssdf') # Deploys the system definition. workspace.ConnectToSystem(engine_demo_path, True, 60000) 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)
def test_custom_devices_legacy(): import random #Getting a handle to the workspace API #Other API: Model, Alarm, AlarmManager, SoftwareForcing, ModelManager wks = NIVeriStand.Workspace2('localhost') #print(statement take a string and it is piped out to a single trace file in the background, for your tracing needs.) print("") #standard way of running a configuration file. VSTANDPROJECTDIR is configured to the location where test project files get sync. So just append your folder and rig file. SYSDEFFILE = os.path.join(configutilities.get_autotest_projects_path(), "CustomDevices", "CustomDevices.nivssdf") print("[b] Deploying %s" % SYSDEFFILE) wks.ConnectToSystem(SYSDEFFILE, 1, 60000) try: #Verify the TEST_ID var on test file. #Every test should have a user variable that have a test ID number to ensure that you are running the correct test configuration. TEST_ID = 10239 # Verify the TEST_ID var on test file. test_ID = wks.GetSingleChannelValue("TEST_ID") assert (test_ID == TEST_ID), "Deployed wrong test file" #Get Parameter from test system if necessary, if you are being passed an argument from the test system then you will need to get the parameters. The following #python code is recommended practice: #Declare variable to store the parameter with a default value since you will always want to trouble shoot your test script without running the full LabVIEW auto test. #TEST_PARAM_IPADDRESS = "localhost" #set default IP address to localhost for manual run. #if EnvVars.ARG_LIST.has_key( "IPADDRESS"): # TEST_PARAM_IPADDRESS = EnvVars.ARG_LIST["IPADDRESS"] #repeat the above process for all parameters you expect to be passed in by the LabVIEW test system. _test_device(wks, "Async", 100 * random.random()) _test_device(wks, "HW", 200 * random.random()) _test_device(wks, "Mdl", 300 * random.random()) print("Test PASSED") finally: #Always stop the engine. wks.DisconnectFromSystem("", 1)
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() print('wait') time.sleep(10) print('Wait end') # Uses the ClientAPI interface to get a reference to Workspace2 workspace = NIVeriStand.Workspace2("localhost") engine_demo_path = "C:\\Users\\Public\\Documents\\" \ "National Instruments\\NI VeriStand 2018\\Examples\\Stimulus Profile\\Engine Demo\\Engine Demo.nivssdf" # Deploys the system definition. workspace.ConnectToSystem(engine_demo_path, True, 60000) try: # Uses Python real-time sequences to run a test. # run_py_as_rtseq(run_engine_demo) engine_demo_basic(BooleanValue(True), DoubleValue(2500)) 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)
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() # Wait 30 seconds for the gateway to start time.sleep(30) engine_demo_path = Path(r"C:\Users\Public\Documents\National Instruments\NI VeriStand 2020\Examples\Stimulus Profile\Engine Demo\Engine Demo.nivssdf") if not engine_demo_path.exists(): print("Error! System definition not found!") return # Uses the ClientAPI interface to get a reference to Workspace2 workspace = NIVeriStand.Workspace2("localhost") # engine_demo_path = os.path.join("c:/", "users", "public", "Documents", "National Instruments", "VeriStand 2020", "Examples", "Stimulus Profile", "Engine Demo", "Engine Demo.nivssdf") # Deploys the system definition. workspace.ConnectToSystem(str(engine_demo_path), True, 60000) 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)
def test_worksspace2_api(): wks = NIVeriStand.Workspace2("localhost") print("") SYSDEFINITION = os.path.join(configutilities.get_autotest_projects_path(), "TestWorkspaceAPI","TestWorkspaceAPI.nivssdf") print("Deploying %s" % SYSDEFINITION) wks.ConnectToSystem(SYSDEFINITION,True,60000) try: #Verify the TEST_ID var on test file. test_ID = wks.GetSingleChannelValue("TEST_ID") assert(test_ID == TEST_ID), "Deployed wrong test file" result = wks.GetSystemState() assert(result['systemdefinition_file'] == SYSDEFINITION), "System definition file is not the same as deployed" wks.LockConnection("",'LOCK_PASSWORD') with pytest.raises(NIVeriStandException): wks.DisconnectFromSystem("",0) with pytest.raises(NIVeriStandException): wks.UnlockConnection("") wks.UnlockConnection('LOCK_PASSWORD') print("Get System Node Children") result = wks.GetSystemNodeChildren(r"Controller/Simulation Models/Models/sinewave/Execution") assert(len(result) == 4), "Model Exceution should return 4 node" #test we can still get system node children with full path. result = wks.GetSystemNodeChildren(r"Targets Section/Controller/Simulation Models/Models/sinewave/Execution") assert(len(result) == 4), "Model Exceution should return 4 node" print("Get System Node Channel List") result = wks.GetSystemNodeChannelList('') assert(len(result) >= 100), "At the very list we always have 100 channel" print(result[2]) print("Get Alias List") result = wks.GetAliasList() assert(len(result) == 3), "Expected 3 alias but get something different %d" % len(result) assert(result['TEST_ID'] == r"Targets Section/Controller/User Channel/TEST_ID"), "Expected an alias for TEST_ID incorrect" #Mix up different mode of how we look up system nodes data: full path and also relative to Targets Section. nodes = ('Targets Section/Controller/User Channel', 'Controller/User Channel/TEST_ID') result = wks.GetMultipleSystemNodesData(nodes) assert(len(result) == 2), "Ask for 2 node info get no info" print("Validating channels") section = result[0] print(section) assert(section['isChannel'] == 0), "Expecting a section to returned" testNode = result[1] print(testNode) assert(testNode['isChannel'] == 1), "Expecteing a node to returned" print("Test PASSED") print("") finally: wks.DisconnectFromSystem("",1)
def test_alarm2_api(): wks = NIVeriStand.Workspace2("localhost") print("") SYSDEFINITION = os.path.join(configutilities.get_autotest_projects_path(), "TestAlarmAPI", "TestAlarmAPI.nivssdf") print("Deploying %s" % SYSDEFINITION) wks.ConnectToSystem(SYSDEFINITION, 1, 80000) try: # Verify the TEST_ID var on test file. test_ID = wks.GetSingleChannelValue("TEST_ID") assert (test_ID == TEST_ID), "Deployed wrong test file" print("Testing Alarm manager Get Alarm List") alarmMgr = NIVeriStand.AlarmManager2("localhost") result = alarmMgr.GetAlarmList("Controller") assert (len(result) == 3), "Expected 3 alarms returned from the system" with pytest.raises(NIVeriStandException): alarmMgr.GetAlarmList("Invalid Controller") print("Testing Alarm manager Read Alarm Data") alarms = ('Alarm Group/AlarmTest1', 'Alarm Group/AlarmTest2', 'ConstantBoundAlarm') result = alarmMgr.GetMultipleAlarmsData("Controller", alarms, 60000) print("Verifying alarm data returned") assert (len(result) == 3), "Expected to get 3 alarms data back" with pytest.raises(NIVeriStandException): alarmMgr.GetMultipleAlarmsData("INVALID CONTROLLER", alarms, 60000) print("Verifying Alarm Data") alarmTest1 = result[0] alarmTest2 = result[1] constantBoundAlarm = result[2] print(alarmTest1) assert (alarmTest1['WatchChannel'] == r"AlarmChannel1" ), "Fail to confirm alarm channel" assert ((alarmTest1['HighLimitIsConstant'] == 0) or (alarmTest1['HighLimitChannel'] == r"AlarmChannel1High")), "Fail to confirm high limit" assert ((alarmTest1['LowLimitIsConstant'] == 0) or (alarmTest1['LowLimitChannel'] == r"AlarmChannel1Low")), "Fail to confirm low limit" assert (alarmTest1['DelayDuration'] == 0.5 ), "Fail to confirm delay duration" assert (alarmTest1['ProcedureName'] == r"ResetAlarmTest1" ), "Fail to confirm procedure" assert (alarmTest1['Priority'] == 2 ), "Fail to confirm priority (deprecated)" assert (alarmTest1['PriorityNumber'] == 5 ), "Fail to confirm priority number" assert (alarmTest1['State'] == 1), "Fail to confirm state" assert (alarmTest1['Mode'] == 0), "Fail to confirm mode" assert (alarmTest1['GroupNumber'] == 1), "Fail to confirm alarm group" print("Test alarm interface") print("Test Alarm constructor mode") Constructor1 = NIVeriStand.Alarm('Alarm Group/Alarm Test2') Constructor2 = NIVeriStand.Alarm('Alarm Group/Alarm Test2', 'Controller') Constructor3 = NIVeriStand.Alarm('Alarm Group/Alarm Test2', None, 'localhost') Constructor4 = NIVeriStand.Alarm('Alarm Group/Alarm Test2', 'Controller', 'localhost') print("Test access to alarm") BoundAlarmRef = NIVeriStand.Alarm('ConstantBoundAlarm', 'Controller', 'localhost') result = BoundAlarmRef.GetAlarmData(30000) assert (result == constantBoundAlarm ), "Alarm data from alarm interface differ from alarm manager" print("Test modifying alarm data") modAlarmData = result modAlarmData['HighLimit'] = 3 modAlarmData['LowLimit'] = -3 BoundAlarmRef.SetAlarmData2(modAlarmData) sleep() result = BoundAlarmRef.GetAlarmData(30000) assert (result == modAlarmData), "Alarm data set cannot be confirmed" print("Test modifying alarm state and mode") BoundAlarmRef.SetEnabledState(0) #indicate only BoundAlarmRef.SetAlarmMode(1) sleep() result = BoundAlarmRef.GetAlarmData(30000) assert (result['State'] == 0), "Alarm Mode is wrong" assert (result['Mode'] == 1), "Alarm Mode is wrong" BoundAlarmRef.SetEnabledState(1) BoundAlarmRef.SetAlarmMode(0) sleep() sleep() wks.SetSingleChannelValue(r"Controller/User Channel/AlarmChannel1", 20) wks.SetSingleChannelValue(r"Controller/User Channel/AlarmChannel2", 10) sleep() sleep() print("Testing alarm mutual exclusion within a group") AlarmTest2Ref = NIVeriStand.Alarm('Alarm Group/AlarmTest2') AlarmTest1Ref = NIVeriStand.Alarm('Alarm Group/AlarmTest1') result = AlarmTest1Ref.GetAlarmData(30000) result2 = AlarmTest2Ref.GetAlarmData(30000) assert (result['State'] == 2), "Alarm should be tripped" assert ( result2['State'] != 2 ), "Alarm should not be running due to an execution of a higher priority." print("Testing Alarm Execution Across Groups") result = BoundAlarmRef.GetAlarmData(30000) result2 = AlarmTest2Ref.GetAlarmData(30000) assert ((result['State'] == 2) and (result2['State'] == 2)), " Two alarms should be tripped simulteneously." print("Test PASSED") print("") finally: wks.DisconnectFromSystem("", 1)
def deploy_veristand(system_definition_file_path): """Customize each system definition file for B, C, D, E Truck""" workspace = NIVeriStand.Workspace2('localhost') path = system_definition_file_path workspace.ConnectToSystem(path, True, 60000) return workspace
def test_reconnect_to_system(): wks = NIVeriStand.Workspace2(GATEWAY) print("") print("Connecting to the gateway %(gateway)s, target %(target)s" % { 'gateway': GATEWAY, "target": TARGET }) wks.ReconnectToSystem(TARGET, True, None, 60000) try: result = wks.GetSystemState() assert (result['systemdefinition_file'] == SDF ), "System definition file is not the same as deployed" print("Get System Node Children") result = wks.GetSystemNodeChildren( r"Controller/Simulation Models/Models/sinewave/Execution") assert (len(result) == 4), "Model Exceution should return 4 node" #test we can still get system node children with full path. result = wks.GetSystemNodeChildren( r"Targets/Controller/Simulation Models/Models/sinewave/Execution") assert (len(result) == 4), "Model Exceution should return 4 node" print("Get System Node Channel List") result = wks.GetSystemNodeChannelList('') assert (len(result) >= 100), "At the very least we always have 100 channel" print(result[2]) print("Get Alias List") result = wks.GetAliasList() assert ( len(result) == 6 ), "Expected 6 aliases but get something different %d" % len(result) assert ( result['SineWave'] == r"Targets/Controller/Simulation Models/Models/sinewave/Signals/sine/SineWave" ), "Alias for SineWave incorrect" #Mix up different mode of how we look up system nodes data: full path and also relative to Targets Section. nodes = (SINE_WAVE, LOOP_RATE) result = wks.GetMultipleSystemNodesData(nodes) assert (len(result) == 2), "Ask for 2 node info get no info" print("Validating channels") section = result[0] print(section) assert (section['isChannel'] == 1 ), "Expected channel, got something different." testNode = result[1] print(testNode) assert (testNode['isChannel'] == 1 ), "Expected channel, got something different." print("Test PASSED") print("") finally: pass wks.DisconnectFromSystem("", True)
from niveristand.library import wait from examples.engine_demo.engine_demo_basic import run_engine_demo from examples.engine_demo.engine_demo_advanced import run_engine_demo_advanced import os from time import sleep #Create Variable to use within the code to set RPM setRPM = 2500 file_path = r"C:\Users\ahidalgo\Documents\VeriStand Projects\Engine Demo\Engine Demo.nivsproj" #Start NI VeriStand os.startfile(file_path) sleep(17) #Open the Workspace, this is to use the Legacy functionality to manipulate the controls and indicators in the project workspace = NIVeriStand.Workspace2('localhost') #engine_demo_path = r'C:\Users\Public\Documents\National Instruments\NI VeriStand 2020\Examples\Stimulus Profile\Engine Demo\Engine Demo.nivssdf' engine_demo_path = r'C:\Users\ahidalgo\Documents\VeriStand Projects\Engine Demo\Engine Demo.nivssdf' try: #Initiate Connection and Deploy a Sysem Definition File workspace.ConnectToSystem(engine_demo_path, True, 60000) sleep(4) run_py_as_rtseq(run_engine_demo) print("Test Success") run_py_as_rtseq(run_engine_demo_advanced) print("Advanced Test Success") # #Turn on the Engine
def test_model_manager2_legacy(): #Getting a handle to the workspace API #Other API: Model, Alarm, AlarmManager, SoftwareForcing, ModelManager wks = NIVeriStand.Workspace2('localhost') mmgr = NIVeriStand.ModelManager2('localhost') SYSDEFINITION = os.path.join(configutilities.get_autotest_projects_path(), "ModelParameterAPI_AUTOTEST", "ModelParameterAPI_AUTOTEST.nivssdf") print("Deploying %s" % SYSDEFINITION) wks.ConnectToSystem(SYSDEFINITION, 1, 60000) try: #Verify the TEST_ID var on test file. test_ID = wks.GetSingleChannelValue("TEST_ID") assert (test_ID == TEST_ID), "Deployed wrong test file" #declaring known and expected system values models = [ "VectMod", "VectModWorkspace", "VectModWorkspace2", "clocktest", "sinewave" ] sinewaveParams = ["Amplitude", "Bias", "Frequency", "Gain", "Phase"] workspaceList = ["CONST1by5", "CONST2by3", "CONST5by1"] paramList = [ "VectMod/1by5Param/Value", "VectMod/2by3Param/Value", "VectMod/5by1Param/Value" ] vectorParamList = workspaceList + paramList nonVectorParamList = sinewaveParams allParamInSystem = vectorParamList + nonVectorParamList CONST_1by5_initValue = [[1, 2, 3, 4, 5]] CONST_2by3_initValue = [[1, 2, 3], [10, 20, 30]] CONST_5by1_initValue = [[1], [2], [3], [4], [5]] CONST_VALUES = [ CONST_1by5_initValue, CONST_2by3_initValue, CONST_5by1_initValue ] #Now do your test print("Testing GetModelList") sysmodels = mmgr.GetModelList("Controller") for model in models: assert model in sysmodels, "Missing model expected to be returned by system" with pytest.raises(NIVeriStandException): mmgr.GetModelList("NON_EXISTING_CONTROLLER") print("Testing GetParameterList") sysparamlist = mmgr.GetParametersList("Controller") for param in allParamInSystem: assert param in sysparamlist, "Missing parameter expected to be returned by system %s" % param with pytest.raises(NIVeriStandException): mmgr.GetParametersList("NON_EXISTING_CONTROLLER") print("Testing Get Single Parameter Value") result = mmgr.GetSingleParameterValue("Controller", workspaceList[1]) assert ( result == CONST_1by5_initValue[0][0] ), "Error on getting single parameter value get %f and expected %d" % ( result, CONST_1by5_initValue[0][0]) with pytest.raises(NIVeriStandException): mmgr.GetSingleParameterValue("NON_EXISTING_CONTROLLER", workspaceList[1]) print("Testing Get Multiple Parameter Values") result = mmgr.GetMultipleParameterValues("Controller", vectorParamList) expresult = [1, 1, 1, 1, 1, 1] for i in result: assert ( i == 1 ), "Error on getting multiple parameter value get %d and expected 1" % i with pytest.raises(NIVeriStandException): mmgr.GetMultipleParameterValues("NON_EXISTING_CONTROLLER", vectorParamList) print("Testing Get Parameter Vector Values") for i in range(0, 3): result = mmgr.GetParameterVectorValues("Controller", workspaceList[i]) assert (result == CONST_VALUES[i] ), "Error verifying vector values %s" % workspaceList[i] with pytest.raises(NIVeriStandException): mmgr.GetParameterVectorValues("NON_EXISTING_CONTROLLER", workspaceList[1]) print("Testing Get Parameter Vector Values 2") for i in range(0, 3): result = mmgr.GetParameterVectorValues("Controller", paramList[i]) assert (result == CONST_VALUES[i] ), "Error verifying vector values %s" % paramList[i] print("Test Set Single Parameter Value") for param in nonVectorParamList: print(("Set parameter " + param)) mmgr.SetSingleParameterValue("Controller", param, 2) sleep() with pytest.raises(NIVeriStandException): mmgr.SetSingleParameterValue("NON_EXISTING_CONTROLLER", nonVectorParamList[1], 2) for param in nonVectorParamList: print(("Verifying Set Paramater " + param)) result = mmgr.GetSingleParameterValue("Controller", param) assert (result == 2 ), "Error verifying set single parameter value %s %d" % ( param, result) print("Test Set Multiple Parameter Values") newValue = (3, 3, 3, 3, 3) mmgr.SetMultipleParameterValues("Controller", nonVectorParamList, newValue) sleep() result = mmgr.GetMultipleParameterValues("Controller", nonVectorParamList) for i in result: assert ( i == 3 ), "Error verifying set multiple parameter value get %d and expected 3" % i with pytest.raises(NIVeriStandException): mmgr.SetMultipleParameterValues("NON_EXISTING_CONTROLLER", nonVectorParamList, newValue) print("Test Set Single Vector Values") CONST_1by5_modValue = [[6, 7, 8, 9, 10]] CONST_2by3_modValue = [[4.25, 5.25, 6.25], [7.5, 8.5, 9.5]] CONST_5by1_modValue = [[6], [7], [8], [9], [10]] CONST_MODVALUES = [ CONST_1by5_modValue, CONST_2by3_modValue, CONST_5by1_modValue, CONST_1by5_modValue, CONST_2by3_modValue, CONST_5by1_modValue ] for i in range(0, 6): print("Set Parameter Vector for " + vectorParamList[i]) mmgr.SetParameterVectorValues("Controller", vectorParamList[i], CONST_MODVALUES[i]) sleep() for i in range(0, 6): print("Verifying Set Parameter Vector for " + vectorParamList[i]) result = mmgr.GetParameterVectorValues("Controller", vectorParamList[i]) assert ( result == CONST_MODVALUES[i] ), "Error verifying set parameter vector values %s" % vectorParamList[ i] print("Test Set Parameters Values") TESTPARAMS = ["Amplitude", "CONST1by5", "VectMod/2by3Param/Value"] SINGLE_PARAM_TESTVALUE = [[10]] CONST_1by5_TestValue = [[100, 200, 300, 400, 500]] CONST_2by3_TestValue = [[1000.25, 2000.25, 3000.25], [4000.5, 5000.5, 6000.5]] TESTVALUES = [ SINGLE_PARAM_TESTVALUE, CONST_1by5_TestValue, CONST_2by3_TestValue ] mmgr.SetParameterValues("Controller", TESTPARAMS, TESTVALUES) sleep() sleep() assert (mmgr.GetSingleParameterValue("Controller", "Amplitude") == 10 ), "Error verifying set parameter values to a single parameter" assert ( mmgr.GetParameterVectorValues("Controller", "CONST1by5") == CONST_1by5_TestValue ), "Error verifying set parameter vector values to a 1 by 5 parameter" assert ( mmgr.GetParameterVectorValues( "Controller", "VectMod/2by3Param/Value") == CONST_2by3_TestValue ), "Error verifying set parameter vector values to a 2 by 3 parameter" print("Test Set and Get Vector Channel Values") #VectModWorksace_2by3Out value = VectModWorkspace_2by3In value + CONST2by3 param value #VectModWorksace2_2by3Out value = VectModWorkspace2_2by3In value + CONST2by3 param value CONST_2by3_VECTOR = [[1, 2, 3], [10, 20, 30]] CONST_2by3_VECTOR_TIMES2 = [[2, 4, 6], [20, 40, 60]] CONST_2by3_VECTOR_ZEROES = [[0, 0, 0], [0, 0, 0]] inports = ["VectModWorkspace_2by3In", "VectModWorkspace2_2by3In"] outports = ["VectModWorkspace_2by3Out", "VectModWorkspace2_2by3Out"] wks.SetChannelVectorValues(inports[0], CONST_2by3_VECTOR_ZEROES) wks.SetChannelVectorValues(inports[1], CONST_2by3_VECTOR) mmgr.SetParameterVectorValues("Controller", "CONST2by3", CONST_2by3_VECTOR) sleep() result = wks.GetChannelVectorValues(outports[0]) print(result) assert ( result == CONST_2by3_VECTOR ), "Error verifying get channel vector value for %s" % outports[0] result = wks.GetChannelVectorValues(outports[1]) print(result) assert ( result == CONST_2by3_VECTOR_TIMES2 ), "Error verifying get channel vector value for %s" % outports[1] print("Test Set Channel Values") CONST_2by3_VECTOR_Hundreds = [[100, 200, 300], [400, 500, 600]] CONST_2by3_VECTOR_Thousands = [[1000, 2000, 3000], [4000, 5000, 6000]] wks.SetChannelValues( inports, [CONST_2by3_VECTOR_Hundreds, CONST_2by3_VECTOR_Thousands]) sleep() result = wks.GetChannelVectorValues(outports[0]) print(result) assert (result == [[101, 202, 303], [ 410, 520, 630 ]]), "Error verifying get channel vector value for %s" % outports[0] result = wks.GetChannelVectorValues(outports[1]) print(result) assert (result == [[1001, 2002, 3003], [ 4010, 5020, 6030 ]]), "Error verifying get channel vector value for %s" % outports[1] print("Test Model Set State") print("Test various constructor mode") Constructor1 = NIVeriStand.Model("VectMod") Constructor2 = NIVeriStand.Model("VectMod", "Controller") Constructor3 = NIVeriStand.Model("VectMod", None, "localhost") model = NIVeriStand.Model("VectMod", "Controller", "localhost") #return 'time' : 'state' #Running = 0 Paused = 1 Resetting = 2 Idle = 3 Stopped = 4 Restoring = 5 Stopping = 6 #Start = 0, Pause = 1, Reset = 2 result = model.GetModelExecutionState() assert (result['state'] == 0), "Expected the model to be running" model.SetModelExecutionState(1) sleep() result = model.GetModelExecutionState() assert (result['state'] == 1), "Expected the model to be paused" model.SetModelExecutionState(2) sleep() result = model.GetModelExecutionState() assert (result['state'] == 3), "Expected the model to be idle" model.SetModelExecutionState(0) sleep() result = model.GetModelExecutionState() assert (result['state'] == 0), "Expected the model to be running" print("Test Save and Restore Model state") import tempfile SAVE_STATE_LOC = os.path.join(tempfile.mkdtemp(), 'saveModelState.txt') clock = NIVeriStand.Model("clocktest") print("Pause and get clock time") clock.SetModelExecutionState(1) sleep() result = clock.GetModelExecutionState() timeAtSave = result['time'] print("Time At Save %d" % timeAtSave) clock.SaveModelState(SAVE_STATE_LOC) sleep() print("Set model running") clock.SetModelExecutionState(0) sleep() sleep() sleep() sleep() sleep() print("Check if save state file exist on disk") assert ( (os.path.isfile(SAVE_STATE_LOC)) == 1 ), "Error verifying that the save parameter state file is on disk %s" % SAVE_STATE_LOC print("Pause and restore model state") clock.SetModelExecutionState(1) sleep() result = clock.GetModelExecutionState() currentTime = result['time'] print("Current Model Time %d" % currentTime) clock.RestoreModelState(SAVE_STATE_LOC) sleep() clock.SetModelExecutionState(0) sleep() result = clock.GetModelExecutionState() timeRestored = result['time'] print("Time Restored %d" % timeRestored) assert timeAtSave <= timeRestored <= currentTime, "Error verifying restore parameter state" print("Test PASSED") finally: #Always stop the engine. wks.StopWorkspaceFile("")
def test_procedures_legacy(): wks = NIVeriStand.Workspace2("localhost") SYSDEFINITION = os.path.join(configutilities.get_autotest_projects_path(), "ProceduresTest", "ProceduresTest.nivssdf") print("Deploying %s" % SYSDEFINITION) wks.ConnectToSystem(SYSDEFINITION, 1, 60000) try: #Verify the TEST_ID var on test file. test_ID = wks.GetSingleChannelValue("TEST_ID") assert (test_ID == TEST_ID), "Deployed wrong test file" print("") print("Test ID =", TEST_ID) #Now do your test #Sample common operation #Give some time for the startup procedure to finish setting the initial variables time.sleep(2) print("") #Check that we skipped the first procedure and executed the Startup Procedure assert (wks.GetSingleChannelValue("Test Channel 6") >= 0), "Invalid procedure executed before Startup!" print( "Successfully skipped initial procedure. Checking Startup Procedure was invoked..." ) channelValues = wks.GetMultipleChannelValues( ("Test Channel 0", "Test Channel 1", "Test Channel 2", "Test Channel 3", "Test Channel 4", "Test Channel 7", "Test Channel 10", "Test Channel 11")) print("Startup channel values =", channelValues) assert (channelValues == [1000, 2000, 20000, 30000, 40000, 0, 10, 11]), "Startup Test Data Errors!" print("Startup Procedure invoked successfully") print( "Checking that Startup Procedure is waiting on Test Channel 5 before continuing" ) #Check that AfterStartupProcedure hasn't run yet. StartupProcedure should be waiting for TC5 >= 50000 assert (wks.GetSingleChannelValue("Test Channel 5") != -50000), "After Startup Procedure premature execution!" print("Startup Procedure successfully waiting") #Set Test Channel 5 to 50000 so that the Startup Procedure ends and proceeds to After Startup Procedure print("Triggering After Startup Procedure") wks.SetSingleChannelValue("Test Channel 5", 50000) time.sleep(2) assert (wks.GetSingleChannelValue("Test Channel 5") == -50000 ), "Failed to move onto After Startup Procedure" print("After Startup Procedure Executed Successfully") #Check that we don't move onto Also Should Not Run Procedure, because After Startup ends with End time.sleep(1) assert (wks.GetSingleChannelValue("Test Channel 6") >= 0), "Invalid procedure executed after After Startup!" print("Procedure execution ended successfully") #Test triggering alarms #Set number of alarm triggers. Each triggered alarm procedure should increment its trigger count variable. x = 5 print("Triggering Alarm 1 and 2 and 3", x, "times") for i in range(x): wks.SetSingleChannelValue("Alarm Channel 1", 1) time.sleep(2) wks.SetSingleChannelValue("Alarm Channel 2", 1) time.sleep(2) wks.SetSingleChannelValue("Alarm Channel 3", 1) time.sleep(2) a1TrigCount = wks.GetSingleChannelValue("Alarm 1 Trigger Count") a2TrigCount = wks.GetSingleChannelValue("Alarm 2 Trigger Count") a3TrigCount = wks.GetSingleChannelValue("Alarm 3 Trigger Count") print("Alarm 1 Trigger Count =", a1TrigCount) print("Alarm 2 Trigger Count =", a2TrigCount) print("Alarm 3 Trigger Count =", a3TrigCount) assert ((a1TrigCount == x) and (a2TrigCount == x)), "Alarms failed to trigger Alarm Procedures!" print("Alarm procedures successfully triggered") assert (a3TrigCount <= 0), "Alarm 3 triggered while disabled!" print("Alarm 3 successfully disabled, did not trigger") print("Triggering Procedure 4 which should enable Alarm 3") wks.SetSingleChannelValue("Alarm Channel 4", 1) time.sleep(1) print("Attempting to trigger Alarm 3...") wks.SetSingleChannelValue("Alarm Channel 3", 1) time.sleep(1) a3TrigCount = wks.GetSingleChannelValue("Alarm 3 Trigger Count") assert (a3TrigCount == 1), "Alarm 3 not successfully enabled!" print("Alarm 3 Trigger Count =", a3TrigCount) print("Alarm 3 successfully triggered") print( "Attempting to retrigger Alarm 3, which should now be disabled again after Alarm 3 Procedure executed" ) wks.SetSingleChannelValue("Alarm Channel 3", 1) time.sleep(1) a3TrigCount = wks.GetSingleChannelValue("Alarm 3 Trigger Count") assert (a3TrigCount == 1 ), "Alarm 3 failed to be set to disabled and was triggered!" print("Alarm 3 Trigger Count =", a3TrigCount) print("Alarm 3 successfully disabled and not triggered") #Alarms 5 and 6 test resetting multiple alarms in same sub-procedure using "Reset This Alarm". #Alarms 7 and 8 test the "Triggered alarm" checkbox of an Alarm command by having one sub-procedure which can reset any calling alarm. #(Using a sub-procedure tests to make sure that the triggered alarm is correctly passed to sub-procedures) x = 3 print("Triggering Alarm 5, 6, 7 and ", x, "times") for i in range(x): wks.SetSingleChannelValue("Alarm Channel 5", 1) time.sleep(2) wks.SetSingleChannelValue("Alarm Channel 6", 1) time.sleep(2) wks.SetSingleChannelValue("Alarm Channel 7", 1) time.sleep(2) wks.SetSingleChannelValue("Alarm Channel 8", 1) time.sleep(2) a5TrigCount = wks.GetSingleChannelValue("Alarm 5 Trigger Count") a6TrigCount = wks.GetSingleChannelValue("Alarm 6 Trigger Count") a7TrigCount = wks.GetSingleChannelValue("Alarm 7 Trigger Count") a8TrigCount = wks.GetSingleChannelValue("Alarm 8 Trigger Count") print("Alarm 5 Trigger Count =", a5TrigCount) print("Alarm 6 Trigger Count =", a6TrigCount) print("Alarm 7 Trigger Count =", a7TrigCount) print("Alarm 8 Trigger Count =", a8TrigCount) #Testing the alarm call stack with alarms 9, 10, and 11. Each alarm waits 5 seconds, then calls "Reset Triggered Alarm Sub-Procedure". #During this test, procedure 9 starts and is interrupted by procedure 10, which is interrupted by procedure 11. #The whole thing is run twice and makes sure that preempted alarms are properly reset once they resume. x = 2 print("Triggering Alarm 9, 10, 11 and ", x, "times") for i in range(x): wks.SetSingleChannelValue("Alarm Channel 9", 1) time.sleep(2) wks.SetSingleChannelValue("Alarm Channel 10", 1) time.sleep(2) wks.SetSingleChannelValue("Alarm Channel 11", 1) time.sleep(20) a9TrigCount = wks.GetSingleChannelValue("Alarm 9 Trigger Count") a10TrigCount = wks.GetSingleChannelValue("Alarm 10 Trigger Count") a11TrigCount = wks.GetSingleChannelValue("Alarm 11 Trigger Count") print("Alarm 9 Trigger Count =", a9TrigCount) print("Alarm 10 Trigger Count =", a10TrigCount) print("Alarm 11 Trigger Count =", a11TrigCount) assert ((a9TrigCount == x) and (a10TrigCount == x) and (a11TrigCount == x)), "Alarms failed to trigger Alarm Procedures!" print("Alarm procedures successfully triggered") print("Test PASSED") finally: #Always stop the engine. wks.StopWorkspaceFile("")
# SineWave Delay project file path: C:\Users\Public\Documents\National Instruments\NI VeriStand 2020\Projects\Example\Sinewave Delay.nivsproj # Press Ctrl + C to stop the program. GATEWAY = "localhost" TARGET = "Controller" SINE_WAVE = 'Aliases/SineWave' LOOP_RATE = 'Targets/Controller/System Channels/Actual Loop Rate' # channel adresses can be entered as full paths or aliases def sleep(): time.sleep(0.1) wks = NIVeriStand.Workspace2(GATEWAY) # create workspace object try: print("Connecting to the gateway %(gateway)s, target %(target)s" % { 'gateway': GATEWAY, "target": TARGET }) wks.ReconnectToSystem(TARGET, True, None, 60000) # reconnect to already deployed system print("NI VeriStand Running and Client Connected!") input( "Press Enter to start printing data values, then you can press Ctrl+C to disconnect." ) while (1): print("Actual Loop Rate: ", wks.GetSingleChannelValue(LOOP_RATE)) print("Sine wave:", wks.GetSingleChannelValue(SINE_WAVE))