GodSharp.Opc.Da.OpcNetApi库opcda源码
时间: 2023-10-07 18:09:49 浏览: 140
OPCda官方客户端源码资源
以下是GodSharp.Opc.Da.OpcNetApi库中opcda的源码示例:
```csharp
public class OpcDa : IDisposable
{
private const int ShutdownTimeout = 10000;
private readonly object _lockObject = new object();
private readonly OpcServer _server;
private readonly IOPCServer _opcServer;
private readonly IConnectionPoint _connectionPoint;
private readonly OPCShutdown _opcShutdown;
private readonly Dictionary<int, OpcGroup> _groups = new Dictionary<int, OpcGroup>();
private int _groupId;
private bool _disposed;
public OpcDa(string host)
{
_server = new OpcServer();
_server.Connect(host);
_opcServer = _server.GetOPCServer();
_opcShutdown = new OPCShutdown(this);
var cpContainer = (IConnectionPointContainer)_opcServer;
var cpGuid = typeof(IOPCShutdown).GUID;
cpContainer.FindConnectionPoint(ref cpGuid, out _connectionPoint);
_connectionPoint.Advise(_opcShutdown, out var cookie);
}
public void Dispose()
{
lock (_lockObject)
{
if (_disposed)
{
return;
}
_disposed = true;
_connectionPoint.Unadvise(_opcShutdown.Cookie);
foreach (var group in _groups.Values)
{
group.Dispose();
}
_server.Disconnect(ShutdownTimeout);
}
}
public OpcGroup AddGroup(string name, int updateRate)
{
lock (_lockObject)
{
var group = new OpcGroup(this, ++_groupId, name, updateRate);
_groups.Add(group.GroupId, group);
return group;
}
}
public void RemoveGroup(OpcGroup group)
{
lock (_lockObject)
{
if (_groups.TryGetValue(group.GroupId, out var target))
{
target.Dispose();
_groups.Remove(target.GroupId);
}
}
}
public IOPCItemProperties GetItemProperties()
{
_opcServer.QueryInterface(typeof(IOPCItemProperties).GUID, out var itemProperties);
return (IOPCItemProperties)itemProperties;
}
public IOPCBrowseServerAddressSpace GetBrowser()
{
_opcServer.QueryInterface(typeof(IOPCBrowseServerAddressSpace).GUID, out var browser);
return (IOPCBrowseServerAddressSpace)browser;
}
public void ShutdownRequest()
{
Dispose();
}
internal IOPCServer OpcServer => _opcServer;
internal void RemoveGroup(int groupId)
{
lock (_lockObject)
{
if (_groups.TryGetValue(groupId, out var target))
{
target.Dispose();
_groups.Remove(target.GroupId);
}
}
}
private class OPCShutdown : IOPCShutdown
{
private readonly OpcDa _parent;
public OPCShutdown(OpcDa parent)
{
_parent = parent;
}
public int Cookie { get; private set; }
public void ShutdownRequest(string reason)
{
_parent.ShutdownRequest();
}
}
}
```
该类提供了与OPC DA服务器通信的功能。它使用OpcServer对象连接到OPC服务器,并提供添加/删除组以及获取ItemProperties和Browser的功能。在Dispose方法中,它释放了与OPC服务器的连接并释放了所有组。 OPCShutdown类用于处理OPC服务器关闭请求。
阅读全文