Reconnect to OPC

1.5k Views Asked by At

I am creating an OPC connection and I get the data as follows. When the connection is lost, the operation does not continue. I need to reconnect to OPC when the connection is broken.

How can I do it? or How can I understand that the connection is broken?

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

There are 1 best solutions below

0
On

If there is a single datapoint that you know for sure should always have "good" quality in the OPC Server (like a heartbeat), you could monitor it in DataChanged or somewhere else in your program. When quality goes "bad", attempt a reconnect.

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