我正在尝试读取 PLC 的变量。
在自动化平台中,我有一个插件来启动我的测试(我用 C# 编写的)。
当我第一次执行插件时,它总是给我同样的错误。但是如果再次执行它就很好了。
我使用 aList<IOnlineVarRef6> vars
来读取我的变量。我的错误是我vars
的State
是NotMonitoredYet
。例子:
private bool CompareValues(TestCase test, List<IOnlineVarRef6> vars)
{
// Stop here the first time
if (vars.First().State == VarRefState.NotMonitoredYet)
return false;
// Execute well the other times
List<Variable> initialVars = test.initialVariables;
for (int i = 0; i < vars.Count(); i++)
{
object initialValue = initialVars.Single(v => v.Name == vars[i].Expression.ToString()).Value;
if (!vars[i].Value.Equals(initialValue))
return false;
}
return true;
}
我认为问题在于获取我的变量的方法:
/// <summary>
/// Create a variable watch for each of the specified variable in the list
/// </summary>
/// <example>
/// Variable should include object hierarchy up to Device
/// GPX.Diesel_Control.CTRL.PB_CRANK1
/// </example>
public List<IOnlineVarRef6> CreateVariableWatch(List<string> vars)
{
IVarRef2 varref;
IOnlineVarRef6 iov;
IOnlineApplication17 onlineapp = (IOnlineApplication17)onlineMgr.GetApplication(SystemInstances.Engine.Projects.PrimaryProject.ActiveApplication);
List<IOnlineVarRef6> lstVarRef = new List<IOnlineVarRef6>();
foreach (string var in vars)
{
varref = (IVarRef2)SystemInstances.LanguageModelMgr.GetVarReference(var);
iov = (IOnlineVarRef6)onlineMgr.CreateWatch(varref);
lstVarRef.Add(iov);
}
return lstVarRef;
}
我有一个在调用 CompareValues() 之前等待的方法,它重试 3 次,然后在重试之前等待:
public void SetIsTestPassed(TestCase test)
{
Thread.Sleep(test.delayedStart);
int retries = test.retries;
do
{
List<IOnlineVarRef6> vars = SetCurrentVars(test);
test.IsTestPassed = CompareValues(test, vars);
if (test.retryDelay > 0 && !test.IsTestPassed)
Thread.Sleep(test.retryDelay);
retries--;
} while (retries != 0 && !test.IsTestPassed);
}
private List<IOnlineVarRef6> SetCurrentVars(TestCase test)
{
OnlineManagerHelper OnlineMgr = new OnlineManagerHelper(true);
return OnlineMgr.CreateVariableWatch(
test.initialVariables
.Select(v => Settings.Default.InstancePath + v.Name)
.ToList());
}