using System;
using System.Text;
using AMWD.Protocols.Modbus.Common.Contracts;
using AMWD.Protocols.Modbus.Common.Protocols;
namespace AMWD.Protocols.Modbus.Tcp
{
///
/// Default implementation of a Modbus TCP client.
///
public class ModbusTcpClient : ModbusClientBase
{
///
/// Initializes a new instance of the class with a hostname and port number.
///
/// The DNS name of the remote host to which the connection is intended to.
/// The port number of the remote host to which the connection is intended to.
public ModbusTcpClient(string hostname, int port = 502)
: this(new ModbusTcpConnection { Hostname = hostname, Port = port })
{ }
///
/// Initializes a new instance of the class with a specific .
///
/// The responsible for invoking the requests.
public ModbusTcpClient(IModbusConnection connection)
: this(connection, true)
{ }
///
/// Initializes a new instance of the class with a specific .
///
/// The responsible for invoking the requests.
///
/// if the connection should be disposed of by Dispose(),
/// otherwise if you inted to reuse the connection.
///
public ModbusTcpClient(IModbusConnection connection, bool disposeConnection)
: base(connection, disposeConnection)
{
Protocol = new TcpProtocol();
}
///
public TimeSpan IdleTimeout
{
get => connection.IdleTimeout;
set => connection.IdleTimeout = value;
}
///
public TimeSpan ConnectTimeout
{
get => connection.ConnectTimeout;
set => connection.ConnectTimeout = value;
}
///
public TimeSpan ReadTimeout
{
get => connection.ReadTimeout;
set => connection.ReadTimeout = value;
}
///
public TimeSpan WriteTimeout
{
get => connection.WriteTimeout;
set => connection.WriteTimeout = value;
}
///
public string Hostname
{
get
{
if (connection is ModbusTcpConnection tcpConnection)
return tcpConnection.Hostname;
return default;
}
set
{
if (connection is ModbusTcpConnection tcpConnection)
tcpConnection.Hostname = value;
}
}
///
public int Port
{
get
{
if (connection is ModbusTcpConnection tcpConnection)
return tcpConnection.Port;
return default;
}
set
{
if (connection is ModbusTcpConnection tcpConnection)
tcpConnection.Port = value;
}
}
///
public override string ToString()
{
var sb = new StringBuilder();
sb.AppendLine($"TCP Client {Hostname}");
sb.AppendLine($" {nameof(Port)}: {Port}");
return sb.ToString();
}
}
}