大家好,又见面了,我是你们的朋友全栈君。
【实例简介】TestOPC
【实例截图】
【核心代码】
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HaiGrang.Package.OpcNetApiChs.DaNet;
using HaiGrang.Package.OpcNetApiChs.Opc;
using HaiGrang.Package.OpcNetApiChs.Da;
namespace TestOPC
{
public class OPC_Interface
{
/// OPC服务器打开状态
bool openStatus = false;
/// OPC服务器地址
string serverIp = “”;
/// OPC服务器名称
string serverName = “”;
/// OPC连接服务对象
OpcServer _OpcServer;
/// 读取组对象
SyncIOGroup syncIoGroup;
///
/// 构造函数
///
/// OPC服务器地址
/// OPC服务器名称
public OPC_Interface(string _serverIp, string _serverName)
{
serverIp = _serverIp;
serverName = _serverName;
}
///
/// 打开OPC服务器
///
public void OpenServer()
{
int rtc = -1;
try
{
_OpcServer = new OpcServer();
var opcServerType = Type.GetTypeFromProgID(serverName, serverIp);
//rtc = _OpcServer.Logon(“Administrator”, “1”);
//Guid _guid = new Guid(“b6eacb30-42d5-11d0-9517-0020afaa4b3c”);
rtc = _OpcServer.Connect(serverIp, opcServerType.GUID);
if (HRESULTS.Succeeded(rtc))
{
openStatus = true;
syncIoGroup = new SyncIOGroup(_OpcServer);
}
else
{
openStatus = false;
_OpcServer = null;
}
}
catch(Exception exp)
{
openStatus = false;
_OpcServer = null;
throw exp;
//CommonClass.WriteLog(“连接OPC服务器异常:” exp.StackTrace, LogType.Error);
//记录日志
}
}
///
/// 断开与OPC服务器的连接
///
public void Close()
{
try
{
syncIoGroup.Dispose();
_OpcServer.Disconnect();
}
catch (Exception exp)
{
// CommonClass.WriteLog(“断开OPC服务器连接异常:” exp.StackTrace, LogType.Error);
//记录日志
}
}
/// 获取OPC服务器打开状态
public bool GetOpenStatus()
{
return openStatus;
}
///
/// 读取OPC服务器内指定item的值
///
/// item全名称
///
public object Read(string ItemName)
{
object retVal = null;
try
{
if (syncIoGroup.Item(ItemName) == null)
{
syncIoGroup.Add(ItemName);
}
ItemDef _OpcItem = syncIoGroup.Item(ItemName);
OPCDATASOURCE theSrc = OPCDATASOURCE.OPC_DS_DEVICE;
OPCItemState theVal = new OPCItemState();
int rtc = syncIoGroup.Read(theSrc, _OpcItem, out theVal);
if (HRESULTS.Succeeded(rtc))
{
if (theVal.DataValue != null)
retVal = theVal.DataValue;
}
}
catch (Exception exp)
{
//记录日志
// CommonClass.WriteLog(string.Format(“从OPC服务器读取Item({0})异常:”, ItemName) exp.StackTrace, LogType.Error);
}
return retVal;
}
///
/// 向OPC服务器写值
///
/// item全名称
/// 要写入的值
///
public bool Write(string ItemName, object theVal)
{
bool result = false;
try
{
if (syncIoGroup.Item(ItemName) == null)
{
syncIoGroup.Add(ItemName);
}
ItemDef _OpcItem = syncIoGroup.Item(ItemName);
int rtc = syncIoGroup.Write(_OpcItem, theVal);
if (HRESULTS.Succeeded(rtc))
{
result = true;
}
}
catch (Exception exp)
{
//CommonClass.WriteLog(string.Format(“从OPC服务器写Item({0})数据异常:”, ItemName) exp.StackTrace, LogType.Error);
//记录日志
}
return result;
}
}
}
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/151338.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...