using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using OPCAutomation; //需要手动添加
using System.Net; //需要手动添加
namespace OPCtest
{
public partial class Form1 : Form
{
//本机实例化
IPHostEntry IPHostEntry = new IPHostEntry();
#region 通信变量
/// <summary>
/// 1 OPC服务器对象
/// </summary>
OPCServer opcServer;
/// <summary>
/// 6 OPC服务器中的变量集
/// </summary>
OPCBrowser opcBrowser;
/// <summary>
/// 2 OPC组集合对象
/// </summary>
OPCGroups opcGroups;
/// <summary>
/// 3 OPC组对象
/// </summary>
OPCGroup opcGroup;
OPCGroup opcGroup1;
/// <summary>
/// 4 OPC多变量添加项目
/// </summary>
OPCItems opcItems;
/// <summary>
/// 5 OPC单变量添加项目数组
/// </summary>
OPCItem opcItem;
/// <summary>
/// 变量名数组
/// </summary>
Array itemIDs;
/// <summary>
/// 8 变量对应的标签数组
/// </summary>
int serverHandles;
#endregion
#region 其它变量
/// <summary>
/// 主机名
/// </summary>
string strHostName = "";
/// <summary>
/// OPC服务器名
/// </summary>
string strOPCServerName = "";
/// <summary>
/// OPC服务器连接状态
/// </summary>
bool connectState = false;
/// <summary>
/// 7 OPC变量对象包含:变量名称,变量值,读取质量,读取时间
/// </summary>
List<ClassOPCValue> opcValueList = new List<ClassOPCValue>();
List<OPCItem> oPCItemlist = new List<OPCItem>();
#endregion
int count = 0;
bool isconnected;
public Form1()
{
InitializeComponent();
}
private void btn_ref_Click(object sender, EventArgs e)
{
try
{
//初始清空
this.comboBox1.Items.Clear();
//ip
IPAddress ip= IPAddress.Parse("127.0.0.1");
//获取本地计算机名
strHostName = Dns.GetHostName();
//主机解析
IPHostEntry = Dns.GetHostEntry(strHostName);
//strHostName = IPHostEntry.HostName;
//服务器实例化
opcServer = new OPCServer();
//获取opc服务器
object opcserverlist = opcServer.GetOPCServers(strHostName);
//显示到下拉框
foreach (var item in (Array)opcserverlist)
{
if (!this.comboBox1.Items.Contains(item.ToString()))
{
this.comboBox1.Items.Add(item.ToString());
}
}
this.comboBox1.SelectedIndex = 0;
}
catch (Exception)
{
MessageBox.Show("未找到服务器");
}
}
private void btn_con_Click(object sender, EventArgs e)
{
if(this.comboBox1.Text == "")
{
MessageBox.Show("请先选择服务器");
return;
}
try
{
this.listbox_brow.Items.Clear();
//连接到选择的服务器
opcServer.Connect(this.comboBox1.Text.Trim());
//创建节点浏览器
opcBrowser = opcServer.CreateBrowser();
//展示节点分支
opcBrowser.ShowBranches();
//展示
opcBrowser.ShowLeafs(true);
foreach (var item in opcBrowser)
{
if(!this.listbox_brow.Items.Contains(item))
{
this.listbox_brow.Items.Add(item.ToString());
}
}
//开启组集合
opcGroups = opcServer.OPCGroups;
//死区
opcGroups.DefaultGroupDeadband = 0;
//激活组集合
opcGroups.DefaultGroupIsActive = true;
//刷新 ms ,服务器向客户端提交变化数据的更新速率(这个数值应比服务器设定的最小值大)
opcGroups.DefaultGroupUpdateRate = 200;
//添加组
opcGroup = opcGroups.Add("Mygroup");
//激活组
opcGroup.IsActive = true;
//是否开启异步回调(使用订阅功能,即可以异步,默认false)
opcGroup.IsSubscribed = true;
//开启项目
opcItems = opcGroup.OPCItems;
//回调方法
opcGroup.DataChange += OpcGroup_DataChange;
isconnected = true;
lab_con.Text = "已连接到"+ comboBox1.Text.Trim();
}
catch (Exception)
{
MessageBox.Show("连接失败");;
}
}
private void OpcGroup_DataChange(int TransactionID, int NumItems, ref Array ClientHandles, ref Array ItemValues, ref Array Qualities, ref Array TimeStamps)
{
for (int i = 1; i < NumItems+1; i++)
{
serverHandles = Convert.ToInt32( ClientHandles.GetValue(i));
opcValueList[serverHandles - 1].Value = ItemValues.GetValue(i).ToString();
opcValueList[serverHandles - 1].Qualities = Qualities.GetValue(i).ToString();
opcValueList[serverHandles - 1].Time = Convert.ToDateTime(TimeStamps.GetValue(i));
this.dataGridView1.DataSource = null;
this.dataGridView1.DataSource = opcValueList;
};
}
private void listbox_brow_DoubleClick(object sender, EventArgs e)
{
if(isconnected==false)
{
MessageBox.Show("未连接");
return;
}
opcValueList.Add(new ClassOPCValue());
opcValueList[count].Name = this.listbox_brow.Text.Trim();
opcItem =opcItems.AddItem(this.listbox_brow.Text.Trim(), count + 1);
oPCItemlist.Add(opcItem);
count++;
}
private void dataGridView1_DoubleClick(object sender, EventArgs e)
{
Form_setvalue form_Setvalue = new Form_setvalue();
form_Setvalue.SetvalueEvent += Form_Setvalue_SetvalueEvent;
form_Setvalue.ShowDialog();
}
private void Form_Setvalue_SetvalueEvent(string value, bool check)
{
int[] reSeverHandle = new int[2] { 0, oPCItemlist[this.dataGridView1.CurrentRow.Index].ServerHandle };
Array SeverHandle = (Array)reSeverHandle;
object[] reValue = new object[2] { "", value };
Array Values = (Array)reValue;
Array WriteErrors;
int CancelID;
if(check)
{
//异步方式写入
opcGroup.AsyncWrite(1,ref SeverHandle, Values,out WriteErrors, 2020,out CancelID);
}
else
{
//同步方式写入
oPCItemlist[this.dataGridView1.CurrentRow.Index].Write(value);
}
}
private void btn_dis_Click(object sender, EventArgs e)
{
if(isconnected == true)
{
opcServer.Disconnect();
isconnected = false;
lab_con.Text = "连接已断开";
}
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace OPCtest
{
public partial class Form_setvalue : Form
{
public Form_setvalue()
{
InitializeComponent();
}
//定义委托
public delegate void Setvalue(string value, bool check);
//定义事件
public event Setvalue SetvalueEvent;
private void btn_setvalue_Click(object sender, EventArgs e)
{
SetvalueEvent(this.txb_value.Text.Trim(), this.checkBox1.Checked);
}
}
}