using Modbus.Device;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using thinger.cn.DataConvertHelper;
namespace DAL
{
public class NmodbusTCPhelper
{
private TcpClient tcpClient = null;
private ModbusIpMaster master;
public bool Connected
{
get => tcpClient.Connected;
}
#region 打开与关闭Socket
public bool Connect(string ip, int port, int MaxConnectTime)
{
try
{
tcpClient = new TcpClient();
if (!tcpClient.ConnectAsync(ip, port).Wait(3000))
{
//连接失败
throw new Exception(string.Format("客户端连接在{0}:{1}失败", ip, port));
}
else
{
master = ModbusIpMaster.CreateIp(tcpClient);
//
// 通讯传输参数配置: 读写超时2000ms,重试次数:3次,重试间隔:1000ms
master.Transport.ReadTimeout = 2000;
master.Transport.WriteTimeout = 2000;
master.Transport.Retries = 3;
master.Transport.WaitToRetryMilliseconds = 1000;
return true;
}
}
catch (Exception e)
{
throw e;
}
}
public bool Disconnect()
{
if (tcpClient!=null)
{
tcpClient.Close();
return true;
}
else
{
return false;
}
}
#endregion
#region 读4区寄存器
/// <summary>
///
/// </summary>
/// <param name="iAdress">偏移量</param>
/// <param name="iLength">寄存器个数</param>
/// <returns></returns>
public byte[] ReedKeepReg(int iAdress, int iLength)
{
try
{
ushort[] des = master.ReadHoldingRegisters(Convert.ToUInt16(iAdress), Convert.ToUInt16(iLength));
byte[] res = ByteArrayLib.GetByteArrayFromUShortArray(des,DataFormat.BADC);//ABCD,BADC,CDAB
return res;
}
catch (Exception)
{
return null;
}
}
#endregion
#region 读取一区数据
public byte[] ReedCoilReg(int iAdress, int iLength)
{
try
{
bool[] des = master.ReadCoils(Convert.ToUInt16(iAdress), Convert.ToUInt16(iLength));
byte[] res = ByteArrayLib.GetByteArrayFromBoolArray(des);
return res;
}
catch (Exception)
{
return null;
}
}
#endregion
#region 预置保持寄存器
public bool PreSetFloatReg(int iAdress, ushort[] data)
{
try
{
master.WriteMultipleRegisters(Convert.ToUInt16(iAdress), data);
return true;
}
catch (Exception)
{
return false;
}
}
#endregion
}
}