OPC服务器通常支持两种类型的访问接口,它们分别为不同的编程语言环境提供访问机制。这两种接口是:自动化接口(Automation interface);自定义接口(Custom interface)。 OPCAutomation.OPCItems MyOPCItems;
OPCAutomation.OPCItem MyOPCItem;
int[] cH_temp;
int[] sH_temp;
Array sH;
object[] oVal;
object[] dTime;
object[] wQuality;
//OPCServer的名称。
string strOPCServerName = "";
//装有OPCServer的计算机名称或IP地址。
string strOPCServerNodeName = "";
//设备的连接状态。
private byte blState = 0;
//OPCServer的数据变化事件的最小时间。
private int MyUpdateRate = 50;
//OPCServer的数据变化死区,范围0-100。
private float MyDeadBand = 0;
//OPCServer的数据变化事件是否有效。
private bool MyIsActive = true;
//需要读取或写入数据的变量数组。
private string[] sTagName = null;
//OPC组名称
private string OPCGroupName = "";
public enum OPCServerState : int
{
Open = 1,
Close = 6
}
///// <summary>
///// OPCServer强制关闭事件。
///// </summary>
///// <remarks></remarks>
////public event ShutDownEventHandler interfaceDevice.ShutDown
////public delegate void ShutDownEventHandler();
//private void MyOPCServer_ServerShutDown(string Reason)
//{
// DisConnect();
// blState = 2;
// if (ShutDown != null)
// {
// ShutDown();
// }
//}
/////// <summary>
/////// 信息事件。
/////// </summary>
/////// <param name="Message">详细信息。</param>
/////// <param name="EventType">信息类型。</param>
/////// <remarks></remarks>
//////public event InfoEventHandler interfaceDevice.Info;
////public delegate void InfoEventHandler(string Message, Events EventType);
/// <summary>
/// 异步写入所有变量,自动返回写入成功或失败。
/// </summary>
/// <param name="Value">输出结果,True:写入成功;False:写入失败。</param>
/// <remarks></remarks>
public event AsyncWriteCompleteEventHandler AsyncWriteComplete;
public delegate void AsyncWriteCompleteEventHandler(ref bool Value);
/// <summary>
/// 异步读取所有变量,自动返回变量值。
/// </summary>
/// <param name="Value">所有变量值。</param>
/// <remarks></remarks>
public event AsyncReadCompleteEventHandler AsyncReadComplete;
public delegate void AsyncReadCompleteEventHandler(ref object[] Value);
/// <summary>
/// 只读属性,设备的连接状态,值 0:连接失败; 1:连接成功; 2:OPCServer强制关闭; 3:连接的OPCServer不存在。
/// </summary>
/// <value></value>
/// <returns></returns>
/// <remarks></remarks>
public byte State
{
get { return blState; }
}
byte interfaceDevice1.Status
{
get { return State; }
}
/// <summary>
/// OPCServer的数据变化事件的最小时间。
/// </summary>
/// <value></value>
/// <returns></returns>
/// <remarks></remarks>
public int UpdateRate
{
get { return MyUpdateRate; }
set { MyUpdateRate = value; }
}
/// <summary>
/// OPCServer的数据变化死区,范围0-100。
/// </summary>
/// <value></value>
/// <returns></returns>
/// <remarks></remarks>
public float DeadBand
{
get { return MyDeadBand; }
set
{
if (value < 0)
{
value = 0;
}
else if (value > 100)
{
value = 100;
}
MyDeadBand = value;
}
}
/// <summary>
/// OPCGroup事件是否有效,True:有效;False:无效。
/// </summary>
/// <value></value>
/// <returns></returns>
/// <remarks></remarks>
public bool IsActive
{
get { return MyIsActive; }
set { MyIsActive = value; }
}
/// <summary>
/// 只读属性,设备的变量数组。
/// </summary>
/// <value></value>
/// <returns></returns>
/// <remarks></remarks>
public string[] TagNames
{
get { return sTagName; }
}
/// <summary>
/// 初始化。
/// </summary>
/// <param name="OPCServerName">OPCServer的名称。</param>
/// <param name="OPCGroupName">设备名称,不能重复。</param>
/// <param name="OPCServerNodeName">装有OPCServer的计算机名称或IP地址,默认为本机。</param>
/// <remarks></remarks>
public void clsOPC(string OPCServerName, string OPCGroupName, string OPCServerNodeName)
{
//OPCServerNodeName="";
strOPCServerName = OPCServerName;
strOPCServerNodeName = OPCServerNodeName;
this.OPCGroupName = OPCGroupName;
}
///// <summary>
///// 返回服务器内的所有OPCServer的名称,返回值为一维数组。
///// </summary>
///// <returns></returns>
///// <remarks></remarks>
//public string[] GetOPCServerName()
//{
// return _GetOPCServerName();
//}
//private string[] _GetOPCServerName()
//{
// OPCAutomation.OPCServer OPCServer = default(OPCAutomation.OPCServer);
// object Servers = null;
// OPCServer = new OPCAutomation.OPCServer();
// Servers = OPCServer.GetOPCServers;
// return Convert.ToString(Servers);
//}
/// <summary>
/// 连接设备,返回值为布尔类型,True:连接成功; False:连接失败。
/// </summary>
/// <returns></returns>
/// <remarks></remarks>
public bool Connect()
{
return _Connect();
}
private bool _Connect()
{
try
{
if (blState != 1)
{
MyOPCServer = new OPCAutomation.OPCServer();
System.Threading.Thread.Sleep(1000);
if (MyOPCServer == null)
return false;
if (MyOPCServer.ServerState == Convert.ToInt32(OPCServerState.Close))
{
MyOPCServer.Connect(strOPCServerName, strOPCServerNodeName);
int a = Convert.ToInt32(OPCServerState.Open);
if (MyOPCServer.ServerState == Convert.ToInt32(OPCServerState.Open))
{
blState = 1;
}
else
{
blState = 0;
}
}
else
{
blState = 1;
}
}
}
catch (Exception)
{
blState = 3;
//MessageBox("设备【" DeviceName "】连接'" strOPCServerName "'失败:" Environment.NewLine ex.Message, Events.Err);
//MessageBox.Show("设备连接失败:" Environment.NewLine ex.Message);
}
switch (blState)
{
case 0:
return false;
case 1:
return true;
case 2:
return true;
case 3:
return false;
default:
return true;
}
}
bool interfaceDevice1.Connect()
{
return _Connect();
}
/// <summary>
/// 断开设备,返回值为布尔类型,True:断开成功; False:断开失败。
/// </summary>
/// <returns></returns>
/// <remarks></remarks>
public bool DisConnect()
{
return _DisConnect();
}
private bool _DisConnect()
{
try
{
if ((MyOPCGroup != null))
{
MyOPCGroup.IsActive = false;
}
if ((MyOPCGroups != null))
{
if (MyOPCGroups.Count != 0)
{
MyOPCGroups.RemoveAll();
}
}
MyOPCItems = null;
MyOPCItem = null;
MyOPCGroups = null;
MyOPCGroup = null;
if ((MyOPCServer != null))
{
if (MyOPCServer.ServerState != Convert.ToInt32(OPCServerState.Close))
{
MyOPCServer.Disconnect();
}
MyOPCServer = null;
}
blState = 0;
}
catch (Exception)
{
//MessageBox("设备【" DeviceName "】断开:" Environment.NewLine ex.Message, Events.Err);
}
System.GC.Collect();
return true;
}
bool interfaceDevice1.DisConnect()
{
return _DisConnect();
}
/// <summary>
/// 为设备注册变量。
/// </summary>
/// <param name="TagNames">变量名,一维数组。</param>
/// <returns></returns>
/// <remarks></remarks>
public bool TagRegister(string[] TagNames)
{
return _TagRegister(TagNames);
}
private bool _TagRegister(string[] TagNames)
{
Array ServerHandles = null;
Array Errors = null;
Array RequestedDataTypes = null;
Array AccessPaths = null;
UInt16 Index = 0;
try
{
sTagName = TagNames;
if (sTagName == null)
return false;
if (sTagName.Length == 0)
return true;
sH_temp = new int[sTagName.Length 1];
oVal = new object[sTagName.Length 1];
cH_temp = new int[sTagName.Length 1];
MyOPCGroups = MyOPCServer.OPCGroups;
MyOPCGroup = MyOPCGroups.Add(OPCGroupName);
MyOPCGroup.UpdateRate = MyUpdateRate;
MyOPCGroup.IsActive = MyIsActive;
MyOPCGroup.DeadBand = MyDeadBand;
MyOPCGroup.IsSubscribed = MyOPCGroup.IsActive;
MyOPCItems = MyOPCGroup.OPCItems;
string[] sItemName_temp = new string[sTagName.Length 1];
for (Index = 1; Index <= Convert.ToUInt16(sTagName.Length); Index )
{
sItemName_temp[Index] = sTagName[Index - 1];
cH_temp[Index] = Index;
}
Array sItemName = sItemName_temp;
Array cH = cH_temp;
MyOPCItems.AddItems(sTagName.Length, ref sItemName, ref cH, out ServerHandles, out Errors, RequestedDataTypes, AccessPaths);
for (Index = 1; Index <= Convert.ToUInt16(sTagName.Length); Index )
{
if (Convert.ToInt32(Errors.GetValue(Index)) == 0)
{
sH_temp[Index] = Convert.ToInt32(ServerHandles.GetValue(Index));
}
else
{
//log.Info(GetCurrentTime() " " "OPC变量【" sTagName[Index] "】注册失败!");
//TXT_LOG.AppendText(GetCurrentTime() " " "OPC变量【" sTagName[Index] "】注册失败!" "\r\n");
return false;
}
}
sH = (Array)sH_temp;
}
catch (Exception)
{
//MessageBox("设备【" DeviceName "】的变量注册失败:" Environment.NewLine ex.Message, Events.Err);
//log.Fatal("OPC组【" OPCGroupName "】的变量注册失败!", new Exception("发生了一个致命错误"));
return false;
}
return true;
}
bool interfaceDevice1.TagRegister(string[] TagNames)
{
return _TagRegister(TagNames);
}
/// <summary>
/// 同步读取指定变量的值,类型为object。
/// </summary>
/// <param name="TagName">变量名称。</param>
/// <returns></returns>
/// <remarks></remarks>
public object Read(string TagName)
{
return _Read(TagName);
}
private object _Read(string TagName)
{
object Value = null;
object Quality = null;
object TimeStamp = null;
try
{
if (sTagName == null)
return null;
if (MyIsActive == true)
{
return oVal[Array.IndexOf(sTagName, TagName) 1];
}
else
{
OPCAutomation.OPCItem anItem = default(OPCAutomation.OPCItem);
anItem = MyOPCGroup.OPCItems.Item(Array.IndexOf(sTagName, TagName) 1);
anItem.Read(Convert.ToInt16(OPCAutomation.OPCDataSource.OPCDevice), out Value, out Quality, out TimeStamp);
return anItem.Value;
}
}
catch (Exception)
{
//MessageBox("设备【" DeviceName "】的变量'" TagName "'读取值失败:" Environment.NewLine ex.Message, Events.Err);
return null;
}
}
object interfaceDevice1.Read(string TagName)
{
return _Read(TagName);
}
/// <summary>
/// 同步读取所有变量的值,类型为object。
/// </summary>
/// <returns></returns>
/// <remarks></remarks>
public object SyncRead()
{
return _SyncRead();
}
private object _SyncRead()
{
object Quality = null;
object TimeStamp = null;
try
{
Array Errors = null;
Array oVal_temp = oVal;
MyOPCGroup.SyncRead(Convert.ToInt16(OPCAutomation.OPCDataSource.OPCDevice), sTagName.Length, ref sH, out oVal_temp, out Errors, out Quality, out TimeStamp);
return oVal_temp;
}
catch (Exception)
{
//MessageBox("设备【" DeviceName "】的所有变量值读取失败:" Environment.NewLine ex.Message, Events.Err);
return null;
}
}
/// <summary>
/// 异步读取所有变量的值,调用AsyncReadComplete事件返回所有变量值。
/// </summary>
/// <remarks></remarks>
public void AsyncRead()
{
_AsyncRead();
}
private void _AsyncRead()
{
try
{
int wTransID = 1;
int wCancelID = 0;
Array Errors = null;
MyOPCGroup.AsyncRead(sTagName.Length, ref sH, out Errors, wTransID, out wCancelID);
}
catch (Exception)
{
//MessageBox("设备【" DeviceName "】的所有变量值读取失败:" Environment.NewLine ex.Message, Events.Err);
}
}
private void MyOPCGroup_AsyncReadComplete(int TransactionID, int NumItems, ref System.Array ClientHandles, ref System.Array ItemValues, ref System.Array Qualities, ref System.Array TimeStamps, ref System.Array Errors)
{
Array.Copy(ItemValues, 1, oVal, 1, ItemValues.Length);
if (AsyncReadComplete != null)
{
AsyncReadComplete(ref oVal);
}
}
/// <summary>
/// 同步写入指定变量的值,返回值为布尔类型,True:写入成功; False:写入失败。
/// </summary>
/// <param name="TagName">变量名称。</param>
/// <param name="Value">写入值,类型为object。</param>
/// <returns></returns>
/// <remarks></remarks>
public bool Write(string TagName, object Value)
{
return _Write(TagName, Value);
}
private bool _Write(string TagName, object Value)
{
try
{
OPCAutomation.OPCItem anItem = default(OPCAutomation.OPCItem);
anItem = MyOPCGroup.OPCItems.Item(Array.IndexOf(sTagName, TagName) 1);
anItem.Write(Value);
return true;
}
catch (Exception)
{
//MessageBox("设备【" DeviceName "】的变量'" TagName "'写入值失败:" Environment.NewLine ex.Message, Events.Err);
return false;
}
}
bool interfaceDevice1.Write(string TagName, object Value)
{
return _Write(TagName, Value);
}
/// <summary>
/// 同步写入所有变量的值,返回值为布尔类型,True:写入成功; False:写入失败。
/// </summary>
/// <param name="Value">所有变量的值,类型为Array,不能为空.格式如下:
/// object[] valueTemp = new object[] { "", "aa", "cc" };
/// Array Value = (Array)valueTemp;
/// </param>
/// <returns></returns>
/// <remarks></remarks>
public bool SyncWrite(Array Value)
{
return _SyncWrite(Value);
}
private bool _SyncWrite(Array Value)
{
try
{
Array Errors = null;
MyOPCGroup.SyncWrite(Convert.ToInt32(sTagName.Length), ref sH, ref Value, out Errors);
return true;
}
catch (Exception)
{
//MessageBox("设备【" DeviceName "】的所有变量值写入失败:" Environment.NewLine ex.Message, Events.Err);
return false;
}
}
/// <summary>
/// 异步写入所有变量的值,返回值为布尔类型, False:写入失败,调用AsyncWriteComplete事件判断写入是否成功。
/// </summary>
/// <param name="Value">所有变量的值,类型为Array,不能为空。</param>
/// <remarks></remarks>
public bool AsyncWrite(Array Value)
{
return _AsyncWrite(Value);
}
private bool _AsyncWrite(Array Value)
{
try
{
int wTransID = 1;
int wCancelID = 0;
Array Errors = null;
MyOPCGroup.AsyncWrite(sTagName.Length, ref sH, ref Value, out Errors, wTransID, out wCancelID);
return true;
}
catch (Exception)
{
//MessageBox("设备【" DeviceName "】的所有变量值写入失败:" Environment.NewLine ex.Message, Events.Err);
return false;
}
}
private void MyOPCGroup_AsyncWriteComplete(int TransactionID, int NumItems, ref System.Array ClientHandles, ref System.Array Errors)
{
//object i = null;
bool sTrue = true;
bool sFalse = false;
for (int i = 1; i <= NumItems; i )
{
if (Convert.ToInt32(Errors.GetValue(i)) != 0)
{
if (AsyncWriteComplete != null)
{
AsyncWriteComplete(ref sFalse);
}
return;
}
}
if (AsyncWriteComplete != null)
{
AsyncWriteComplete(ref sTrue);
}
}
/// <summary>
/// 数据变化事件。
/// </summary>
/// <param name="TransactionID"></param>
/// <param name="NumItems"></param>
/// <param name="ClientHandles"></param>
/// <param name="ItemValues"></param>
/// <param name="Qualities"></param>
/// <param name="TimeStamps"></param>
/// <remarks></remarks>
private void OPCMyGroup_DataChange(int TransactionID, int NumItems, ref System.Array ClientHandles, ref System.Array ItemValues, ref System.Array Qualities, ref System.Array TimeStamps)
{
try
{
for (int i = 1; i <= NumItems; i )
{
oVal[Convert.ToInt32(ClientHandles.GetValue(i))] = ItemValues.GetValue(i);
}
}
catch (Exception)
{
}
System.GC.Collect();
}
}
}
评论