上一篇我们对FINS-TCP读写PLC的地址进行封装,链接如下:
C#使用欧姆龙PLC的Fins协议读写PLC地址(基本封装)_ylq1045的专栏-CSDN博客
我们使用WInform界面来进行测试:
新建winform应用程序OmronFinsDemo,框架.net framework4.5.
将默认的Form1重命名为FormOmronFinsTcp。
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 OmronFinsDemo
{
public partial class FormOmronFinsTcp : Form
{
FinsTcpUtil finsTcpUtil = new FinsTcpUtil();
public FormOmronFinsTcp()
{
InitializeComponent();
cboReadType.SelectedIndex = 0;
cboWriteType.SelectedIndex = 0;
List omronAddressTypeCollection = new List()
{
OmronAddressType.AR,
OmronAddressType.CIO,
OmronAddressType.CNT,
OmronAddressType.DM,
OmronAddressType.HR,
OmronAddressType.TIM,
OmronAddressType.WR
};
this.ddlDataAddressTypeRead.DataSource = omronAddressTypeCollection;
this.ddlDataAddressTypeWrite.DataSource = omronAddressTypeCollection;
this.ddlDataAddressTypeLong.DataSource = omronAddressTypeCollection;
ddlDataAddressTypeRead.SelectedIndex = 3;
ddlDataAddressTypeWrite.SelectedIndex = 3;
ddlDataAddressTypeLong.SelectedIndex = 3;
}
///
/// 显示文本框的消息
///
///
private void DisplayInfo(RichTextBox rtxbResult, string message)
{
this.BeginInvoke(new Action(() =>
{
if (rtxbResult.TextLength >= 20480)
{
rtxbResult.Clear();
}
rtxbResult.AppendText($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} --> {message}\n");
rtxbResult.ScrollToCaret();
}));
}
private async void btnConnect_Click(object sender, EventArgs e)
{
bool result = false;
Task task = Task.Factory.StartNew(() =>
{
try
{
result = finsTcpUtil.ConnectPlc(txtIP.Text, int.Parse(txtPort.Text), 1);
}
catch (Exception ex)
{
DisplayInfo(rtxtMessageRead, $"连接欧姆龙PLC失败:{ex.Message}");
//MessageBox.Show($"连接欧姆龙PLC失败:{ex.Message}");
}
return result;
});
await task;
finsTcpUtil.RecordDataEvent -= FinsTcp_RecordDataEvent;
finsTcpUtil.RecordDataEvent += FinsTcp_RecordDataEvent;
DisplayInfo(rtxtMessageRead, $"连接欧姆龙PLC结果:{result}");
MessageBox.Show($"连接欧姆龙PLC结果:{result}");
}
///
/// 记录数据包事件
///
///
///
///
private void FinsTcp_RecordDataEvent(byte[] sendBuffer, byte[] receiveBuffer, double spendTime)
{
DisplayInfo(rtxtMessageRead,
$"发送命令【{string.Join(" ", sendBuffer.Select(element => element.ToString("X2")))}】\n接收命令【{string.Join(" ", receiveBuffer.Select(element => element.ToString("X2")))}】\n通信耗时【{spendTime}】ms");
}
private void btnDisconnect_Click(object sender, EventArgs e)
{
//解除事件绑定
finsTcpUtil.RecordDataEvent -= FinsTcp_RecordDataEvent;
finsTcpUtil.Disconnect();
DisplayInfo(rtxtMessageRead, $"连接已断开,当前连接状态:{finsTcpUtil.IsConnected}");
}
private void btnReadBasic_Click(object sender, EventArgs e)
{
Button button = sender as Button;
if (button == null)
{
return;
}
int result = -99;
try
{
int startAddress = int.Parse(txtReadAddr.Text);
OmronAddressType omronAddressType;
Enum.TryParse(Convert.ToString(ddlDataAddressTypeRead.SelectedValue), true, out omronAddressType);
string msg = string.Empty;
switch (button.Name)
{
case "btnReadBasic":
object resultBasic = ReadBasicValue(omronAddressType, cboReadType.Text, startAddress, out result, out msg);
txtReadValBasic.Text = Convert.ToString(resultBasic);
break;
case "btnReadString":
string barcode;
result = finsTcpUtil.ReadLongString(omronAddressType, startAddress, int.Parse(txtReadStringLength.Text), out barcode, out msg);
txtReadValString.Text = barcode;
break;
case "btnReadArray":
byte[] buffer;
result = finsTcpUtil.ReadValue(omronAddressType, startAddress, int.Parse(txtReadArrayLength.Text), out buffer, out msg);
rtxtReadValArray.Text = string.Join(" ", buffer.Select(element => element.ToString("X2")));
break;
}
DisplayInfo(rtxtMessageRead, $"读取地址【MW{txtReadAddr.Text}】的操作结果:错误号【{result}】{msg}");
}
catch (Exception ex)
{
DisplayInfo(rtxtMessageRead, $"读取地址【MW{txtReadAddr.Text}】的操作出现异常:{ex.Message}");
}
}
///
/// 读取基本数据类型
///
///
///
///
///
private object ReadBasicValue(OmronAddressType omronAddressType, string typeName, int startAddress, out int operateResult, out string msg)
{
operateResult = -1;
msg = string.Empty;
object result = 0;
switch (typeName)
{
case "short":
short valShort;
operateResult = finsTcpUtil.ReadValue(omronAddressType, startAddress, out valShort, out msg);
result = valShort;
DisplayInfo(rtxtMessageRead, $"对应字节【{string.Join(",", BitConverter.GetBytes(valShort))}】");
break;
case "ushort":
ushort valUshort;
operateResult = finsTcpUtil.ReadValue(omronAddressType, startAddress, out valUshort, out msg);
result = valUshort;
DisplayInfo(rtxtMessageRead, $"对应字节【{string.Join(",", BitConverter.GetBytes(valUshort))}】");
break;
case "int":
int valInt;
operateResult = finsTcpUtil.ReadValue(omronAddressType, startAddress, out valInt, out msg);
result = valInt;
DisplayInfo(rtxtMessageRead, $"对应字节【{string.Join(",", BitConverter.GetBytes(valInt))}】");
break;
case "uint":
uint valUint;
operateResult = finsTcpUtil.ReadValue(omronAddressType, startAddress, out valUint, out msg);
result = valUint;
DisplayInfo(rtxtMessageRead, $"对应字节【{string.Join(",", BitConverter.GetBytes(valUint))}】");
break;
case "long":
long valLong;
operateResult = finsTcpUtil.ReadValue(omronAddressType, startAddress, out valLong, out msg);
result = valLong;
DisplayInfo(rtxtMessageRead, $"对应字节【{string.Join(",", BitConverter.GetBytes(valLong))}】");
break;
case "ulong":
ulong valUlong;
operateResult = finsTcpUtil.ReadValue(omronAddressType, startAddress, out valUlong, out msg);
result = valUlong;
DisplayInfo(rtxtMessageRead, $"对应字节【{string.Join(",", BitConverter.GetBytes(valUlong))}】");
break;
case "float":
float valFloat;
operateResult = finsTcpUtil.ReadValue(omronAddressType, startAddress, out valFloat, out msg);
result = valFloat;
DisplayInfo(rtxtMessageRead, $"对应字节【{string.Join(",", BitConverter.GetBytes(valFloat))}】");
break;
case "double":
double valDouble;
operateResult = finsTcpUtil.ReadValue(omronAddressType, startAddress, out valDouble, out msg);
result = valDouble;
DisplayInfo(rtxtMessageRead, $"对应字节【{string.Join(",", BitConverter.GetBytes(valDouble))}】");
break;
case "byte":
byte valByte;
operateResult = finsTcpUtil.ReadValue(omronAddressType, startAddress, out valByte, out msg);
result = valByte;
DisplayInfo(rtxtMessageRead, $"对应字节【{string.Join(",", valByte)}】");
break;
case "sbyte":
sbyte valSbyte;
operateResult = finsTcpUtil.ReadValue(omronAddressType, startAddress, out valSbyte, out msg);
result = valSbyte;
DisplayInfo(rtxtMessageRead, $"对应字节【{string.Join(",", (byte)valSbyte)}】");
break;
case "bool":
bool valBool;
operateResult = finsTcpUtil.ReadValue(omronAddressType, startAddress, out valBool, out msg);
result = valBool;
DisplayInfo(rtxtMessageRead, $"对应字节【{string.Join(",", BitConverter.GetBytes(valBool))}】");
break;
}
return result;
}
private void btnWriteBasic_Click(object sender, EventArgs e)
{
Button button = sender as Button;
if (button == null)
{
return;
}
int result = -99;
try
{
int startAddress = int.Parse(txtWriteAddr.Text);
OmronAddressType omronAddressType;
Enum.TryParse(Convert.ToString(ddlDataAddressTypeWrite.SelectedValue), true, out omronAddressType);
string msg = string.Empty;
switch (button.Name)
{
case "btnWriteBasic":
WriteBasicValue(omronAddressType, cboWriteType.Text, startAddress, txtWriteValBasic.Text, out result, out msg);
DisplayInfo(rtxtMessageWrite, $"向地址【{startAddress}】写入值【{txtWriteValBasic.Text}】的结果:错误号【{result}】{msg}");
break;
case "btnWriteString":
result = finsTcpUtil.WriteString(omronAddressType, startAddress, int.Parse(txtWriteStringLength.Text), txtWriteValString.Text, out msg);
DisplayInfo(rtxtMessageWrite, $"向地址【{startAddress}】写入值【{txtWriteValString.Text}】的结果:错误号【{result}】{msg}");
break;
case "btnWriteArray":
byte[] buffer = rtxtWriteValArray.Text.Trim().Split(' ').Select(str => Convert.ToByte(str, 16)).ToArray();
result = finsTcpUtil.WriteValue(omronAddressType, startAddress, buffer, out msg);
DisplayInfo(rtxtMessageWrite, $"向地址【{startAddress}】写入值【{rtxtWriteValArray.Text}】的结果:错误号【{result}】{msg}");
break;
}
}
catch (Exception ex)
{
DisplayInfo(rtxtMessageWrite, $"写入地址【MW{txtWriteAddr.Text}】的操作出现异常:{ex.Message}");
}
}
///
/// 写基本数据类型
///
///
///
///
///
private void WriteBasicValue(OmronAddressType omronAddressType, string typeName, int startAddress, object writeValue, out int operateResult, out string msg)
{
msg = string.Empty;
operateResult = -99;
switch (typeName)
{
case "short":
short valShort = Convert.ToInt16(writeValue);
operateResult = finsTcpUtil.WriteValue(omronAddressType, startAddress, valShort, out msg);
break;
case "ushort":
ushort valUshort = Convert.ToUInt16(writeValue);
operateResult = finsTcpUtil.WriteValue(omronAddressType, startAddress, valUshort, out msg);
break;
case "int":
int valInt = Convert.ToInt32(writeValue);
operateResult = finsTcpUtil.WriteValue(omronAddressType, startAddress, valInt, out msg);
break;
case "uint":
uint valUint = Convert.ToUInt32(writeValue);
operateResult = finsTcpUtil.WriteValue(omronAddressType, startAddress, valUint, out msg);
break;
case "long":
long valLong = Convert.ToInt64(writeValue);
operateResult = finsTcpUtil.WriteValue(omronAddressType, startAddress, valLong, out msg);
break;
case "ulong":
ulong valUlong = Convert.ToUInt64(writeValue);
operateResult = finsTcpUtil.WriteValue(omronAddressType, startAddress, valUlong, out msg);
break;
case "float":
float valFloat = Convert.ToSingle(writeValue);
operateResult = finsTcpUtil.WriteValue(omronAddressType, startAddress, valFloat, out msg);
break;
case "double":
double valDouble = Convert.ToDouble(writeValue);
operateResult = finsTcpUtil.WriteValue(omronAddressType, startAddress, valDouble, out msg);
break;
case "byte":
byte valByte = Convert.ToByte(writeValue);
operateResult = finsTcpUtil.WriteValue(omronAddressType, startAddress, valByte, out msg);
break;
case "sbyte":
sbyte valSbyte = Convert.ToSByte(writeValue);
operateResult = finsTcpUtil.WriteValue(omronAddressType, startAddress, valSbyte, out msg);
break;
case "bool":
bool valBool = Convert.ToBoolean(writeValue);
operateResult = finsTcpUtil.WriteValue(omronAddressType, startAddress, valBool, out msg);
break;
}
}
private void btnWriteLongString_Click(object sender, EventArgs e)
{
string msg = "";
int startAddress = int.Parse(txtLongStrAddr.Text);
OmronAddressType omronAddressType;
Enum.TryParse(Convert.ToString(ddlDataAddressTypeLong.SelectedValue), true, out omronAddressType);
int result = finsTcpUtil.WriteLongString(omronAddressType, startAddress, rtxtLongString.Text, out msg);
DisplayInfo(rtxtMessageWrite, $"写入地址【MW{startAddress}】的操作结果:错误号【{result}】{msg}");
}
private void btnReadLongString_Click(object sender, EventArgs e)
{
string barcode;
string msg = "";
int startAddress = int.Parse(txtLongStrAddr.Text);
OmronAddressType omronAddressType;
Enum.TryParse(Convert.ToString(ddlDataAddressTypeLong.SelectedValue), true, out omronAddressType);
int result = finsTcpUtil.ReadLongString(omronAddressType, startAddress, int.Parse(txtLongLength.Text), out barcode, out msg);
rtxtLongString.Text = barcode;
DisplayInfo(rtxtMessageRead, $"读取地址【MW{startAddress}】的操作结果:错误号【{result}】{msg}");
}
private void FormOmronFinsTcp_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult dialogResult = MessageBox.Show("确定要关闭吗?", "提示", MessageBoxButtons.YesNo);
if (dialogResult != DialogResult.Yes)
{
e.Cancel = true;
return;
}
btnDisconnect_Click(null, e);
Application.Exit();
}
}
}