void MakeSureClientIsConnected() { if (_client != null && !_client.Connected) { _client.Dispose(); _client = null; _adapter.Dispose(); _adapter = null; _master.Dispose(); _master = null; } if (_client == null) { _client = new TcpClient(_configuration.Ip, _configuration.Port); _adapter = new TcpClientAdapter(_client); var factory = new ModbusFactory(); if (_configuration.UseASCII) { _master = factory.CreateAsciiMaster(_adapter); } else if (_configuration.Protocol == Protocol.Tcp) { _master = factory.CreateMaster(_client); } else { _master = factory.CreateRtuMaster(_adapter); } } }
private IModbusMaster CreateTcpMaster(ModbusFactory factory) { _tcpClient = new TcpClient(_configurationSettings.IpAddress, _configurationSettings.IpPort); IModbusMaster master = null; if (_configurationSettings.ConnectionType.CurrentType == ConnectionType.TcpIp) { master = factory.CreateMaster(_tcpClient); } if (_configurationSettings.ConnectionType.CurrentType == ConnectionType.RtuAsciiOverTcpIp) { var adapter = new TcpClientAdapter(_tcpClient); if (_configurationSettings.UseRtu) { master = factory.CreateRtuMaster(adapter); } if (_configurationSettings.UseAscii) { master = factory.CreateAsciiMaster(adapter); } } master.Transport.ReadTimeout = _configurationSettings.Timeout; return(master); }
/// <summary> /// Simple Modbus serial ASCII master read holding registers example. /// </summary> public static void ModbusSerialAsciiMasterReadRegisters() { using (SerialPort port = new SerialPort(PrimarySerialPortName)) { // configure serial port port.BaudRate = 9600; port.DataBits = 8; port.Parity = Parity.None; port.StopBits = StopBits.One; port.Open(); var factory = new ModbusFactory(); IModbusSerialMaster master = factory.CreateAsciiMaster(port); byte slaveId = 1; ushort startAddress = 1; ushort numRegisters = 5; // read five registers ushort[] registers = master.ReadHoldingRegisters(slaveId, startAddress, numRegisters); for (int i = 0; i < numRegisters; i++) { Console.WriteLine($"Register {startAddress + i}={registers[i]}"); } } // output: // Register 1=0 // Register 2=0 // Register 3=0 // Register 4=0 // Register 5=0 }
private IModbusMaster CreateSerialPortMaster(ModbusFactory factory) { IModbusMaster master = null; _serialPort = new SerialPort { PortName = _configurationSettings.SerialPort, BaudRate = _configurationSettings.BaudRate.Current, DataBits = _configurationSettings.DataBits, Parity = _configurationSettings.Parity, StopBits = _configurationSettings.StopBits }; _serialPort.Open(); if (_configurationSettings.UseRtu) { master = factory.CreateRtuMaster(new SerialPortAdapter(_serialPort)); } if (_configurationSettings.UseAscii) { master = factory.CreateAsciiMaster(new SerialPortAdapter(_serialPort)); } master.Transport.ReadTimeout = _configurationSettings.Timeout; return(master); }