对汇川PLC采用Modbus-TCP进行读写寄存器测试示例
新建WinForms应用程序InovancePlcDemo,.net framework 4.5。
重命名窗体名为FormInovancePlcDemo
使用上一篇的InovanceTcp类,
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 InovancePlcDemo
{
public partial class FormInovancePlcDemo : Form
{
///
/// 汇川PLC操作相关对象
///
InovanceTcp inovanceTcp;
public FormInovancePlcDemo()
{
InitializeComponent();
cboReadType.SelectedIndex = 0;
cboWriteType.SelectedIndex = 0;
//默认字节顺次为CDAB 字颠倒
cboByteCategory.SelectedIndex = 2;
}
///
/// 显示文本框的消息
///
///
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 void btnConnect_Click(object sender, EventArgs e)
{
try
{
inovanceTcp = new InovanceTcp(txtIP.Text, int.Parse(txtPort.Text));
inovanceTcp.Connect();
inovanceTcp.RecordDataEvent -= InovanceTcp_RecordDataEvent;
inovanceTcp.RecordDataEvent += InovanceTcp_RecordDataEvent;
DisplayInfo(rtxtMessageRead, $"连接汇川PLC结果:{inovanceTcp.IsConnected}");
MessageBox.Show($"连接汇川PLC结果:{inovanceTcp.IsConnected}");
}
catch (Exception ex)
{
DisplayInfo(rtxtMessageRead, $"连接汇川PLC失败:{ex.Message}");
MessageBox.Show($"连接汇川PLC失败:{ex.Message}");
}
}
///
/// 记录数据包事件
///
///
///
///
private void InovanceTcp_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)
{
//解除事件绑定
inovanceTcp.RecordDataEvent -= InovanceTcp_RecordDataEvent;
inovanceTcp.DisConnect();
DisplayInfo(rtxtMessageRead, $"连接已断开,当前连接状态:{inovanceTcp.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);
string msg = string.Empty;
switch (button.Name)
{
case "btnReadBasic":
object resultBasic = ReadBasicValue(cboReadType.Text, startAddress, out result, out msg);
txtReadValBasic.Text = Convert.ToString(resultBasic);
break;
case "btnReadString":
string barcode;
result = inovanceTcp.ReadLongString(startAddress, int.Parse(txtReadStringLength.Text), out barcode, out msg);
txtReadValString.Text = barcode;
break;
case "btnReadArray":
byte[] buffer;
result = inovanceTcp.ReadValue(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(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 = inovanceTcp.ReadValue(startAddress, out valShort, out msg);
result = valShort;
DisplayInfo(rtxtMessageRead, $"对应字节【{string.Join(",", BitConverter.GetBytes(valShort))}】");
break;
case "ushort":
ushort valUshort;
operateResult = inovanceTcp.ReadValue(startAddress, out valUshort, out msg);
result = valUshort;
DisplayInfo(rtxtMessageRead, $"对应字节【{string.Join(",", BitConverter.GetBytes(valUshort))}】");
break;
case "int":
int valInt;
operateResult = inovanceTcp.ReadValue(startAddress, out valInt, out msg);
result = valInt;
DisplayInfo(rtxtMessageRead, $"对应字节【{string.Join(",", BitConverter.GetBytes(valInt))}】");
break;
case "uint":
uint valUint;
operateResult = inovanceTcp.ReadValue(startAddress, out valUint, out msg);
result = valUint;
DisplayInfo(rtxtMessageRead, $"对应字节【{string.Join(",", BitConverter.GetBytes(valUint))}】");
break;
case "long":
long valLong;
operateResult = inovanceTcp.ReadValue(startAddress, out valLong, out msg);
result = valLong;
DisplayInfo(rtxtMessageRead, $"对应字节【{string.Join(",", BitConverter.GetBytes(valLong))}】");
break;
case "ulong":
ulong valUlong;
operateResult = inovanceTcp.ReadValue(startAddress, out valUlong, out msg);
result = valUlong;
DisplayInfo(rtxtMessageRead, $"对应字节【{string.Join(",", BitConverter.GetBytes(valUlong))}】");
break;
case "float":
float valFloat;
operateResult = inovanceTcp.ReadValue(startAddress, out valFloat, out msg);
result = valFloat;
DisplayInfo(rtxtMessageRead, $"对应字节【{string.Join(",", BitConverter.GetBytes(valFloat))}】");
break;
case "double":
double valDouble;
operateResult = inovanceTcp.ReadValue(startAddress, out valDouble, out msg);
result = valDouble;
DisplayInfo(rtxtMessageRead, $"对应字节【{string.Join(",", BitConverter.GetBytes(valDouble))}】");
break;
case "byte":
byte valByte;
operateResult = inovanceTcp.ReadValue(startAddress, out valByte, out msg);
result = valByte;
DisplayInfo(rtxtMessageRead, $"对应字节【{string.Join(",", valByte)}】");
break;
case "sbyte":
sbyte valSbyte;
operateResult = inovanceTcp.ReadValue(startAddress, out valSbyte, out msg);
result = valSbyte;
DisplayInfo(rtxtMessageRead, $"对应字节【{string.Join(",", (byte)valSbyte)}】");
break;
case "bool":
bool valBool;
operateResult = inovanceTcp.ReadValue(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);
string msg = string.Empty;
switch (button.Name)
{
case "btnWriteBasic":
WriteBasicValue(cboWriteType.Text, startAddress, txtWriteValBasic.Text, out result, out msg);
DisplayInfo(rtxtMessageWrite, $"向地址【{startAddress}】写入值【{txtWriteValBasic.Text}】的结果:错误号【{result}】{msg}");
break;
case "btnWriteString":
result = inovanceTcp.WriteString(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 = inovanceTcp.WriteValue(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(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 = inovanceTcp.WriteValue(startAddress, valShort, out msg);
break;
case "ushort":
ushort valUshort = Convert.ToUInt16(writeValue);
operateResult = inovanceTcp.WriteValue(startAddress, valUshort, out msg);
break;
case "int":
int valInt = Convert.ToInt32(writeValue);
operateResult = inovanceTcp.WriteValue(startAddress, valInt, out msg);
break;
case "uint":
uint valUint = Convert.ToUInt32(writeValue);
operateResult = inovanceTcp.WriteValue(startAddress, valUint, out msg);
break;
case "long":
long valLong = Convert.ToInt64(writeValue);
operateResult = inovanceTcp.WriteValue(startAddress, valLong, out msg);
break;
case "ulong":
ulong valUlong = Convert.ToUInt64(writeValue);
operateResult = inovanceTcp.WriteValue(startAddress, valUlong, out msg);
break;
case "float":
float valFloat = Convert.ToSingle(writeValue);
operateResult = inovanceTcp.WriteValue(startAddress, valFloat, out msg);
break;
case "double":
double valDouble = Convert.ToDouble(writeValue);
operateResult = inovanceTcp.WriteValue(startAddress, valDouble, out msg);
break;
case "byte":
byte valByte = Convert.ToByte(writeValue);
operateResult = inovanceTcp.WriteValue(startAddress, valByte, out msg);
break;
case "sbyte":
sbyte valSbyte = Convert.ToSByte(writeValue);
operateResult = inovanceTcp.WriteValue(startAddress, valSbyte, out msg);
break;
case "bool":
bool valBool = Convert.ToBoolean(writeValue);
operateResult = inovanceTcp.WriteValue(startAddress, valBool, out msg);
break;
}
}
private void btnWriteLongString_Click(object sender, EventArgs e)
{
string msg = "";
int startAddress = int.Parse(txtLongStrAddr.Text);
int result = inovanceTcp.WriteLongString(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);
int result = inovanceTcp.ReadLongString(startAddress, int.Parse(txtLongLength.Text), out barcode, out msg);
rtxtLongString.Text = barcode;
DisplayInfo(rtxtMessageRead, $"读取地址【MW{startAddress}】的操作结果:错误号【{result}】{msg}");
}
}
}
长字符串: