当前位置:网站首页>C # read and write data to PLC in conjunction with kepserver
C # read and write data to PLC in conjunction with kepserver
2022-07-22 12:48:00 【Lava of Rodinia】
KepServer The communication protocol of any industrial equipment can be converted into opc agreement , And then use OPCAutomation Read and write data of upper computer .
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using OPCAutomation;
namespace KepTest1
{
public partial class FrmMain : Form
{
public FrmMain()
{
InitializeComponent();
this.Load += FrmMain_Load;
}
private void FrmMain_Load(object sender, EventArgs e)
{
this.btnRefresh_Click(btnRefresh, null);
this.dataGridViewValue.AutoGenerateColumns = false;
}
OPCServer opcServer;
OPCGroups opcGroups;
OPCGroup opcGroup;
OPCItems opcItems;
OPCItem opcItem; // term
Dictionary<string, OPCItem> dicOpcItem = new Dictionary<string, OPCItem>();
List<OPCItem> opcItemList = new List<OPCItem>(); // Collection of items
OPCBrowser opcBrowser;
string strHostName = null;
object opcServerList;
List<OpcValue> opcValueList = new List<OpcValue>();
int clientHandle; //change Handle
int count;
// Asynchronous write Correlation
Array writeErrors;
int cancelId;
private void btnConn_Click(object sender, EventArgs e)
{
// Connect to server
if (opcServer != null)
{
opcServer = new OPCServer();
}
try
{
opcServer.Connect(this.cmb_ServerName.Text, this.cmb_ServerNode.Text);
}
catch (Exception ex)
{
MessageBox.Show(" The connection fails :" + ex.Message);
return;
}
opcBrowser = this.opcServer.CreateBrowser(); // from OPC Node creation browser
opcBrowser.ShowBranches();// Show browser properties
opcBrowser.ShowLeafs(true); // Leaf node display
// binding It's actually a browser browers
this.listBoxServer.Items.Clear();
foreach (var item in opcBrowser)
{
if (!this.listBoxServer.Items.Contains(item))
{
this.listBoxServer.Items.Add(item.ToString());
}
}
// Communication group set
opcGroups = this.opcServer.OPCGroups;
opcGroups.DefaultGroupDeadband = 0; // As long as there's a change , It shows
opcGroups.DefaultGroupIsActive = true;
//opcGroups.DefaultGroupUpdateRate = 200; //200 Millisecond refresh once
// Communication group instantiation
opcGroup = opcGroups.Add("S71500Test");
opcGroup.IsActive = true;
opcGroup.IsSubscribed = true; // Whether to enable asynchronous callback
opcGroup.UpdateRate = 200;
opcItems = opcGroup.OPCItems;
opcGroup.DataChange += OpcGroup_DataChange;
}
// A subscription model
private void OpcGroup_DataChange(int TransactionID, int NumItems, ref Array ClientHandles, ref Array ItemValues, ref Array Qualities, ref Array TimeStamps)
{
for (int i = 0; i < NumItems; i++)
{
//clientHandle = Convert.ToInt32(ClientHandles.GetValue(i + 1));
//opcValueList[clientHandle - 1].Value = ItemValues.GetValue(i + 1).ToString();
//opcValueList[clientHandle - 1].InsertTime = Convert.ToDateTime(TimeStamps.GetValue(i + 1));
//this.dataGridViewValue.DataSource = null;
//this.dataGridViewValue.DataSource = opcValueList;
clientHandle = Convert.ToInt32(ClientHandles.GetValue(i + 1));
opcValueList[clientHandle - 1].Value = ItemValues.GetValue(i + 1).ToString();
opcValueList[clientHandle - 1].InsertTime = Convert.ToDateTime(TimeStamps.GetValue(i + 1));
opcValueList[clientHandle - 1].OPCDataType = ItemValues.GetValue(i + 1).GetType().ToString();
opcValueList[clientHandle - 1].OPCQuality = Qualities.GetValue(i + 1).ToString();
}
xktTextShowBasic1.VarValue = opcValueList[0].Value;
}
private void btnRefresh_Click(object sender, EventArgs e)
{
// Empty
this.cmb_ServerNode.Items.Clear();
this.cmb_ServerName.Items.Clear();
Task.Run(async () =>
{
IPHostEntry IPhost = Dns.GetHostEntry(Environment.MachineName);
if (IPhost.AddressList.Length > 0)
{
for (int i = 0; i < IPhost.AddressList.Length; i++)
{
await Task.Delay(500);
string host = Dns.GetHostEntry(IPhost.AddressList[i]).HostName;// Computer name
if (!this.cmb_ServerNode.Items.Contains(host))
{
this.cmb_ServerNode.Invoke(new Action(() =>
{
this.cmb_ServerNode.Items.Add(host);
}));
}
}
}
});
}
// If you change
private void cmb_ServerNode_SelectedIndexChanged(object sender, EventArgs e)
{
if (opcServer == null)
{
opcServer = new OPCServer();
}
this.cmb_ServerName.Items.Clear();
strHostName = this.cmb_ServerNode.Text.Trim(); // Get the hostname
try
{
opcServerList = opcServer.GetOPCServers(strHostName);
//object serviceList = KepServer.GetOPCServers(this.cmb_ServerNode.Text);
Task.Run(async () =>
{
foreach (var item in (Array)opcServerList)
{
await Task.Delay(500);
if (!this.cmb_ServerName.Items.Contains(item))
{
this.cmb_ServerName.Invoke(new Action(() =>
{
this.cmb_ServerName.Items.Add(item);
}));
}
}
});
}
catch (Exception)
{
}
}
private void listBoxServer_MouseDoubleClick(object sender, MouseEventArgs e)
{
opcValueList.Add(new OpcValue());
opcValueList[count].Name = this.listBoxServer.Text.Trim();
opcItem = opcItems.AddItem(this.listBoxServer.Text.Trim(), count + 1);
opcItemList.Add(opcItem);
count += 1;
}
// Read
private void button1_Click(object sender, EventArgs e)
{
opcValueList.Add(new OpcValue() {
Name = "MD200",ItemId = "Siemens1500.siemens1513.MD200" });
opcValueList.Add(new OpcValue() {
Name = "DB24DBW8", ItemId = "Siemens1500.siemens1513.DB24DBW8" });
opcValueList.Add(new OpcValue() {
Name = "DB24DBD34",ItemId = "Siemens1500.siemens1513.DB24DBD34" });
for (int i = 0; i < opcValueList.Count; i++)
{
opcItem = opcItems.AddItem(opcValueList[i].ItemId, i + 1);
opcItemList.Add(opcItem);
dicOpcItem.Add(opcValueList[i].Name, opcItem);
}
}
private void btnWrite_Click(object sender, EventArgs e)
{
string value = txtWrite.Text.Trim();
// Synchronous write
//dicOpcItem["MD200"].Write(value);
// Asynchronous write
int[] reServerHandle = new int[2] {
0, dicOpcItem["MD200"].ServerHandle };
Array arrayReServerHandle = reServerHandle.ToArray();
object[] reValue = new object[2] {
"", value};
Array values = reValue.ToArray();
opcGroup.AsyncWrite(1, ref arrayReServerHandle, ref values, out writeErrors, 2022, out cancelId);
}
private void btnDisc_Click(object sender, EventArgs e)
{
opcServer.Disconnect();
Environment.Exit(0);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KepTest1
{
public class OpcValue
{
public int Id {
get; set; }
public string ItemId {
get; set; }
public string Name {
get; set; }
public string Value {
get; set; }
// Communication quality
public string OPCQuality {
get; set; }
//ClientHandle
public int ClientHandle {
get; set; }
public string OPCDataType {
get; set; }
public DateTime InsertTime {
get; set; }
}
}
KepServer To configure :
Siemens PLC To configure :
#T1(IN := #start,
PT := t#1S);
#C1(CU := #T1.Q,
R := #reset,
PV := 30000);
IF #T1.Q THEN
RESET_TIMER(#T1);
;
END_IF;
IF #start THEN
"OpcDb".ushort[1] := #C1.CV;
"OpcDb".ushort[2] := "OpcDb".ushort[1] + 1;
"OpcDb".ushort[3] := "OpcDb".ushort[2] + 1;
"OpcDb".ushort[4] := "OpcDb".ushort[3] + 1;
"OpcDb".ushort[5] := "OpcDb".ushort[4] + 1;
"OpcDb".ushort[6] := "OpcDb".ushort[5] + 1;
"MD204" := "OpcDb".ushort[6] + 1.1;
"MD208" := "OpcDb".ushort[6] + 1.2;
"MD200" := "OpcDb".ushort[6] + 5.5;
"OpcDb".float[0] := "OpcDb".ushort[6] + 6.6;
"OpcDb".float[1] := "OpcDb".ushort[6] + 7.1;
"OpcDb".float[2] := "OpcDb".ushort[6] + 8.1;
"OpcDb".float[3] := "OpcDb".ushort[6] + 9.9;
END_IF;
边栏推荐
- [record of question brushing] 17 Letter combination of telephone number
- Common shortcut keys for Ad
- Shell learning notes (VI) -- practical battle I: Script Writing
- How to give selenium Chrome write extension intercepts or forwards requests
- Google test framework
- 无代码生产新模式探索
- SIM卡交换方案的工作原理
- Review of knowledge points (continuously updated version)
- 攻防演习和传统的渗透测试有哪些差别
- Easycvr platform security scanning prompt go pprof debugging information leakage solution
猜你喜欢
Anaconda环境下Pycharm的配置
Ylarn causal learning open source project "contributor program" is coming!
Programming skills │ amazing syntax of advanced markdown editor
What are the advantages of WMS warehouse management system based on bar code
小程序毕设作品之微信酒店预订小程序毕业设计(2)小程序功能
Mongodb learning journey
Multifunctional embedded decoding software (2)
[PHP environment setup /wamp/ interpreter / download]
121. The best time to buy and sell stocks
There are four ways to get started with precious metals
随机推荐
Prefix and & difference
How to achieve zero trust
Redis core principles
牛客网——华为题库(91~100)
SIM卡交换方案的工作原理
Wallpaper tutorial – beautiful underwater effects
There are four ways to get started with precious metals
STM32最小系统设计
OAuth2.0
A 15-year-old ABAP veteran's suggestion: understanding these basic knowledge is beneficial to ABAP development
Common shortcut keys for Ad
Working principle of Brushless DC motor
How to realize the bottom pop-up box encapsulation of wechat applet
AD常用术语
力扣上的行星碰撞问题(函数递归方法)
Detailed analysis process of lapsus stealing Microsoft Bing source code
攻防演习和传统的渗透测试有哪些差别
代码评审中用好7招,成功建立起你的反对同盟
等额本金和等额本息还款方式的差异分析
80% 应聘者都不及格的 JS 面试题