973 lines
30 KiB
C#
973 lines
30 KiB
C#
using ControlzEx.Standard;
|
||
using HalconDotNet;
|
||
using HslCommunication.Core;
|
||
using HslCommunication.Core.Net;
|
||
using HslCommunication.ModBus;
|
||
using HslCommunication.Profinet.Melsec;
|
||
using System;
|
||
using System.Collections;
|
||
using System.Collections.Generic;
|
||
using System.IO;
|
||
using System.Linq;
|
||
using System.Net;
|
||
using System.Net.Sockets;
|
||
using System.Text;
|
||
using System.Threading;
|
||
using System.Threading.Tasks;
|
||
using System.Web.Services.Description;
|
||
|
||
namespace Model.HSL.ModbusTCP
|
||
{
|
||
/// <summary>
|
||
/// ModbusTCP
|
||
/// </summary>
|
||
public class ModbusHsl : HslParent
|
||
{
|
||
#region 字段与属性
|
||
/// <summary>
|
||
/// 发送超时时间
|
||
/// </summary>
|
||
public int SendTimeOut { get; set; } = 2000;
|
||
|
||
/// <summary>
|
||
/// 接收超时时间
|
||
/// </summary>
|
||
public int ReceiveTimeOut { get; set; } = 2000;
|
||
|
||
//创建一个Socket对象
|
||
private Socket socket;
|
||
|
||
/// <summary>
|
||
/// 每次接收前延时的时间
|
||
/// </summary>
|
||
public int SleepTime { get; set; } = 1;
|
||
|
||
/// <summary>
|
||
/// 最大的等待次数
|
||
/// </summary>
|
||
public int MaxWaitTimes { get; set; } = 10;
|
||
|
||
/// <summary>
|
||
/// 单元标识符
|
||
/// </summary>
|
||
public byte SlaveId { get; set; } = 0x01;
|
||
|
||
private DataFormat dataFormat = DataFormat.ABCD;
|
||
|
||
IPAddress iPAddress;
|
||
|
||
/// <summary>
|
||
/// 锁对象
|
||
/// </summary>
|
||
private SimpleHybridLock hyBirdLock = new SimpleHybridLock();
|
||
#endregion
|
||
|
||
public ModbusHsl(string ip, int port)
|
||
{
|
||
ConnectionType = 3;
|
||
this.IP = ip;
|
||
this.Port = port;
|
||
PlcStatus = new ShowInfo() { StatuInfo = "等待连接", StatusBackground = ColorStr.Yellow };
|
||
PlcRunStatus = new ShowInfo() { StatuInfo = "未知", StatusBackground = ColorStr.Blue };
|
||
}
|
||
|
||
public override bool Conneced()
|
||
{
|
||
//Socket实例化
|
||
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
|
||
//设置超时时间
|
||
this.socket.SendTimeout = SendTimeOut;
|
||
this.socket.ReceiveTimeout = ReceiveTimeOut;
|
||
|
||
try
|
||
{
|
||
//判断传入的是ip地址还是域名
|
||
if (IPAddress.TryParse(this.IP, out iPAddress))
|
||
{
|
||
//如果能转换为IP地址,用IP地址连接
|
||
this.socket.Connect(iPAddress, this.Port);
|
||
PlcStatus.StatuInfo = "连接成功";
|
||
PlcStatus.StatusBackground = ColorStr.Green;
|
||
}
|
||
else
|
||
{
|
||
//如果不能转换为IP地址,用域名连接
|
||
this.socket.Connect(this.IP, this.Port);
|
||
PlcStatus.StatuInfo = "连接成功";
|
||
PlcStatus.StatusBackground = ColorStr.Green;
|
||
}
|
||
}
|
||
catch (Exception)
|
||
{
|
||
PlcStatus.StatuInfo = "连接失败";
|
||
PlcStatus.StatusBackground = ColorStr.Red;
|
||
return false;
|
||
}
|
||
return true;
|
||
}
|
||
|
||
public override void Disconnect()
|
||
{
|
||
if (this.socket != null)
|
||
{
|
||
this.socket.Close();
|
||
PlcStatus.StatuInfo = "断开成功";
|
||
PlcStatus.StatusBackground = ColorStr.Red;
|
||
}
|
||
|
||
}
|
||
|
||
#region 读取数据
|
||
public override bool ReadBool(string address)
|
||
{
|
||
byte[] result = null;
|
||
ushort start = (ushort)Convert.ToInt32(address);
|
||
result = ReadOutPutCoils(start, 1);
|
||
if (result != null)
|
||
{
|
||
return ConvertLib.GetBitArrayFromByteArray(result, 0, 1)[0];
|
||
}
|
||
else
|
||
{
|
||
return false;
|
||
}
|
||
}
|
||
|
||
public override bool[] ReadBool(string address, ushort length)
|
||
{
|
||
byte[] result = null;
|
||
ushort start = (ushort)Convert.ToInt32(address);
|
||
result = ReadOutPutCoils(start, 1);
|
||
if (result != null)
|
||
{
|
||
return ConvertLib.GetBitArrayFromByteArray(result, 0, 1);
|
||
}
|
||
else
|
||
{
|
||
return new bool[0];
|
||
}
|
||
}
|
||
|
||
public override byte[] ReadByte(string address, ushort length)
|
||
{
|
||
byte[] result = null;
|
||
ushort start = (ushort)Convert.ToInt32(address);
|
||
result = ReadOutputRegisters(start, 1);
|
||
if (result != null)
|
||
{
|
||
return result;
|
||
}
|
||
else
|
||
{
|
||
return null;
|
||
}
|
||
}
|
||
|
||
public override double ReadDouble(string address)
|
||
{
|
||
throw new NotImplementedException();
|
||
}
|
||
|
||
public override double[] ReadDouble(string address, ushort length)
|
||
{
|
||
throw new NotImplementedException();
|
||
}
|
||
|
||
public override float ReadFloat(string address)
|
||
{
|
||
byte[] result = null;
|
||
ushort start = (ushort)Convert.ToInt32(address);
|
||
result = ReadOutputRegisters(start, 1);
|
||
if (result != null)
|
||
{
|
||
return ConvertLib.GetFloatArrayFromByteArray(result, this.dataFormat)[0];
|
||
}
|
||
else
|
||
{
|
||
return 0;
|
||
}
|
||
}
|
||
|
||
public override float[] ReadFloat(string address, ushort length)
|
||
{
|
||
byte[] result = null;
|
||
ushort start = (ushort)Convert.ToInt32(address);
|
||
result = ReadOutputRegisters(start, 1);
|
||
if (result != null)
|
||
{
|
||
return ConvertLib.GetFloatArrayFromByteArray(result, this.dataFormat);
|
||
}
|
||
else
|
||
{
|
||
return new float[0];
|
||
}
|
||
}
|
||
public override int ReadInt32(string address)
|
||
{
|
||
byte[] result = null;
|
||
ushort start = (ushort)Convert.ToInt32(address);
|
||
result = ReadOutputRegisters(start, 1);
|
||
if (result != null)
|
||
{
|
||
return ConvertLib.GetIntArrayFromByteArray(result, this.dataFormat)[0];
|
||
}
|
||
else
|
||
{
|
||
return 0;
|
||
}
|
||
}
|
||
|
||
public override int[] ReadInt32(string address, ushort length)
|
||
{
|
||
byte[] result = null;
|
||
ushort start = (ushort)Convert.ToInt32(address);
|
||
result = ReadOutputRegisters(start, 1);
|
||
if (result != null)
|
||
{
|
||
return ConvertLib.GetIntArrayFromByteArray(result, this.dataFormat);
|
||
}
|
||
else
|
||
{
|
||
return new int[0];
|
||
}
|
||
}
|
||
|
||
public override long ReadLong(string address)
|
||
{
|
||
throw new NotImplementedException();
|
||
}
|
||
|
||
public override long[] ReadLong(string address, ushort length)
|
||
{
|
||
throw new NotImplementedException();
|
||
}
|
||
|
||
public override short ReadShort(string address)
|
||
{
|
||
byte[] result = null;
|
||
ushort start = (ushort)Convert.ToInt32(address);
|
||
result = ReadOutputRegisters(start, 1);
|
||
if (result != null)
|
||
{
|
||
return ConvertLib.GetShortArrayFromByteArray(result)[0];
|
||
}
|
||
else
|
||
{
|
||
return 0;
|
||
}
|
||
}
|
||
|
||
public override short[] ReadShort(string address, ushort length)
|
||
{
|
||
byte[] result = null;
|
||
ushort start = (ushort)Convert.ToInt32(address);
|
||
result = ReadOutputRegisters(start, 1);
|
||
if (result != null)
|
||
{
|
||
return ConvertLib.GetShortArrayFromByteArray(result);
|
||
}
|
||
else
|
||
{
|
||
return new short[0];
|
||
}
|
||
}
|
||
|
||
public override string ReadString(string address, ushort Strlength)
|
||
{
|
||
throw new NotImplementedException();
|
||
}
|
||
|
||
public override uint ReadUint(string address)
|
||
{
|
||
byte[] result = null;
|
||
ushort start = (ushort)Convert.ToInt32(address);
|
||
result = ReadOutputRegisters(start, 1);
|
||
if (result != null)
|
||
{
|
||
return ConvertLib.GetUIntArrayFromByteArray(result, this.dataFormat)[0];
|
||
}
|
||
else
|
||
{
|
||
return 0;
|
||
}
|
||
}
|
||
|
||
public override uint[] ReadUint(string address, ushort length)
|
||
{
|
||
byte[] result = null;
|
||
ushort start = (ushort)Convert.ToInt32(address);
|
||
result = ReadOutputRegisters(start, 1);
|
||
if (result != null)
|
||
{
|
||
return ConvertLib.GetUIntArrayFromByteArray(result, this.dataFormat);
|
||
}
|
||
else
|
||
{
|
||
return new uint[0];
|
||
}
|
||
}
|
||
|
||
public override ushort ReadUint16(string address)
|
||
{
|
||
throw new NotImplementedException();
|
||
}
|
||
|
||
public override ushort[] ReadUint16(string address, ushort length)
|
||
{
|
||
throw new NotImplementedException();
|
||
}
|
||
|
||
public override ulong ReadUlong(string address)
|
||
{
|
||
throw new NotImplementedException();
|
||
}
|
||
|
||
public override ulong[] ReadUlong(string address, ushort length)
|
||
{
|
||
throw new NotImplementedException();
|
||
}
|
||
#endregion
|
||
|
||
#region 写入数据
|
||
public override bool Write(string address, params ushort[] val)
|
||
{
|
||
throw new NotImplementedException();
|
||
}
|
||
|
||
public override bool Write(string address, params short[] val)
|
||
{
|
||
ushort start = (ushort)Convert.ToInt32(address);
|
||
return PreSetMultiRegisters(start, ConvertLib.GetByteArrayFromShortArray(val));
|
||
}
|
||
|
||
public override bool Write(string address, params int[] val)
|
||
{
|
||
ushort start = (ushort)Convert.ToInt32(address);
|
||
return PreSetMultiRegisters(start, ConvertLib.GetByteArrayFromIntArray(val));
|
||
}
|
||
|
||
public override bool Write(string address, params long[] val)
|
||
{
|
||
throw new NotImplementedException();
|
||
}
|
||
|
||
public override bool Write(string address, params float[] val)
|
||
{
|
||
ushort start = (ushort)Convert.ToInt32(address);
|
||
return PreSetMultiRegisters(start, ConvertLib.GetByteArrayFromFloatArray(val));
|
||
}
|
||
|
||
public override bool Write(string address, params byte[] val)
|
||
{
|
||
ushort start = (ushort)Convert.ToInt32(address);
|
||
return PreSetMultiRegisters(start, val);
|
||
}
|
||
|
||
public override bool Write(string address, params double[] val)
|
||
{
|
||
throw new NotImplementedException();
|
||
}
|
||
|
||
public override bool Write(string address, params bool[] val)
|
||
{
|
||
ushort start = (ushort)Convert.ToInt32(address);
|
||
return PreSetSingleCoil(start, val[0]);
|
||
}
|
||
|
||
public override bool Write(string address, string val)
|
||
{
|
||
throw new NotImplementedException();
|
||
}
|
||
#endregion
|
||
|
||
#region ModbusMethod
|
||
#region 01H读取输出线圈
|
||
/// <summary>
|
||
/// 01H读取输出线圈
|
||
/// </summary>
|
||
/// <param name="start">起始线圈地址</param>
|
||
/// <param name="length">线圈长度</param>
|
||
/// <returns>返回数据</returns>
|
||
public byte[] ReadOutPutCoils(ushort start, ushort length)
|
||
{
|
||
//第一步:拼接报文
|
||
|
||
//创建一个ByteArray对象
|
||
ByteArray SendCommand = new ByteArray();
|
||
|
||
//事务处理+协议标识+长度+单元标识+功能码+起始线圈地址+线圈长度
|
||
|
||
//事务处理+协议标识
|
||
SendCommand.Add(0x00, 0x00, 0x00, 0x00);
|
||
|
||
//长度+单元标识+功能码
|
||
SendCommand.Add(0x00, 0x06, SlaveId, 0x01);
|
||
|
||
//起始线圈地址+线圈长度
|
||
SendCommand.Add(start);
|
||
SendCommand.Add(length);
|
||
|
||
byte[] receive = null;
|
||
|
||
int byteLength = length % 8 == 0 ? length / 8 : length / 8 + 1;
|
||
//第二步 第三步:发送并接收报文
|
||
if (SendAndReceive(SendCommand.Array, ref receive))
|
||
{
|
||
//第四步:验证报文
|
||
if (receive.Length == 9 + byteLength)
|
||
{
|
||
if (receive[6] == SlaveId && receive[7] == 0x01 && receive[8] == byteLength)
|
||
{
|
||
//第五部:解析报文
|
||
byte[] result = new byte[byteLength];
|
||
|
||
Array.Copy(receive, 9, result, 0, byteLength);
|
||
|
||
return result;
|
||
}
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
#endregion
|
||
|
||
#region 02H读取输入线圈
|
||
/// <summary>
|
||
/// 02H读取输入线圈
|
||
/// </summary>
|
||
/// <param name="start">起始线圈地址</param>
|
||
/// <param name="length">线圈长度</param>
|
||
/// <returns>返回数据</returns>
|
||
public byte[] ReadInPutCoils(ushort start, ushort length)
|
||
{
|
||
//第一步:拼接报文
|
||
|
||
//创建一个ByteArray对象
|
||
ByteArray SendCommand = new ByteArray();
|
||
|
||
//事务处理+协议标识+长度+单元标识+功能码+起始线圈地址+线圈长度
|
||
|
||
//事务处理+协议标识
|
||
SendCommand.Add(0x00, 0x00, 0x00, 0x00);
|
||
|
||
//长度+单元标识+功能码
|
||
SendCommand.Add(0x00, 0x06, SlaveId, 0x02);
|
||
|
||
//起始线圈地址+线圈长度
|
||
SendCommand.Add(start);
|
||
SendCommand.Add(length);
|
||
|
||
byte[] receive = null;
|
||
|
||
int byteLength = length % 8 == 0 ? length / 8 : length / 8 + 1;
|
||
//第二步 第三步:发送并接收报文
|
||
if (SendAndReceive(SendCommand.Array, ref receive))
|
||
{
|
||
//第四步:验证报文
|
||
if (receive.Length == 9 + byteLength)
|
||
{
|
||
if (receive[6] == SlaveId && receive[7] == 0x02 && receive[8] == byteLength)
|
||
{
|
||
//第五部:解析报文
|
||
byte[] result = new byte[byteLength];
|
||
|
||
Array.Copy(receive, 9, result, 0, byteLength);
|
||
|
||
return result;
|
||
}
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
#endregion
|
||
|
||
#region 03H读取输出寄存器
|
||
/// <summary>
|
||
/// 03H读取输出寄存器
|
||
/// </summary>
|
||
/// <param name="start">起始寄存器地址</param>
|
||
/// <param name="length">寄存器长度</param>
|
||
/// <returns>返回字节数组</returns>
|
||
public byte[] ReadOutputRegisters(ushort start, ushort length)
|
||
{
|
||
//第一步:拼接报文
|
||
|
||
//创建一个ByteArray对象
|
||
ByteArray SendCommand = new ByteArray();
|
||
|
||
//事务处理+协议标识+长度+单元标识+功能码+起始寄存器地址+寄存器长度
|
||
|
||
//事务处理+协议标识
|
||
SendCommand.Add(0x00, 0x00, 0x00, 0x00);
|
||
|
||
//长度+单元标识+功能码
|
||
SendCommand.Add(0x00, 0x06, SlaveId, 0x03);
|
||
|
||
//起始线圈地址+线圈长度
|
||
SendCommand.Add(start);
|
||
SendCommand.Add(length);
|
||
|
||
byte[] receive = null;
|
||
|
||
int byteLength = length * 2;
|
||
//第二步 第三步:发送并接收报文
|
||
if (SendAndReceive(SendCommand.Array, ref receive))
|
||
{
|
||
//第四步:验证报文
|
||
if (receive.Length == 9 + byteLength)
|
||
{
|
||
if (receive[6] == SlaveId && receive[7] == 0x03 && receive[8] == byteLength)
|
||
{
|
||
//第五部:解析报文
|
||
byte[] result = new byte[byteLength];
|
||
|
||
Array.Copy(receive, 9, result, 0, byteLength);
|
||
|
||
return result;
|
||
}
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
#endregion
|
||
|
||
#region 04H读取输入寄存器
|
||
/// <summary>
|
||
/// 04H读取输入寄存器
|
||
/// </summary>
|
||
/// <param name="start">起始寄存器地址</param>
|
||
/// <param name="length">寄存器长度</param>
|
||
/// <returns>返回字节数组</returns>
|
||
public byte[] ReadInputRegisters(ushort start, ushort length)
|
||
{
|
||
//第一步:拼接报文
|
||
|
||
//创建一个ByteArray对象
|
||
ByteArray SendCommand = new ByteArray();
|
||
|
||
//事务处理+协议标识+长度+单元标识+功能码+起始寄存器地址+寄存器长度
|
||
|
||
//事务处理+协议标识
|
||
SendCommand.Add(0x01, 0x00, 0x00, 0x00);
|
||
|
||
//长度+单元标识+功能码
|
||
SendCommand.Add(0x00, 0x06, SlaveId, 0x04);
|
||
|
||
//起始线圈地址+线圈长度
|
||
SendCommand.Add(start);
|
||
SendCommand.Add(length);
|
||
|
||
byte[] receive = null;
|
||
|
||
int byteLength = length * 2;
|
||
//第二步 第三步:发送并接收报文
|
||
if (SendAndReceive(SendCommand.Array, ref receive))
|
||
{
|
||
//第四步:验证报文
|
||
if (receive.Length == 9 + byteLength)
|
||
{
|
||
if (receive[6] == SlaveId && receive[7] == 0x04 && receive[8] == byteLength)
|
||
{
|
||
//第五部:解析报文
|
||
byte[] result = new byte[byteLength];
|
||
|
||
Array.Copy(receive, 9, result, 0, byteLength);
|
||
|
||
return result;
|
||
}
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
#endregion
|
||
|
||
#region 05H预置单线圈
|
||
/// <summary>
|
||
/// 预置单线圈
|
||
/// </summary>
|
||
/// <param name="start">线圈地址</param>
|
||
/// <param name="value">线圈值</param>
|
||
/// <returns>返回结果</returns>
|
||
public bool PreSetSingleCoil(ushort start, bool value)
|
||
{
|
||
//第一步:拼接报文
|
||
|
||
//创建一个ByteArray对象
|
||
ByteArray SendCommand = new ByteArray();
|
||
|
||
//事务处理+协议标识+长度+单元标识+功能码+线圈地址+线圈值(0xFF 0x00/00x00 0x00)
|
||
|
||
//事务处理+协议标识
|
||
SendCommand.Add(0x00, 0x00, 0x00, 0x00);
|
||
|
||
//长度+单元标识+功能码
|
||
SendCommand.Add(0x00, 0x06, SlaveId, 0x05);
|
||
|
||
//线圈地址
|
||
SendCommand.Add(start);
|
||
|
||
//线圈值
|
||
SendCommand.Add(value ? (byte)0xFF : (byte)0x00, 0x00);
|
||
|
||
byte[] receive = null;
|
||
//第二步 第三步:发送并接收报文
|
||
if (SendAndReceive(SendCommand.Array, ref receive))
|
||
{
|
||
//第四步:验证报文
|
||
if (receive.Length == 12)
|
||
{
|
||
return ByteArrayEquals(SendCommand.Array, receive);
|
||
}
|
||
}
|
||
return false;
|
||
}
|
||
#endregion
|
||
|
||
#region 06H预置单寄存器
|
||
/// <summary>
|
||
/// 预置单寄存器
|
||
/// </summary>
|
||
/// <param name="start">寄存器地址</param>
|
||
/// <param name="value">寄存器值</param>
|
||
/// <returns>返回结果</returns>
|
||
public bool PreSetSingleRegister(ushort start, byte[] value)
|
||
{
|
||
//第一步:拼接报文
|
||
|
||
//创建一个ByteArray对象
|
||
ByteArray SendCommand = new ByteArray();
|
||
|
||
//事务处理+协议标识+长度+单元标识+功能码+寄存器地址+寄存器值
|
||
|
||
//事务处理+协议标识
|
||
SendCommand.Add(0x00, 0x00, 0x00, 0x00);
|
||
|
||
//长度+单元标识+功能码
|
||
SendCommand.Add(0x00, 0x06, SlaveId, 0x06);
|
||
|
||
//线圈地址
|
||
SendCommand.Add(start);
|
||
|
||
//线圈值
|
||
SendCommand.Add(value);
|
||
|
||
byte[] receive = null;
|
||
//第二步 第三步:发送并接收报文
|
||
if (SendAndReceive(SendCommand.Array, ref receive))
|
||
{
|
||
//第四步:验证报文
|
||
if (receive.Length == 12)
|
||
{
|
||
return ByteArrayEquals(SendCommand.Array, receive);
|
||
}
|
||
}
|
||
return false;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 预置单寄存器
|
||
/// </summary>
|
||
/// <param name="slaveId">站地址</param>
|
||
/// <param name="start">寄存器地址</param>
|
||
/// <param name="value">short类型</param>
|
||
/// <returns>返回结果</returns>
|
||
public bool PreSetSingleRegister(ushort start, short value)
|
||
{
|
||
return PreSetSingleRegister(start, BitConverter.GetBytes(value).Reverse().ToArray());
|
||
//BitConverter.GetBytes(value) 将value转换为字节数组
|
||
//转换后高低字节翻转,需要.Reverse().ToArray()再次翻转值才正确
|
||
}
|
||
|
||
/// <summary>
|
||
/// 预置单寄存器
|
||
/// </summary>
|
||
/// <param name="slaveId">站地址</param>
|
||
/// <param name="start">寄存器地址</param>
|
||
/// <param name="value">ushort类型</param>
|
||
/// <returns>返回结果</returns>
|
||
public bool PreSetSingleRegister(ushort start, ushort value)
|
||
{
|
||
return PreSetSingleRegister(start, BitConverter.GetBytes(value).Reverse().ToArray());
|
||
//BitConverter.GetBytes(value) 将value转换为字节数组
|
||
}
|
||
|
||
#endregion
|
||
|
||
#region 0FH预置多线圈
|
||
/// <summary>
|
||
/// 预置多线圈
|
||
/// </summary>
|
||
/// <param name="start">起始线圈地址</param>
|
||
/// <param name="value">写入的值</param>
|
||
/// <returns>返回的结果</returns>
|
||
public bool PreSetMultiCoils(ushort start, bool[] value)
|
||
{
|
||
//第一步:拼接报文
|
||
|
||
//创建一个ByteArray对象
|
||
ByteArray SendCommand = new ByteArray();
|
||
|
||
byte[] setArray = GetBytesArrayFromBoolArray(value);
|
||
|
||
//事务处理+协议标识+长度+单元标识+功能码+起始线圈地址+线圈数量+字节计数+字节数据
|
||
|
||
//事务处理+协议标识
|
||
SendCommand.Add(0x00, 0x00, 0x00, 0x00);
|
||
|
||
//长度
|
||
SendCommand.Add((short)(7 + setArray.Length));
|
||
|
||
//单元标识 + 功能码
|
||
SendCommand.Add(SlaveId, 0x0F);
|
||
|
||
//线圈地址
|
||
SendCommand.Add(start);
|
||
|
||
//线圈数量
|
||
SendCommand.Add((short)value.Length);
|
||
|
||
//字节计数
|
||
SendCommand.Add((byte)setArray.Length);
|
||
|
||
//字节数据
|
||
SendCommand.Add(setArray);
|
||
|
||
byte[] receive = null;
|
||
//第二步 第三步:发送并接收报文
|
||
if (SendAndReceive(SendCommand.Array, ref receive))
|
||
{
|
||
//第四步:验证报文
|
||
//将发送报文前12位截取,把长度换成06,与接收报文对比
|
||
byte[] send = new byte[12];
|
||
|
||
Array.Copy(SendCommand.Array, 0, send, 0, 12);
|
||
|
||
send[4] = 0x00;
|
||
send[5] = 0x06;
|
||
|
||
return ByteArrayEquals(send, receive);
|
||
}
|
||
return false;
|
||
}
|
||
|
||
#endregion
|
||
|
||
#region 10H预置多寄存器
|
||
/// <summary>
|
||
/// 预置多寄存器
|
||
/// </summary>
|
||
/// <param name="start">起始寄存器地址</param>
|
||
/// <param name="value">写入的值</param>
|
||
/// <returns>返回的结果</returns>
|
||
public bool PreSetMultiRegisters(ushort start, byte[] values)
|
||
{
|
||
//第一步:拼接报文(一个寄存器是两个字节,必须是偶数)
|
||
if (values == null || values.Length == 0 || values.Length % 2 == 1)
|
||
{
|
||
return false;
|
||
}
|
||
|
||
//创建一个ByteArray对象
|
||
ByteArray SendCommand = new ByteArray();
|
||
|
||
//事务处理+协议标识+长度+单元标识+功能码+起始线圈地址+线圈数量+字节计数+字节数据
|
||
|
||
//事务处理+协议标识
|
||
SendCommand.Add(0x00, 0x00, 0x00, 0x00);
|
||
|
||
//长度
|
||
SendCommand.Add((short)(7 + values.Length));
|
||
|
||
//单元标识 + 功能码
|
||
SendCommand.Add(SlaveId, 0x10);
|
||
|
||
//线圈地址
|
||
SendCommand.Add(start);
|
||
|
||
//寄存器数量
|
||
SendCommand.Add((short)(values.Length / 2));
|
||
|
||
//字节计数
|
||
SendCommand.Add((byte)values.Length);
|
||
|
||
//字节数据
|
||
SendCommand.Add(values);
|
||
|
||
byte[] receive = null;
|
||
//第二步 第三步:发送并接收报文
|
||
if (SendAndReceive(SendCommand.Array, ref receive))
|
||
{
|
||
//第四步:验证报文
|
||
//将发送报文前12位截取,把长度换成06,与接收报文对比
|
||
byte[] send = new byte[12];
|
||
|
||
Array.Copy(SendCommand.Array, 0, send, 0, 12);
|
||
|
||
send[4] = 0x00;
|
||
send[5] = 0x06;
|
||
|
||
return ByteArrayEquals(send, receive);
|
||
}
|
||
return false;
|
||
}
|
||
#endregion
|
||
|
||
#region 通用发送并接收
|
||
|
||
/// <summary>
|
||
/// 通用发送并接收方法
|
||
/// </summary>
|
||
/// <param name="send">发送报文</param>
|
||
/// <param name="receive">接收报文</param>
|
||
/// <returns>返回结果</returns>
|
||
private bool SendAndReceive(byte[] send, ref byte[] receive)
|
||
{
|
||
//加锁
|
||
hyBirdLock.Enter();
|
||
|
||
//定义一个Buffer
|
||
byte[] buffer = new byte[1024];
|
||
//定义一个内存流
|
||
MemoryStream stream = new MemoryStream();
|
||
|
||
try
|
||
{
|
||
//发送报文
|
||
socket.Send(send, send.Length, SocketFlags.None);
|
||
|
||
int timer = 0;
|
||
|
||
while (true)
|
||
{
|
||
Thread.Sleep(SleepTime);
|
||
|
||
//判断缓冲区有没有数据
|
||
if (socket.Available > 0)
|
||
{
|
||
//接收数据斌放到Buffer
|
||
int count = socket.Receive(buffer, SocketFlags.None);
|
||
|
||
//将读取的数据放到Stream中
|
||
stream.Write(buffer, 0, count);
|
||
}
|
||
else
|
||
{
|
||
timer++;
|
||
//先判断Stream有没有数据
|
||
if (stream.Length > 0)
|
||
{
|
||
break;
|
||
}
|
||
//判断是否超时
|
||
else if (timer > MaxWaitTimes)
|
||
{
|
||
return false;
|
||
}
|
||
}
|
||
}
|
||
receive = stream.ToArray();
|
||
return true;
|
||
}
|
||
catch (Exception)
|
||
{
|
||
throw;
|
||
}
|
||
finally
|
||
{
|
||
hyBirdLock.Leave();
|
||
}
|
||
|
||
|
||
}
|
||
|
||
#endregion
|
||
|
||
#region 数组比较方法(比较是否相等)
|
||
private bool ByteArrayEquals(byte[] b1, byte[] b2)
|
||
{
|
||
//简洁的方法
|
||
return BitConverter.ToString(b1) == BitConverter.ToString(b2);
|
||
}
|
||
#endregion
|
||
|
||
#region 将布尔数组转换成字节数组
|
||
/// <summary>
|
||
/// 将布尔数组转换为字节数组
|
||
/// </summary>
|
||
/// <param name="value"></param>
|
||
/// <returns></returns>
|
||
public byte[] GetBytesArrayFromBoolArray(bool[] value)
|
||
{
|
||
int byteLength = value.Length % 8 == 0 ? value.Length / 8 : value.Length / 8 + 1;
|
||
|
||
byte[] result = new byte[byteLength];
|
||
|
||
for (int i = 0; (i < result.Length); i++)
|
||
{
|
||
//获取每个字节的值
|
||
// 15 = 8,7
|
||
int total = value.Length < 8 * (i + 1) ? value.Length - 8 * i : 8;
|
||
for (int j = 0; j < total; j++)
|
||
{
|
||
result[i] = SetBitvalue(result[i], j, value[8 * i + j]);
|
||
}
|
||
}
|
||
return result;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 给字节的某个位赋值(将某个字节的某个位置位或复位)
|
||
/// </summary>
|
||
/// <param name="src">原字节</param>
|
||
/// <param name="bit">第几位</param>
|
||
/// <param name="value">值</param>
|
||
/// <returns></returns>
|
||
private byte SetBitvalue(byte src, int bit, bool value)
|
||
{
|
||
return value ? (byte)(src | (byte)Math.Pow(2, bit)) : (byte)(src & ~(byte)Math.Pow(2, bit));
|
||
}
|
||
#endregion
|
||
#endregion
|
||
}
|
||
|
||
#region 简单混合锁
|
||
/// <summary>
|
||
/// 简单混合锁
|
||
/// </summary>
|
||
public sealed class SimpleHybridLock : IDisposable
|
||
{
|
||
//由基元用户模式构造(Interlocked的方法)使用
|
||
private int _waiters = 0;
|
||
|
||
//AutoResetEvent 是基元内核模式构造
|
||
private AutoResetEvent _waiterLock = new AutoResetEvent(false);
|
||
|
||
public void Enter()
|
||
{
|
||
//指出这个线程想要获得锁
|
||
if (Interlocked.Increment(ref _waiters) == 1)
|
||
return; //锁可自由使用,无竞争,直接返回
|
||
|
||
//另一个线程拥有锁(发生竞争),使这个线程等待
|
||
_waiterLock.WaitOne(); //这里产生较大的性能影响
|
||
//WaitOne返回后,这个线程拿到锁了
|
||
}
|
||
|
||
public void Leave()
|
||
{
|
||
//这个线程准备释放锁
|
||
if (Interlocked.Decrement(ref _waiters) == 0)
|
||
return; //没有其他线程正在等待,直接返回
|
||
|
||
//有其他线程正在阻塞,唤醒其中一个
|
||
_waiterLock.Set(); //这里产生较大的性能影响
|
||
}
|
||
|
||
public void Dispose()
|
||
{
|
||
_waiterLock.Dispose();
|
||
}
|
||
}
|
||
#endregion
|
||
}
|