using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using OPCAutomation;
using System.Threading;
namespace OpcCilent
{
/// <summary>
/// 连接OPC的客户端
/// </summary>
public partial class Form1 : Form
{
OPCServer KepServer;
OPCGroups KepGroups;
OPCGroup KepGroup;
OPCItems KepItems;
OPCItem KepItem;
/// <summary>
/// 初始话窗口
/// </summary>
public Form1()
{
InitializeComponent();
}
/// <summary>
/// 连接按钮的单机事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
try
{
String serIp = "localhost";//服务器的IP地址
String serverName = "Matrikon.OPC.Simulation.1";//OPC服务器名称
KepServer = new OPCServer();
//连接OPC服务器,opc服务名,ip
KepServer.Connect(serverName, serIp);
//判断连接状态
if (KepServer.ServerState == (int)OPCServerState.OPCRunning)
{
textBox1.Text = "已连接到-" + KepServer.ServerName + " ";
}
else
{
//这里你可以根据返回的状态来自定义显示信息,请查看自动化接口API文档
textBox1.Text = "状态:" + KepServer.ServerState.ToString() + " ";
return;
}
KepGroups = KepServer.OPCGroups;
Thread t1, ; // 开1个线程用于读取数据
t1 = new Thread(new ThreadStart(kepProcess));
t1.Start();
}catch(Exception ex){
textBox1.Text = ex.Message;
}
}
//当数据改变时触发的事件
public void KepGroup_DataChange(int TransactionID, int NumItems, ref Array ClientHandles, ref Array ItemValues, ref Array Qualities, ref Array TimeStamps)
{
listBox1.Items.Add(ItemValues.GetValue(1));//取到改变的值
}
///线程1
public void kepProcess() {
KepGroup = KepGroups.Add("Group0");
KepGroup.UpdateRate = 250;
KepGroup.IsActive = true;
KepGroup.IsSubscribed = true;//当KepGroup中数据发生改变的触发事件
KepGroup.DataChange += new DIOPCGroupEvent_DataChangeEventHandler(KepGroup_DataChange);
KepItems = KepGroup.OPCItems;
int[] temp = new int[2];
temp[0] = 0;
KepItems.AddItem("Random Int1", 1);
OPCItem bItem = KepItems.Item(1);
Array serverHandles = (Array)temp;
Array values;
Array Errors;
Object cancel;
Object Qualities;
KepGroup.SyncRead((short)OPCAutomation.OPCDataSource.OPCCache, serverHandles.Length, ref serverHandles, out values, out Errors, out Qualities, out cancel);
}
//关闭连接
private void button2_Click(object sender, EventArgs e)
{
label6.Text = KepServer.CurrentTime.ToString();
KepServer.Disconnect();//关闭连服务器textBox1.Text = "未连接 ";
}
}
}
联系客服