重新连接到OPC

时间:2017-12-08 06:15:50

标签: c# opc opc-da

我正在创建一个OPC connection,我得到的数据如下。当连接为lost时,操作不会继续。当连接断开时,我需要reconnect到OPC。

我该怎么办?或者我如何理解连接断开?

public Opc.Da.Server Server { get; set; }
public Opc.Da.Subscription GroupRead { get; set; }

public Result StartListening()
{
    Result result = new Result(true);

    try
    {
        var surl = string.Format("opcda://{0}", MyOpcClientClass.ServerName);
        var url = new Opc.URL(surl);
        Server = new Opc.Da.Server(new OpcCom.Factory(), null);
        Server.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential()));

        Server.ServerShutdown += ServerShutdown;

        var group = new Opc.Da.SubscriptionState();
        group.Name = MyOpcClientClass.GroupName;
        group.UpdateRate = MyOpcClientClass.Period;
        group.Active = true;

        GroupRead = (Opc.Da.Subscription)Server.CreateSubscription(group);
        GroupRead.DataChanged += new Opc.Da.DataChangedEventHandler(DataChanged);

        var items = this.MyOpcClientClassFieldMappingList.Select(i => new Opc.Da.Item
        {
            ItemName = i.OpcTagName
        }).ToList();

        GroupRead.AddItems(items.ToArray());

    }
    catch (Exception e)
    {
        // error log
    }

    return result;
}

private void DataChanged(object subscriptionHandle, object requestHandle, Opc.Da.ItemValueResult[] values)
{
    try
    {
        // do smth...
    }
    catch (Exception e)
    {
        // error log
    }
}

1 个答案:

答案 0 :(得分:1)

如果您确定的单个数据点在OPC服务器中始终具有“良好”质量(如心跳),则可以在DataChanged或程序中的其他位置监视它。当质量变得“糟糕”时,尝试重新连接。

if(values[1].Quality.ToString() == "bad") //Where 1 is the datapoint you expect to be good
{
     StartListening();
}