打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
C#开发OPC客户端
1.本文采用MatrikonOPC做示例.
2.引入OPCDAAuto.dll(下载地址:http://download.csdn.net/detail/cgsyck/6519443)
3.下面是具体代码

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 = "未连接 ";
}

}
}

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
(C#)OPC客户端源码
基于C#开发OPC自动化接口客户端
通讯软件009——分分钟学会OPC Client
终于有人把西门子PLC通信说明白了
kepserver opc ua配置,opc kepserver
智能制造技术的应用第二讲 基于PROFINET和OPC UA的多机器人通信
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服