Modbus TCP 连接与重连
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 } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」