using Modbus.Device; using System; using System.Collections.Generic; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace AnQing.Commons { public class ModbusClient { private TcpClient tcpClient; private ModbusIpMaster modbusMaster; public ModbusClient(string ipAddress, int port) { tcpClient = new TcpClient(ipAddress, port); modbusMaster = ModbusIpMaster.CreateIp(tcpClient); } // 发送:写单个寄存器 public void WriteSingleRegister(ushort address, ushort value) { try { modbusMaster.WriteSingleRegister(address, value); Console.WriteLine($"成功写入寄存器地址 {address},值为 {value}"); } catch (Exception ex) { Console.WriteLine($"写寄存器时发生错误: {ex.Message}"); } } // 发送:写多个寄存器 public void WriteMultipleRegisters(ushort startAddress, ushort[] values) { try { modbusMaster.WriteMultipleRegisters(startAddress, values); Console.WriteLine($"成功写入多个寄存器,从地址 {startAddress} 开始"); } catch (Exception ex) { Console.WriteLine($"写多个寄存器时发生错误: {ex.Message}"); } } // 接收:读取多个保持寄存器 public ushort[] ReadHoldingRegisters(ushort startAddress, ushort numRegisters) { try { ushort[] registers = modbusMaster.ReadHoldingRegisters(startAddress, numRegisters); Console.WriteLine($"成功读取 {numRegisters} 个保持寄存器,从地址 {startAddress} 开始"); return registers; } catch (Exception ex) { Console.WriteLine($"读取寄存器时发生错误: {ex.Message}"); return null; } } // 接收:读取单个保持寄存器 public ushort ReadHoldingRegister(ushort address) { try { ushort registerValue = modbusMaster.ReadHoldingRegisters(address, 1)[0]; Console.WriteLine($"成功读取寄存器地址 {address} 的值:{registerValue}"); return registerValue; } catch (Exception ex) { Console.WriteLine($"读取寄存器时发生错误: {ex.Message}"); return 0; } } // 关闭连接 public void Close() { modbusMaster?.Dispose(); tcpClient.Close(); } } }