我正在使用this ua-client为WPF编写控制软件/ HMI,并将Kepwere作为OPC服务器。
今天我正在进行一些连接测试,断开PLC的以太网电缆并更改软件中的一些监控项目值。显然这种变化不会生效,因为连接状态,但是,重新连接后为什么不刷新PLC标签与我之前设置的值?
或者这是预期的行为,我需要制作一些内部存储变量来复制它?
Kepserver有一个System.NoError标签,指示PLC上是否有错误,所以我知道PLC何时离线。但我正在尝试在重新连接时离线时重新发送最新的更改。
我覆盖了SetProperty方法:
protected override bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
{
if(ServerState != CommunicationState.Opened || (!System_NoError && "System_NoError" != propertyName))
{
m_eventsPending.Add(new WriteEvent
{
PropertyName = propertyName,
PropertyValue = value
});
return false;
}
return base.SetProperty(ref storage, value, propertyName);
}
然后用以下方法监听服务器状态更改事件:
public void OnStateChangeEvent(CommunicationState state)
{
ServerState = state;
}
对System_NoError的每次更改我都这样做:
private void OnError()
{
if(System_NoError)
{
while(m_eventsPending.Count > 0)
{
WriteEvent e = m_eventsPending.ElementAt(0);
bool storage = !(bool)e.PropertyValue;
var p = this.GetType().GetProperty(e.PropertyName);
p.SetValue(this, storage);
p.SetValue(this, e.PropertyValue);
m_eventsPending.RemoveAt(0);
}
}
}
我做了一些初始化并将其保存在m_eventsPending列表中,并在连接完成(打开)时开始发送,但PLC端没有任何事情发生。可能有什么不对?
P.S:根据我的代码(按钮,滑块等),与软件的任何其他交互在PLC上进行正确的更改
最诚挚的问候 Jose Truyol
答案 0 :(得分:0)
考虑直接在属性设置器中编写标记。此示例尝试编写绿灯,每5秒重试一次,直到成功。
public class TrafficLightViewModel : ViewModelBase
{
private bool green;
private bool red;
private bool yellow;
private CancellationTokenSource greenCts;
private CancellationTokenSource redCts;
private CancellationTokenSource yellowCts;
private UaTcpSessionClient session;
public TrafficLightViewModel(UaTcpSessionClient session)
{
this.session = session;
}
public bool Green
{
get { return this.green; }
set
{
this.green = value;
this.greenCts?.Cancel();
this.greenCts = new CancellationTokenSource();
var request = new WriteRequest
{
NodesToWrite = new[]
{
new WriteValue
{
NodeId = NodeId.Parse("ns=2;s=GreenLight"),
AttributeId = AttributeIds.Value,
Value = new DataValue(value)
}
}
};
this.WriteOutputAsync(request, this.greenCts.Token);
}
}
// add yellow and red
private async void WriteOutputAsync(WriteRequest request, CancellationToken token)
{
try
{
while (!await this.TryWriteAsync(request))
{
await Task.Delay(5000, token);
}
}
catch (TaskCanceledException)
{
Debug.WriteLine($"Canceled writing output : {request.NodesToWrite[0].NodeId}");
}
}
private async Task<bool> TryWriteAsync(WriteRequest request)
{
try
{
var response = await this.session.WriteAsync(request);
for (int i = 0; i < response.Results.Length; i++)
{
if (StatusCode.IsBad(response.Results[i]))
{
Debug.WriteLine($"Error writing output '{request.NodesToWrite[i].NodeId}' {request.NodesToWrite[i].Value.GetValue()}: {StatusCodes.GetDefaultMessage(response.Results[i])}");
return false;
}
}
return true;
}
catch (Exception ex)
{
Debug.WriteLine($"Error writing outputs : {ex.Message}");
return false;
}
}
}
希望这会有所帮助。 安德鲁