8 Commits

Author SHA1 Message Date
885079ae70 Fixed wrong R/W timeout handling on tcp listener handling. v0.4.2 2025-02-07 17:05:23 +01:00
17fc216658 Bump to v0.4.1 2025-02-06 17:04:38 +01:00
885231466b Fix of #7 tried to set DualMode on IPv4 network 2025-02-06 17:02:52 +01:00
5b8a2a8af1 Changed UnitTests for further improvements on testing 2025-02-05 20:46:13 +01:00
980dab22f3 Small .NET optimizations 2025-02-03 22:29:42 +01:00
9270f49519 CLI writing to error 2025-02-03 22:28:59 +01:00
241a9d114c Async optimization 2025-02-03 22:28:31 +01:00
9283b04971 Provide license as file on NuGet.
This will provide the file also in the NuGet package and can be seen when looking into projects dependencies.
2025-02-03 22:26:06 +01:00
37 changed files with 841 additions and 1199 deletions

View File

@@ -10,19 +10,27 @@ namespace AMWD.Protocols.Modbus.Common.Contracts
/// <summary> /// <summary>
/// Base implementation of a Modbus client. /// Base implementation of a Modbus client.
/// </summary> /// </summary>
public abstract class ModbusClientBase : IDisposable /// <remarks>
/// Initializes a new instance of the <see cref="ModbusClientBase"/> class with a specific <see cref="IModbusConnection"/>.
/// </remarks>
/// <param name="connection">The <see cref="IModbusConnection"/> responsible for invoking the requests.</param>
/// <param name="disposeConnection">
/// <see langword="true"/> if the connection should be disposed of by Dispose(),
/// <see langword="false"/> otherwise if you inted to reuse the connection.
/// </param>
public abstract class ModbusClientBase(IModbusConnection connection, bool disposeConnection) : IDisposable
{ {
private bool _isDisposed; private bool _isDisposed;
/// <summary> /// <summary>
/// Gets or sets a value indicating whether the connection should be disposed of by <see cref="Dispose()"/>. /// Gets or sets a value indicating whether the connection should be disposed of by <see cref="Dispose()"/>.
/// </summary> /// </summary>
protected readonly bool disposeConnection; protected readonly bool disposeConnection = disposeConnection;
/// <summary> /// <summary>
/// Gets or sets the <see cref="IModbusConnection"/> responsible for invoking the requests. /// Gets or sets the <see cref="IModbusConnection"/> responsible for invoking the requests.
/// </summary> /// </summary>
protected readonly IModbusConnection connection; protected readonly IModbusConnection connection = connection ?? throw new ArgumentNullException(nameof(connection));
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="ModbusClientBase"/> class with a specific <see cref="IModbusConnection"/>. /// Initializes a new instance of the <see cref="ModbusClientBase"/> class with a specific <see cref="IModbusConnection"/>.
@@ -32,20 +40,6 @@ namespace AMWD.Protocols.Modbus.Common.Contracts
: this(connection, true) : this(connection, true)
{ } { }
/// <summary>
/// Initializes a new instance of the <see cref="ModbusClientBase"/> class with a specific <see cref="IModbusConnection"/>.
/// </summary>
/// <param name="connection">The <see cref="IModbusConnection"/> responsible for invoking the requests.</param>
/// <param name="disposeConnection">
/// <see langword="true"/> if the connection should be disposed of by Dispose(),
/// <see langword="false"/> otherwise if you inted to reuse the connection.
/// </param>
public ModbusClientBase(IModbusConnection connection, bool disposeConnection)
{
this.connection = connection ?? throw new ArgumentNullException(nameof(connection));
this.disposeConnection = disposeConnection;
}
/// <summary> /// <summary>
/// Gets or sets the protocol type to use. /// Gets or sets the protocol type to use.
/// </summary> /// </summary>
@@ -67,7 +61,7 @@ namespace AMWD.Protocols.Modbus.Common.Contracts
Assertions(); Assertions();
var request = Protocol.SerializeReadCoils(unitId, startAddress, count); var request = Protocol.SerializeReadCoils(unitId, startAddress, count);
var response = await connection.InvokeAsync(request, Protocol.CheckResponseComplete, cancellationToken); var response = await connection.InvokeAsync(request, Protocol.CheckResponseComplete, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
Protocol.ValidateResponse(request, response); Protocol.ValidateResponse(request, response);
// The protocol processes complete bytes from the response. // The protocol processes complete bytes from the response.
@@ -92,7 +86,7 @@ namespace AMWD.Protocols.Modbus.Common.Contracts
Assertions(); Assertions();
var request = Protocol.SerializeReadDiscreteInputs(unitId, startAddress, count); var request = Protocol.SerializeReadDiscreteInputs(unitId, startAddress, count);
var response = await connection.InvokeAsync(request, Protocol.CheckResponseComplete, cancellationToken); var response = await connection.InvokeAsync(request, Protocol.CheckResponseComplete, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
Protocol.ValidateResponse(request, response); Protocol.ValidateResponse(request, response);
// The protocol processes complete bytes from the response. // The protocol processes complete bytes from the response.
@@ -117,7 +111,7 @@ namespace AMWD.Protocols.Modbus.Common.Contracts
Assertions(); Assertions();
var request = Protocol.SerializeReadHoldingRegisters(unitId, startAddress, count); var request = Protocol.SerializeReadHoldingRegisters(unitId, startAddress, count);
var response = await connection.InvokeAsync(request, Protocol.CheckResponseComplete, cancellationToken); var response = await connection.InvokeAsync(request, Protocol.CheckResponseComplete, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
Protocol.ValidateResponse(request, response); Protocol.ValidateResponse(request, response);
var holdingRegisters = Protocol.DeserializeReadHoldingRegisters(response).ToList(); var holdingRegisters = Protocol.DeserializeReadHoldingRegisters(response).ToList();
@@ -140,7 +134,7 @@ namespace AMWD.Protocols.Modbus.Common.Contracts
Assertions(); Assertions();
var request = Protocol.SerializeReadInputRegisters(unitId, startAddress, count); var request = Protocol.SerializeReadInputRegisters(unitId, startAddress, count);
var response = await connection.InvokeAsync(request, Protocol.CheckResponseComplete, cancellationToken); var response = await connection.InvokeAsync(request, Protocol.CheckResponseComplete, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
Protocol.ValidateResponse(request, response); Protocol.ValidateResponse(request, response);
var inputRegisters = Protocol.DeserializeReadInputRegisters(response).ToList(); var inputRegisters = Protocol.DeserializeReadInputRegisters(response).ToList();
@@ -184,7 +178,7 @@ namespace AMWD.Protocols.Modbus.Common.Contracts
do do
{ {
var request = Protocol.SerializeReadDeviceIdentification(unitId, category, requestObjectId); var request = Protocol.SerializeReadDeviceIdentification(unitId, category, requestObjectId);
var response = await connection.InvokeAsync(request, Protocol.CheckResponseComplete, cancellationToken); var response = await connection.InvokeAsync(request, Protocol.CheckResponseComplete, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
Protocol.ValidateResponse(request, response); Protocol.ValidateResponse(request, response);
result = Protocol.DeserializeReadDeviceIdentification(response); result = Protocol.DeserializeReadDeviceIdentification(response);
@@ -247,7 +241,7 @@ namespace AMWD.Protocols.Modbus.Common.Contracts
Assertions(); Assertions();
var request = Protocol.SerializeWriteSingleCoil(unitId, coil); var request = Protocol.SerializeWriteSingleCoil(unitId, coil);
var response = await connection.InvokeAsync(request, Protocol.CheckResponseComplete, cancellationToken); var response = await connection.InvokeAsync(request, Protocol.CheckResponseComplete, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
Protocol.ValidateResponse(request, response); Protocol.ValidateResponse(request, response);
var result = Protocol.DeserializeWriteSingleCoil(response); var result = Protocol.DeserializeWriteSingleCoil(response);
@@ -268,7 +262,7 @@ namespace AMWD.Protocols.Modbus.Common.Contracts
Assertions(); Assertions();
var request = Protocol.SerializeWriteSingleHoldingRegister(unitId, register); var request = Protocol.SerializeWriteSingleHoldingRegister(unitId, register);
var response = await connection.InvokeAsync(request, Protocol.CheckResponseComplete, cancellationToken); var response = await connection.InvokeAsync(request, Protocol.CheckResponseComplete, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
Protocol.ValidateResponse(request, response); Protocol.ValidateResponse(request, response);
var result = Protocol.DeserializeWriteSingleHoldingRegister(response); var result = Protocol.DeserializeWriteSingleHoldingRegister(response);
@@ -289,7 +283,7 @@ namespace AMWD.Protocols.Modbus.Common.Contracts
Assertions(); Assertions();
var request = Protocol.SerializeWriteMultipleCoils(unitId, coils); var request = Protocol.SerializeWriteMultipleCoils(unitId, coils);
var response = await connection.InvokeAsync(request, Protocol.CheckResponseComplete, cancellationToken); var response = await connection.InvokeAsync(request, Protocol.CheckResponseComplete, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
Protocol.ValidateResponse(request, response); Protocol.ValidateResponse(request, response);
var (firstAddress, count) = Protocol.DeserializeWriteMultipleCoils(response); var (firstAddress, count) = Protocol.DeserializeWriteMultipleCoils(response);
@@ -309,7 +303,7 @@ namespace AMWD.Protocols.Modbus.Common.Contracts
Assertions(); Assertions();
var request = Protocol.SerializeWriteMultipleHoldingRegisters(unitId, registers); var request = Protocol.SerializeWriteMultipleHoldingRegisters(unitId, registers);
var response = await connection.InvokeAsync(request, Protocol.CheckResponseComplete, cancellationToken); var response = await connection.InvokeAsync(request, Protocol.CheckResponseComplete, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
Protocol.ValidateResponse(request, response); Protocol.ValidateResponse(request, response);
var (firstAddress, count) = Protocol.DeserializeWriteMultipleHoldingRegisters(response); var (firstAddress, count) = Protocol.DeserializeWriteMultipleHoldingRegisters(response);

View File

@@ -10,6 +10,22 @@ namespace AMWD.Protocols.Modbus.Common.Protocols
/// </summary> /// </summary>
public class RtuProtocol : IModbusProtocol public class RtuProtocol : IModbusProtocol
{ {
#region Fields
private static readonly byte[] _readFunctionCodes = [
(byte)ModbusFunctionCode.ReadCoils,
(byte)ModbusFunctionCode.ReadDiscreteInputs,
(byte)ModbusFunctionCode.ReadHoldingRegisters,
(byte)ModbusFunctionCode.ReadInputRegisters];
private static readonly byte[] _writeFunctionCodes = [
(byte)ModbusFunctionCode.WriteSingleCoil,
(byte)ModbusFunctionCode.WriteSingleRegister,
(byte)ModbusFunctionCode.WriteMultipleCoils,
(byte)ModbusFunctionCode.WriteMultipleRegisters];
#endregion Fields
#region Constants #region Constants
/// <summary> /// <summary>
@@ -627,7 +643,7 @@ namespace AMWD.Protocols.Modbus.Common.Protocols
// - 0x03 Read Holding Registers // - 0x03 Read Holding Registers
// - 0x04 Read Input Registers // - 0x04 Read Input Registers
// do have a "following bytes" at position 3 // do have a "following bytes" at position 3
if (new[] { 0x01, 0x02, 0x03, 0x04 }.Contains(responseBytes[1])) if (_readFunctionCodes.Contains(responseBytes[1]))
{ {
// Unit ID, Function Code, ByteCount, 2x CRC and length of ByteCount // Unit ID, Function Code, ByteCount, 2x CRC and length of ByteCount
if (responseBytes.Count < 5 + responseBytes[2]) if (responseBytes.Count < 5 + responseBytes[2])
@@ -638,7 +654,7 @@ namespace AMWD.Protocols.Modbus.Common.Protocols
// - 0x06 Write Single Register // - 0x06 Write Single Register
// - 0x0F Write Multiple Coils // - 0x0F Write Multiple Coils
// - 0x10 Write Multiple Registers // - 0x10 Write Multiple Registers
if (new[] { 0x05, 0x06, 0x0F, 0x10 }.Contains(responseBytes[1])) if (_writeFunctionCodes.Contains(responseBytes[1]))
{ {
// Write Single => Unit ID, Function code, 2x Address, 2x Value, 2x CRC // Write Single => Unit ID, Function code, 2x Address, 2x Value, 2x CRC
// Write Multi => Unit ID, Function code, 2x Address, 2x QuantityWritten, 2x CRC // Write Multi => Unit ID, Function code, 2x Address, 2x QuantityWritten, 2x CRC
@@ -715,13 +731,13 @@ namespace AMWD.Protocols.Modbus.Common.Protocols
if (isError) if (isError)
throw new ModbusException("Remote Error") { ErrorCode = (ModbusErrorCode)response[2] }; throw new ModbusException("Remote Error") { ErrorCode = (ModbusErrorCode)response[2] };
if (new[] { 0x01, 0x02, 0x03, 0x04 }.Contains(fnCode)) if (_readFunctionCodes.Contains(fnCode))
{ {
if (response.Count != 5 + response[2]) if (response.Count != 5 + response[2])
throw new ModbusException("Number of following bytes does not match."); throw new ModbusException("Number of following bytes does not match.");
} }
if (new[] { 0x05, 0x06, 0x0F, 0x10 }.Contains(fnCode)) if (_writeFunctionCodes.Contains(fnCode))
{ {
if (response.Count != 8) if (response.Count != 8)
throw new ModbusException("Number of bytes does not match."); throw new ModbusException("Number of bytes does not match.");

View File

@@ -71,7 +71,7 @@ namespace AMWD.Protocols.Modbus.Common.Protocols
public DeviceIdentificationRaw DeserializeReadDeviceIdentification(IReadOnlyList<byte> response) public DeviceIdentificationRaw DeserializeReadDeviceIdentification(IReadOnlyList<byte> response)
{ {
if (!_devices.TryGetValue(response[0], out var device)) if (!_devices.TryGetValue(response[0], out var _))
throw new TimeoutException("Device not found."); throw new TimeoutException("Device not found.");
var result = new DeviceIdentificationRaw var result = new DeviceIdentificationRaw

View File

@@ -192,17 +192,16 @@ namespace AMWD.Protocols.Modbus.Serial
public Task StopAsync(CancellationToken cancellationToken = default) public Task StopAsync(CancellationToken cancellationToken = default)
{ {
Assertions(); Assertions();
return StopAsyncInternal(cancellationToken); StopAsyncInternal();
return Task.CompletedTask;
} }
private Task StopAsyncInternal(CancellationToken cancellationToken) private void StopAsyncInternal()
{ {
_stopCts?.Cancel(); _stopCts?.Cancel();
_serialPort.Close(); _serialPort.Close();
_serialPort.DataReceived -= OnDataReceived; _serialPort.DataReceived -= OnDataReceived;
return Task.CompletedTask;
} }
/// <summary> /// <summary>
@@ -215,7 +214,7 @@ namespace AMWD.Protocols.Modbus.Serial
_isDisposed = true; _isDisposed = true;
StopAsyncInternal(CancellationToken.None).Wait(); StopAsyncInternal();
_serialPort.Dispose(); _serialPort.Dispose();
_stopCts?.Dispose(); _stopCts?.Dispose();
@@ -332,7 +331,7 @@ namespace AMWD.Protocols.Modbus.Serial
responseBytes.AddRange(requestBytes.Take(2)); responseBytes.AddRange(requestBytes.Take(2));
try try
{ {
var coils = await Client.ReadCoilsAsync(unitId, firstAddress, count, cancellationToken); var coils = await Client.ReadCoilsAsync(unitId, firstAddress, count, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
byte[] values = new byte[(int)Math.Ceiling(coils.Count / 8.0)]; byte[] values = new byte[(int)Math.Ceiling(coils.Count / 8.0)];
for (int i = 0; i < coils.Count; i++) for (int i = 0; i < coils.Count; i++)
@@ -371,7 +370,7 @@ namespace AMWD.Protocols.Modbus.Serial
responseBytes.AddRange(requestBytes.Take(2)); responseBytes.AddRange(requestBytes.Take(2));
try try
{ {
var discreteInputs = await Client.ReadDiscreteInputsAsync(unitId, firstAddress, count, cancellationToken); var discreteInputs = await Client.ReadDiscreteInputsAsync(unitId, firstAddress, count, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
byte[] values = new byte[(int)Math.Ceiling(discreteInputs.Count / 8.0)]; byte[] values = new byte[(int)Math.Ceiling(discreteInputs.Count / 8.0)];
for (int i = 0; i < discreteInputs.Count; i++) for (int i = 0; i < discreteInputs.Count; i++)
@@ -410,7 +409,7 @@ namespace AMWD.Protocols.Modbus.Serial
responseBytes.AddRange(requestBytes.Take(2)); responseBytes.AddRange(requestBytes.Take(2));
try try
{ {
var holdingRegisters = await Client.ReadHoldingRegistersAsync(unitId, firstAddress, count, cancellationToken); var holdingRegisters = await Client.ReadHoldingRegistersAsync(unitId, firstAddress, count, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
byte[] values = new byte[holdingRegisters.Count * 2]; byte[] values = new byte[holdingRegisters.Count * 2];
for (int i = 0; i < holdingRegisters.Count; i++) for (int i = 0; i < holdingRegisters.Count; i++)
@@ -444,7 +443,7 @@ namespace AMWD.Protocols.Modbus.Serial
responseBytes.AddRange(requestBytes.Take(2)); responseBytes.AddRange(requestBytes.Take(2));
try try
{ {
var inputRegisters = await Client.ReadInputRegistersAsync(unitId, firstAddress, count, cancellationToken); var inputRegisters = await Client.ReadInputRegistersAsync(unitId, firstAddress, count, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
byte[] values = new byte[count * 2]; byte[] values = new byte[count * 2];
for (int i = 0; i < count; i++) for (int i = 0; i < count; i++)
@@ -492,7 +491,7 @@ namespace AMWD.Protocols.Modbus.Serial
LowByte = requestBytes[5], LowByte = requestBytes[5],
}; };
bool isSuccess = await Client.WriteSingleCoilAsync(requestBytes[0], coil, cancellationToken); bool isSuccess = await Client.WriteSingleCoilAsync(requestBytes[0], coil, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
if (isSuccess) if (isSuccess)
{ {
// Response is an echo of the request // Response is an echo of the request
@@ -531,7 +530,7 @@ namespace AMWD.Protocols.Modbus.Serial
LowByte = requestBytes[5] LowByte = requestBytes[5]
}; };
bool isSuccess = await Client.WriteSingleHoldingRegisterAsync(requestBytes[0], register, cancellationToken); bool isSuccess = await Client.WriteSingleHoldingRegisterAsync(requestBytes[0], register, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
if (isSuccess) if (isSuccess)
{ {
// Response is an echo of the request // Response is an echo of the request
@@ -591,7 +590,7 @@ namespace AMWD.Protocols.Modbus.Serial
}); });
} }
bool isSuccess = await Client.WriteMultipleCoilsAsync(requestBytes[0], coils, cancellationToken); bool isSuccess = await Client.WriteMultipleCoilsAsync(requestBytes[0], coils, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
if (isSuccess) if (isSuccess)
{ {
// Response is an echo of the request // Response is an echo of the request
@@ -648,7 +647,7 @@ namespace AMWD.Protocols.Modbus.Serial
}); });
} }
bool isSuccess = await Client.WriteMultipleHoldingRegistersAsync(requestBytes[0], list, cancellationToken); bool isSuccess = await Client.WriteMultipleHoldingRegistersAsync(requestBytes[0], list, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
if (isSuccess) if (isSuccess)
{ {
// Response is an echo of the request // Response is an echo of the request
@@ -705,7 +704,7 @@ namespace AMWD.Protocols.Modbus.Serial
try try
{ {
var deviceInfo = await Client.ReadDeviceIdentificationAsync(requestBytes[0], category, firstObject, cancellationToken); var deviceInfo = await Client.ReadDeviceIdentificationAsync(requestBytes[0], category, firstObject, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
var bodyBytes = new List<byte>(); var bodyBytes = new List<byte>();
@@ -855,5 +854,21 @@ namespace AMWD.Protocols.Modbus.Serial
} }
#endregion Request Handling #endregion Request Handling
/// <inheritdoc/>
public override string ToString()
{
var sb = new StringBuilder();
sb.AppendLine($"RTU Proxy");
sb.AppendLine($" {nameof(PortName)}: {PortName}");
sb.AppendLine($" {nameof(BaudRate)}: {(int)BaudRate}");
sb.AppendLine($" {nameof(DataBits)}: {DataBits}");
sb.AppendLine($" {nameof(StopBits)}: {StopBits}");
sb.AppendLine($" {nameof(Parity)}: {Parity}");
sb.AppendLine($" {nameof(Client)}: {Client.GetType().Name}");
return sb.ToString();
}
} }
} }

View File

@@ -31,8 +31,7 @@ namespace AMWD.Protocols.Modbus.Serial
private readonly Task _processingTask; private readonly Task _processingTask;
private readonly AsyncQueue<RequestQueueItem> _requestQueue = new(); private readonly AsyncQueue<RequestQueueItem> _requestQueue = new();
// Only required to cover all logic branches on unit tests. private readonly bool _isLinux;
private bool _isUnitTest = false;
#endregion Fields #endregion Fields
@@ -41,6 +40,8 @@ namespace AMWD.Protocols.Modbus.Serial
/// </summary> /// </summary>
public ModbusSerialConnection(string portName) public ModbusSerialConnection(string portName)
{ {
_isLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
if (string.IsNullOrWhiteSpace(portName)) if (string.IsNullOrWhiteSpace(portName))
throw new ArgumentNullException(nameof(portName)); throw new ArgumentNullException(nameof(portName));
@@ -268,7 +269,7 @@ namespace AMWD.Protocols.Modbus.Serial
try try
{ {
// Get next request to process // Get next request to process
var item = await _requestQueue.DequeueAsync(cancellationToken); var item = await _requestQueue.DequeueAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
// Remove registration => already removed from queue // Remove registration => already removed from queue
item.CancellationTokenRegistration.Dispose(); item.CancellationTokenRegistration.Dispose();
@@ -276,13 +277,13 @@ namespace AMWD.Protocols.Modbus.Serial
// Build combined cancellation token // Build combined cancellation token
using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, item.CancellationTokenSource.Token); using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, item.CancellationTokenSource.Token);
// Wait for exclusive access // Wait for exclusive access
await _portLock.WaitAsync(linkedCts.Token); await _portLock.WaitAsync(linkedCts.Token).ConfigureAwait(continueOnCapturedContext: false);
try try
{ {
// Ensure connection is up // Ensure connection is up
await AssertConnection(linkedCts.Token); await AssertConnection(linkedCts.Token);
await _serialPort.WriteAsync(item.Request, linkedCts.Token); await _serialPort.WriteAsync(item.Request, linkedCts.Token).ConfigureAwait(continueOnCapturedContext: false);
linkedCts.Token.ThrowIfCancellationRequested(); linkedCts.Token.ThrowIfCancellationRequested();
@@ -291,7 +292,7 @@ namespace AMWD.Protocols.Modbus.Serial
do do
{ {
int readCount = await _serialPort.ReadAsync(buffer, 0, buffer.Length, linkedCts.Token); int readCount = await _serialPort.ReadAsync(buffer, 0, buffer.Length, linkedCts.Token).ConfigureAwait(continueOnCapturedContext: false);
if (readCount < 1) if (readCount < 1)
throw new EndOfStreamException(); throw new EndOfStreamException();
@@ -322,7 +323,7 @@ namespace AMWD.Protocols.Modbus.Serial
_portLock.Release(); _portLock.Release();
_idleTimer.Change(IdleTimeout, Timeout.InfiniteTimeSpan); _idleTimer.Change(IdleTimeout, Timeout.InfiniteTimeSpan);
await Task.Delay(InterRequestDelay, cancellationToken); await Task.Delay(InterRequestDelay, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
} }
} }
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
@@ -353,7 +354,7 @@ namespace AMWD.Protocols.Modbus.Serial
_serialPort.Close(); _serialPort.Close();
_serialPort.ResetRS485DriverStateFlags(); _serialPort.ResetRS485DriverStateFlags();
if (DriverEnabledRS485 && (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || _isUnitTest)) if (DriverEnabledRS485 && _isLinux)
{ {
var flags = _serialPort.GetRS485DriverStateFlags(); var flags = _serialPort.GetRS485DriverStateFlags();
flags |= RS485Flags.Enabled; flags |= RS485Flags.Enabled;
@@ -361,7 +362,7 @@ namespace AMWD.Protocols.Modbus.Serial
_serialPort.ChangeRS485DriverStateFlags(flags); _serialPort.ChangeRS485DriverStateFlags(flags);
} }
using var connectTask = Task.Run(_serialPort.Open); using var connectTask = Task.Run(_serialPort.Open, cancellationToken);
if (await Task.WhenAny(connectTask, Task.Delay(ReadTimeout, cancellationToken)) == connectTask) if (await Task.WhenAny(connectTask, Task.Delay(ReadTimeout, cancellationToken)) == connectTask)
{ {
await connectTask; await connectTask;
@@ -379,7 +380,7 @@ namespace AMWD.Protocols.Modbus.Serial
try try
{ {
await Task.Delay(TimeSpan.FromSeconds(delay), cancellationToken); await Task.Delay(TimeSpan.FromSeconds(delay), cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
} }
catch catch
{ /* keep it quiet */ } { /* keep it quiet */ }

View File

@@ -12,7 +12,7 @@ namespace System.IO
int offset = 0; int offset = 0;
do do
{ {
int count = await stream.ReadAsync(buffer, offset, expectedBytes - offset, cancellationToken); int count = await stream.ReadAsync(buffer, offset, expectedBytes - offset, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
if (count < 1) if (count < 1)
throw new EndOfStreamException(); throw new EndOfStreamException();
@@ -30,7 +30,7 @@ namespace System.IO
int offset = 0; int offset = 0;
do do
{ {
int count = await stream.ReadAsync(buffer, offset, expectedBytes - offset, cancellationToken); int count = await stream.ReadAsync(buffer, offset, expectedBytes - offset, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
if (count < 1) if (count < 1)
throw new EndOfStreamException(); throw new EndOfStreamException();

View File

@@ -0,0 +1,17 @@
using System.Threading.Tasks;
namespace AMWD.Protocols.Modbus.Tcp.Extensions
{
internal static class TaskExtensions
{
public static async void Forget(this Task task)
{
try
{
await task;
}
catch
{ /* keep it quiet */ }
}
}
}

View File

@@ -65,8 +65,12 @@ namespace AMWD.Protocols.Modbus.Tcp
get => _readTimeout; get => _readTimeout;
set set
{ {
#if NET8_0_OR_GREATER
ArgumentOutOfRangeException.ThrowIfLessThan(value, TimeSpan.Zero);
#else
if (value < TimeSpan.Zero) if (value < TimeSpan.Zero)
throw new ArgumentOutOfRangeException(nameof(value)); throw new ArgumentOutOfRangeException(nameof(value));
#endif
_readTimeout = value; _readTimeout = value;
@@ -81,8 +85,12 @@ namespace AMWD.Protocols.Modbus.Tcp
get => _writeTimeout; get => _writeTimeout;
set set
{ {
#if NET8_0_OR_GREATER
ArgumentOutOfRangeException.ThrowIfLessThan(value, TimeSpan.Zero);
#else
if (value < TimeSpan.Zero) if (value < TimeSpan.Zero)
throw new ArgumentOutOfRangeException(nameof(value)); throw new ArgumentOutOfRangeException(nameof(value));
#endif
_writeTimeout = value; _writeTimeout = value;
@@ -208,7 +216,7 @@ namespace AMWD.Protocols.Modbus.Tcp
try try
{ {
// Get next request to process // Get next request to process
var item = await _requestQueue.DequeueAsync(cancellationToken); var item = await _requestQueue.DequeueAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
// Remove registration => already removed from queue // Remove registration => already removed from queue
item.CancellationTokenRegistration.Dispose(); item.CancellationTokenRegistration.Dispose();
@@ -216,19 +224,19 @@ namespace AMWD.Protocols.Modbus.Tcp
// Build combined cancellation token // Build combined cancellation token
using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, item.CancellationTokenSource.Token); using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, item.CancellationTokenSource.Token);
// Wait for exclusive access // Wait for exclusive access
await _clientLock.WaitAsync(linkedCts.Token); await _clientLock.WaitAsync(linkedCts.Token).ConfigureAwait(continueOnCapturedContext: false);
try try
{ {
// Ensure connection is up // Ensure connection is up
await AssertConnection(linkedCts.Token); await AssertConnection(linkedCts.Token).ConfigureAwait(continueOnCapturedContext: false);
var stream = _tcpClient.GetStream(); var stream = _tcpClient.GetStream();
await stream.FlushAsync(linkedCts.Token); await stream.FlushAsync(linkedCts.Token);
#if NET6_0_OR_GREATER #if NET6_0_OR_GREATER
await stream.WriteAsync(item.Request, linkedCts.Token); await stream.WriteAsync(item.Request, linkedCts.Token).ConfigureAwait(continueOnCapturedContext: false);
#else #else
await stream.WriteAsync(item.Request, 0, item.Request.Length, linkedCts.Token); await stream.WriteAsync(item.Request, 0, item.Request.Length, linkedCts.Token).ConfigureAwait(continueOnCapturedContext: false);
#endif #endif
linkedCts.Token.ThrowIfCancellationRequested(); linkedCts.Token.ThrowIfCancellationRequested();
@@ -239,9 +247,9 @@ namespace AMWD.Protocols.Modbus.Tcp
do do
{ {
#if NET6_0_OR_GREATER #if NET6_0_OR_GREATER
int readCount = await stream.ReadAsync(buffer, linkedCts.Token); int readCount = await stream.ReadAsync(buffer, linkedCts.Token).ConfigureAwait(continueOnCapturedContext: false);
#else #else
int readCount = await stream.ReadAsync(buffer, 0, buffer.Length, linkedCts.Token); int readCount = await stream.ReadAsync(buffer, 0, buffer.Length, linkedCts.Token).ConfigureAwait(continueOnCapturedContext: false);
#endif #endif
if (readCount < 1) if (readCount < 1)
throw new EndOfStreamException(); throw new EndOfStreamException();
@@ -332,7 +340,7 @@ namespace AMWD.Protocols.Modbus.Tcp
try try
{ {
await Task.Delay(TimeSpan.FromSeconds(delay), cancellationToken); await Task.Delay(TimeSpan.FromSeconds(delay), cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
} }
catch catch
{ /* keep it quiet */ } { /* keep it quiet */ }
@@ -376,10 +384,9 @@ namespace AMWD.Protocols.Modbus.Tcp
try try
{ {
return Dns.GetHostAddresses(hostname) return [.. Dns.GetHostAddresses(hostname)
.Where(a => a.AddressFamily == AddressFamily.InterNetwork || a.AddressFamily == AddressFamily.InterNetworkV6) .Where(a => a.AddressFamily == AddressFamily.InterNetwork || a.AddressFamily == AddressFamily.InterNetworkV6)
.OrderBy(a => a.AddressFamily) // prefer IPv4 .OrderBy(a => a.AddressFamily)]; // prefer IPv4
.ToArray();
} }
catch catch
{ {

View File

@@ -10,6 +10,7 @@ using System.Threading.Tasks;
using AMWD.Protocols.Modbus.Common; using AMWD.Protocols.Modbus.Common;
using AMWD.Protocols.Modbus.Common.Contracts; using AMWD.Protocols.Modbus.Common.Contracts;
using AMWD.Protocols.Modbus.Common.Protocols; using AMWD.Protocols.Modbus.Common.Protocols;
using AMWD.Protocols.Modbus.Tcp.Extensions;
using AMWD.Protocols.Modbus.Tcp.Utils; using AMWD.Protocols.Modbus.Tcp.Utils;
namespace AMWD.Protocols.Modbus.Tcp namespace AMWD.Protocols.Modbus.Tcp
@@ -17,7 +18,12 @@ namespace AMWD.Protocols.Modbus.Tcp
/// <summary> /// <summary>
/// Implements a Modbus TCP server proxying all requests to a Modbus client of choice. /// Implements a Modbus TCP server proxying all requests to a Modbus client of choice.
/// </summary> /// </summary>
public class ModbusTcpProxy : IModbusProxy /// <remarks>
/// Initializes a new instance of the <see cref="ModbusTcpProxy"/> class.
/// </remarks>
/// <param name="client">The <see cref="ModbusClientBase"/> used to request the remote device, that should be proxied.</param>
/// <param name="listenAddress">An <see cref="IPAddress"/> to listen on.</param>
public class ModbusTcpProxy(ModbusClientBase client, IPAddress listenAddress) : IModbusProxy
{ {
#region Fields #region Fields
@@ -25,30 +31,17 @@ namespace AMWD.Protocols.Modbus.Tcp
private TimeSpan _readWriteTimeout = TimeSpan.FromSeconds(100); private TimeSpan _readWriteTimeout = TimeSpan.FromSeconds(100);
private TcpListenerWrapper _tcpListener; private readonly TcpListenerWrapper _tcpListener = new(listenAddress, 502);
private CancellationTokenSource _stopCts; private CancellationTokenSource _stopCts;
private Task _clientConnectTask = Task.CompletedTask; private Task _clientConnectTask = Task.CompletedTask;
private readonly SemaphoreSlim _clientListLock = new(1, 1); private readonly SemaphoreSlim _clientListLock = new(1, 1);
private readonly List<TcpClientWrapper> _clients = []; private readonly List<TcpClientWrapper> _clients = [];
private readonly List<Task> _clientTasks = [];
#endregion Fields #endregion Fields
#region Constructors #region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ModbusTcpProxy"/> class.
/// </summary>
/// <param name="client">The <see cref="ModbusClientBase"/> used to request the remote device, that should be proxied.</param>
/// <param name="listenAddress">An <see cref="IPAddress"/> to listen on.</param>
public ModbusTcpProxy(ModbusClientBase client, IPAddress listenAddress)
{
Client = client ?? throw new ArgumentNullException(nameof(client));
_tcpListener = new TcpListenerWrapper(listenAddress, 502);
}
#endregion Constructors #endregion Constructors
#region Properties #region Properties
@@ -56,7 +49,7 @@ namespace AMWD.Protocols.Modbus.Tcp
/// <summary> /// <summary>
/// Gets the Modbus client used to request the remote device, that should be proxied. /// Gets the Modbus client used to request the remote device, that should be proxied.
/// </summary> /// </summary>
public ModbusClientBase Client { get; } public ModbusClientBase Client { get; } = client ?? throw new ArgumentNullException(nameof(client));
/// <summary> /// <summary>
/// Gets the <see cref="IPAddress"/> to listen on. /// Gets the <see cref="IPAddress"/> to listen on.
@@ -115,7 +108,10 @@ namespace AMWD.Protocols.Modbus.Tcp
_stopCts?.Dispose(); _stopCts?.Dispose();
_stopCts = new CancellationTokenSource(); _stopCts = new CancellationTokenSource();
_tcpListener.Socket.DualMode = ListenAddress.AddressFamily == AddressFamily.InterNetworkV6; // Only allowed to set, if the socket is in the InterNetworkV6 address family.
// See: https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.socket.dualmode?view=netstandard-2.0#exceptions
if (ListenAddress.AddressFamily == AddressFamily.InterNetworkV6)
_tcpListener.Socket.DualMode = true;
_tcpListener.Start(); _tcpListener.Start();
_clientConnectTask = WaitForClientAsync(_stopCts.Token); _clientConnectTask = WaitForClientAsync(_stopCts.Token);
@@ -140,16 +136,7 @@ namespace AMWD.Protocols.Modbus.Tcp
try try
{ {
await Task.WhenAny(_clientConnectTask, Task.Delay(Timeout.Infinite, cancellationToken)); await Task.WhenAny(_clientConnectTask, Task.Delay(Timeout.Infinite, cancellationToken)).ConfigureAwait(continueOnCapturedContext: false);
}
catch (OperationCanceledException)
{
// Terminated
}
try
{
await Task.WhenAny(Task.WhenAll(_clientTasks), Task.Delay(Timeout.Infinite, cancellationToken));
} }
catch (OperationCanceledException) catch (OperationCanceledException)
{ {
@@ -174,6 +161,7 @@ namespace AMWD.Protocols.Modbus.Tcp
_tcpListener.Dispose(); _tcpListener.Dispose();
_stopCts?.Dispose(); _stopCts?.Dispose();
GC.SuppressFinalize(this);
} }
private void Assertions() private void Assertions()
@@ -196,12 +184,13 @@ namespace AMWD.Protocols.Modbus.Tcp
{ {
try try
{ {
var client = await _tcpListener.AcceptTcpClientAsync(cancellationToken); var client = await _tcpListener.AcceptTcpClientAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
await _clientListLock.WaitAsync(cancellationToken); await _clientListLock.WaitAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
try try
{ {
_clients.Add(client); _clients.Add(client);
_clientTasks.Add(HandleClientAsync(client, cancellationToken)); // Can be ignored as it will terminate by itself on cancellation
HandleClientAsync(client, cancellationToken).Forget();
} }
finally finally
{ {
@@ -224,23 +213,32 @@ namespace AMWD.Protocols.Modbus.Tcp
{ {
var requestBytes = new List<byte>(); var requestBytes = new List<byte>();
using (var cts = new CancellationTokenSource(ReadWriteTimeout)) // Waiting for next request
using (cancellationToken.Register(cts.Cancel)) byte[] headerBytes = await stream.ReadExpectedBytesAsync(6, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
{
byte[] headerBytes = await stream.ReadExpectedBytesAsync(6, cts.Token);
requestBytes.AddRange(headerBytes); requestBytes.AddRange(headerBytes);
ushort length = headerBytes ushort length = headerBytes
.Skip(4).Take(2).ToArray() .Skip(4).Take(2).ToArray()
.GetBigEndianUInt16(); .GetBigEndianUInt16();
byte[] bodyBytes = await stream.ReadExpectedBytesAsync(length, cts.Token); // Waiting for the remaining required data
using (var cts = new CancellationTokenSource(ReadWriteTimeout))
using (cancellationToken.Register(cts.Cancel))
{
byte[] bodyBytes = await stream.ReadExpectedBytesAsync(length, cts.Token).ConfigureAwait(continueOnCapturedContext: false);
requestBytes.AddRange(bodyBytes); requestBytes.AddRange(bodyBytes);
} }
byte[] responseBytes = await HandleRequestAsync([.. requestBytes], cancellationToken); byte[] responseBytes = await HandleRequestAsync([.. requestBytes], cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
if (responseBytes != null) if (responseBytes != null)
await stream.WriteAsync(responseBytes, 0, responseBytes.Length, cancellationToken); {
// Write response when available
using (var cts = new CancellationTokenSource(ReadWriteTimeout))
using (cancellationToken.Register(cts.Cancel))
{
await stream.WriteAsync(responseBytes, 0, responseBytes.Length, cts.Token).ConfigureAwait(continueOnCapturedContext: false);
}
}
} }
} }
catch catch
@@ -249,7 +247,7 @@ namespace AMWD.Protocols.Modbus.Tcp
} }
finally finally
{ {
await _clientListLock.WaitAsync(cancellationToken); await _clientListLock.WaitAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
try try
{ {
_clients.Remove(client); _clients.Remove(client);
@@ -324,7 +322,7 @@ namespace AMWD.Protocols.Modbus.Tcp
responseBytes.AddRange(requestBytes.Take(8)); responseBytes.AddRange(requestBytes.Take(8));
try try
{ {
var coils = await Client.ReadCoilsAsync(unitId, firstAddress, count, cancellationToken); var coils = await Client.ReadCoilsAsync(unitId, firstAddress, count, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
byte[] values = new byte[(int)Math.Ceiling(coils.Count / 8.0)]; byte[] values = new byte[(int)Math.Ceiling(coils.Count / 8.0)];
for (int i = 0; i < coils.Count; i++) for (int i = 0; i < coils.Count; i++)
@@ -363,7 +361,7 @@ namespace AMWD.Protocols.Modbus.Tcp
responseBytes.AddRange(requestBytes.Take(8)); responseBytes.AddRange(requestBytes.Take(8));
try try
{ {
var discreteInputs = await Client.ReadDiscreteInputsAsync(unitId, firstAddress, count, cancellationToken); var discreteInputs = await Client.ReadDiscreteInputsAsync(unitId, firstAddress, count, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
byte[] values = new byte[(int)Math.Ceiling(discreteInputs.Count / 8.0)]; byte[] values = new byte[(int)Math.Ceiling(discreteInputs.Count / 8.0)];
for (int i = 0; i < discreteInputs.Count; i++) for (int i = 0; i < discreteInputs.Count; i++)
@@ -402,7 +400,7 @@ namespace AMWD.Protocols.Modbus.Tcp
responseBytes.AddRange(requestBytes.Take(8)); responseBytes.AddRange(requestBytes.Take(8));
try try
{ {
var holdingRegisters = await Client.ReadHoldingRegistersAsync(unitId, firstAddress, count, cancellationToken); var holdingRegisters = await Client.ReadHoldingRegistersAsync(unitId, firstAddress, count, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
byte[] values = new byte[holdingRegisters.Count * 2]; byte[] values = new byte[holdingRegisters.Count * 2];
for (int i = 0; i < holdingRegisters.Count; i++) for (int i = 0; i < holdingRegisters.Count; i++)
@@ -436,7 +434,7 @@ namespace AMWD.Protocols.Modbus.Tcp
responseBytes.AddRange(requestBytes.Take(8)); responseBytes.AddRange(requestBytes.Take(8));
try try
{ {
var inputRegisters = await Client.ReadInputRegistersAsync(unitId, firstAddress, count, cancellationToken); var inputRegisters = await Client.ReadInputRegistersAsync(unitId, firstAddress, count, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
byte[] values = new byte[count * 2]; byte[] values = new byte[count * 2];
for (int i = 0; i < count; i++) for (int i = 0; i < count; i++)
@@ -484,7 +482,7 @@ namespace AMWD.Protocols.Modbus.Tcp
LowByte = requestBytes[11], LowByte = requestBytes[11],
}; };
bool isSuccess = await Client.WriteSingleCoilAsync(requestBytes[6], coil, cancellationToken); bool isSuccess = await Client.WriteSingleCoilAsync(requestBytes[6], coil, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
if (isSuccess) if (isSuccess)
{ {
// Response is an echo of the request // Response is an echo of the request
@@ -524,7 +522,7 @@ namespace AMWD.Protocols.Modbus.Tcp
LowByte = requestBytes[11] LowByte = requestBytes[11]
}; };
bool isSuccess = await Client.WriteSingleHoldingRegisterAsync(requestBytes[6], register, cancellationToken); bool isSuccess = await Client.WriteSingleHoldingRegisterAsync(requestBytes[6], register, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
if (isSuccess) if (isSuccess)
{ {
// Response is an echo of the request // Response is an echo of the request
@@ -584,7 +582,7 @@ namespace AMWD.Protocols.Modbus.Tcp
}); });
} }
bool isSuccess = await Client.WriteMultipleCoilsAsync(requestBytes[6], coils, cancellationToken); bool isSuccess = await Client.WriteMultipleCoilsAsync(requestBytes[6], coils, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
if (isSuccess) if (isSuccess)
{ {
// Response is an echo of the request // Response is an echo of the request
@@ -641,7 +639,7 @@ namespace AMWD.Protocols.Modbus.Tcp
}); });
} }
bool isSuccess = await Client.WriteMultipleHoldingRegistersAsync(requestBytes[6], list, cancellationToken); bool isSuccess = await Client.WriteMultipleHoldingRegistersAsync(requestBytes[6], list, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
if (isSuccess) if (isSuccess)
{ {
// Response is an echo of the request // Response is an echo of the request
@@ -698,7 +696,7 @@ namespace AMWD.Protocols.Modbus.Tcp
try try
{ {
var deviceInfo = await Client.ReadDeviceIdentificationAsync(requestBytes[6], category, firstObject, cancellationToken); var deviceInfo = await Client.ReadDeviceIdentificationAsync(requestBytes[6], category, firstObject, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
var bodyBytes = new List<byte>(); var bodyBytes = new List<byte>();
@@ -761,7 +759,7 @@ namespace AMWD.Protocols.Modbus.Tcp
} }
} }
private byte[] GetDeviceObject(byte objectId, DeviceIdentification deviceIdentification) private static byte[] GetDeviceObject(byte objectId, DeviceIdentification deviceIdentification)
{ {
var result = new List<byte> { objectId }; var result = new List<byte> { objectId };
switch ((ModbusDeviceIdentificationObject)objectId) switch ((ModbusDeviceIdentificationObject)objectId)
@@ -851,5 +849,18 @@ namespace AMWD.Protocols.Modbus.Tcp
} }
#endregion Request Handling #endregion Request Handling
/// <inheritdoc/>
public override string ToString()
{
var sb = new StringBuilder();
sb.AppendLine($"TCP Proxy");
sb.AppendLine($" {nameof(ListenAddress)}: {ListenAddress}");
sb.AppendLine($" {nameof(ListenPort)}: {ListenPort}");
sb.AppendLine($" {nameof(Client)}: {Client.GetType().Name}");
return sb.ToString();
}
} }
} }

View File

@@ -1,15 +1,13 @@
using System.Net; using System.Net;
using System.Net.Sockets;
namespace AMWD.Protocols.Modbus.Tcp.Utils namespace AMWD.Protocols.Modbus.Tcp.Utils
{ {
internal class IPEndPointWrapper /// <inheritdoc cref="IPEndPoint" />
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
internal class IPEndPointWrapper(EndPoint endPoint)
{ {
private IPEndPoint _ipEndPoint; private readonly IPEndPoint _ipEndPoint = (IPEndPoint)endPoint;
public IPEndPointWrapper(EndPoint endPoint)
{
_ipEndPoint = (IPEndPoint)endPoint;
}
#region Properties #region Properties

View File

@@ -8,14 +8,9 @@ namespace AMWD.Protocols.Modbus.Tcp.Utils
{ {
/// <inheritdoc cref="NetworkStream" /> /// <inheritdoc cref="NetworkStream" />
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
internal class NetworkStreamWrapper : IDisposable internal class NetworkStreamWrapper(NetworkStream stream) : IDisposable
{ {
private readonly NetworkStream _stream; private readonly NetworkStream _stream = stream;
public NetworkStreamWrapper(NetworkStream stream)
{
_stream = stream;
}
/// <inheritdoc cref="NetworkStream.Dispose" /> /// <inheritdoc cref="NetworkStream.Dispose" />
public virtual void Dispose() public virtual void Dispose()

View File

@@ -3,14 +3,11 @@ using System.Net.Sockets;
namespace AMWD.Protocols.Modbus.Tcp.Utils namespace AMWD.Protocols.Modbus.Tcp.Utils
{ {
internal class SocketWrapper : IDisposable /// <inheritdoc cref="Socket" />
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
internal class SocketWrapper(Socket socket) : IDisposable
{ {
private Socket _socket; private readonly Socket _socket = socket;
public SocketWrapper(Socket socket)
{
_socket = socket;
}
/// <inheritdoc cref="Socket.DualMode" /> /// <inheritdoc cref="Socket.DualMode" />
public virtual bool DualMode public virtual bool DualMode

View File

@@ -3,6 +3,9 @@ using System.Net.Sockets;
namespace AMWD.Protocols.Modbus.Tcp.Utils namespace AMWD.Protocols.Modbus.Tcp.Utils
{ {
/// <summary>
/// Factory for creating <see cref="TcpClientWrapper"/> instances.
/// </summary>
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
internal class TcpClientWrapperFactory internal class TcpClientWrapperFactory
{ {

View File

@@ -6,22 +6,18 @@ using System.Threading.Tasks;
namespace AMWD.Protocols.Modbus.Tcp.Utils namespace AMWD.Protocols.Modbus.Tcp.Utils
{ {
/// <inheritdoc cref="TcpListener" />
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
internal class TcpListenerWrapper : IDisposable internal class TcpListenerWrapper(IPAddress localaddr, int port) : IDisposable
{ {
#region Fields #region Fields
private TcpListener _tcpListener; private readonly TcpListener _tcpListener = new(localaddr, port);
#endregion Fields #endregion Fields
#region Constructor #region Constructor
public TcpListenerWrapper(IPAddress localaddr, int port)
{
_tcpListener = new TcpListener(localaddr, port);
}
#endregion Constructor #endregion Constructor
#region Properties #region Properties

View File

@@ -105,16 +105,13 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Contracts
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void ShouldThrowExceptionOnNullConnection() public void ShouldThrowExceptionOnNullConnection()
{ {
// Arrange // Arrange
IModbusConnection connection = null; IModbusConnection connection = null;
// Act // Act + Assert
new ModbusClientBaseWrapper(connection); Assert.ThrowsException<ArgumentNullException>(() => new ModbusClientBaseWrapper(connection));
// Assert - ArgumentNullException
} }
[DataTestMethod] [DataTestMethod]
@@ -155,31 +152,25 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Contracts
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ObjectDisposedException))]
public async Task ShouldAssertDisposed() public async Task ShouldAssertDisposed()
{ {
// Arrange // Arrange
var client = GetClient(); var client = GetClient();
client.Dispose(); client.Dispose();
// Act // Act + Assert
await client.ReadCoilsAsync(UNIT_ID, START_ADDRESS, READ_COUNT); await Assert.ThrowsExceptionAsync<ObjectDisposedException>(() => client.ReadCoilsAsync(UNIT_ID, START_ADDRESS, READ_COUNT));
// Assert - ObjectDisposedException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public async Task ShouldAssertProtocolSet() public async Task ShouldAssertProtocolSet()
{ {
// Arrange // Arrange
var client = GetClient(); var client = GetClient();
client.Protocol = null; client.Protocol = null;
// Act // Act + Assert
await client.ReadCoilsAsync(UNIT_ID, START_ADDRESS, READ_COUNT); await Assert.ThrowsExceptionAsync<ArgumentNullException>(() => client.ReadCoilsAsync(UNIT_ID, START_ADDRESS, READ_COUNT));
// Assert - ArgumentNullException
} }
#endregion Common/Connection/Assertions #endregion Common/Connection/Assertions

View File

@@ -41,20 +41,16 @@
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void ShouldThrowNullOnGetSingle() public void ShouldThrowNullOnGetSingle()
{ {
// Arrange // Arrange
HoldingRegister[] registers = null; HoldingRegister[] registers = null;
// Act // Act + Assert
registers.GetSingle(0); Assert.ThrowsException<ArgumentNullException>(() => registers.GetSingle(0));
// Assert - ArgumentNullException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ShouldThrowArgumentOnGetSingleForLength() public void ShouldThrowArgumentOnGetSingleForLength()
{ {
// Arrange // Arrange
@@ -63,16 +59,13 @@
new() { Address = 101, HighByte = 0x01, LowByte = 0x02 } new() { Address = 101, HighByte = 0x01, LowByte = 0x02 }
}; };
// Act // Act + Assert
registers.GetSingle(0); Assert.ThrowsException<ArgumentException>(() => registers.GetSingle(0));
// Assert - ArgumentException
} }
[DataTestMethod] [DataTestMethod]
[DataRow(1)] [DataRow(1)]
[DataRow(-1)] [DataRow(-1)]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowArgumentOutOfRangeOnGetSingle(int startIndex) public void ShouldThrowArgumentOutOfRangeOnGetSingle(int startIndex)
{ {
// Arrange // Arrange
@@ -82,14 +75,11 @@
new() { Address = 100, HighByte = 0x03, LowByte = 0x04 } new() { Address = 100, HighByte = 0x03, LowByte = 0x04 }
}; };
// Act // Act + Assert
registers.GetSingle(startIndex); Assert.ThrowsException<ArgumentOutOfRangeException>(() => registers.GetSingle(startIndex));
// Assert - ArgumentOutOfRangeException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ShouldThrowArgumentOnGetSingleForType() public void ShouldThrowArgumentOnGetSingleForType()
{ {
// Arrange // Arrange
@@ -99,10 +89,8 @@
new InputRegister { Address = 101, HighByte = 0x03, LowByte = 0x04 } new InputRegister { Address = 101, HighByte = 0x03, LowByte = 0x04 }
}; };
// Act // Act + Assert
registers.GetSingle(0); Assert.ThrowsException<ArgumentException>(() => registers.GetSingle(0));
// Assert - ArgumentException
} }
[TestMethod] [TestMethod]
@@ -145,20 +133,16 @@
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void ShouldThrowNullOnGetDouble() public void ShouldThrowNullOnGetDouble()
{ {
// Arrange // Arrange
HoldingRegister[] registers = null; HoldingRegister[] registers = null;
// Act // Act + Assert
registers.GetDouble(0); Assert.ThrowsException<ArgumentNullException>(() => registers.GetDouble(0));
// Assert - ArgumentNullException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ShouldThrowArgumentOnGetDoubleForLength() public void ShouldThrowArgumentOnGetDoubleForLength()
{ {
// Arrange // Arrange
@@ -169,16 +153,13 @@
new() { Address = 102, HighByte = 0x7A, LowByte = 0xE1 } new() { Address = 102, HighByte = 0x7A, LowByte = 0xE1 }
}; };
// Act // Act + Assert
registers.GetDouble(0); Assert.ThrowsException<ArgumentException>(() => registers.GetDouble(0));
// Assert - ArgumentException
} }
[DataTestMethod] [DataTestMethod]
[DataRow(1)] [DataRow(1)]
[DataRow(-1)] [DataRow(-1)]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowArgumentOutOfRangeOnGetDouble(int startIndex) public void ShouldThrowArgumentOutOfRangeOnGetDouble(int startIndex)
{ {
// Arrange // Arrange
@@ -190,14 +171,11 @@
new() { Address = 103, HighByte = 0x47, LowByte = 0xAE } new() { Address = 103, HighByte = 0x47, LowByte = 0xAE }
}; };
// Act // Act + Assert
registers.GetDouble(startIndex); Assert.ThrowsException<ArgumentOutOfRangeException>(() => registers.GetDouble(startIndex));
// Assert - ArgumentOutOfRangeException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ShouldThrowArgumentOnGetDoubleForType() public void ShouldThrowArgumentOnGetDoubleForType()
{ {
// Arrange // Arrange
@@ -209,10 +187,8 @@
new InputRegister { Address = 103, HighByte = 0x47, LowByte = 0xAE } new InputRegister { Address = 103, HighByte = 0x47, LowByte = 0xAE }
}; };
// Act // Act + Assert
registers.GetDouble(0); Assert.ThrowsException<ArgumentException>(() => registers.GetDouble(0));
// Assert - ArgumentException
} }
#endregion Modbus to value #endregion Modbus to value

View File

@@ -30,16 +30,13 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Extensions
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void ShouldThrowNullOnGetBoolean() public void ShouldThrowNullOnGetBoolean()
{ {
// Arrange // Arrange
Coil coil = null; Coil coil = null;
// Act // Act + Assert
coil.GetBoolean(); Assert.ThrowsException<ArgumentNullException>(() => coil.GetBoolean());
// Assert - ArgumentNullException
} }
[TestMethod] [TestMethod]
@@ -95,35 +92,28 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Extensions
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void ShouldThrowNullOnString() public void ShouldThrowNullOnString()
{ {
// Arrange // Arrange
HoldingRegister[] list = null; HoldingRegister[] list = null;
// Act // Act + Assert
list.GetString(2); Assert.ThrowsException<ArgumentNullException>(() => list.GetString(2));
// Assert - ArgumentNullException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ShouldThrowArgumentOnStringForEmptyList() public void ShouldThrowArgumentOnStringForEmptyList()
{ {
// Arrange // Arrange
var registers = Array.Empty<HoldingRegister>(); var registers = Array.Empty<HoldingRegister>();
// Act // Act + Assert
registers.GetString(2); Assert.ThrowsException<ArgumentException>(() => registers.GetString(2));
// Assert - ArgumentException
} }
[DataTestMethod] [DataTestMethod]
[DataRow(1)] [DataRow(1)]
[DataRow(-1)] [DataRow(-1)]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowArgumentOutOfRangeOnString(int startIndex) public void ShouldThrowArgumentOutOfRangeOnString(int startIndex)
{ {
// Arrange // Arrange
@@ -133,14 +123,11 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Extensions
new() { Address = 2, HighByte = 67, LowByte = 0 } new() { Address = 2, HighByte = 67, LowByte = 0 }
}; };
// Act // Act + Assert
registers.GetString(2, startIndex); Assert.ThrowsException<ArgumentOutOfRangeException>(() => registers.GetString(2, startIndex));
// Assert - ArgumentOutOfRangeException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ShouldThrowArgumentOnStringForMixedTypes() public void ShouldThrowArgumentOnStringForMixedTypes()
{ {
// Arrange // Arrange
@@ -150,10 +137,8 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Extensions
new InputRegister { Address = 2, HighByte = 67, LowByte = 0 } new InputRegister { Address = 2, HighByte = 67, LowByte = 0 }
}; };
// Act // Act + Assert
registers.GetString(2); Assert.ThrowsException<ArgumentException>(() => registers.GetString(2));
// Assert - ArgumentException
} }
#endregion Modbus to value #endregion Modbus to value
@@ -272,16 +257,13 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Extensions
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void ShouldThrowNullOnGetString() public void ShouldThrowNullOnGetString()
{ {
// Arrange // Arrange
string str = null; string str = null;
// Act // Act + Assert
_ = str.ToRegisters(100).ToArray(); Assert.ThrowsException<ArgumentNullException>(() => str.ToRegisters(100).ToArray());
// Assert - ArgumentNullException
} }
#endregion Value to Modbus #endregion Value to Modbus

View File

@@ -32,31 +32,23 @@
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void ShouldThrowNullForGetSByte() public void ShouldThrowNullForGetSByte()
{ {
// Arrange // Arrange
HoldingRegister register = null; HoldingRegister register = null;
// Act // Act + Assert
register.GetSByte(); Assert.ThrowsException<ArgumentNullException>(() => register.GetSByte());
// Assert - ArgumentNullException
Assert.Fail();
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ShouldThrowArgumentForGetSByte() public void ShouldThrowArgumentForGetSByte()
{ {
// Arrange // Arrange
var obj = new Coil(); var obj = new Coil();
// Act // Act + Assert
obj.GetSByte(); Assert.ThrowsException<ArgumentException>(() => obj.GetSByte());
// Assert - ArgumentException
Assert.Fail();
} }
[TestMethod] [TestMethod]
@@ -86,31 +78,23 @@
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void ShouldThrowNullForGetInt16() public void ShouldThrowNullForGetInt16()
{ {
// Arrange // Arrange
HoldingRegister register = null; HoldingRegister register = null;
// Act // Act + Assert
register.GetInt16(); Assert.ThrowsException<ArgumentNullException>(() => register.GetInt16());
// Assert - ArgumentNullException
Assert.Fail();
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ShouldThrowArgumentForGetInt16() public void ShouldThrowArgumentForGetInt16()
{ {
// Arrange // Arrange
var obj = new Coil(); var obj = new Coil();
// Act // Act + Assert
obj.GetInt16(); Assert.ThrowsException<ArgumentException>(() => obj.GetInt16());
// Assert - ArgumentException
Assert.Fail();
} }
[TestMethod] [TestMethod]
@@ -149,21 +133,16 @@
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void ShouldThrowNullOnGetInt32() public void ShouldThrowNullOnGetInt32()
{ {
// Arrange // Arrange
HoldingRegister[] registers = null; HoldingRegister[] registers = null;
// Act // Act + Assert
registers.GetInt32(0); Assert.ThrowsException<ArgumentNullException>(() => registers.GetInt32(0));
// Assert - ArgumentNullException
Assert.Fail();
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ShouldThrowArgumentOnGetInt32ForLength() public void ShouldThrowArgumentOnGetInt32ForLength()
{ {
// Arrange // Arrange
@@ -172,17 +151,13 @@
new HoldingRegister { Address = 101, HighByte = 0x01, LowByte = 0x02 } new HoldingRegister { Address = 101, HighByte = 0x01, LowByte = 0x02 }
}; };
// Act // Act + Assert
registers.GetInt32(0); Assert.ThrowsException<ArgumentException>(() => registers.GetInt32(0));
// Assert - ArgumentException
Assert.Fail();
} }
[DataTestMethod] [DataTestMethod]
[DataRow(1)] [DataRow(1)]
[DataRow(-1)] [DataRow(-1)]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowArgumentOutOfRangeOnGetInt32(int startIndex) public void ShouldThrowArgumentOutOfRangeOnGetInt32(int startIndex)
{ {
// Arrange // Arrange
@@ -192,15 +167,11 @@
new HoldingRegister { Address = 100, HighByte = 0x03, LowByte = 0x04 } new HoldingRegister { Address = 100, HighByte = 0x03, LowByte = 0x04 }
}; };
// Act // Act + Assert
registers.GetInt32(startIndex); Assert.ThrowsException<ArgumentOutOfRangeException>(() => registers.GetInt32(startIndex));
// Assert - ArgumentOutOfRangeException
Assert.Fail();
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ShouldThrowArgumentOnGetInt32ForType() public void ShouldThrowArgumentOnGetInt32ForType()
{ {
// Arrange // Arrange
@@ -210,11 +181,8 @@
new InputRegister { Address = 101, HighByte = 0x03, LowByte = 0x04 } new InputRegister { Address = 101, HighByte = 0x03, LowByte = 0x04 }
}; };
// Act // Act + Assert
registers.GetInt32(0); Assert.ThrowsException<ArgumentException>(() => registers.GetInt32(0));
// Assert - ArgumentException
Assert.Fail();
} }
[TestMethod] [TestMethod]
@@ -257,21 +225,16 @@
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void ShouldThrowNullOnGetInt64() public void ShouldThrowNullOnGetInt64()
{ {
// Arrange // Arrange
HoldingRegister[] registers = null; HoldingRegister[] registers = null;
// Act // Act + Assert
registers.GetInt64(0); Assert.ThrowsException<ArgumentNullException>(() => registers.GetInt64(0));
// Assert - ArgumentNullException
Assert.Fail();
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ShouldThrowArgumentOnGetInt64ForLength() public void ShouldThrowArgumentOnGetInt64ForLength()
{ {
// Arrange // Arrange
@@ -282,17 +245,13 @@
new HoldingRegister { Address = 103, HighByte = 0x03, LowByte = 0x04 } new HoldingRegister { Address = 103, HighByte = 0x03, LowByte = 0x04 }
}; };
// Act // Act + Assert
registers.GetInt64(0); Assert.ThrowsException<ArgumentException>(() => registers.GetInt64(0));
// Assert - ArgumentException
Assert.Fail();
} }
[DataTestMethod] [DataTestMethod]
[DataRow(1)] [DataRow(1)]
[DataRow(-1)] [DataRow(-1)]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowArgumentOutOfRangeOnGetInt64(int startIndex) public void ShouldThrowArgumentOutOfRangeOnGetInt64(int startIndex)
{ {
// Arrange // Arrange
@@ -304,15 +263,11 @@
new HoldingRegister { Address = 103, HighByte = 0x03, LowByte = 0x04 } new HoldingRegister { Address = 103, HighByte = 0x03, LowByte = 0x04 }
}; };
// Act // Act + Assert
registers.GetInt64(startIndex); Assert.ThrowsException<ArgumentOutOfRangeException>(() => registers.GetInt64(startIndex));
// Assert - ArgumentOutOfRangeException
Assert.Fail();
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ShouldThrowArgumentOnGetInt64ForType() public void ShouldThrowArgumentOnGetInt64ForType()
{ {
// Arrange // Arrange
@@ -324,11 +279,8 @@
new InputRegister { Address = 103, HighByte = 0x03, LowByte = 0x04 } new InputRegister { Address = 103, HighByte = 0x03, LowByte = 0x04 }
}; };
// Act // Act + Assert
registers.GetInt64(0); Assert.ThrowsException<ArgumentException>(() => registers.GetInt64(0));
// Assert - ArgumentException
Assert.Fail();
} }
#endregion Modbus to value #endregion Modbus to value

View File

@@ -32,29 +32,23 @@
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void ShouldThrowNullForGetByte() public void ShouldThrowNullForGetByte()
{ {
// Arrange // Arrange
HoldingRegister register = null; HoldingRegister register = null;
// Act // Act + Assert
register.GetByte(); Assert.ThrowsException<ArgumentNullException>(() => register.GetByte());
// Assert - ArgumentNullException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ShouldThrowArgumentForGetByte() public void ShouldThrowArgumentForGetByte()
{ {
// Arrange // Arrange
var obj = new Coil(); var obj = new Coil();
// Act // Act + Assert
obj.GetByte(); Assert.ThrowsException<ArgumentException>(() => obj.GetByte());
// Assert - ArgumentException
} }
[TestMethod] [TestMethod]
@@ -84,29 +78,23 @@
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void ShouldThrowNullForGetUInt16() public void ShouldThrowNullForGetUInt16()
{ {
// Arrange // Arrange
HoldingRegister register = null; HoldingRegister register = null;
// Act // Act + Assert
register.GetUInt16(); Assert.ThrowsException<ArgumentNullException>(() => register.GetUInt16());
// Assert - ArgumentNullException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ShouldThrowArgumentForGetUInt16() public void ShouldThrowArgumentForGetUInt16()
{ {
// Arrange // Arrange
var obj = new Coil(); var obj = new Coil();
// Act // Act + Assert
obj.GetUInt16(); Assert.ThrowsException<ArgumentException>(() => obj.GetUInt16());
// Assert - ArgumentException
} }
[TestMethod] [TestMethod]
@@ -145,21 +133,16 @@
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void ShouldThrowNullOnGetUInt32() public void ShouldThrowNullOnGetUInt32()
{ {
// Arrange // Arrange
HoldingRegister[] registers = null; HoldingRegister[] registers = null;
// Act // Act + Assert
registers.GetUInt32(0); Assert.ThrowsException<ArgumentNullException>(() => registers.GetUInt32(0));
// Assert - ArgumentNullException
Assert.Fail();
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ShouldThrowArgumentOnGetUInt32ForLength() public void ShouldThrowArgumentOnGetUInt32ForLength()
{ {
// Arrange // Arrange
@@ -168,16 +151,13 @@
new() { Address = 101, HighByte = 0x01, LowByte = 0x02 } new() { Address = 101, HighByte = 0x01, LowByte = 0x02 }
}; };
// Act // Act + Assert
registers.GetUInt32(0); Assert.ThrowsException<ArgumentException>(() => registers.GetUInt32(1));
// Assert - ArgumentException
} }
[DataTestMethod] [DataTestMethod]
[DataRow(1)] [DataRow(1)]
[DataRow(-1)] [DataRow(-1)]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowArgumentOutOfRangeOnGetUInt32(int startIndex) public void ShouldThrowArgumentOutOfRangeOnGetUInt32(int startIndex)
{ {
// Arrange // Arrange
@@ -187,14 +167,11 @@
new() { Address = 100, HighByte = 0x03, LowByte = 0x04 } new() { Address = 100, HighByte = 0x03, LowByte = 0x04 }
}; };
// Act // Act + Assert
registers.GetUInt32(startIndex); Assert.ThrowsException<ArgumentOutOfRangeException>(() => registers.GetUInt32(startIndex));
// Assert - ArgumentOutOfRangeException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ShouldThrowArgumentOnGetUInt32ForType() public void ShouldThrowArgumentOnGetUInt32ForType()
{ {
// Arrange // Arrange
@@ -204,10 +181,8 @@
new InputRegister { Address = 101, HighByte = 0x03, LowByte = 0x04 } new InputRegister { Address = 101, HighByte = 0x03, LowByte = 0x04 }
}; };
// Act // Act + Assert
registers.GetUInt32(0); Assert.ThrowsException<ArgumentException>(() => registers.GetUInt32(0));
// Assert - ArgumentException
} }
[TestMethod] [TestMethod]
@@ -250,21 +225,16 @@
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void ShouldThrowNullOnGetUInt64() public void ShouldThrowNullOnGetUInt64()
{ {
// Arrange // Arrange
HoldingRegister[] registers = null; HoldingRegister[] registers = null;
// Act // Act + Assert
registers.GetUInt64(0); Assert.ThrowsException<ArgumentNullException>(() => registers.GetUInt64(0));
// Assert - ArgumentNullException
Assert.Fail();
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ShouldThrowArgumentOnGetUInt64ForLength() public void ShouldThrowArgumentOnGetUInt64ForLength()
{ {
// Arrange // Arrange
@@ -275,16 +245,13 @@
new() { Address = 103, HighByte = 0x03, LowByte = 0x04 } new() { Address = 103, HighByte = 0x03, LowByte = 0x04 }
}; };
// Act // Act + Assert
registers.GetUInt64(0); Assert.ThrowsException<ArgumentException>(() => registers.GetUInt64(0));
// Assert - ArgumentException
} }
[DataTestMethod] [DataTestMethod]
[DataRow(1)] [DataRow(1)]
[DataRow(-1)] [DataRow(-1)]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowArgumentOutOfRangeOnGetUInt64(int startIndex) public void ShouldThrowArgumentOutOfRangeOnGetUInt64(int startIndex)
{ {
// Arrange // Arrange
@@ -296,14 +263,11 @@
new() { Address = 103, HighByte = 0x03, LowByte = 0x04 } new() { Address = 103, HighByte = 0x03, LowByte = 0x04 }
}; };
// Act // Act + Assert
registers.GetUInt64(startIndex); Assert.ThrowsException<ArgumentOutOfRangeException>(() => registers.GetUInt64(startIndex));
// Assert - ArgumentOutOfRangeException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ShouldThrowArgumentOnGetUInt64ForType() public void ShouldThrowArgumentOnGetUInt64ForType()
{ {
// Arrange // Arrange
@@ -315,10 +279,8 @@
new InputRegister { Address = 103, HighByte = 0x03, LowByte = 0x04 } new InputRegister { Address = 103, HighByte = 0x03, LowByte = 0x04 }
}; };
// Act // Act + Assert
registers.GetUInt64(0); Assert.ThrowsException<ArgumentException>(() => registers.GetUInt64(0));
// Assert - ArgumentException
} }
#endregion Modbus to value #endregion Modbus to value

View File

@@ -32,29 +32,23 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
[DataTestMethod] [DataTestMethod]
[DataRow(0)] [DataRow(0)]
[DataRow(2001)] [DataRow(2001)]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowOutOfRangeForCountOnSerializeReadCoils(int count) public void ShouldThrowOutOfRangeForCountOnSerializeReadCoils(int count)
{ {
// Arrange // Arrange
var protocol = new AsciiProtocol(); var protocol = new AsciiProtocol();
// Act // Act + Assert
protocol.SerializeReadCoils(UNIT_ID, 19, (ushort)count); Assert.ThrowsException<ArgumentOutOfRangeException>(() => protocol.SerializeReadCoils(UNIT_ID, 19, (ushort)count));
// Assert - ArgumentOutOfRangeException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowOutOfRangeForStartingAddressOnSerializeReadCoils() public void ShouldThrowOutOfRangeForStartingAddressOnSerializeReadCoils()
{ {
// Arrange // Arrange
var protocol = new AsciiProtocol(); var protocol = new AsciiProtocol();
// Act // Act + Assert
protocol.SerializeReadCoils(UNIT_ID, ushort.MaxValue, 2); Assert.ThrowsException<ArgumentOutOfRangeException>(() => protocol.SerializeReadCoils(UNIT_ID, ushort.MaxValue, 2));
// Assert - ArgumentOutOfRangeException
} }
[TestMethod] [TestMethod]
@@ -88,7 +82,6 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowExceptionOnDeserializeReadCoils() public void ShouldThrowExceptionOnDeserializeReadCoils()
{ {
// Arrange // Arrange
@@ -98,10 +91,8 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
var protocol = new AsciiProtocol(); var protocol = new AsciiProtocol();
// Act // Act + Assert
_ = protocol.DeserializeReadCoils(responseBytes); Assert.ThrowsException<ModbusException>(() => protocol.DeserializeReadCoils(responseBytes));
// Assert - ModbusException
} }
#endregion Read Coils #endregion Read Coils
@@ -129,29 +120,23 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
[DataTestMethod] [DataTestMethod]
[DataRow(0)] [DataRow(0)]
[DataRow(2001)] [DataRow(2001)]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowOutOfRangeForCountOnSerializeReadDiscreteInputs(int count) public void ShouldThrowOutOfRangeForCountOnSerializeReadDiscreteInputs(int count)
{ {
// Arrange // Arrange
var protocol = new AsciiProtocol(); var protocol = new AsciiProtocol();
// Act // Act + Assert
protocol.SerializeReadDiscreteInputs(UNIT_ID, 19, (ushort)count); Assert.ThrowsException<ArgumentOutOfRangeException>(() => protocol.SerializeReadDiscreteInputs(UNIT_ID, 19, (ushort)count));
// Assert - ArgumentOutOfRangeException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowOutOfRangeForStartingAddressOnSerializeReadDiscreteInputs() public void ShouldThrowOutOfRangeForStartingAddressOnSerializeReadDiscreteInputs()
{ {
// Arrange // Arrange
var protocol = new AsciiProtocol(); var protocol = new AsciiProtocol();
// Act // Act + Assert
protocol.SerializeReadDiscreteInputs(UNIT_ID, ushort.MaxValue, 2); Assert.ThrowsException<ArgumentOutOfRangeException>(() => protocol.SerializeReadDiscreteInputs(UNIT_ID, ushort.MaxValue, 2));
// Assert - ArgumentOutOfRangeException
} }
[TestMethod] [TestMethod]
@@ -185,7 +170,6 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowExceptionOnDeserializeReadDiscreteInputs() public void ShouldThrowExceptionOnDeserializeReadDiscreteInputs()
{ {
// Arrange // Arrange
@@ -195,10 +179,8 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
var protocol = new AsciiProtocol(); var protocol = new AsciiProtocol();
// Act // Act + Assert
protocol.DeserializeReadDiscreteInputs(responseBytes); Assert.ThrowsException<ModbusException>(() => protocol.DeserializeReadDiscreteInputs(responseBytes));
// Assert - ModbusException
} }
#endregion Read Discrete Inputs #endregion Read Discrete Inputs
@@ -226,29 +208,23 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
[DataTestMethod] [DataTestMethod]
[DataRow(0)] [DataRow(0)]
[DataRow(2001)] [DataRow(2001)]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowOutOfRangeForCountOnSerializeReadHoldingRegisters(int count) public void ShouldThrowOutOfRangeForCountOnSerializeReadHoldingRegisters(int count)
{ {
// Arrange // Arrange
var protocol = new AsciiProtocol(); var protocol = new AsciiProtocol();
// Act // Act + Assert
protocol.SerializeReadHoldingRegisters(UNIT_ID, 19, (ushort)count); Assert.ThrowsException<ArgumentOutOfRangeException>(() => protocol.SerializeReadHoldingRegisters(UNIT_ID, 19, (ushort)count));
// Assert - ArgumentOutOfRangeException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowOutOfRangeForStartingAddressOnSerializeReadHoldingRegisters() public void ShouldThrowOutOfRangeForStartingAddressOnSerializeReadHoldingRegisters()
{ {
// Arrange // Arrange
var protocol = new AsciiProtocol(); var protocol = new AsciiProtocol();
// Act // Act + Assert
protocol.SerializeReadHoldingRegisters(UNIT_ID, ushort.MaxValue, 2); Assert.ThrowsException<ArgumentOutOfRangeException>(() => protocol.SerializeReadHoldingRegisters(UNIT_ID, ushort.MaxValue, 2));
// Assert - ArgumentOutOfRangeException
} }
[TestMethod] [TestMethod]
@@ -276,7 +252,6 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowExceptionOnDeserializeReadHoldingRegisters() public void ShouldThrowExceptionOnDeserializeReadHoldingRegisters()
{ {
// Arrange // Arrange
@@ -286,10 +261,8 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
var protocol = new AsciiProtocol(); var protocol = new AsciiProtocol();
// Act // Act + Assert
protocol.DeserializeReadHoldingRegisters(responseBytes); Assert.ThrowsException<ModbusException>(() => protocol.DeserializeReadHoldingRegisters(responseBytes));
// Assert - ModbusException
} }
#endregion Read Holding Registers #endregion Read Holding Registers
@@ -317,29 +290,23 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
[DataTestMethod] [DataTestMethod]
[DataRow(0)] [DataRow(0)]
[DataRow(2001)] [DataRow(2001)]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowOutOfRangeForCountOnSerializeReadInputRegisters(int count) public void ShouldThrowOutOfRangeForCountOnSerializeReadInputRegisters(int count)
{ {
// Arrange // Arrange
var protocol = new AsciiProtocol(); var protocol = new AsciiProtocol();
// Act // Act + Assert
protocol.SerializeReadInputRegisters(UNIT_ID, 19, (ushort)count); Assert.ThrowsException<ArgumentOutOfRangeException>(() => protocol.SerializeReadInputRegisters(UNIT_ID, 19, (ushort)count));
// Assert - ArgumentOutOfRangeException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowOutOfRangeForStartingAddressOnSerializeReadInputRegisters() public void ShouldThrowOutOfRangeForStartingAddressOnSerializeReadInputRegisters()
{ {
// Arrange // Arrange
var protocol = new AsciiProtocol(); var protocol = new AsciiProtocol();
// Act // Act + Assert
protocol.SerializeReadInputRegisters(UNIT_ID, ushort.MaxValue, 2); Assert.ThrowsException<ArgumentOutOfRangeException>(() => protocol.SerializeReadInputRegisters(UNIT_ID, ushort.MaxValue, 2));
// Assert - ArgumentOutOfRangeException
} }
[TestMethod] [TestMethod]
@@ -367,7 +334,6 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowExceptionOnDeserializeReadInputRegisters() public void ShouldThrowExceptionOnDeserializeReadInputRegisters()
{ {
// Arrange // Arrange
@@ -377,10 +343,8 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
var protocol = new AsciiProtocol(); var protocol = new AsciiProtocol();
// Act // Act + Assert
protocol.DeserializeReadInputRegisters(responseBytes); Assert.ThrowsException<ModbusException>(() => protocol.DeserializeReadInputRegisters(responseBytes));
// Assert - ModbusException
} }
#endregion Read Input Registers #endregion Read Input Registers
@@ -410,16 +374,13 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowOutOfRangeExceptionForCategoryOnSerializeReadDeviceIdentification() public void ShouldThrowOutOfRangeExceptionForCategoryOnSerializeReadDeviceIdentification()
{ {
// Arrange // Arrange
var protocol = new AsciiProtocol(); var protocol = new AsciiProtocol();
// Act // Act + Assert
protocol.SerializeReadDeviceIdentification(UNIT_ID, (ModbusDeviceIdentificationCategory)10, ModbusDeviceIdentificationObject.ProductCode); Assert.ThrowsException<ArgumentOutOfRangeException>(() => protocol.SerializeReadDeviceIdentification(UNIT_ID, (ModbusDeviceIdentificationCategory)10, ModbusDeviceIdentificationObject.ProductCode));
// Assert - ArgumentOutOfRangeException
} }
[DataTestMethod] [DataTestMethod]
@@ -449,7 +410,6 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowExceptionOnDeserializeReadDeviceIdentificationForMeiType() public void ShouldThrowExceptionOnDeserializeReadDeviceIdentificationForMeiType()
{ {
// Arrange // Arrange
@@ -459,12 +419,11 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
var protocol = new AsciiProtocol(); var protocol = new AsciiProtocol();
// Act // Act + Assert
protocol.DeserializeReadDeviceIdentification(responseBytes); Assert.ThrowsException<ModbusException>(() => protocol.DeserializeReadDeviceIdentification(responseBytes));
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowExceptionOnDeserializeReadDeviceIdentificationForCategory() public void ShouldThrowExceptionOnDeserializeReadDeviceIdentificationForCategory()
{ {
// Arrange // Arrange
@@ -474,8 +433,8 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
var protocol = new AsciiProtocol(); var protocol = new AsciiProtocol();
// Act // Act + Assert
protocol.DeserializeReadDeviceIdentification(responseBytes); Assert.ThrowsException<ModbusException>(() => protocol.DeserializeReadDeviceIdentification(responseBytes));
} }
#endregion Read Device Identification #endregion Read Device Identification
@@ -502,16 +461,13 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void ShouldThrowArgumentNullOnSerializeWriteSingleCoil() public void ShouldThrowArgumentNullOnSerializeWriteSingleCoil()
{ {
// Arrange // Arrange
var protocol = new AsciiProtocol(); var protocol = new AsciiProtocol();
// Act // Act + Assert
protocol.SerializeWriteSingleCoil(UNIT_ID, null); Assert.ThrowsException<ArgumentNullException>(() => protocol.SerializeWriteSingleCoil(UNIT_ID, null));
// Assert - ArgumentNullException
} }
[TestMethod] [TestMethod]
@@ -557,16 +513,13 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void ShouldThrowArgumentNullOnSerializeWriteSingleHoldingRegister() public void ShouldThrowArgumentNullOnSerializeWriteSingleHoldingRegister()
{ {
// Arrange // Arrange
var protocol = new AsciiProtocol(); var protocol = new AsciiProtocol();
// Act // Act + Assert
protocol.SerializeWriteSingleHoldingRegister(UNIT_ID, null); Assert.ThrowsException<ArgumentNullException>(() => protocol.SerializeWriteSingleHoldingRegister(UNIT_ID, null));
// Assert - ArgumentNullException
} }
[TestMethod] [TestMethod]
@@ -619,22 +572,18 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void ShouldThrowArgumentNullOnSerializeWriteMultipleCoils() public void ShouldThrowArgumentNullOnSerializeWriteMultipleCoils()
{ {
// Arrange // Arrange
var protocol = new AsciiProtocol(); var protocol = new AsciiProtocol();
// Act // Act + Assert
protocol.SerializeWriteMultipleCoils(UNIT_ID, null); Assert.ThrowsException<ArgumentNullException>(() => protocol.SerializeWriteMultipleCoils(UNIT_ID, null));
// Assert - ArgumentNullException
} }
[DataTestMethod] [DataTestMethod]
[DataRow(0)] [DataRow(0)]
[DataRow(1969)] [DataRow(1969)]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowOutOfRangeForCountOnSerializeWriteMultipleCoils(int count) public void ShouldThrowOutOfRangeForCountOnSerializeWriteMultipleCoils(int count)
{ {
// Arrange // Arrange
@@ -644,14 +593,11 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
var protocol = new AsciiProtocol(); var protocol = new AsciiProtocol();
// Act // Act + Assert
protocol.SerializeWriteMultipleCoils(UNIT_ID, coils); Assert.ThrowsException<ArgumentOutOfRangeException>(() => protocol.SerializeWriteMultipleCoils(UNIT_ID, coils));
// Assert - ArgumentOutOfRangeException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ShouldThrowArgumentExceptionForDuplicateEntryOnSerializeMultipleCoils() public void ShouldThrowArgumentExceptionForDuplicateEntryOnSerializeMultipleCoils()
{ {
// Arrange // Arrange
@@ -662,14 +608,11 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
}; };
var protocol = new AsciiProtocol(); var protocol = new AsciiProtocol();
// Act // Act + Assert
protocol.SerializeWriteMultipleCoils(UNIT_ID, coils); Assert.ThrowsException<ArgumentException>(() => protocol.SerializeWriteMultipleCoils(UNIT_ID, coils));
// Assert - ArgumentException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ShouldThrowArgumentExceptionForGapInAddressOnSerializeMultipleCoils() public void ShouldThrowArgumentExceptionForGapInAddressOnSerializeMultipleCoils()
{ {
// Arrange // Arrange
@@ -680,10 +623,8 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
}; };
var protocol = new AsciiProtocol(); var protocol = new AsciiProtocol();
// Act // Act + Assert
protocol.SerializeWriteMultipleCoils(UNIT_ID, coils); Assert.ThrowsException<ArgumentException>(() => protocol.SerializeWriteMultipleCoils(UNIT_ID, coils));
// Assert - ArgumentException
} }
[TestMethod] [TestMethod]
@@ -732,22 +673,18 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void ShouldThrowArgumentNullOnSerializeWriteMultipleHoldingRegisters() public void ShouldThrowArgumentNullOnSerializeWriteMultipleHoldingRegisters()
{ {
// Arrange // Arrange
var protocol = new AsciiProtocol(); var protocol = new AsciiProtocol();
// Act // Act + Assert
protocol.SerializeWriteMultipleHoldingRegisters(UNIT_ID, null); Assert.ThrowsException<ArgumentNullException>(() => protocol.SerializeWriteMultipleHoldingRegisters(UNIT_ID, null));
// Assert - ArgumentNullException
} }
[DataTestMethod] [DataTestMethod]
[DataRow(0)] [DataRow(0)]
[DataRow(124)] [DataRow(124)]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowOutOfRangeForCountOnSerializeWriteMultipleHoldingRegisters(int count) public void ShouldThrowOutOfRangeForCountOnSerializeWriteMultipleHoldingRegisters(int count)
{ {
// Arrange // Arrange
@@ -757,14 +694,11 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
var protocol = new AsciiProtocol(); var protocol = new AsciiProtocol();
// Act // Act + Assert
protocol.SerializeWriteMultipleHoldingRegisters(UNIT_ID, registers); Assert.ThrowsException<ArgumentOutOfRangeException>(() => protocol.SerializeWriteMultipleHoldingRegisters(UNIT_ID, registers));
// Assert - ArgumentOutOfRangeException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ShouldThrowArgumentExceptionForDuplicateEntryOnSerializeMultipleHoldingRegisters() public void ShouldThrowArgumentExceptionForDuplicateEntryOnSerializeMultipleHoldingRegisters()
{ {
// Arrange // Arrange
@@ -775,14 +709,11 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
}; };
var protocol = new AsciiProtocol(); var protocol = new AsciiProtocol();
// Act // Act + Assert
protocol.SerializeWriteMultipleHoldingRegisters(UNIT_ID, registers); Assert.ThrowsException<ArgumentException>(() => protocol.SerializeWriteMultipleHoldingRegisters(UNIT_ID, registers));
// Assert - ArgumentException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ShouldThrowArgumentExceptionForGapInAddressOnSerializeMultipleHoldingRegisters() public void ShouldThrowArgumentExceptionForGapInAddressOnSerializeMultipleHoldingRegisters()
{ {
// Arrange // Arrange
@@ -793,10 +724,8 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
}; };
var protocol = new AsciiProtocol(); var protocol = new AsciiProtocol();
// Act // Act + Assert
protocol.SerializeWriteMultipleHoldingRegisters(UNIT_ID, registers); Assert.ThrowsException<ArgumentException>(() => protocol.SerializeWriteMultipleHoldingRegisters(UNIT_ID, registers));
// Assert - ArgumentException
} }
[TestMethod] [TestMethod]
@@ -898,7 +827,6 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowForMissingHeaderOnValidateResponse() public void ShouldThrowForMissingHeaderOnValidateResponse()
{ {
// Arrange // Arrange
@@ -907,12 +835,11 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
AddTrailer(ref response); AddTrailer(ref response);
var protocol = new AsciiProtocol(); var protocol = new AsciiProtocol();
// Act // Act + Assert
protocol.ValidateResponse(Encoding.ASCII.GetBytes(request), Encoding.ASCII.GetBytes(response)); Assert.ThrowsException<ModbusException>(() => protocol.ValidateResponse(Encoding.ASCII.GetBytes(request), Encoding.ASCII.GetBytes(response)));
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowForMissingTrailerOnValidateResponse() public void ShouldThrowForMissingTrailerOnValidateResponse()
{ {
// Arrange // Arrange
@@ -920,12 +847,11 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
string response = $":{UNIT_ID:X2}010100"; string response = $":{UNIT_ID:X2}010100";
var protocol = new AsciiProtocol(); var protocol = new AsciiProtocol();
// Act // Act + Assert
protocol.ValidateResponse(Encoding.ASCII.GetBytes(request), Encoding.ASCII.GetBytes(response)); Assert.ThrowsException<ModbusException>(() => protocol.ValidateResponse(Encoding.ASCII.GetBytes(request), Encoding.ASCII.GetBytes(response)));
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowForUnitIdOnValidateResponse() public void ShouldThrowForUnitIdOnValidateResponse()
{ {
// Arrange // Arrange
@@ -934,12 +860,11 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
AddTrailer(ref response); AddTrailer(ref response);
var protocol = new AsciiProtocol(); var protocol = new AsciiProtocol();
// Act // Act + Assert
protocol.ValidateResponse(Encoding.ASCII.GetBytes(request), Encoding.ASCII.GetBytes(response)); Assert.ThrowsException<ModbusException>(() => protocol.ValidateResponse(Encoding.ASCII.GetBytes(request), Encoding.ASCII.GetBytes(response)));
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowForLrcOnValidateResponse() public void ShouldThrowForLrcOnValidateResponse()
{ {
// Arrange // Arrange
@@ -947,12 +872,11 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
string response = $":{UNIT_ID:X2}010001FF00XX\r\n"; string response = $":{UNIT_ID:X2}010001FF00XX\r\n";
var protocol = new AsciiProtocol(); var protocol = new AsciiProtocol();
// Act // Act + Assert
protocol.ValidateResponse(Encoding.ASCII.GetBytes(request), Encoding.ASCII.GetBytes(response)); Assert.ThrowsException<ModbusException>(() => protocol.ValidateResponse(Encoding.ASCII.GetBytes(request), Encoding.ASCII.GetBytes(response)));
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowForFunctionCodeOnValidateResponse() public void ShouldThrowForFunctionCodeOnValidateResponse()
{ {
// Arrange // Arrange
@@ -961,12 +885,11 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
AddTrailer(ref response); AddTrailer(ref response);
var protocol = new AsciiProtocol(); var protocol = new AsciiProtocol();
// Act // Act + Assert
protocol.ValidateResponse(Encoding.ASCII.GetBytes(request), Encoding.ASCII.GetBytes(response)); Assert.ThrowsException<ModbusException>(() => protocol.ValidateResponse(Encoding.ASCII.GetBytes(request), Encoding.ASCII.GetBytes(response)));
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowForErrorOnValidateResponse() public void ShouldThrowForErrorOnValidateResponse()
{ {
// Arrange // Arrange
@@ -975,8 +898,8 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
AddTrailer(ref response); AddTrailer(ref response);
var protocol = new AsciiProtocol(); var protocol = new AsciiProtocol();
// Act // Act + Assert
protocol.ValidateResponse(Encoding.ASCII.GetBytes(request), Encoding.ASCII.GetBytes(response)); Assert.ThrowsException<ModbusException>(() => protocol.ValidateResponse(Encoding.ASCII.GetBytes(request), Encoding.ASCII.GetBytes(response)));
} }
[DataTestMethod] [DataTestMethod]
@@ -984,7 +907,6 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
[DataRow(0x02)] [DataRow(0x02)]
[DataRow(0x03)] [DataRow(0x03)]
[DataRow(0x04)] [DataRow(0x04)]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowForReadLengthOnValidateResponse(int fn) public void ShouldThrowForReadLengthOnValidateResponse(int fn)
{ {
// Arrange // Arrange
@@ -993,8 +915,8 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
AddTrailer(ref response); AddTrailer(ref response);
var protocol = new AsciiProtocol(); var protocol = new AsciiProtocol();
// Act // Act + Assert
protocol.ValidateResponse(Encoding.ASCII.GetBytes(request), Encoding.ASCII.GetBytes(response)); Assert.ThrowsException<ModbusException>(() => protocol.ValidateResponse(Encoding.ASCII.GetBytes(request), Encoding.ASCII.GetBytes(response)));
} }
[DataTestMethod] [DataTestMethod]
@@ -1002,7 +924,6 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
[DataRow(0x06)] [DataRow(0x06)]
[DataRow(0x0F)] [DataRow(0x0F)]
[DataRow(0x10)] [DataRow(0x10)]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowForWriteLengthOnValidateResponse(int fn) public void ShouldThrowForWriteLengthOnValidateResponse(int fn)
{ {
// Arrange // Arrange
@@ -1011,8 +932,8 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
AddTrailer(ref response); AddTrailer(ref response);
var protocol = new AsciiProtocol(); var protocol = new AsciiProtocol();
// Act // Act + Assert
protocol.ValidateResponse(Encoding.ASCII.GetBytes(request), Encoding.ASCII.GetBytes(response)); Assert.ThrowsException<ModbusException>(() => protocol.ValidateResponse(Encoding.ASCII.GetBytes(request), Encoding.ASCII.GetBytes(response)));
} }
[TestMethod] [TestMethod]
@@ -1033,58 +954,46 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
[DataRow("")] [DataRow("")]
[DataRow(" ")] [DataRow(" ")]
[DataRow("\t")] [DataRow("\t")]
[ExpectedException(typeof(ArgumentNullException))]
public void ShouldThrowArgumentNullExceptionForMessageOnLrc(string msg) public void ShouldThrowArgumentNullExceptionForMessageOnLrc(string msg)
{ {
// Arrange // Arrange
// Act // Act + Assert
AsciiProtocol.LRC(msg); Assert.ThrowsException<ArgumentNullException>(() => AsciiProtocol.LRC(msg));
// Assert - ArgumentNullException
} }
[DataTestMethod] [DataTestMethod]
[DataRow(-1)] [DataRow(-1)]
[DataRow(4)] [DataRow(4)]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowArgumentOutOfRangeExceptionForStartOnLrc(int start) public void ShouldThrowArgumentOutOfRangeExceptionForStartOnLrc(int start)
{ {
// Arrange // Arrange
string msg = "0207"; string msg = "0207";
// Act // Act + Assert
AsciiProtocol.LRC(msg, start); Assert.ThrowsException<ArgumentOutOfRangeException>(() => AsciiProtocol.LRC(msg, start));
// Assert - ArgumentOutOfRangeException
} }
[DataTestMethod] [DataTestMethod]
[DataRow(0)] [DataRow(0)]
[DataRow(5)] [DataRow(5)]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowArgumentOutOfRangeExceptionForLengthOnLrc(int length) public void ShouldThrowArgumentOutOfRangeExceptionForLengthOnLrc(int length)
{ {
// Arrange // Arrange
string msg = "0207"; string msg = "0207";
// Act // Act + Assert
AsciiProtocol.LRC(msg, 0, length); Assert.ThrowsException<ArgumentOutOfRangeException>(() => AsciiProtocol.LRC(msg, 0, length));
// Assert - ArgumentOutOfRangeException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ShouldThrowArgumentExceptionForMessageLengthOnLrc() public void ShouldThrowArgumentExceptionForMessageLengthOnLrc()
{ {
// Arrange // Arrange
string msg = "0207"; string msg = "0207";
// Act // Act + Assert
AsciiProtocol.LRC(msg); Assert.ThrowsException<ArgumentException>(() => AsciiProtocol.LRC(msg));
// Assert - ArgumentException
} }
#endregion Validation #endregion Validation

View File

@@ -55,29 +55,23 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
[DataTestMethod] [DataTestMethod]
[DataRow(0)] [DataRow(0)]
[DataRow(2001)] [DataRow(2001)]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowOutOfRangeForCountOnSerializeReadCoils(int count) public void ShouldThrowOutOfRangeForCountOnSerializeReadCoils(int count)
{ {
// Arrange // Arrange
var protocol = new RtuOverTcpProtocol(); var protocol = new RtuOverTcpProtocol();
// Act // Act + Assert
protocol.SerializeReadCoils(UNIT_ID, 19, (ushort)count); Assert.ThrowsException<ArgumentOutOfRangeException>(() => protocol.SerializeReadCoils(UNIT_ID, 19, (ushort)count));
// Assert - ArgumentOutOfRangeException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowOutOfRangeForStartingAddressOnSerializeReadCoils() public void ShouldThrowOutOfRangeForStartingAddressOnSerializeReadCoils()
{ {
// Arrange // Arrange
var protocol = new RtuOverTcpProtocol(); var protocol = new RtuOverTcpProtocol();
// Act // Act + Assert
protocol.SerializeReadCoils(UNIT_ID, ushort.MaxValue, 2); Assert.ThrowsException<ArgumentOutOfRangeException>(() => protocol.SerializeReadCoils(UNIT_ID, ushort.MaxValue, 2));
// Assert - ArgumentOutOfRangeException
} }
[TestMethod] [TestMethod]
@@ -106,16 +100,13 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowExceptionOnDeserializeReadCoils() public void ShouldThrowExceptionOnDeserializeReadCoils()
{ {
// Arrange // Arrange
var protocol = new RtuOverTcpProtocol(); var protocol = new RtuOverTcpProtocol();
// Act // Act + Assert
protocol.DeserializeReadCoils([0x00, 0x01, 0x00, 0x00, 0x00, 0x08, UNIT_ID, 0x01, 0x02, 0xCD, 0x6B, 0x05, 0x00, 0x00]); Assert.ThrowsException<ModbusException>(() => protocol.DeserializeReadCoils([0x00, 0x01, 0x00, 0x00, 0x00, 0x08, UNIT_ID, 0x01, 0x02, 0xCD, 0x6B, 0x05, 0x00, 0x00]));
// Assert - ModbusException
} }
#endregion Read Coils #endregion Read Coils
@@ -166,29 +157,23 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
[DataTestMethod] [DataTestMethod]
[DataRow(0)] [DataRow(0)]
[DataRow(2001)] [DataRow(2001)]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowOutOfRangeForCountOnSerializeReadDiscreteInputs(int count) public void ShouldThrowOutOfRangeForCountOnSerializeReadDiscreteInputs(int count)
{ {
// Arrange // Arrange
var protocol = new RtuOverTcpProtocol(); var protocol = new RtuOverTcpProtocol();
// Act // Act + Assert
protocol.SerializeReadDiscreteInputs(UNIT_ID, 19, (ushort)count); Assert.ThrowsException<ArgumentOutOfRangeException>(() => protocol.SerializeReadDiscreteInputs(UNIT_ID, 19, (ushort)count));
// Assert - ArgumentOutOfRangeException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowOutOfRangeForStartingAddressOnSerializeReadDiscreteInputs() public void ShouldThrowOutOfRangeForStartingAddressOnSerializeReadDiscreteInputs()
{ {
// Arrange // Arrange
var protocol = new RtuOverTcpProtocol(); var protocol = new RtuOverTcpProtocol();
// Act // Act + Assert
protocol.SerializeReadDiscreteInputs(UNIT_ID, ushort.MaxValue, 2); Assert.ThrowsException<ArgumentOutOfRangeException>(() => protocol.SerializeReadDiscreteInputs(UNIT_ID, ushort.MaxValue, 2));
// Assert - ArgumentOutOfRangeException
} }
[TestMethod] [TestMethod]
@@ -217,16 +202,13 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowExceptionOnDeserializeReadDiscreteInputs() public void ShouldThrowExceptionOnDeserializeReadDiscreteInputs()
{ {
// Arrange // Arrange
var protocol = new RtuOverTcpProtocol(); var protocol = new RtuOverTcpProtocol();
// Act // Act + Assert
protocol.DeserializeReadDiscreteInputs([0x00, 0x01, 0x00, 0x00, 0x00, 0x08, UNIT_ID, 0x02, 0x02, 0xCD, 0x6B, 0x05, 0x00, 0x00]); Assert.ThrowsException<ModbusException>(() => protocol.DeserializeReadDiscreteInputs([0x00, 0x01, 0x00, 0x00, 0x00, 0x08, UNIT_ID, 0x02, 0x02, 0xCD, 0x6B, 0x05, 0x00, 0x00]));
// Assert - ModbusException
} }
#endregion Read Discrete Inputs #endregion Read Discrete Inputs
@@ -277,29 +259,23 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
[DataTestMethod] [DataTestMethod]
[DataRow(0)] [DataRow(0)]
[DataRow(126)] [DataRow(126)]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowOutOfRangeForCountOnSerializeReadHoldingRegisters(int count) public void ShouldThrowOutOfRangeForCountOnSerializeReadHoldingRegisters(int count)
{ {
// Arrange // Arrange
var protocol = new RtuOverTcpProtocol(); var protocol = new RtuOverTcpProtocol();
// Act // Act + Assert
protocol.SerializeReadHoldingRegisters(UNIT_ID, 19, (ushort)count); Assert.ThrowsException<ArgumentOutOfRangeException>(() => protocol.SerializeReadHoldingRegisters(UNIT_ID, 19, (ushort)count));
// Assert - ArgumentOutOfRangeException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowOutOfRangeForStartingAddressOnSerializeReadHoldingRegisters() public void ShouldThrowOutOfRangeForStartingAddressOnSerializeReadHoldingRegisters()
{ {
// Arrange // Arrange
var protocol = new RtuOverTcpProtocol(); var protocol = new RtuOverTcpProtocol();
// Act // Act + Assert
protocol.SerializeReadHoldingRegisters(UNIT_ID, ushort.MaxValue, 2); Assert.ThrowsException<ArgumentOutOfRangeException>(() => protocol.SerializeReadHoldingRegisters(UNIT_ID, ushort.MaxValue, 2));
// Assert - ArgumentOutOfRangeException
} }
[TestMethod] [TestMethod]
@@ -323,16 +299,13 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowExceptionOnDeserializeReadHoldingRegisters() public void ShouldThrowExceptionOnDeserializeReadHoldingRegisters()
{ {
// Arrange // Arrange
var protocol = new RtuOverTcpProtocol(); var protocol = new RtuOverTcpProtocol();
// Act // Act + Assert
protocol.DeserializeReadHoldingRegisters([0x00, 0x01, 0x00, 0x00, 0x00, 0x07, UNIT_ID, 0x03, 0x04, 0x02, 0x2B, 0x00, 0x00]); Assert.ThrowsException<ModbusException>(() => protocol.DeserializeReadHoldingRegisters([0x00, 0x01, 0x00, 0x00, 0x00, 0x08, UNIT_ID, 0x03, 0x04, 0x02, 0x2B, 0x00, 0x00]));
// Assert - ModbusException
} }
#endregion Read Holding Registers #endregion Read Holding Registers
@@ -383,29 +356,23 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
[DataTestMethod] [DataTestMethod]
[DataRow(0)] [DataRow(0)]
[DataRow(126)] [DataRow(126)]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowOutOfRangeForCountOnSerializeReadInputRegisters(int count) public void ShouldThrowOutOfRangeForCountOnSerializeReadInputRegisters(int count)
{ {
// Arrange // Arrange
var protocol = new RtuOverTcpProtocol(); var protocol = new RtuOverTcpProtocol();
// Act // Act + Assert
protocol.SerializeReadInputRegisters(UNIT_ID, 19, (ushort)count); Assert.ThrowsException<ArgumentOutOfRangeException>(() => protocol.SerializeReadInputRegisters(UNIT_ID, 19, (ushort)count));
// Assert - ArgumentOutOfRangeException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowOutOfRangeForStartingAddressOnSerializeReadInputRegisters() public void ShouldThrowOutOfRangeForStartingAddressOnSerializeReadInputRegisters()
{ {
// Arrange // Arrange
var protocol = new RtuOverTcpProtocol(); var protocol = new RtuOverTcpProtocol();
// Act // Act + Assert
protocol.SerializeReadInputRegisters(UNIT_ID, ushort.MaxValue, 2); Assert.ThrowsException<ArgumentOutOfRangeException>(() => protocol.SerializeReadInputRegisters(UNIT_ID, ushort.MaxValue, 2));
// Assert - ArgumentOutOfRangeException
} }
[TestMethod] [TestMethod]
@@ -429,16 +396,13 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowExceptionOnDeserializeReadInputRegisters() public void ShouldThrowExceptionOnDeserializeReadInputRegisters()
{ {
// Arrange // Arrange
var protocol = new RtuOverTcpProtocol(); var protocol = new RtuOverTcpProtocol();
// Act // Act + Assert
protocol.DeserializeReadInputRegisters([0x00, 0x01, 0x00, 0x00, 0x00, 0x07, UNIT_ID, 0x04, 0x04, 0x02, 0x2B, 0x00, 0x00]); Assert.ThrowsException<ModbusException>(() => protocol.DeserializeReadInputRegisters([0x00, 0x01, 0x00, 0x00, 0x00, 0x08, UNIT_ID, 0x04, 0x04, 0x02, 0x2B, 0x00, 0x00]));
// Assert - ModbusException
} }
#endregion Read Input Registers #endregion Read Input Registers
@@ -493,16 +457,13 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowOutOfRangeExceptionForCategoryOnSerializeReadDeviceIdentification() public void ShouldThrowOutOfRangeExceptionForCategoryOnSerializeReadDeviceIdentification()
{ {
// Arrange // Arrange
var protocol = new RtuOverTcpProtocol(); var protocol = new RtuOverTcpProtocol();
// Act // Act + Assert
protocol.SerializeReadDeviceIdentification(UNIT_ID, (ModbusDeviceIdentificationCategory)10, ModbusDeviceIdentificationObject.ProductCode); Assert.ThrowsException<ArgumentOutOfRangeException>(() => protocol.SerializeReadDeviceIdentification(UNIT_ID, (ModbusDeviceIdentificationCategory)10, ModbusDeviceIdentificationObject.ProductCode));
// Assert - ArgumentOutOfRangeException
} }
[DataTestMethod] [DataTestMethod]
@@ -529,27 +490,25 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowExceptionOnDeserializeReadDeviceIdentificationForMeiType() public void ShouldThrowExceptionOnDeserializeReadDeviceIdentificationForMeiType()
{ {
// Arrange // Arrange
byte[] response = [0x00, 0x01, 0x00, 0x00, 0x00, 0x05, UNIT_ID, 0x2B, 0x0D, 0x00, 0x00]; byte[] response = [0x00, 0x01, 0x00, 0x00, 0x00, 0x05, UNIT_ID, 0x2B, 0x0D, 0x00, 0x00];
var protocol = new RtuOverTcpProtocol(); var protocol = new RtuOverTcpProtocol();
// Act // Act + Assert
protocol.DeserializeReadDeviceIdentification(response); Assert.ThrowsException<ModbusException>(() => protocol.DeserializeReadDeviceIdentification(response));
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowExceptionOnDeserializeReadDeviceIdentificationForCategory() public void ShouldThrowExceptionOnDeserializeReadDeviceIdentificationForCategory()
{ {
// Arrange // Arrange
byte[] response = [0x00, 0x01, 0x00, 0x00, 0x00, 0x06, UNIT_ID, 0x2B, 0x0E, 0x08, 0x00, 0x00]; byte[] response = [0x00, 0x01, 0x00, 0x00, 0x00, 0x06, UNIT_ID, 0x2B, 0x0E, 0x08, 0x00, 0x00];
var protocol = new RtuOverTcpProtocol(); var protocol = new RtuOverTcpProtocol();
// Act // Act + Assert
protocol.DeserializeReadDeviceIdentification(response); Assert.ThrowsException<ModbusException>(() => protocol.DeserializeReadDeviceIdentification(response));
} }
#endregion Read Device Identification #endregion Read Device Identification
@@ -600,16 +559,13 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void ShouldThrowArgumentNullOnSerializeWriteSingleCoil() public void ShouldThrowArgumentNullOnSerializeWriteSingleCoil()
{ {
// Arrange // Arrange
var protocol = new RtuOverTcpProtocol(); var protocol = new RtuOverTcpProtocol();
// Act // Act + Assert
protocol.SerializeWriteSingleCoil(UNIT_ID, null); Assert.ThrowsException<ArgumentNullException>(() => protocol.SerializeWriteSingleCoil(UNIT_ID, null));
// Assert - ArgumentNullException
} }
[TestMethod] [TestMethod]
@@ -676,16 +632,13 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void ShouldThrowArgumentNullOnSerializeWriteSingleHoldingRegister() public void ShouldThrowArgumentNullOnSerializeWriteSingleHoldingRegister()
{ {
// Arrange // Arrange
var protocol = new RtuOverTcpProtocol(); var protocol = new RtuOverTcpProtocol();
// Act // Act + Assert
protocol.SerializeWriteSingleHoldingRegister(UNIT_ID, null); Assert.ThrowsException<ArgumentNullException>(() => protocol.SerializeWriteSingleHoldingRegister(UNIT_ID, null));
// Assert - ArgumentNullException
} }
[TestMethod] [TestMethod]
@@ -765,22 +718,18 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void ShouldThrowArgumentNullOnSerializeWriteMultipleCoils() public void ShouldThrowArgumentNullOnSerializeWriteMultipleCoils()
{ {
// Arrange // Arrange
var protocol = new RtuOverTcpProtocol(); var protocol = new RtuOverTcpProtocol();
// Act // Act + Assert
protocol.SerializeWriteMultipleCoils(UNIT_ID, null); Assert.ThrowsException<ArgumentNullException>(() => protocol.SerializeWriteMultipleCoils(UNIT_ID, null));
// Assert - ArgumentNullException
} }
[DataTestMethod] [DataTestMethod]
[DataRow(0)] [DataRow(0)]
[DataRow(1969)] [DataRow(1969)]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowOutOfRangeForCountOnSerializeWriteMultipleCoils(int count) public void ShouldThrowOutOfRangeForCountOnSerializeWriteMultipleCoils(int count)
{ {
// Arrange // Arrange
@@ -790,14 +739,11 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
var protocol = new RtuOverTcpProtocol(); var protocol = new RtuOverTcpProtocol();
// Act // Act + Assert
protocol.SerializeWriteMultipleCoils(UNIT_ID, coils); Assert.ThrowsException<ArgumentOutOfRangeException>(() => protocol.SerializeWriteMultipleCoils(UNIT_ID, coils));
// Assert - ArgumentOutOfRangeException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ShouldThrowArgumentExceptionForDuplicateEntryOnSerializeMultipleCoils() public void ShouldThrowArgumentExceptionForDuplicateEntryOnSerializeMultipleCoils()
{ {
// Arrange // Arrange
@@ -808,14 +754,11 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
}; };
var protocol = new RtuOverTcpProtocol(); var protocol = new RtuOverTcpProtocol();
// Act // Act + Assert
protocol.SerializeWriteMultipleCoils(UNIT_ID, coils); Assert.ThrowsException<ArgumentException>(() => protocol.SerializeWriteMultipleCoils(UNIT_ID, coils));
// Assert - ArgumentException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ShouldThrowArgumentExceptionForGapInAddressOnSerializeMultipleCoils() public void ShouldThrowArgumentExceptionForGapInAddressOnSerializeMultipleCoils()
{ {
// Arrange // Arrange
@@ -826,10 +769,8 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
}; };
var protocol = new RtuOverTcpProtocol(); var protocol = new RtuOverTcpProtocol();
// Act // Act + Assert
protocol.SerializeWriteMultipleCoils(UNIT_ID, coils); Assert.ThrowsException<ArgumentException>(() => protocol.SerializeWriteMultipleCoils(UNIT_ID, coils));
// Assert - ArgumentException
} }
[TestMethod] [TestMethod]
@@ -908,22 +849,18 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void ShouldThrowArgumentNullOnSerializeWriteMultipleHoldingRegisters() public void ShouldThrowArgumentNullOnSerializeWriteMultipleHoldingRegisters()
{ {
// Arrange // Arrange
var protocol = new RtuOverTcpProtocol(); var protocol = new RtuOverTcpProtocol();
// Act // Act + Assert
protocol.SerializeWriteMultipleHoldingRegisters(UNIT_ID, null); Assert.ThrowsException<ArgumentNullException>(() => protocol.SerializeWriteMultipleHoldingRegisters(UNIT_ID, null));
// Assert - ArgumentNullException
} }
[DataTestMethod] [DataTestMethod]
[DataRow(0)] [DataRow(0)]
[DataRow(124)] [DataRow(124)]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowOutOfRangeForCountOnSerializeWriteMultipleHoldingRegisters(int count) public void ShouldThrowOutOfRangeForCountOnSerializeWriteMultipleHoldingRegisters(int count)
{ {
// Arrange // Arrange
@@ -933,14 +870,11 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
var protocol = new RtuOverTcpProtocol(); var protocol = new RtuOverTcpProtocol();
// Act // Act + Assert
protocol.SerializeWriteMultipleHoldingRegisters(UNIT_ID, registers); Assert.ThrowsException<ArgumentOutOfRangeException>(() => protocol.SerializeWriteMultipleHoldingRegisters(UNIT_ID, registers));
// Assert - ArgumentOutOfRangeException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ShouldThrowArgumentExceptionForDuplicateEntryOnSerializeMultipleHoldingRegisters() public void ShouldThrowArgumentExceptionForDuplicateEntryOnSerializeMultipleHoldingRegisters()
{ {
// Arrange // Arrange
@@ -951,14 +885,11 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
}; };
var protocol = new RtuOverTcpProtocol(); var protocol = new RtuOverTcpProtocol();
// Act // Act + Assert
protocol.SerializeWriteMultipleHoldingRegisters(UNIT_ID, registers); Assert.ThrowsException<ArgumentException>(() => protocol.SerializeWriteMultipleHoldingRegisters(UNIT_ID, registers));
// Assert - ArgumentException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ShouldThrowArgumentExceptionForGapInAddressOnSerializeMultipleHoldingRegisters() public void ShouldThrowArgumentExceptionForGapInAddressOnSerializeMultipleHoldingRegisters()
{ {
// Arrange // Arrange
@@ -969,10 +900,8 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
}; };
var protocol = new RtuOverTcpProtocol(); var protocol = new RtuOverTcpProtocol();
// Act // Act + Assert
protocol.SerializeWriteMultipleHoldingRegisters(UNIT_ID, registers); Assert.ThrowsException<ArgumentException>(() => protocol.SerializeWriteMultipleHoldingRegisters(UNIT_ID, registers));
// Assert - ArgumentException
} }
[TestMethod] [TestMethod]
@@ -1065,7 +994,6 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
[DataTestMethod] [DataTestMethod]
[DataRow(0x00, 0x00)] [DataRow(0x00, 0x00)]
[DataRow(0x01, 0x01)] [DataRow(0x01, 0x01)]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowForTransactionIdOnValidateResponse(int hi, int lo) public void ShouldThrowForTransactionIdOnValidateResponse(int hi, int lo)
{ {
// Arrange // Arrange
@@ -1074,14 +1002,13 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
SetCrc(response); SetCrc(response);
var protocol = new RtuOverTcpProtocol(); var protocol = new RtuOverTcpProtocol();
// Act // Act + Assert
protocol.ValidateResponse(request, response); Assert.ThrowsException<ModbusException>(() => protocol.ValidateResponse(request, response));
} }
[DataTestMethod] [DataTestMethod]
[DataRow(0x00, 0x01)] [DataRow(0x00, 0x01)]
[DataRow(0x01, 0x00)] [DataRow(0x01, 0x00)]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowForProtocolIdOnValidateResponse(int hi, int lo) public void ShouldThrowForProtocolIdOnValidateResponse(int hi, int lo)
{ {
// Arrange // Arrange
@@ -1090,12 +1017,11 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
SetCrc(response); SetCrc(response);
var protocol = new RtuOverTcpProtocol(); var protocol = new RtuOverTcpProtocol();
// Act // Act + Assert
protocol.ValidateResponse(request, response); Assert.ThrowsException<ModbusException>(() => protocol.ValidateResponse(request, response));
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowForFollowingBytesOnValidateResponse() public void ShouldThrowForFollowingBytesOnValidateResponse()
{ {
// Arrange // Arrange
@@ -1104,12 +1030,11 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
SetCrc(response); SetCrc(response);
var protocol = new RtuOverTcpProtocol(); var protocol = new RtuOverTcpProtocol();
// Act // Act + Assert
protocol.ValidateResponse(request, response); Assert.ThrowsException<ModbusException>(() => protocol.ValidateResponse(request, response));
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowForUnitIdOnValidateResponse() public void ShouldThrowForUnitIdOnValidateResponse()
{ {
// Arrange // Arrange
@@ -1118,12 +1043,11 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
SetCrc(response); SetCrc(response);
var protocol = new RtuOverTcpProtocol(); var protocol = new RtuOverTcpProtocol();
// Act // Act + Assert
protocol.ValidateResponse(request, response); Assert.ThrowsException<ModbusException>(() => protocol.ValidateResponse(request, response));
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowForFunctionCodeOnValidateResponse() public void ShouldThrowForFunctionCodeOnValidateResponse()
{ {
// Arrange // Arrange
@@ -1132,12 +1056,11 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
SetCrc(response); SetCrc(response);
var protocol = new RtuOverTcpProtocol(); var protocol = new RtuOverTcpProtocol();
// Act // Act + Assert
protocol.ValidateResponse(request, response); Assert.ThrowsException<ModbusException>(() => protocol.ValidateResponse(request, response));
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowForModbusErrorOnValidateResponse() public void ShouldThrowForModbusErrorOnValidateResponse()
{ {
// Arrange // Arrange
@@ -1146,14 +1069,13 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
SetCrc(response); SetCrc(response);
var protocol = new RtuOverTcpProtocol(); var protocol = new RtuOverTcpProtocol();
// Act // Act + Assert
protocol.ValidateResponse(request, response); Assert.ThrowsException<ModbusException>(() => protocol.ValidateResponse(request, response));
} }
[DataTestMethod] [DataTestMethod]
[DataRow(0x59, 0x6C)] [DataRow(0x59, 0x6C)]
[DataRow(0x58, 0x6B)] [DataRow(0x58, 0x6B)]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowForCrcOnValidateResponse(int hi, int lo) public void ShouldThrowForCrcOnValidateResponse(int hi, int lo)
{ {
// Arrange // Arrange
@@ -1161,8 +1083,8 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
byte[] response = [0x00, 0x01, 0x00, 0x00, 0x00, 0x06, UNIT_ID, 0x01, 0x01, 0x00, (byte)hi, (byte)lo]; byte[] response = [0x00, 0x01, 0x00, 0x00, 0x00, 0x06, UNIT_ID, 0x01, 0x01, 0x00, (byte)hi, (byte)lo];
var protocol = new RtuOverTcpProtocol(); var protocol = new RtuOverTcpProtocol();
// Act // Act + Assert
protocol.ValidateResponse(request, response); Assert.ThrowsException<ModbusException>(() => protocol.ValidateResponse(request, response));
} }
#endregion Validation #endregion Validation

View File

@@ -43,29 +43,23 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
[DataTestMethod] [DataTestMethod]
[DataRow(0)] [DataRow(0)]
[DataRow(2001)] [DataRow(2001)]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowOutOfRangeForCountOnSerializeReadCoils(int count) public void ShouldThrowOutOfRangeForCountOnSerializeReadCoils(int count)
{ {
// Arrange // Arrange
var protocol = new RtuProtocol(); var protocol = new RtuProtocol();
// Act // Act + Assert
protocol.SerializeReadCoils(UNIT_ID, 19, (ushort)count); Assert.ThrowsException<ArgumentOutOfRangeException>(() => protocol.SerializeReadCoils(UNIT_ID, 19, (ushort)count));
// Assert - ArgumentOutOfRangeException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowOutOfRangeForStartingAddressOnSerializeReadCoils() public void ShouldThrowOutOfRangeForStartingAddressOnSerializeReadCoils()
{ {
// Arrange // Arrange
var protocol = new RtuProtocol(); var protocol = new RtuProtocol();
// Act // Act + Assert
protocol.SerializeReadCoils(UNIT_ID, ushort.MaxValue, 2); Assert.ThrowsException<ArgumentOutOfRangeException>(() => protocol.SerializeReadCoils(UNIT_ID, ushort.MaxValue, 2));
// Assert - ArgumentOutOfRangeException
} }
[TestMethod] [TestMethod]
@@ -94,16 +88,13 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowExceptionOnDeserializeReadCoils() public void ShouldThrowExceptionOnDeserializeReadCoils()
{ {
// Arrange // Arrange
var protocol = new RtuProtocol(); var protocol = new RtuProtocol();
// Act // Act + Assert
_ = protocol.DeserializeReadCoils([UNIT_ID, 0x01, 0x02, 0xCD, 0x6B, 0x05, 0x00, 0x00]); Assert.ThrowsException<ModbusException>(() => protocol.DeserializeReadCoils([UNIT_ID, 0x01, 0x02, 0xCD, 0x6B, 0x05, 0x00, 0x00]));
// Assert - ModbusException
} }
#endregion Read Coils #endregion Read Coils
@@ -142,29 +133,23 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
[DataTestMethod] [DataTestMethod]
[DataRow(0)] [DataRow(0)]
[DataRow(2001)] [DataRow(2001)]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowOutOfRangeForCountOnSerializeReadDiscreteInputs(int count) public void ShouldThrowOutOfRangeForCountOnSerializeReadDiscreteInputs(int count)
{ {
// Arrange // Arrange
var protocol = new RtuProtocol(); var protocol = new RtuProtocol();
// Act // Act + Assert
protocol.SerializeReadDiscreteInputs(UNIT_ID, 19, (ushort)count); Assert.ThrowsException<ArgumentOutOfRangeException>(() => protocol.SerializeReadDiscreteInputs(UNIT_ID, 19, (ushort)count));
// Assert - ArgumentOutOfRangeException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowOutOfRangeForStartingAddressOnSerializeReadDiscreteInputs() public void ShouldThrowOutOfRangeForStartingAddressOnSerializeReadDiscreteInputs()
{ {
// Arrange // Arrange
var protocol = new RtuProtocol(); var protocol = new RtuProtocol();
// Act // Act + Assert
protocol.SerializeReadDiscreteInputs(UNIT_ID, ushort.MaxValue, 2); Assert.ThrowsException<ArgumentOutOfRangeException>(() => protocol.SerializeReadDiscreteInputs(UNIT_ID, ushort.MaxValue, 2));
// Assert - ArgumentOutOfRangeException
} }
[TestMethod] [TestMethod]
@@ -193,16 +178,13 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowExceptionOnDeserializeReadDiscreteInputs() public void ShouldThrowExceptionOnDeserializeReadDiscreteInputs()
{ {
// Arrange // Arrange
var protocol = new RtuProtocol(); var protocol = new RtuProtocol();
// Act // Act + Assert
_ = protocol.DeserializeReadDiscreteInputs([UNIT_ID, 0x02, 0x02, 0xCD, 0x6B, 0x05, 0x00, 0x00]); Assert.ThrowsException<ModbusException>(() => protocol.DeserializeReadDiscreteInputs([UNIT_ID, 0x02, 0x02, 0xCD, 0x6B, 0x05, 0x00, 0x00]));
// Assert - ModbusException
} }
#endregion Read Discrete Inputs #endregion Read Discrete Inputs
@@ -241,29 +223,23 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
[DataTestMethod] [DataTestMethod]
[DataRow(0)] [DataRow(0)]
[DataRow(126)] [DataRow(126)]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowOutOfRangeForCountOnSerializeReadHoldingRegisters(int count) public void ShouldThrowOutOfRangeForCountOnSerializeReadHoldingRegisters(int count)
{ {
// Arrange // Arrange
var protocol = new RtuProtocol(); var protocol = new RtuProtocol();
// Act // Act + Assert
protocol.SerializeReadHoldingRegisters(UNIT_ID, 19, (ushort)count); Assert.ThrowsException<ArgumentOutOfRangeException>(() => protocol.SerializeReadHoldingRegisters(UNIT_ID, 19, (ushort)count));
// Assert - ArgumentOutOfRangeException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowOutOfRangeForStartingAddressOnSerializeReadHoldingRegisters() public void ShouldThrowOutOfRangeForStartingAddressOnSerializeReadHoldingRegisters()
{ {
// Arrange // Arrange
var protocol = new RtuProtocol(); var protocol = new RtuProtocol();
// Act // Act + Assert
protocol.SerializeReadHoldingRegisters(UNIT_ID, ushort.MaxValue, 2); Assert.ThrowsException<ArgumentOutOfRangeException>(() => protocol.SerializeReadHoldingRegisters(UNIT_ID, ushort.MaxValue, 2));
// Assert - ArgumentOutOfRangeException
} }
[TestMethod] [TestMethod]
@@ -287,16 +263,13 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowExceptionOnDeserializeReadHoldingRegisters() public void ShouldThrowExceptionOnDeserializeReadHoldingRegisters()
{ {
// Arrange // Arrange
var protocol = new RtuProtocol(); var protocol = new RtuProtocol();
// Act // Act + Assert
protocol.DeserializeReadHoldingRegisters([UNIT_ID, 0x03, 0x04, 0x02, 0x2B, 0x00, 0x00]); Assert.ThrowsException<ModbusException>(() => protocol.DeserializeReadHoldingRegisters([UNIT_ID, 0x03, 0x04, 0x02, 0x2B, 0x00, 0x00]));
// Assert - ModbusException
} }
#endregion Read Holding Registers #endregion Read Holding Registers
@@ -335,29 +308,23 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
[DataTestMethod] [DataTestMethod]
[DataRow(0)] [DataRow(0)]
[DataRow(126)] [DataRow(126)]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowOutOfRangeForCountOnSerializeReadInputRegisters(int count) public void ShouldThrowOutOfRangeForCountOnSerializeReadInputRegisters(int count)
{ {
// Arrange // Arrange
var protocol = new RtuProtocol(); var protocol = new RtuProtocol();
// Act // Act + Assert
protocol.SerializeReadInputRegisters(UNIT_ID, 19, (ushort)count); Assert.ThrowsException<ArgumentOutOfRangeException>(() => protocol.SerializeReadInputRegisters(UNIT_ID, 19, (ushort)count));
// Assert - ArgumentOutOfRangeException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowOutOfRangeForStartingAddressOnSerializeReadInputRegisters() public void ShouldThrowOutOfRangeForStartingAddressOnSerializeReadInputRegisters()
{ {
// Arrange // Arrange
var protocol = new RtuProtocol(); var protocol = new RtuProtocol();
// Act // Act + Assert
protocol.SerializeReadInputRegisters(UNIT_ID, ushort.MaxValue, 2); Assert.ThrowsException<ArgumentOutOfRangeException>(() => protocol.SerializeReadInputRegisters(UNIT_ID, ushort.MaxValue, 2));
// Assert - ArgumentOutOfRangeException
} }
[TestMethod] [TestMethod]
@@ -381,16 +348,13 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowExceptionOnDeserializeReadInputRegisters() public void ShouldThrowExceptionOnDeserializeReadInputRegisters()
{ {
// Arrange // Arrange
var protocol = new RtuProtocol(); var protocol = new RtuProtocol();
// Act // Act + Assert
protocol.DeserializeReadInputRegisters([UNIT_ID, 0x04, 0x04, 0x02, 0x2B, 0x00, 0x00]); Assert.ThrowsException<ModbusException>(() => protocol.DeserializeReadInputRegisters([UNIT_ID, 0x04, 0x04, 0x02, 0x2B, 0x00, 0x00]));
// Assert - ModbusException
} }
#endregion Read Input Registers #endregion Read Input Registers
@@ -433,16 +397,13 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowOutOfRangeExceptionForCategoryOnSerializeReadDeviceIdentification() public void ShouldThrowOutOfRangeExceptionForCategoryOnSerializeReadDeviceIdentification()
{ {
// Arrange // Arrange
var protocol = new RtuProtocol(); var protocol = new RtuProtocol();
// Act // Act + Assert
protocol.SerializeReadDeviceIdentification(UNIT_ID, (ModbusDeviceIdentificationCategory)10, ModbusDeviceIdentificationObject.ProductCode); Assert.ThrowsException<ArgumentOutOfRangeException>(() => protocol.SerializeReadDeviceIdentification(UNIT_ID, (ModbusDeviceIdentificationCategory)10, ModbusDeviceIdentificationObject.ProductCode));
// Assert - ArgumentOutOfRangeException
} }
[DataTestMethod] [DataTestMethod]
@@ -469,27 +430,25 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowExceptionOnDeserializeReadDeviceIdentificationForMeiType() public void ShouldThrowExceptionOnDeserializeReadDeviceIdentificationForMeiType()
{ {
// Arrange // Arrange
byte[] response = [UNIT_ID, 0x2B, 0x0D, 0x00, 0x00]; byte[] response = [UNIT_ID, 0x2B, 0x0D, 0x00, 0x00];
var protocol = new RtuProtocol(); var protocol = new RtuProtocol();
// Act // Act + Assert
protocol.DeserializeReadDeviceIdentification(response); Assert.ThrowsException<ModbusException>(() => protocol.DeserializeReadDeviceIdentification(response));
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowExceptionOnDeserializeReadDeviceIdentificationForCategory() public void ShouldThrowExceptionOnDeserializeReadDeviceIdentificationForCategory()
{ {
// Arrange // Arrange
byte[] response = [UNIT_ID, 0x2B, 0x0E, 0x08, 0x00, 0x00]; byte[] response = [UNIT_ID, 0x2B, 0x0E, 0x08, 0x00, 0x00];
var protocol = new RtuProtocol(); var protocol = new RtuProtocol();
// Act // Act + Assert
protocol.DeserializeReadDeviceIdentification(response); Assert.ThrowsException<ModbusException>(() => protocol.DeserializeReadDeviceIdentification(response));
} }
#endregion Read Device Identification #endregion Read Device Identification
@@ -528,16 +487,13 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void ShouldThrowArgumentNullOnSerializeWriteSingleCoil() public void ShouldThrowArgumentNullOnSerializeWriteSingleCoil()
{ {
// Arrange // Arrange
var protocol = new RtuProtocol(); var protocol = new RtuProtocol();
// Act // Act + Assert
protocol.SerializeWriteSingleCoil(UNIT_ID, null); Assert.ThrowsException<ArgumentNullException>(() => protocol.SerializeWriteSingleCoil(UNIT_ID, null));
// Assert - ArgumentNullException
} }
[TestMethod] [TestMethod]
@@ -592,16 +548,13 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void ShouldThrowArgumentNullOnSerializeWriteSingleHoldingRegister() public void ShouldThrowArgumentNullOnSerializeWriteSingleHoldingRegister()
{ {
// Arrange // Arrange
var protocol = new RtuProtocol(); var protocol = new RtuProtocol();
// Act // Act + Assert
protocol.SerializeWriteSingleHoldingRegister(UNIT_ID, null); Assert.ThrowsException<ArgumentNullException>(() => protocol.SerializeWriteSingleHoldingRegister(UNIT_ID, null));
// Assert - ArgumentNullException
} }
[TestMethod] [TestMethod]
@@ -669,22 +622,18 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void ShouldThrowArgumentNullOnSerializeWriteMultipleCoils() public void ShouldThrowArgumentNullOnSerializeWriteMultipleCoils()
{ {
// Arrange // Arrange
var protocol = new RtuProtocol(); var protocol = new RtuProtocol();
// Act // Act + Assert
protocol.SerializeWriteMultipleCoils(UNIT_ID, null); Assert.ThrowsException<ArgumentNullException>(() => protocol.SerializeWriteMultipleCoils(UNIT_ID, null));
// Assert - ArgumentNullException
} }
[DataTestMethod] [DataTestMethod]
[DataRow(0)] [DataRow(0)]
[DataRow(1969)] [DataRow(1969)]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowOutOfRangeForCountOnSerializeWriteMultipleCoils(int count) public void ShouldThrowOutOfRangeForCountOnSerializeWriteMultipleCoils(int count)
{ {
// Arrange // Arrange
@@ -694,14 +643,11 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
var protocol = new RtuProtocol(); var protocol = new RtuProtocol();
// Act // Act + Assert
protocol.SerializeWriteMultipleCoils(UNIT_ID, coils); Assert.ThrowsException<ArgumentOutOfRangeException>(() => protocol.SerializeWriteMultipleCoils(UNIT_ID, coils));
// Assert - ArgumentOutOfRangeException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ShouldThrowArgumentExceptionForDuplicateEntryOnSerializeMultipleCoils() public void ShouldThrowArgumentExceptionForDuplicateEntryOnSerializeMultipleCoils()
{ {
// Arrange // Arrange
@@ -712,14 +658,11 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
}; };
var protocol = new RtuProtocol(); var protocol = new RtuProtocol();
// Act // Act + Assert
protocol.SerializeWriteMultipleCoils(UNIT_ID, coils); Assert.ThrowsException<ArgumentException>(() => protocol.SerializeWriteMultipleCoils(UNIT_ID, coils));
// Assert - ArgumentException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ShouldThrowArgumentExceptionForGapInAddressOnSerializeMultipleCoils() public void ShouldThrowArgumentExceptionForGapInAddressOnSerializeMultipleCoils()
{ {
// Arrange // Arrange
@@ -730,10 +673,8 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
}; };
var protocol = new RtuProtocol(); var protocol = new RtuProtocol();
// Act // Act + Assert
protocol.SerializeWriteMultipleCoils(UNIT_ID, coils); Assert.ThrowsException<ArgumentException>(() => protocol.SerializeWriteMultipleCoils(UNIT_ID, coils));
// Assert - ArgumentException
} }
[TestMethod] [TestMethod]
@@ -800,22 +741,18 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void ShouldThrowArgumentNullOnSerializeWriteMultipleHoldingRegisters() public void ShouldThrowArgumentNullOnSerializeWriteMultipleHoldingRegisters()
{ {
// Arrange // Arrange
var protocol = new RtuProtocol(); var protocol = new RtuProtocol();
// Act // Act + Assert
protocol.SerializeWriteMultipleHoldingRegisters(UNIT_ID, null); Assert.ThrowsException<ArgumentNullException>(() => protocol.SerializeWriteMultipleHoldingRegisters(UNIT_ID, null));
// Assert - ArgumentNullException
} }
[DataTestMethod] [DataTestMethod]
[DataRow(0)] [DataRow(0)]
[DataRow(124)] [DataRow(124)]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowOutOfRangeForCountOnSerializeWriteMultipleHoldingRegisters(int count) public void ShouldThrowOutOfRangeForCountOnSerializeWriteMultipleHoldingRegisters(int count)
{ {
// Arrange // Arrange
@@ -825,14 +762,11 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
var protocol = new RtuProtocol(); var protocol = new RtuProtocol();
// Act // Act + Assert
protocol.SerializeWriteMultipleHoldingRegisters(UNIT_ID, registers); Assert.ThrowsException<ArgumentOutOfRangeException>(() => protocol.SerializeWriteMultipleHoldingRegisters(UNIT_ID, registers));
// Assert - ArgumentOutOfRangeException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ShouldThrowArgumentExceptionForDuplicateEntryOnSerializeMultipleHoldingRegisters() public void ShouldThrowArgumentExceptionForDuplicateEntryOnSerializeMultipleHoldingRegisters()
{ {
// Arrange // Arrange
@@ -843,14 +777,11 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
}; };
var protocol = new RtuProtocol(); var protocol = new RtuProtocol();
// Act // Act + Assert
protocol.SerializeWriteMultipleHoldingRegisters(UNIT_ID, registers); Assert.ThrowsException<ArgumentException>(() => protocol.SerializeWriteMultipleHoldingRegisters(UNIT_ID, registers));
// Assert - ArgumentException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ShouldThrowArgumentExceptionForGapInAddressOnSerializeMultipleHoldingRegisters() public void ShouldThrowArgumentExceptionForGapInAddressOnSerializeMultipleHoldingRegisters()
{ {
// Arrange // Arrange
@@ -861,10 +792,8 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
}; };
var protocol = new RtuProtocol(); var protocol = new RtuProtocol();
// Act // Act + Assert
protocol.SerializeWriteMultipleHoldingRegisters(UNIT_ID, registers); Assert.ThrowsException<ArgumentException>(() => protocol.SerializeWriteMultipleHoldingRegisters(UNIT_ID, registers));
// Assert - ArgumentException
} }
[TestMethod] [TestMethod]
@@ -1105,7 +1034,6 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowForUnitIdOnValidateResponse() public void ShouldThrowForUnitIdOnValidateResponse()
{ {
// Arrange // Arrange
@@ -1114,14 +1042,13 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
SetCrc(response); SetCrc(response);
var protocol = new RtuProtocol(); var protocol = new RtuProtocol();
// Act // Act + Assert
protocol.ValidateResponse(request, response); Assert.ThrowsException<ModbusException>(() => protocol.ValidateResponse(request, response));
} }
[DataTestMethod] [DataTestMethod]
[DataRow(0x57, 0x6C)] [DataRow(0x57, 0x6C)]
[DataRow(0x58, 0x6B)] [DataRow(0x58, 0x6B)]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowForCrcOnValidateResponse(int hi, int lo) public void ShouldThrowForCrcOnValidateResponse(int hi, int lo)
{ {
// Arrange // Arrange
@@ -1129,12 +1056,11 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
byte[] response = [UNIT_ID, 0x01, 0x01, 0x00, (byte)hi, (byte)lo]; byte[] response = [UNIT_ID, 0x01, 0x01, 0x00, (byte)hi, (byte)lo];
var protocol = new RtuProtocol(); var protocol = new RtuProtocol();
// Act // Act + Assert
protocol.ValidateResponse(request, response); Assert.ThrowsException<ModbusException>(() => protocol.ValidateResponse(request, response));
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowForFunctionCodeOnValidateResponse() public void ShouldThrowForFunctionCodeOnValidateResponse()
{ {
// Arrange // Arrange
@@ -1143,12 +1069,11 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
SetCrc(response); SetCrc(response);
var protocol = new RtuProtocol(); var protocol = new RtuProtocol();
// Act // Act + Assert
protocol.ValidateResponse(request, response); Assert.ThrowsException<ModbusException>(() => protocol.ValidateResponse(request, response));
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowForErrorOnValidateResponse() public void ShouldThrowForErrorOnValidateResponse()
{ {
// Arrange // Arrange
@@ -1157,8 +1082,8 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
SetCrc(response); SetCrc(response);
var protocol = new RtuProtocol(); var protocol = new RtuProtocol();
// Act // Act + Assert
protocol.ValidateResponse(request, response); Assert.ThrowsException<ModbusException>(() => protocol.ValidateResponse(request, response));
} }
[DataTestMethod] [DataTestMethod]
@@ -1166,7 +1091,6 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
[DataRow(0x02)] [DataRow(0x02)]
[DataRow(0x03)] [DataRow(0x03)]
[DataRow(0x04)] [DataRow(0x04)]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowForReadLengthOnValidateResponse(int fn) public void ShouldThrowForReadLengthOnValidateResponse(int fn)
{ {
// Arrange // Arrange
@@ -1175,8 +1099,8 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
SetCrc(response); SetCrc(response);
var protocol = new RtuProtocol(); var protocol = new RtuProtocol();
// Act // Act + Assert
protocol.ValidateResponse(request, response); Assert.ThrowsException<ModbusException>(() => protocol.ValidateResponse(request, response));
} }
[DataTestMethod] [DataTestMethod]
@@ -1184,7 +1108,6 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
[DataRow(0x06)] [DataRow(0x06)]
[DataRow(0x0F)] [DataRow(0x0F)]
[DataRow(0x10)] [DataRow(0x10)]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowForWriteLengthOnValidateResponse(int fn) public void ShouldThrowForWriteLengthOnValidateResponse(int fn)
{ {
// Arrange // Arrange
@@ -1193,8 +1116,8 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
SetCrc(response); SetCrc(response);
var protocol = new RtuProtocol(); var protocol = new RtuProtocol();
// Act // Act + Assert
protocol.ValidateResponse(request, response); Assert.ThrowsException<ModbusException>(() => protocol.ValidateResponse(request, response));
} }
[TestMethod] [TestMethod]
@@ -1217,43 +1140,36 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
[DataTestMethod] [DataTestMethod]
[DataRow(null)] [DataRow(null)]
[DataRow(new byte[0])] [DataRow(new byte[0])]
[ExpectedException(typeof(ArgumentNullException))]
public void ShuldThrowArgumentNullExceptionForBytesOnCrc16(byte[] bytes) public void ShuldThrowArgumentNullExceptionForBytesOnCrc16(byte[] bytes)
{ {
// Act // Arrange
_ = RtuProtocol.CRC16(bytes);
// Assert - ArgumentNullException // Act + Assert
Assert.ThrowsException<ArgumentNullException>(() => RtuProtocol.CRC16(bytes));
} }
[DataTestMethod] [DataTestMethod]
[DataRow(-1)] [DataRow(-1)]
[DataRow(10)] [DataRow(10)]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowArgumentOutOfRangeForStartOnCrc16(int start) public void ShouldThrowArgumentOutOfRangeForStartOnCrc16(int start)
{ {
// Arrange // Arrange
byte[] bytes = Encoding.UTF8.GetBytes("0123456789"); byte[] bytes = Encoding.UTF8.GetBytes("0123456789");
// Act // Act + Assert
_ = RtuProtocol.CRC16(bytes, start); Assert.ThrowsException<ArgumentOutOfRangeException>(() => RtuProtocol.CRC16(bytes, start));
// Assert - ArgumentOutOfRangeException
} }
[DataTestMethod] [DataTestMethod]
[DataRow(0)] [DataRow(0)]
[DataRow(11)] [DataRow(11)]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowArgumentOutOfRangeForLengthOnCrc16(int length) public void ShouldThrowArgumentOutOfRangeForLengthOnCrc16(int length)
{ {
// Arrange // Arrange
byte[] bytes = Encoding.UTF8.GetBytes("0123456789"); byte[] bytes = Encoding.UTF8.GetBytes("0123456789");
// Act // Act + Assert
_ = RtuProtocol.CRC16(bytes, 0, length); Assert.ThrowsException<ArgumentOutOfRangeException>(() => RtuProtocol.CRC16(bytes, 0, length));
// Assert - ArgumentOutOfRangeException
} }
#endregion Validation #endregion Validation

View File

@@ -53,29 +53,23 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
[DataTestMethod] [DataTestMethod]
[DataRow(0)] [DataRow(0)]
[DataRow(2001)] [DataRow(2001)]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowOutOfRangeForCountOnSerializeReadCoils(int count) public void ShouldThrowOutOfRangeForCountOnSerializeReadCoils(int count)
{ {
// Arrange // Arrange
var protocol = new TcpProtocol(); var protocol = new TcpProtocol();
// Act // Act + Assert
protocol.SerializeReadCoils(UNIT_ID, 19, (ushort)count); Assert.ThrowsException<ArgumentOutOfRangeException>(() => protocol.SerializeReadCoils(UNIT_ID, 19, (ushort)count));
// Assert - ArgumentOutOfRangeException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowOutOfRangeForStartingAddressOnSerializeReadCoils() public void ShouldThrowOutOfRangeForStartingAddressOnSerializeReadCoils()
{ {
// Arrange // Arrange
var protocol = new TcpProtocol(); var protocol = new TcpProtocol();
// Act // Act + Assert
protocol.SerializeReadCoils(UNIT_ID, ushort.MaxValue, 2); Assert.ThrowsException<ArgumentOutOfRangeException>(() => protocol.SerializeReadCoils(UNIT_ID, ushort.MaxValue, 2));
// Assert - ArgumentOutOfRangeException
} }
[TestMethod] [TestMethod]
@@ -104,16 +98,13 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowExceptionOnDeserializeReadCoils() public void ShouldThrowExceptionOnDeserializeReadCoils()
{ {
// Arrange // Arrange
var protocol = new TcpProtocol(); var protocol = new TcpProtocol();
// Act // Act + Assert
var coils = protocol.DeserializeReadCoils([0x00, 0x01, 0x00, 0x00, 0x00, 0x06, 0x2A, 0x01, 0x02, 0xCD, 0x6B, 0x05]); Assert.ThrowsException<ModbusException>(() => protocol.DeserializeReadCoils([0x00, 0x01, 0x00, 0x00, 0x00, 0x06, 0x2A, 0x01, 0x02, 0xCD, 0x6B, 0x05]));
// Assert - ModbusException
} }
#endregion Read Coils #endregion Read Coils
@@ -162,29 +153,23 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
[DataTestMethod] [DataTestMethod]
[DataRow(0)] [DataRow(0)]
[DataRow(2001)] [DataRow(2001)]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowOutOfRangeForCountOnSerializeReadDiscreteInputs(int count) public void ShouldThrowOutOfRangeForCountOnSerializeReadDiscreteInputs(int count)
{ {
// Arrange // Arrange
var protocol = new TcpProtocol(); var protocol = new TcpProtocol();
// Act // Act + Assert
protocol.SerializeReadDiscreteInputs(UNIT_ID, 19, (ushort)count); Assert.ThrowsException<ArgumentOutOfRangeException>(() => protocol.SerializeReadDiscreteInputs(UNIT_ID, 19, (ushort)count));
// Assert - ArgumentOutOfRangeException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowOutOfRangeForStartingAddressOnSerializeReadDiscreteInputs() public void ShouldThrowOutOfRangeForStartingAddressOnSerializeReadDiscreteInputs()
{ {
// Arrange // Arrange
var protocol = new TcpProtocol(); var protocol = new TcpProtocol();
// Act // Act + Assert
protocol.SerializeReadDiscreteInputs(UNIT_ID, ushort.MaxValue, 2); Assert.ThrowsException<ArgumentOutOfRangeException>(() => protocol.SerializeReadDiscreteInputs(UNIT_ID, ushort.MaxValue, 2));
// Assert - ArgumentOutOfRangeException
} }
[TestMethod] [TestMethod]
@@ -213,16 +198,13 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowExceptionOnDeserializeReadDiscreteInputs() public void ShouldThrowExceptionOnDeserializeReadDiscreteInputs()
{ {
// Arrange // Arrange
var protocol = new TcpProtocol(); var protocol = new TcpProtocol();
// Act // Act + Assert
protocol.DeserializeReadDiscreteInputs([0x00, 0x01, 0x00, 0x00, 0x00, 0x06, 0x2A, 0x02, 0x03, 0xCD, 0x6B]); Assert.ThrowsException<ModbusException>(() => protocol.DeserializeReadDiscreteInputs([0x00, 0x01, 0x00, 0x00, 0x00, 0x06, 0x2A, 0x02, 0x03, 0xCD, 0x6B]));
// Assert - ModbusException
} }
#endregion Read Discrete Inputs #endregion Read Discrete Inputs
@@ -271,29 +253,23 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
[DataTestMethod] [DataTestMethod]
[DataRow(0)] [DataRow(0)]
[DataRow(126)] [DataRow(126)]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowOutOfRangeForCountOnSerializeReadHoldingRegisters(int count) public void ShouldThrowOutOfRangeForCountOnSerializeReadHoldingRegisters(int count)
{ {
// Arrange // Arrange
var protocol = new TcpProtocol(); var protocol = new TcpProtocol();
// Act // Act + Assert
protocol.SerializeReadHoldingRegisters(UNIT_ID, 19, (ushort)count); Assert.ThrowsException<ArgumentOutOfRangeException>(() => protocol.SerializeReadHoldingRegisters(UNIT_ID, 19, (ushort)count));
// Assert - ArgumentOutOfRangeException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowOutOfRangeForStartingAddressOnSerializeReadHoldingRegisters() public void ShouldThrowOutOfRangeForStartingAddressOnSerializeReadHoldingRegisters()
{ {
// Arrange // Arrange
var protocol = new TcpProtocol(); var protocol = new TcpProtocol();
// Act // Act + Assert
protocol.SerializeReadHoldingRegisters(UNIT_ID, ushort.MaxValue, 2); Assert.ThrowsException<ArgumentOutOfRangeException>(() => protocol.SerializeReadHoldingRegisters(UNIT_ID, ushort.MaxValue, 2));
// Assert - ArgumentOutOfRangeException
} }
[TestMethod] [TestMethod]
@@ -317,16 +293,13 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowExceptionOnDeserializeReadHoldingRegisters() public void ShouldThrowExceptionOnDeserializeReadHoldingRegisters()
{ {
// Arrange // Arrange
var protocol = new TcpProtocol(); var protocol = new TcpProtocol();
// Act // Act + Assert
protocol.DeserializeReadHoldingRegisters([0x00, 0x01, 0x00, 0x00, 0x00, 0x06, 0x2A, 0x03, 0x04, 0x02, 0x2B]); Assert.ThrowsException<ModbusException>(() => protocol.DeserializeReadHoldingRegisters([0x00, 0x01, 0x00, 0x00, 0x00, 0x06, 0x2A, 0x03, 0x04, 0x02, 0x2B]));
// Assert - ModbusException
} }
#endregion Read Holding Registers #endregion Read Holding Registers
@@ -375,29 +348,23 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
[DataTestMethod] [DataTestMethod]
[DataRow(0)] [DataRow(0)]
[DataRow(126)] [DataRow(126)]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowOutOfRangeForCountOnSerializeReadInputRegisters(int count) public void ShouldThrowOutOfRangeForCountOnSerializeReadInputRegisters(int count)
{ {
// Arrange // Arrange
var protocol = new TcpProtocol(); var protocol = new TcpProtocol();
// Act // Act + Assert
protocol.SerializeReadInputRegisters(UNIT_ID, 19, (ushort)count); Assert.ThrowsException<ArgumentOutOfRangeException>(() => protocol.SerializeReadInputRegisters(UNIT_ID, 19, (ushort)count));
// Assert - ArgumentOutOfRangeException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowOutOfRangeForStartingAddressOnSerializeReadInputRegisters() public void ShouldThrowOutOfRangeForStartingAddressOnSerializeReadInputRegisters()
{ {
// Arrange // Arrange
var protocol = new TcpProtocol(); var protocol = new TcpProtocol();
// Act // Act + Assert
protocol.SerializeReadInputRegisters(UNIT_ID, ushort.MaxValue, 2); Assert.ThrowsException<ArgumentOutOfRangeException>(() => protocol.SerializeReadInputRegisters(UNIT_ID, ushort.MaxValue, 2));
// Assert - ArgumentOutOfRangeException
} }
[TestMethod] [TestMethod]
@@ -421,16 +388,13 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowExceptionOnDeserializeReadInputRegisters() public void ShouldThrowExceptionOnDeserializeReadInputRegisters()
{ {
// Arrange // Arrange
var protocol = new TcpProtocol(); var protocol = new TcpProtocol();
// Act // Act + Assert
protocol.DeserializeReadInputRegisters([0x00, 0x01, 0x00, 0x00, 0x00, 0x06, 0x2A, 0x04, 0x04, 0x02, 0x2B]); Assert.ThrowsException<ModbusException>(() => protocol.DeserializeReadInputRegisters([0x00, 0x01, 0x00, 0x00, 0x00, 0x06, 0x2A, 0x04, 0x04, 0x02, 0x2B]));
// Assert - ModbusException
} }
#endregion Read Input Registers #endregion Read Input Registers
@@ -483,16 +447,13 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowOutOfRangeExceptionOnSerializeReadDeviceIdentification() public void ShouldThrowOutOfRangeExceptionOnSerializeReadDeviceIdentification()
{ {
// Arrange // Arrange
var protocol = new TcpProtocol(); var protocol = new TcpProtocol();
// Act // Act + Assert
protocol.SerializeReadDeviceIdentification(UNIT_ID, (ModbusDeviceIdentificationCategory)10, ModbusDeviceIdentificationObject.ProductCode); Assert.ThrowsException<ArgumentOutOfRangeException>(() => protocol.SerializeReadDeviceIdentification(UNIT_ID, (ModbusDeviceIdentificationCategory)10, ModbusDeviceIdentificationObject.ProductCode));
// Assert - ArgumentOutOfRangeException
} }
[DataTestMethod] [DataTestMethod]
@@ -519,27 +480,25 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowExceptionOnDeserializeReadDeviceIdentificationForMeiType() public void ShouldThrowExceptionOnDeserializeReadDeviceIdentificationForMeiType()
{ {
// Arrange // Arrange
byte[] response = [0x00, 0x01, 0x00, 0x00, 0x00, 0x0D, 0x2A, 0x2B, 0x0D]; byte[] response = [0x00, 0x01, 0x00, 0x00, 0x00, 0x0D, 0x2A, 0x2B, 0x0D];
var protocol = new TcpProtocol(); var protocol = new TcpProtocol();
// Act // Act + Assert
protocol.DeserializeReadDeviceIdentification(response); Assert.ThrowsException<ModbusException>(() => protocol.DeserializeReadDeviceIdentification(response));
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowExceptionOnDeserializeReadDeviceIdentificationForCategory() public void ShouldThrowExceptionOnDeserializeReadDeviceIdentificationForCategory()
{ {
// Arrange // Arrange
byte[] response = [0x00, 0x01, 0x00, 0x00, 0x00, 0x0D, 0x2A, 0x2B, 0x0E, 0x08]; byte[] response = [0x00, 0x01, 0x00, 0x00, 0x00, 0x0D, 0x2A, 0x2B, 0x0E, 0x08];
var protocol = new TcpProtocol(); var protocol = new TcpProtocol();
// Act // Act + Assert
protocol.DeserializeReadDeviceIdentification(response); Assert.ThrowsException<ModbusException>(() => protocol.DeserializeReadDeviceIdentification(response));
} }
#endregion Read Device Identification #endregion Read Device Identification
@@ -588,16 +547,13 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void ShouldThrowArgumentNullOnSerializeWriteSingleCoil() public void ShouldThrowArgumentNullOnSerializeWriteSingleCoil()
{ {
// Arrange // Arrange
var protocol = new TcpProtocol(); var protocol = new TcpProtocol();
// Act // Act + Assert
protocol.SerializeWriteSingleCoil(UNIT_ID, null); Assert.ThrowsException<ArgumentNullException>(() => protocol.SerializeWriteSingleCoil(UNIT_ID, null));
// Assert - ArgumentNullException
} }
[TestMethod] [TestMethod]
@@ -662,16 +618,13 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void ShouldThrowArgumentNullOnSerializeWriteSingleHoldingRegister() public void ShouldThrowArgumentNullOnSerializeWriteSingleHoldingRegister()
{ {
// Arrange // Arrange
var protocol = new TcpProtocol(); var protocol = new TcpProtocol();
// Act // Act + Assert
protocol.SerializeWriteSingleHoldingRegister(UNIT_ID, null); Assert.ThrowsException<ArgumentNullException>(() => protocol.SerializeWriteSingleHoldingRegister(UNIT_ID, null));
// Assert - ArgumentNullException
} }
[TestMethod] [TestMethod]
@@ -749,22 +702,18 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void ShouldThrowArgumentNullOnSerializeWriteMultipleCoils() public void ShouldThrowArgumentNullOnSerializeWriteMultipleCoils()
{ {
// Arrange // Arrange
var protocol = new TcpProtocol(); var protocol = new TcpProtocol();
// Act // Act + Assert
protocol.SerializeWriteMultipleCoils(UNIT_ID, null); Assert.ThrowsException<ArgumentNullException>(() => protocol.SerializeWriteMultipleCoils(UNIT_ID, null));
// Assert - ArgumentNullException
} }
[DataTestMethod] [DataTestMethod]
[DataRow(0)] [DataRow(0)]
[DataRow(1969)] [DataRow(1969)]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowOutOfRangeForCountOnSerializeWriteMultipleCoils(int count) public void ShouldThrowOutOfRangeForCountOnSerializeWriteMultipleCoils(int count)
{ {
// Arrange // Arrange
@@ -774,14 +723,11 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
var protocol = new TcpProtocol(); var protocol = new TcpProtocol();
// Act // Act + Assert
protocol.SerializeWriteMultipleCoils(UNIT_ID, coils); Assert.ThrowsException<ArgumentOutOfRangeException>(() => protocol.SerializeWriteMultipleCoils(UNIT_ID, coils));
// Assert - ArgumentOutOfRangeException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ShouldThrowArgumentExceptionForDuplicateEntryOnSerializeMultipleCoils() public void ShouldThrowArgumentExceptionForDuplicateEntryOnSerializeMultipleCoils()
{ {
// Arrange // Arrange
@@ -792,14 +738,11 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
}; };
var protocol = new TcpProtocol(); var protocol = new TcpProtocol();
// Act // Act + Assert
protocol.SerializeWriteMultipleCoils(UNIT_ID, coils); Assert.ThrowsException<ArgumentException>(() => protocol.SerializeWriteMultipleCoils(UNIT_ID, coils));
// Assert - ArgumentException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ShouldThrowArgumentExceptionForGapInAddressOnSerializeMultipleCoils() public void ShouldThrowArgumentExceptionForGapInAddressOnSerializeMultipleCoils()
{ {
// Arrange // Arrange
@@ -810,10 +753,8 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
}; };
var protocol = new TcpProtocol(); var protocol = new TcpProtocol();
// Act // Act + Assert
protocol.SerializeWriteMultipleCoils(UNIT_ID, coils); Assert.ThrowsException<ArgumentException>(() => protocol.SerializeWriteMultipleCoils(UNIT_ID, coils));
// Assert - ArgumentException
} }
[TestMethod] [TestMethod]
@@ -890,22 +831,18 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void ShouldThrowArgumentNullOnSerializeWriteMultipleHoldingRegisters() public void ShouldThrowArgumentNullOnSerializeWriteMultipleHoldingRegisters()
{ {
// Arrange // Arrange
var protocol = new TcpProtocol(); var protocol = new TcpProtocol();
// Act // Act + Assert
protocol.SerializeWriteMultipleHoldingRegisters(UNIT_ID, null); Assert.ThrowsException<ArgumentNullException>(() => protocol.SerializeWriteMultipleHoldingRegisters(UNIT_ID, null));
// Assert - ArgumentNullException
} }
[DataTestMethod] [DataTestMethod]
[DataRow(0)] [DataRow(0)]
[DataRow(124)] [DataRow(124)]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowOutOfRangeForCountOnSerializeWriteMultipleHoldingRegisters(int count) public void ShouldThrowOutOfRangeForCountOnSerializeWriteMultipleHoldingRegisters(int count)
{ {
// Arrange // Arrange
@@ -915,14 +852,11 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
var protocol = new TcpProtocol(); var protocol = new TcpProtocol();
// Act // Act + Assert
protocol.SerializeWriteMultipleHoldingRegisters(UNIT_ID, registers); Assert.ThrowsException<ArgumentOutOfRangeException>(() => protocol.SerializeWriteMultipleHoldingRegisters(UNIT_ID, registers));
// Assert - ArgumentOutOfRangeException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ShouldThrowArgumentExceptionForDuplicateEntryOnSerializeMultipleHoldingRegisters() public void ShouldThrowArgumentExceptionForDuplicateEntryOnSerializeMultipleHoldingRegisters()
{ {
// Arrange // Arrange
@@ -933,14 +867,11 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
}; };
var protocol = new TcpProtocol(); var protocol = new TcpProtocol();
// Act // Act + Assert
protocol.SerializeWriteMultipleHoldingRegisters(UNIT_ID, registers); Assert.ThrowsException<ArgumentException>(() => protocol.SerializeWriteMultipleHoldingRegisters(UNIT_ID, registers));
// Assert - ArgumentException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ShouldThrowArgumentExceptionForGapInAddressOnSerializeMultipleHoldingRegisters() public void ShouldThrowArgumentExceptionForGapInAddressOnSerializeMultipleHoldingRegisters()
{ {
// Arrange // Arrange
@@ -951,10 +882,8 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
}; };
var protocol = new TcpProtocol(); var protocol = new TcpProtocol();
// Act // Act + Assert
protocol.SerializeWriteMultipleHoldingRegisters(UNIT_ID, registers); Assert.ThrowsException<ArgumentException>(() => protocol.SerializeWriteMultipleHoldingRegisters(UNIT_ID, registers));
// Assert - ArgumentException
} }
[TestMethod] [TestMethod]
@@ -1045,7 +974,6 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
[DataTestMethod] [DataTestMethod]
[DataRow(0x00, 0x00)] [DataRow(0x00, 0x00)]
[DataRow(0x01, 0x01)] [DataRow(0x01, 0x01)]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowForTransactionIdOnValidateResponse(int hi, int lo) public void ShouldThrowForTransactionIdOnValidateResponse(int hi, int lo)
{ {
// Arrange // Arrange
@@ -1053,14 +981,13 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
byte[] response = [0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x2A, 0x01, 0x01, 0x00]; byte[] response = [0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x2A, 0x01, 0x01, 0x00];
var protocol = new TcpProtocol(); var protocol = new TcpProtocol();
// Act // Act + Assert
protocol.ValidateResponse(request, response); Assert.ThrowsException<ModbusException>(() => protocol.ValidateResponse(request, response));
} }
[DataTestMethod] [DataTestMethod]
[DataRow(0x00, 0x01)] [DataRow(0x00, 0x01)]
[DataRow(0x01, 0x00)] [DataRow(0x01, 0x00)]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowForProtocolIdOnValidateResponse(int hi, int lo) public void ShouldThrowForProtocolIdOnValidateResponse(int hi, int lo)
{ {
// Arrange // Arrange
@@ -1068,12 +995,11 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
byte[] response = [0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x2A, 0x01, 0x01, 0x00]; byte[] response = [0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x2A, 0x01, 0x01, 0x00];
var protocol = new TcpProtocol(); var protocol = new TcpProtocol();
// Act // Act + Assert
protocol.ValidateResponse(request, response); Assert.ThrowsException<ModbusException>(() => protocol.ValidateResponse(request, response));
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowForFollowingBytesOnValidateResponse() public void ShouldThrowForFollowingBytesOnValidateResponse()
{ {
// Arrange // Arrange
@@ -1081,12 +1007,11 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
byte[] response = [0x00, 0x01, 0x00, 0x00, 0x00, 0x05, 0x2A, 0x01, 0x01, 0x00]; byte[] response = [0x00, 0x01, 0x00, 0x00, 0x00, 0x05, 0x2A, 0x01, 0x01, 0x00];
var protocol = new TcpProtocol(); var protocol = new TcpProtocol();
// Act // Act + Assert
protocol.ValidateResponse(request, response); Assert.ThrowsException<ModbusException>(() => protocol.ValidateResponse(request, response));
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowForUnitIdOnValidateResponse() public void ShouldThrowForUnitIdOnValidateResponse()
{ {
// Arrange // Arrange
@@ -1094,12 +1019,11 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
byte[] response = [0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x2B, 0x01, 0x01, 0x00]; byte[] response = [0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x2B, 0x01, 0x01, 0x00];
var protocol = new TcpProtocol(); var protocol = new TcpProtocol();
// Act // Act + Assert
protocol.ValidateResponse(request, response); Assert.ThrowsException<ModbusException>(() => protocol.ValidateResponse(request, response));
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowForFunctionCodeOnValidateResponse() public void ShouldThrowForFunctionCodeOnValidateResponse()
{ {
// Arrange // Arrange
@@ -1107,12 +1031,11 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
byte[] response = [0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x2A, 0x02, 0x01, 0x00]; byte[] response = [0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x2A, 0x02, 0x01, 0x00];
var protocol = new TcpProtocol(); var protocol = new TcpProtocol();
// Act // Act + Assert
protocol.ValidateResponse(request, response); Assert.ThrowsException<ModbusException>(() => protocol.ValidateResponse(request, response));
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ModbusException))]
public void ShouldThrowForModbusErrorOnValidateResponse() public void ShouldThrowForModbusErrorOnValidateResponse()
{ {
// Arrange // Arrange
@@ -1120,8 +1043,8 @@ namespace AMWD.Protocols.Modbus.Tests.Common.Protocols
byte[] response = [0x00, 0x01, 0x00, 0x00, 0x00, 0x03, 0x2A, 0x81, 0x01]; byte[] response = [0x00, 0x01, 0x00, 0x00, 0x00, 0x03, 0x2A, 0x81, 0x01];
var protocol = new TcpProtocol(); var protocol = new TcpProtocol();
// Act // Act + Assert
protocol.ValidateResponse(request, response); Assert.ThrowsException<ModbusException>(() => protocol.ValidateResponse(request, response));
} }
#endregion Validation #endregion Validation

View File

@@ -144,49 +144,40 @@ namespace AMWD.Protocols.Modbus.Tests.Serial
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void ShouldThrowArgumentNullExceptionOnCreateInstanceForClient() public void ShouldThrowArgumentNullExceptionOnCreateInstanceForClient()
{ {
// Arrange // Arrange
// Act // Act + Assert
new ModbusRtuProxy(null, "some-port"); Assert.ThrowsException<ArgumentNullException>(() => new ModbusRtuProxy(null, "some-port"));
// Assert - ArgumentNullException
} }
[DataTestMethod] [DataTestMethod]
[DataRow(null)] [DataRow(null)]
[DataRow("")] [DataRow("")]
[DataRow(" ")] [DataRow(" ")]
[ExpectedException(typeof(ArgumentNullException))]
public void ShouldThrowArgumentNullExceptionOnCreateInstanceForPortName(string portName) public void ShouldThrowArgumentNullExceptionOnCreateInstanceForPortName(string portName)
{ {
// Arrange // Arrange
var connection = new Mock<IModbusConnection>(); var connection = new Mock<IModbusConnection>();
var clientMock = new Mock<ModbusClientBase>(connection.Object); var clientMock = new Mock<ModbusClientBase>(connection.Object);
// Act // Act + Assert
new ModbusRtuProxy(clientMock.Object, portName); Assert.ThrowsException<ArgumentNullException>(() => new ModbusRtuProxy(clientMock.Object, portName));
// Assert - ArgumentNullException
} }
[DataTestMethod] [DataTestMethod]
[DataRow(null)] [DataRow(null)]
[DataRow("")] [DataRow("")]
[DataRow(" ")] [DataRow(" ")]
[ExpectedException(typeof(ArgumentNullException))]
public async Task ShouldThrowArgumentNullExceptionOnMissingPortName(string portName) public async Task ShouldThrowArgumentNullExceptionOnMissingPortName(string portName)
{ {
// Arrange // Arrange
using var proxy = GetProxy(); using var proxy = GetProxy();
_serialPortMock.Setup(m => m.PortName).Returns(portName); _serialPortMock.Setup(m => m.PortName).Returns(portName);
// Act // Act + Assert
await proxy.StartAsync(); await Assert.ThrowsExceptionAsync<ArgumentNullException>(() => proxy.StartAsync());
// Assert - ArgumentNullException
} }
[TestMethod] [TestMethod]

View File

@@ -94,58 +94,46 @@ namespace AMWD.Protocols.Modbus.Tests.Serial
[DataRow(null)] [DataRow(null)]
[DataRow("")] [DataRow("")]
[DataRow(" ")] [DataRow(" ")]
[ExpectedException(typeof(ArgumentNullException))]
public void ShouldThrowArgumentNullExceptionOnCreate(string portName) public void ShouldThrowArgumentNullExceptionOnCreate(string portName)
{ {
// Arrange // Arrange
// Act // Act + Assert
using var test = new ModbusSerialClient(portName); Assert.ThrowsException<ArgumentNullException>(() => new ModbusSerialClient(portName));
// Assert - ArgumentNullException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ObjectDisposedException))]
public async Task ShouldThrowDisposedExceptionOnInvokeAsync() public async Task ShouldThrowDisposedExceptionOnInvokeAsync()
{ {
// Arrange // Arrange
var connection = GetConnection(); var connection = GetConnection();
connection.Dispose(); connection.Dispose();
// Act // Act + Assert
await connection.InvokeAsync(null, null); await Assert.ThrowsExceptionAsync<ObjectDisposedException>(() => connection.InvokeAsync(null, null));
// Assert - OjbectDisposedException
} }
[DataTestMethod] [DataTestMethod]
[DataRow(null)] [DataRow(null)]
[DataRow(new byte[0])] [DataRow(new byte[0])]
[ExpectedException(typeof(ArgumentNullException))]
public async Task ShouldThrowArgumentNullExceptionForMissingRequestOnInvokeAsync(byte[] request) public async Task ShouldThrowArgumentNullExceptionForMissingRequestOnInvokeAsync(byte[] request)
{ {
// Arrange // Arrange
var connection = GetConnection(); var connection = GetConnection();
// Act // Act + Assert
await connection.InvokeAsync(request, null); await Assert.ThrowsExceptionAsync<ArgumentNullException>(() => connection.InvokeAsync(request, null));
// Assert - ArgumentNullException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public async Task ShouldThrowArgumentNullExceptionForMissingValidationOnInvokeAsync() public async Task ShouldThrowArgumentNullExceptionForMissingValidationOnInvokeAsync()
{ {
// Arrange // Arrange
byte[] request = new byte[1]; byte[] request = new byte[1];
var connection = GetConnection(); var connection = GetConnection();
// Act // Act + Assert
await connection.InvokeAsync(request, null); await Assert.ThrowsExceptionAsync<ArgumentNullException>(() => connection.InvokeAsync(request, null));
// Assert - ArgumentNullException
} }
[TestMethod] [TestMethod]
@@ -176,10 +164,8 @@ namespace AMWD.Protocols.Modbus.Tests.Serial
_serialPortMock.VerifyNoOtherCalls(); _serialPortMock.VerifyNoOtherCalls();
} }
[DataTestMethod] [TestMethod]
[DataRow(false)] public async Task ShouldOpenAndCloseOnInvokeAsyncOnLinuxNotModifyingDriver()
[DataRow(true)]
public async Task ShouldOpenAndCloseOnInvokeAsync(bool modifyDriver)
{ {
// Arrange // Arrange
_alwaysOpen = false; _alwaysOpen = false;
@@ -193,8 +179,9 @@ namespace AMWD.Protocols.Modbus.Tests.Serial
_serialLineResponseQueue.Enqueue(expectedResponse); _serialLineResponseQueue.Enqueue(expectedResponse);
var connection = GetSerialConnection(); var connection = GetSerialConnection();
connection.GetType().GetField("_isLinux", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(connection, true);
connection.IdleTimeout = TimeSpan.FromMilliseconds(200); connection.IdleTimeout = TimeSpan.FromMilliseconds(200);
connection.DriverEnabledRS485 = modifyDriver; connection.DriverEnabledRS485 = false;
// Act // Act
var response = await connection.InvokeAsync(request, validation); var response = await connection.InvokeAsync(request, validation);
@@ -213,11 +200,50 @@ namespace AMWD.Protocols.Modbus.Tests.Serial
_serialPortMock.Verify(c => c.ResetRS485DriverStateFlags(), Times.Exactly(2)); _serialPortMock.Verify(c => c.ResetRS485DriverStateFlags(), Times.Exactly(2));
_serialPortMock.Verify(c => c.Open(), Times.Once); _serialPortMock.Verify(c => c.Open(), Times.Once);
if (modifyDriver) _serialPortMock.Verify(ns => ns.WriteAsync(It.IsAny<byte[]>(), It.IsAny<CancellationToken>()), Times.Once);
_serialPortMock.Verify(ns => ns.ReadAsync(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<CancellationToken>()), Times.Once);
_serialPortMock.VerifyNoOtherCalls();
}
[TestMethod]
public async Task ShouldOpenAndCloseOnInvokeAsyncOnLinuxModifyingDriver()
{ {
// Arrange
_alwaysOpen = false;
_isOpenQueue.Enqueue(false);
_isOpenQueue.Enqueue(true);
_isOpenQueue.Enqueue(true);
byte[] request = [1, 2, 3];
byte[] expectedResponse = [9, 8, 7];
var validation = new Func<IReadOnlyList<byte>, bool>(_ => true);
_serialLineResponseQueue.Enqueue(expectedResponse);
var connection = GetSerialConnection();
connection.GetType().GetField("_isLinux", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(connection, true);
connection.IdleTimeout = TimeSpan.FromMilliseconds(200);
connection.DriverEnabledRS485 = true;
// Act
var response = await connection.InvokeAsync(request, validation);
await Task.Delay(500);
// Assert
Assert.IsNotNull(response);
CollectionAssert.AreEqual(expectedResponse, response.ToArray());
CollectionAssert.AreEqual(request, _serialLineRequestCallbacks.First());
_serialPortMock.VerifyGet(c => c.ReadTimeout, Times.Once);
_serialPortMock.Verify(c => c.IsOpen, Times.Exactly(3));
_serialPortMock.Verify(c => c.Close(), Times.Exactly(2));
_serialPortMock.Verify(c => c.ResetRS485DriverStateFlags(), Times.Exactly(2));
_serialPortMock.Verify(c => c.Open(), Times.Once);
_serialPortMock.Verify(c => c.GetRS485DriverStateFlags(), Times.Once); _serialPortMock.Verify(c => c.GetRS485DriverStateFlags(), Times.Once);
_serialPortMock.Verify(c => c.ChangeRS485DriverStateFlags(It.IsAny<RS485Flags>()), Times.Once); _serialPortMock.Verify(c => c.ChangeRS485DriverStateFlags(It.IsAny<RS485Flags>()), Times.Once);
}
_serialPortMock.Verify(ns => ns.WriteAsync(It.IsAny<byte[]>(), It.IsAny<CancellationToken>()), Times.Once); _serialPortMock.Verify(ns => ns.WriteAsync(It.IsAny<byte[]>(), It.IsAny<CancellationToken>()), Times.Once);
_serialPortMock.Verify(ns => ns.ReadAsync(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<CancellationToken>()), Times.Once); _serialPortMock.Verify(ns => ns.ReadAsync(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<CancellationToken>()), Times.Once);
@@ -226,7 +252,90 @@ namespace AMWD.Protocols.Modbus.Tests.Serial
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(EndOfStreamException))] public async Task ShouldOpenAndCloseOnInvokeAsyncOnOtherOsNotModifyingDriver()
{
// Arrange
_alwaysOpen = false;
_isOpenQueue.Enqueue(false);
_isOpenQueue.Enqueue(true);
_isOpenQueue.Enqueue(true);
byte[] request = [1, 2, 3];
byte[] expectedResponse = [9, 8, 7];
var validation = new Func<IReadOnlyList<byte>, bool>(_ => true);
_serialLineResponseQueue.Enqueue(expectedResponse);
var connection = GetSerialConnection();
connection.GetType().GetField("_isLinux", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(connection, false);
connection.IdleTimeout = TimeSpan.FromMilliseconds(200);
connection.DriverEnabledRS485 = false;
// Act
var response = await connection.InvokeAsync(request, validation);
await Task.Delay(500);
// Assert
Assert.IsNotNull(response);
CollectionAssert.AreEqual(expectedResponse, response.ToArray());
CollectionAssert.AreEqual(request, _serialLineRequestCallbacks.First());
_serialPortMock.VerifyGet(c => c.ReadTimeout, Times.Once);
_serialPortMock.Verify(c => c.IsOpen, Times.Exactly(3));
_serialPortMock.Verify(c => c.Close(), Times.Exactly(2));
_serialPortMock.Verify(c => c.ResetRS485DriverStateFlags(), Times.Exactly(2));
_serialPortMock.Verify(c => c.Open(), Times.Once);
_serialPortMock.Verify(ns => ns.WriteAsync(It.IsAny<byte[]>(), It.IsAny<CancellationToken>()), Times.Once);
_serialPortMock.Verify(ns => ns.ReadAsync(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<CancellationToken>()), Times.Once);
_serialPortMock.VerifyNoOtherCalls();
}
[TestMethod]
public async Task ShouldOpenAndCloseOnInvokeAsyncOnOtherOsModifyingDriver()
{
// Arrange
_alwaysOpen = false;
_isOpenQueue.Enqueue(false);
_isOpenQueue.Enqueue(true);
_isOpenQueue.Enqueue(true);
byte[] request = [1, 2, 3];
byte[] expectedResponse = [9, 8, 7];
var validation = new Func<IReadOnlyList<byte>, bool>(_ => true);
_serialLineResponseQueue.Enqueue(expectedResponse);
var connection = GetSerialConnection();
connection.GetType().GetField("_isLinux", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(connection, false);
connection.IdleTimeout = TimeSpan.FromMilliseconds(200);
connection.DriverEnabledRS485 = true;
// Act
var response = await connection.InvokeAsync(request, validation);
await Task.Delay(500);
// Assert
Assert.IsNotNull(response);
CollectionAssert.AreEqual(expectedResponse, response.ToArray());
CollectionAssert.AreEqual(request, _serialLineRequestCallbacks.First());
_serialPortMock.VerifyGet(c => c.ReadTimeout, Times.Once);
_serialPortMock.Verify(c => c.IsOpen, Times.Exactly(3));
_serialPortMock.Verify(c => c.Close(), Times.Exactly(2));
_serialPortMock.Verify(c => c.ResetRS485DriverStateFlags(), Times.Exactly(2));
_serialPortMock.Verify(c => c.Open(), Times.Once);
_serialPortMock.Verify(ns => ns.WriteAsync(It.IsAny<byte[]>(), It.IsAny<CancellationToken>()), Times.Once);
_serialPortMock.Verify(ns => ns.ReadAsync(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<CancellationToken>()), Times.Once);
_serialPortMock.VerifyNoOtherCalls();
}
[TestMethod]
public async Task ShouldThrowEndOfStreamExceptionOnInvokeAsync() public async Task ShouldThrowEndOfStreamExceptionOnInvokeAsync()
{ {
// Arrange // Arrange
@@ -235,10 +344,8 @@ namespace AMWD.Protocols.Modbus.Tests.Serial
var connection = GetConnection(); var connection = GetConnection();
// Act // Act + Assert
var response = await connection.InvokeAsync(request, validation); await Assert.ThrowsExceptionAsync<EndOfStreamException>(() => connection.InvokeAsync(request, validation));
// Assert - EndOfStreamException
} }
[TestMethod] [TestMethod]
@@ -320,7 +427,6 @@ namespace AMWD.Protocols.Modbus.Tests.Serial
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(TaskCanceledException))]
public async Task ShouldThrowTaskCancelledExceptionForDisposeOnInvokeAsync() public async Task ShouldThrowTaskCancelledExceptionForDisposeOnInvokeAsync()
{ {
// Arrange // Arrange
@@ -332,16 +438,16 @@ namespace AMWD.Protocols.Modbus.Tests.Serial
.Setup(ns => ns.WriteAsync(It.IsAny<byte[]>(), It.IsAny<CancellationToken>())) .Setup(ns => ns.WriteAsync(It.IsAny<byte[]>(), It.IsAny<CancellationToken>()))
.Returns(Task.Delay(100)); .Returns(Task.Delay(100));
// Act // Act + Assert
await Assert.ThrowsExceptionAsync<TaskCanceledException>(async () =>
{
var task = connection.InvokeAsync(request, validation); var task = connection.InvokeAsync(request, validation);
connection.Dispose(); connection.Dispose();
await task; await task;
});
// Assert - TaskCancelledException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(TaskCanceledException))]
public async Task ShouldThrowTaskCancelledExceptionForCancelOnInvokeAsync() public async Task ShouldThrowTaskCancelledExceptionForCancelOnInvokeAsync()
{ {
// Arrange // Arrange
@@ -354,12 +460,13 @@ namespace AMWD.Protocols.Modbus.Tests.Serial
.Setup(ns => ns.WriteAsync(It.IsAny<byte[]>(), It.IsAny<CancellationToken>())) .Setup(ns => ns.WriteAsync(It.IsAny<byte[]>(), It.IsAny<CancellationToken>()))
.Returns(Task.Delay(100)); .Returns(Task.Delay(100));
// Act // Act + Assert
await Assert.ThrowsExceptionAsync<TaskCanceledException>(async () =>
{
var task = connection.InvokeAsync(request, validation, cts.Token); var task = connection.InvokeAsync(request, validation, cts.Token);
cts.Cancel(); cts.Cancel();
await task; await task;
});
// Assert - TaskCancelledException
} }
[TestMethod] [TestMethod]
@@ -375,7 +482,7 @@ namespace AMWD.Protocols.Modbus.Tests.Serial
var connection = GetConnection(); var connection = GetConnection();
_serialPortMock _serialPortMock
.Setup(ns => ns.WriteAsync(It.IsAny<byte[]>(), It.IsAny<CancellationToken>())) .Setup(ns => ns.WriteAsync(It.IsAny<byte[]>(), It.IsAny<CancellationToken>()))
.Callback<byte[], CancellationToken>((req, _) => _serialLineRequestCallbacks.Add(req.ToArray())) .Callback<byte[], CancellationToken>((req, _) => _serialLineRequestCallbacks.Add([.. req]))
.Returns(Task.Delay(100)); .Returns(Task.Delay(100));
// Act // Act
@@ -418,7 +525,7 @@ namespace AMWD.Protocols.Modbus.Tests.Serial
var connection = GetConnection(); var connection = GetConnection();
_serialPortMock _serialPortMock
.Setup(ns => ns.WriteAsync(It.IsAny<byte[]>(), It.IsAny<CancellationToken>())) .Setup(ns => ns.WriteAsync(It.IsAny<byte[]>(), It.IsAny<CancellationToken>()))
.Callback<byte[], CancellationToken>((req, _) => _serialLineRequestCallbacks.Add(req.ToArray())) .Callback<byte[], CancellationToken>((req, _) => _serialLineRequestCallbacks.Add([.. req]))
.Returns(Task.Delay(100)); .Returns(Task.Delay(100));
// Act // Act
@@ -489,9 +596,6 @@ namespace AMWD.Protocols.Modbus.Tests.Serial
(connectionField.GetValue(connection) as SerialPortWrapper)?.Dispose(); (connectionField.GetValue(connection) as SerialPortWrapper)?.Dispose();
connectionField.SetValue(connection, _serialPortMock.Object); connectionField.SetValue(connection, _serialPortMock.Object);
// Set unit test mode
connection.GetType().GetField("_isUnitTest", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(connection, true);
return connection; return connection;
} }
} }

View File

@@ -162,5 +162,18 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
_tcpConnectionMock.VerifyNoOtherCalls(); _tcpConnectionMock.VerifyNoOtherCalls();
} }
[TestMethod]
public void ShouldPrintCleanString()
{
// Arrange
using var client = new ModbusTcpClient(_tcpConnectionMock.Object);
// Act
string str = client.ToString();
// Assert
SnapshotAssert.AreEqual(str);
}
} }
} }

View File

@@ -80,31 +80,25 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
[DataRow(null)] [DataRow(null)]
[DataRow("")] [DataRow("")]
[DataRow(" ")] [DataRow(" ")]
[ExpectedException(typeof(ArgumentNullException))]
public void ShouldThrowArgumentNullExceptionForInvalidHostname(string hostname) public void ShouldThrowArgumentNullExceptionForInvalidHostname(string hostname)
{ {
// Arrange // Arrange
var connection = GetTcpConnection(); var connection = GetTcpConnection();
// Act // Act + Assert
connection.Hostname = hostname; Assert.ThrowsException<ArgumentNullException>(() => connection.Hostname = hostname);
// Assert - ArgumentNullException
} }
[DataTestMethod] [DataTestMethod]
[DataRow(0)] [DataRow(0)]
[DataRow(65536)] [DataRow(65536)]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowArgumentOutOfRangeExceptionForInvalidPort(int port) public void ShouldThrowArgumentOutOfRangeExceptionForInvalidPort(int port)
{ {
// Arrange // Arrange
var connection = GetTcpConnection(); var connection = GetTcpConnection();
// Act // Act + Assert
connection.Port = port; Assert.ThrowsException<ArgumentOutOfRangeException>(() => connection.Port = port);
// Assert - ArgumentOutOfRangeException
} }
[TestMethod] [TestMethod]
@@ -119,46 +113,37 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ObjectDisposedException))]
public async Task ShouldThrowDisposedExceptionOnInvokeAsync() public async Task ShouldThrowDisposedExceptionOnInvokeAsync()
{ {
// Arrange // Arrange
var connection = GetConnection(); var connection = GetConnection();
connection.Dispose(); connection.Dispose();
// Act // Act + Assert
await connection.InvokeAsync(null, null); await Assert.ThrowsExceptionAsync<ObjectDisposedException>(() => connection.InvokeAsync(null, null));
// Assert - OjbectDisposedException
} }
[DataTestMethod] [DataTestMethod]
[DataRow(null)] [DataRow(null)]
[DataRow(new byte[0])] [DataRow(new byte[0])]
[ExpectedException(typeof(ArgumentNullException))]
public async Task ShouldThrowArgumentNullExceptionForMissingRequestOnInvokeAsync(byte[] request) public async Task ShouldThrowArgumentNullExceptionForMissingRequestOnInvokeAsync(byte[] request)
{ {
// Arrange // Arrange
var connection = GetConnection(); var connection = GetConnection();
// Act // Act + Assert
await connection.InvokeAsync(request, null); await Assert.ThrowsExceptionAsync<ArgumentNullException>(() => connection.InvokeAsync(request, null));
// Assert - ArgumentNullException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public async Task ShouldThrowArgumentNullExceptionForMissingValidationOnInvokeAsync() public async Task ShouldThrowArgumentNullExceptionForMissingValidationOnInvokeAsync()
{ {
// Arrange // Arrange
byte[] request = new byte[1]; byte[] request = new byte[1];
var connection = GetConnection(); var connection = GetConnection();
// Act // Act + Assert
await connection.InvokeAsync(request, null); await Assert.ThrowsExceptionAsync<ArgumentNullException>(() => connection.InvokeAsync(request, null));
// Assert - ArgumentNullException
} }
[TestMethod] [TestMethod]
@@ -235,7 +220,6 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(EndOfStreamException))]
public async Task ShouldThrowEndOfStreamExceptionOnInvokeAsync() public async Task ShouldThrowEndOfStreamExceptionOnInvokeAsync()
{ {
// Arrange // Arrange
@@ -244,14 +228,11 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
var connection = GetConnection(); var connection = GetConnection();
// Act // Act + Assert
var response = await connection.InvokeAsync(request, validation); await Assert.ThrowsExceptionAsync<EndOfStreamException>(() => connection.InvokeAsync(request, validation));
// Assert - EndOfStreamException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ApplicationException))]
public async Task ShouldThrowApplicationExceptionWhenHostNotResolvableOnInvokeAsync() public async Task ShouldThrowApplicationExceptionWhenHostNotResolvableOnInvokeAsync()
{ {
// Arrange // Arrange
@@ -264,10 +245,8 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
var connection = GetConnection(); var connection = GetConnection();
connection.GetType().GetField("_hostname", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(connection, ""); connection.GetType().GetField("_hostname", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(connection, "");
// Act // Act + Assert
var response = await connection.InvokeAsync(request, validation); await Assert.ThrowsExceptionAsync<ApplicationException>(() => connection.InvokeAsync(request, validation));
// Assert - ApplicationException
} }
[TestMethod] [TestMethod]
@@ -351,8 +330,7 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(TaskCanceledException))] public async Task ShouldThrowTaskCanceledExceptionForDisposeOnInvokeAsync()
public async Task ShouldThrowTaskCancelledExceptionForDisposeOnInvokeAsync()
{ {
// Arrange // Arrange
byte[] request = [1, 2, 3]; byte[] request = [1, 2, 3];
@@ -363,17 +341,17 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
.Setup(ns => ns.WriteAsync(It.IsAny<ReadOnlyMemory<byte>>(), It.IsAny<CancellationToken>())) .Setup(ns => ns.WriteAsync(It.IsAny<ReadOnlyMemory<byte>>(), It.IsAny<CancellationToken>()))
.Returns(new ValueTask(Task.Delay(100))); .Returns(new ValueTask(Task.Delay(100)));
// Act // Act + Assert
await Assert.ThrowsExceptionAsync<TaskCanceledException>(async () =>
{
var task = connection.InvokeAsync(request, validation); var task = connection.InvokeAsync(request, validation);
connection.Dispose(); connection.Dispose();
await task; await task;
});
// Assert - TaskCancelledException
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(TaskCanceledException))] public async Task ShouldThrowTaskCanceledExceptionForCancelOnInvokeAsync()
public async Task ShouldThrowTaskCancelledExceptionForCancelOnInvokeAsync()
{ {
// Arrange // Arrange
byte[] request = [1, 2, 3]; byte[] request = [1, 2, 3];
@@ -385,12 +363,13 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
.Setup(ns => ns.WriteAsync(It.IsAny<ReadOnlyMemory<byte>>(), It.IsAny<CancellationToken>())) .Setup(ns => ns.WriteAsync(It.IsAny<ReadOnlyMemory<byte>>(), It.IsAny<CancellationToken>()))
.Returns(new ValueTask(Task.Delay(100))); .Returns(new ValueTask(Task.Delay(100)));
// Act // Act + Assert
await Assert.ThrowsExceptionAsync<TaskCanceledException>(async () =>
{
var task = connection.InvokeAsync(request, validation, cts.Token); var task = connection.InvokeAsync(request, validation, cts.Token);
cts.Cancel(); cts.Cancel();
await task; await task;
});
// Assert - TaskCancelledException
} }
[TestMethod] [TestMethod]

View File

@@ -143,7 +143,6 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
await proxy.StopAsync(); await proxy.StopAsync();
// Assert // Assert
_tcpListenerMock.VerifyGet(m => m.Socket, Times.Once);
_tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once); _tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once);
_ipEndPointMock.VerifyGet(m => m.Address, Times.Once); _ipEndPointMock.VerifyGet(m => m.Address, Times.Once);
@@ -151,21 +150,40 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
_tcpListenerMock.Verify(m => m.Stop(), Times.Exactly(2)); _tcpListenerMock.Verify(m => m.Stop(), Times.Exactly(2));
_tcpListenerMock.Verify(m => m.AcceptTcpClientAsync(It.IsAny<CancellationToken>()), Times.Once); _tcpListenerMock.Verify(m => m.AcceptTcpClientAsync(It.IsAny<CancellationToken>()), Times.Once);
_socketMock.VerifySet(m => m.DualMode = false, Times.Once); VerifyNoOtherCalls();
}
[TestMethod]
public async Task ShouldSetSocketToDualModeOnIpV6()
{
// Arrange
_connectClient = false;
using var proxy = GetProxy(IPAddress.IPv6Loopback);
// Act
await proxy.StartAsync();
await proxy.StopAsync();
// Assert
_tcpListenerMock.VerifyGet(m => m.Socket, Times.Once);
_tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once);
_ipEndPointMock.VerifyGet(m => m.Address, Times.Once);
_socketMock.VerifySet(m => m.DualMode = true, Times.Once);
_tcpListenerMock.Verify(m => m.Start(), Times.Once);
_tcpListenerMock.Verify(m => m.Stop(), Times.Exactly(2));
_tcpListenerMock.Verify(m => m.AcceptTcpClientAsync(It.IsAny<CancellationToken>()), Times.Once);
VerifyNoOtherCalls(); VerifyNoOtherCalls();
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void ShouldThrowArgumentNullExceptionOnCreateInstanceForClient() public void ShouldThrowArgumentNullExceptionOnCreateInstanceForClient()
{ {
// Arrange // Arrange
// Act // Act + Assert
new ModbusTcpProxy(null, IPAddress.Loopback); Assert.ThrowsException<ArgumentNullException>(() => new ModbusTcpProxy(null, IPAddress.Loopback));
// Assert - ArgumentNullException
} }
[TestMethod] [TestMethod]
@@ -212,17 +230,14 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
} }
[TestMethod] [TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ShouldThrowArgumentOutOfRangeExceptionForInvalidTimeout() public void ShouldThrowArgumentOutOfRangeExceptionForInvalidTimeout()
{ {
// Arrange // Arrange
_connectClient = false; _connectClient = false;
using var proxy = GetProxy(); using var proxy = GetProxy();
// Act // Act + Assert
proxy.ReadWriteTimeout = TimeSpan.FromSeconds(-3); Assert.ThrowsException<ArgumentOutOfRangeException>(() => proxy.ReadWriteTimeout = TimeSpan.FromSeconds(-3));
// Assert - ArgumentOutOfRangeException
} }
[TestMethod] [TestMethod]
@@ -244,7 +259,6 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
await Task.Delay(100); await Task.Delay(100);
// Assert // Assert
_tcpListenerMock.VerifyGet(m => m.Socket, Times.Once);
_tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once); _tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once);
_tcpListenerMock.Verify(m => m.Start(), Times.Once); _tcpListenerMock.Verify(m => m.Start(), Times.Once);
@@ -252,7 +266,6 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
_tcpListenerMock.Verify(m => m.AcceptTcpClientAsync(It.IsAny<CancellationToken>()), Times.AtLeast(1)); _tcpListenerMock.Verify(m => m.AcceptTcpClientAsync(It.IsAny<CancellationToken>()), Times.AtLeast(1));
_ipEndPointMock.VerifyGet(m => m.Address, Times.Once); _ipEndPointMock.VerifyGet(m => m.Address, Times.Once);
_socketMock.VerifySet(m => m.DualMode = false, Times.Once);
VerifyNoOtherCalls(); VerifyNoOtherCalls();
} }
@@ -269,10 +282,8 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
await Task.Delay(100); await Task.Delay(100);
// Assert // Assert
_tcpListenerMock.VerifyGet(m => m.Socket, Times.Once);
_tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once); _tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once);
_ipEndPointMock.VerifyGet(m => m.Address, Times.Once); _ipEndPointMock.VerifyGet(m => m.Address, Times.Once);
_socketMock.VerifySet(m => m.DualMode = false, Times.Once);
_tcpListenerMock.Verify(m => m.Start(), Times.Once); _tcpListenerMock.Verify(m => m.Start(), Times.Once);
_tcpListenerMock.Verify(m => m.Stop(), Times.Once); _tcpListenerMock.Verify(m => m.Stop(), Times.Once);
@@ -300,10 +311,8 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
await Task.Delay(100); await Task.Delay(100);
// Assert // Assert
_tcpListenerMock.VerifyGet(m => m.Socket, Times.Once);
_tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once); _tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once);
_ipEndPointMock.VerifyGet(m => m.Address, Times.Once); _ipEndPointMock.VerifyGet(m => m.Address, Times.Once);
_socketMock.VerifySet(m => m.DualMode = false, Times.Once);
_tcpListenerMock.Verify(m => m.Start(), Times.Once); _tcpListenerMock.Verify(m => m.Start(), Times.Once);
_tcpListenerMock.Verify(m => m.Stop(), Times.Once); _tcpListenerMock.Verify(m => m.Stop(), Times.Once);
@@ -347,10 +356,8 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
await Task.Delay(100); await Task.Delay(100);
// Assert // Assert
_tcpListenerMock.VerifyGet(m => m.Socket, Times.Once);
_tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once); _tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once);
_ipEndPointMock.VerifyGet(m => m.Address, Times.Once); _ipEndPointMock.VerifyGet(m => m.Address, Times.Once);
_socketMock.VerifySet(m => m.DualMode = false, Times.Once);
_tcpListenerMock.Verify(m => m.Start(), Times.Once); _tcpListenerMock.Verify(m => m.Start(), Times.Once);
_tcpListenerMock.Verify(m => m.Stop(), Times.Once); _tcpListenerMock.Verify(m => m.Stop(), Times.Once);
@@ -388,10 +395,8 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
await Task.Delay(100); await Task.Delay(100);
// Assert // Assert
_tcpListenerMock.VerifyGet(m => m.Socket, Times.Once);
_tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once); _tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once);
_ipEndPointMock.VerifyGet(m => m.Address, Times.Once); _ipEndPointMock.VerifyGet(m => m.Address, Times.Once);
_socketMock.VerifySet(m => m.DualMode = false, Times.Once);
_tcpListenerMock.Verify(m => m.Start(), Times.Once); _tcpListenerMock.Verify(m => m.Start(), Times.Once);
_tcpListenerMock.Verify(m => m.Stop(), Times.Once); _tcpListenerMock.Verify(m => m.Stop(), Times.Once);
@@ -425,10 +430,8 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
await Task.Delay(100); await Task.Delay(100);
// Assert // Assert
_tcpListenerMock.VerifyGet(m => m.Socket, Times.Once);
_tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once); _tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once);
_ipEndPointMock.VerifyGet(m => m.Address, Times.Once); _ipEndPointMock.VerifyGet(m => m.Address, Times.Once);
_socketMock.VerifySet(m => m.DualMode = false, Times.Once);
_tcpListenerMock.Verify(m => m.Start(), Times.Once); _tcpListenerMock.Verify(m => m.Start(), Times.Once);
_tcpListenerMock.Verify(m => m.Stop(), Times.Once); _tcpListenerMock.Verify(m => m.Stop(), Times.Once);
@@ -477,10 +480,8 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
await Task.Delay(100); await Task.Delay(100);
// Assert // Assert
_tcpListenerMock.VerifyGet(m => m.Socket, Times.Once);
_tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once); _tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once);
_ipEndPointMock.VerifyGet(m => m.Address, Times.Once); _ipEndPointMock.VerifyGet(m => m.Address, Times.Once);
_socketMock.VerifySet(m => m.DualMode = false, Times.Once);
_tcpListenerMock.Verify(m => m.Start(), Times.Once); _tcpListenerMock.Verify(m => m.Start(), Times.Once);
_tcpListenerMock.Verify(m => m.Stop(), Times.Once); _tcpListenerMock.Verify(m => m.Stop(), Times.Once);
@@ -518,10 +519,8 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
await Task.Delay(100); await Task.Delay(100);
// Assert // Assert
_tcpListenerMock.VerifyGet(m => m.Socket, Times.Once);
_tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once); _tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once);
_ipEndPointMock.VerifyGet(m => m.Address, Times.Once); _ipEndPointMock.VerifyGet(m => m.Address, Times.Once);
_socketMock.VerifySet(m => m.DualMode = false, Times.Once);
_tcpListenerMock.Verify(m => m.Start(), Times.Once); _tcpListenerMock.Verify(m => m.Start(), Times.Once);
_tcpListenerMock.Verify(m => m.Stop(), Times.Once); _tcpListenerMock.Verify(m => m.Stop(), Times.Once);
@@ -555,10 +554,8 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
await Task.Delay(100); await Task.Delay(100);
// Assert // Assert
_tcpListenerMock.VerifyGet(m => m.Socket, Times.Once);
_tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once); _tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once);
_ipEndPointMock.VerifyGet(m => m.Address, Times.Once); _ipEndPointMock.VerifyGet(m => m.Address, Times.Once);
_socketMock.VerifySet(m => m.DualMode = false, Times.Once);
_tcpListenerMock.Verify(m => m.Start(), Times.Once); _tcpListenerMock.Verify(m => m.Start(), Times.Once);
_tcpListenerMock.Verify(m => m.Stop(), Times.Once); _tcpListenerMock.Verify(m => m.Stop(), Times.Once);
@@ -605,10 +602,8 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
await Task.Delay(100); await Task.Delay(100);
// Assert // Assert
_tcpListenerMock.VerifyGet(m => m.Socket, Times.Once);
_tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once); _tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once);
_ipEndPointMock.VerifyGet(m => m.Address, Times.Once); _ipEndPointMock.VerifyGet(m => m.Address, Times.Once);
_socketMock.VerifySet(m => m.DualMode = false, Times.Once);
_tcpListenerMock.Verify(m => m.Start(), Times.Once); _tcpListenerMock.Verify(m => m.Start(), Times.Once);
_tcpListenerMock.Verify(m => m.Stop(), Times.Once); _tcpListenerMock.Verify(m => m.Stop(), Times.Once);
@@ -646,10 +641,8 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
await Task.Delay(100); await Task.Delay(100);
// Assert // Assert
_tcpListenerMock.VerifyGet(m => m.Socket, Times.Once);
_tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once); _tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once);
_ipEndPointMock.VerifyGet(m => m.Address, Times.Once); _ipEndPointMock.VerifyGet(m => m.Address, Times.Once);
_socketMock.VerifySet(m => m.DualMode = false, Times.Once);
_tcpListenerMock.Verify(m => m.Start(), Times.Once); _tcpListenerMock.Verify(m => m.Start(), Times.Once);
_tcpListenerMock.Verify(m => m.Stop(), Times.Once); _tcpListenerMock.Verify(m => m.Stop(), Times.Once);
@@ -683,10 +676,8 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
await Task.Delay(100); await Task.Delay(100);
// Assert // Assert
_tcpListenerMock.VerifyGet(m => m.Socket, Times.Once);
_tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once); _tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once);
_ipEndPointMock.VerifyGet(m => m.Address, Times.Once); _ipEndPointMock.VerifyGet(m => m.Address, Times.Once);
_socketMock.VerifySet(m => m.DualMode = false, Times.Once);
_tcpListenerMock.Verify(m => m.Start(), Times.Once); _tcpListenerMock.Verify(m => m.Start(), Times.Once);
_tcpListenerMock.Verify(m => m.Stop(), Times.Once); _tcpListenerMock.Verify(m => m.Stop(), Times.Once);
@@ -733,10 +724,8 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
await Task.Delay(100); await Task.Delay(100);
// Assert // Assert
_tcpListenerMock.VerifyGet(m => m.Socket, Times.Once);
_tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once); _tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once);
_ipEndPointMock.VerifyGet(m => m.Address, Times.Once); _ipEndPointMock.VerifyGet(m => m.Address, Times.Once);
_socketMock.VerifySet(m => m.DualMode = false, Times.Once);
_tcpListenerMock.Verify(m => m.Start(), Times.Once); _tcpListenerMock.Verify(m => m.Start(), Times.Once);
_tcpListenerMock.Verify(m => m.Stop(), Times.Once); _tcpListenerMock.Verify(m => m.Stop(), Times.Once);
@@ -774,10 +763,8 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
await Task.Delay(100); await Task.Delay(100);
// Assert // Assert
_tcpListenerMock.VerifyGet(m => m.Socket, Times.Once);
_tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once); _tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once);
_ipEndPointMock.VerifyGet(m => m.Address, Times.Once); _ipEndPointMock.VerifyGet(m => m.Address, Times.Once);
_socketMock.VerifySet(m => m.DualMode = false, Times.Once);
_tcpListenerMock.Verify(m => m.Start(), Times.Once); _tcpListenerMock.Verify(m => m.Start(), Times.Once);
_tcpListenerMock.Verify(m => m.Stop(), Times.Once); _tcpListenerMock.Verify(m => m.Stop(), Times.Once);
@@ -811,10 +798,8 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
await Task.Delay(100); await Task.Delay(100);
// Assert // Assert
_tcpListenerMock.VerifyGet(m => m.Socket, Times.Once);
_tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once); _tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once);
_ipEndPointMock.VerifyGet(m => m.Address, Times.Once); _ipEndPointMock.VerifyGet(m => m.Address, Times.Once);
_socketMock.VerifySet(m => m.DualMode = false, Times.Once);
_tcpListenerMock.Verify(m => m.Start(), Times.Once); _tcpListenerMock.Verify(m => m.Start(), Times.Once);
_tcpListenerMock.Verify(m => m.Stop(), Times.Once); _tcpListenerMock.Verify(m => m.Stop(), Times.Once);
@@ -862,10 +847,8 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
await Task.Delay(100); await Task.Delay(100);
// Assert // Assert
_tcpListenerMock.VerifyGet(m => m.Socket, Times.Once);
_tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once); _tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once);
_ipEndPointMock.VerifyGet(m => m.Address, Times.Once); _ipEndPointMock.VerifyGet(m => m.Address, Times.Once);
_socketMock.VerifySet(m => m.DualMode = false, Times.Once);
_tcpListenerMock.Verify(m => m.Start(), Times.Once); _tcpListenerMock.Verify(m => m.Start(), Times.Once);
_tcpListenerMock.Verify(m => m.Stop(), Times.Once); _tcpListenerMock.Verify(m => m.Stop(), Times.Once);
@@ -886,6 +869,7 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
Assert.AreEqual(ModbusDeviceIdentificationObject.VendorName, objectId); Assert.AreEqual(ModbusDeviceIdentificationObject.VendorName, objectId);
CollectionAssert.AreEqual(expectedResponse, _responseBytesCallbacks.First()); CollectionAssert.AreEqual(expectedResponse, _responseBytesCallbacks.First());
SnapshotAssert.AreEqual(_clientDeviceIdentificationResponse.ToString());
} }
[TestMethod] [TestMethod]
@@ -903,10 +887,8 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
await Task.Delay(100); await Task.Delay(100);
// Assert // Assert
_tcpListenerMock.VerifyGet(m => m.Socket, Times.Once);
_tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once); _tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once);
_ipEndPointMock.VerifyGet(m => m.Address, Times.Once); _ipEndPointMock.VerifyGet(m => m.Address, Times.Once);
_socketMock.VerifySet(m => m.DualMode = false, Times.Once);
_tcpListenerMock.Verify(m => m.Start(), Times.Once); _tcpListenerMock.Verify(m => m.Start(), Times.Once);
_tcpListenerMock.Verify(m => m.Stop(), Times.Once); _tcpListenerMock.Verify(m => m.Stop(), Times.Once);
@@ -935,10 +917,8 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
await Task.Delay(100); await Task.Delay(100);
// Assert // Assert
_tcpListenerMock.VerifyGet(m => m.Socket, Times.Once);
_tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once); _tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once);
_ipEndPointMock.VerifyGet(m => m.Address, Times.Once); _ipEndPointMock.VerifyGet(m => m.Address, Times.Once);
_socketMock.VerifySet(m => m.DualMode = false, Times.Once);
_tcpListenerMock.Verify(m => m.Start(), Times.Once); _tcpListenerMock.Verify(m => m.Start(), Times.Once);
_tcpListenerMock.Verify(m => m.Stop(), Times.Once); _tcpListenerMock.Verify(m => m.Stop(), Times.Once);
@@ -970,10 +950,8 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
await Task.Delay(100); await Task.Delay(100);
// Assert // Assert
_tcpListenerMock.VerifyGet(m => m.Socket, Times.Once);
_tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once); _tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once);
_ipEndPointMock.VerifyGet(m => m.Address, Times.Once); _ipEndPointMock.VerifyGet(m => m.Address, Times.Once);
_socketMock.VerifySet(m => m.DualMode = false, Times.Once);
_tcpListenerMock.Verify(m => m.Start(), Times.Once); _tcpListenerMock.Verify(m => m.Start(), Times.Once);
_tcpListenerMock.Verify(m => m.Stop(), Times.Once); _tcpListenerMock.Verify(m => m.Stop(), Times.Once);
@@ -1005,10 +983,9 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
await Task.Delay(100); await Task.Delay(100);
// Assert // Assert
_tcpListenerMock.VerifyGet(m => m.Socket, Times.Once);
_tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once); _tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once);
_ipEndPointMock.VerifyGet(m => m.Address, Times.Once); _ipEndPointMock.VerifyGet(m => m.Address, Times.Once);
_socketMock.VerifySet(m => m.DualMode = false, Times.Once);
_tcpListenerMock.Verify(m => m.Start(), Times.Once); _tcpListenerMock.Verify(m => m.Start(), Times.Once);
_tcpListenerMock.Verify(m => m.Stop(), Times.Once); _tcpListenerMock.Verify(m => m.Stop(), Times.Once);
@@ -1046,10 +1023,8 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
await Task.Delay(100); await Task.Delay(100);
// Assert // Assert
_tcpListenerMock.VerifyGet(m => m.Socket, Times.Once);
_tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once); _tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once);
_ipEndPointMock.VerifyGet(m => m.Address, Times.Once); _ipEndPointMock.VerifyGet(m => m.Address, Times.Once);
_socketMock.VerifySet(m => m.DualMode = false, Times.Once);
_tcpListenerMock.Verify(m => m.Start(), Times.Once); _tcpListenerMock.Verify(m => m.Start(), Times.Once);
_tcpListenerMock.Verify(m => m.Stop(), Times.Once); _tcpListenerMock.Verify(m => m.Stop(), Times.Once);
@@ -1094,10 +1069,8 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
await Task.Delay(100); await Task.Delay(100);
// Assert // Assert
_tcpListenerMock.VerifyGet(m => m.Socket, Times.Once);
_tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once); _tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once);
_ipEndPointMock.VerifyGet(m => m.Address, Times.Once); _ipEndPointMock.VerifyGet(m => m.Address, Times.Once);
_socketMock.VerifySet(m => m.DualMode = false, Times.Once);
_tcpListenerMock.Verify(m => m.Start(), Times.Once); _tcpListenerMock.Verify(m => m.Start(), Times.Once);
_tcpListenerMock.Verify(m => m.Stop(), Times.Once); _tcpListenerMock.Verify(m => m.Stop(), Times.Once);
@@ -1151,10 +1124,8 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
await Task.Delay(100); await Task.Delay(100);
// Assert // Assert
_tcpListenerMock.VerifyGet(m => m.Socket, Times.Once);
_tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once); _tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once);
_ipEndPointMock.VerifyGet(m => m.Address, Times.Once); _ipEndPointMock.VerifyGet(m => m.Address, Times.Once);
_socketMock.VerifySet(m => m.DualMode = false, Times.Once);
_tcpListenerMock.Verify(m => m.Start(), Times.Once); _tcpListenerMock.Verify(m => m.Start(), Times.Once);
_tcpListenerMock.Verify(m => m.Stop(), Times.Once); _tcpListenerMock.Verify(m => m.Stop(), Times.Once);
@@ -1197,10 +1168,8 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
await Task.Delay(100); await Task.Delay(100);
// Assert // Assert
_tcpListenerMock.VerifyGet(m => m.Socket, Times.Once);
_tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once); _tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once);
_ipEndPointMock.VerifyGet(m => m.Address, Times.Once); _ipEndPointMock.VerifyGet(m => m.Address, Times.Once);
_socketMock.VerifySet(m => m.DualMode = false, Times.Once);
_tcpListenerMock.Verify(m => m.Start(), Times.Once); _tcpListenerMock.Verify(m => m.Start(), Times.Once);
_tcpListenerMock.Verify(m => m.Stop(), Times.Once); _tcpListenerMock.Verify(m => m.Stop(), Times.Once);
@@ -1243,10 +1212,8 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
await Task.Delay(100); await Task.Delay(100);
// Assert // Assert
_tcpListenerMock.VerifyGet(m => m.Socket, Times.Once);
_tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once); _tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once);
_ipEndPointMock.VerifyGet(m => m.Address, Times.Once); _ipEndPointMock.VerifyGet(m => m.Address, Times.Once);
_socketMock.VerifySet(m => m.DualMode = false, Times.Once);
_tcpListenerMock.Verify(m => m.Start(), Times.Once); _tcpListenerMock.Verify(m => m.Start(), Times.Once);
_tcpListenerMock.Verify(m => m.Stop(), Times.Once); _tcpListenerMock.Verify(m => m.Stop(), Times.Once);
@@ -1293,10 +1260,8 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
await Task.Delay(100); await Task.Delay(100);
// Assert // Assert
_tcpListenerMock.VerifyGet(m => m.Socket, Times.Once);
_tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once); _tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once);
_ipEndPointMock.VerifyGet(m => m.Address, Times.Once); _ipEndPointMock.VerifyGet(m => m.Address, Times.Once);
_socketMock.VerifySet(m => m.DualMode = false, Times.Once);
_tcpListenerMock.Verify(m => m.Start(), Times.Once); _tcpListenerMock.Verify(m => m.Start(), Times.Once);
_tcpListenerMock.Verify(m => m.Stop(), Times.Once); _tcpListenerMock.Verify(m => m.Stop(), Times.Once);
@@ -1334,10 +1299,8 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
await Task.Delay(100); await Task.Delay(100);
// Assert // Assert
_tcpListenerMock.VerifyGet(m => m.Socket, Times.Once);
_tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once); _tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once);
_ipEndPointMock.VerifyGet(m => m.Address, Times.Once); _ipEndPointMock.VerifyGet(m => m.Address, Times.Once);
_socketMock.VerifySet(m => m.DualMode = false, Times.Once);
_tcpListenerMock.Verify(m => m.Start(), Times.Once); _tcpListenerMock.Verify(m => m.Start(), Times.Once);
_tcpListenerMock.Verify(m => m.Stop(), Times.Once); _tcpListenerMock.Verify(m => m.Stop(), Times.Once);
@@ -1366,10 +1329,8 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
await Task.Delay(100); await Task.Delay(100);
// Assert // Assert
_tcpListenerMock.VerifyGet(m => m.Socket, Times.Once);
_tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once); _tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once);
_ipEndPointMock.VerifyGet(m => m.Address, Times.Once); _ipEndPointMock.VerifyGet(m => m.Address, Times.Once);
_socketMock.VerifySet(m => m.DualMode = false, Times.Once);
_tcpListenerMock.Verify(m => m.Start(), Times.Once); _tcpListenerMock.Verify(m => m.Start(), Times.Once);
_tcpListenerMock.Verify(m => m.Stop(), Times.Once); _tcpListenerMock.Verify(m => m.Stop(), Times.Once);
@@ -1402,10 +1363,8 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
await Task.Delay(100); await Task.Delay(100);
// Assert // Assert
_tcpListenerMock.VerifyGet(m => m.Socket, Times.Once);
_tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once); _tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once);
_ipEndPointMock.VerifyGet(m => m.Address, Times.Once); _ipEndPointMock.VerifyGet(m => m.Address, Times.Once);
_socketMock.VerifySet(m => m.DualMode = false, Times.Once);
_tcpListenerMock.Verify(m => m.Start(), Times.Once); _tcpListenerMock.Verify(m => m.Start(), Times.Once);
_tcpListenerMock.Verify(m => m.Stop(), Times.Once); _tcpListenerMock.Verify(m => m.Stop(), Times.Once);
@@ -1449,10 +1408,8 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
await Task.Delay(100); await Task.Delay(100);
// Assert // Assert
_tcpListenerMock.VerifyGet(m => m.Socket, Times.Once);
_tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once); _tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once);
_ipEndPointMock.VerifyGet(m => m.Address, Times.Once); _ipEndPointMock.VerifyGet(m => m.Address, Times.Once);
_socketMock.VerifySet(m => m.DualMode = false, Times.Once);
_tcpListenerMock.Verify(m => m.Start(), Times.Once); _tcpListenerMock.Verify(m => m.Start(), Times.Once);
_tcpListenerMock.Verify(m => m.Stop(), Times.Once); _tcpListenerMock.Verify(m => m.Stop(), Times.Once);
@@ -1495,10 +1452,8 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
await Task.Delay(100); await Task.Delay(100);
// Assert // Assert
_tcpListenerMock.VerifyGet(m => m.Socket, Times.Once);
_tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once); _tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once);
_ipEndPointMock.VerifyGet(m => m.Address, Times.Once); _ipEndPointMock.VerifyGet(m => m.Address, Times.Once);
_socketMock.VerifySet(m => m.DualMode = false, Times.Once);
_tcpListenerMock.Verify(m => m.Start(), Times.Once); _tcpListenerMock.Verify(m => m.Start(), Times.Once);
_tcpListenerMock.Verify(m => m.Stop(), Times.Once); _tcpListenerMock.Verify(m => m.Stop(), Times.Once);
@@ -1536,10 +1491,8 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
await Task.Delay(100); await Task.Delay(100);
// Assert // Assert
_tcpListenerMock.VerifyGet(m => m.Socket, Times.Once);
_tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once); _tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once);
_ipEndPointMock.VerifyGet(m => m.Address, Times.Once); _ipEndPointMock.VerifyGet(m => m.Address, Times.Once);
_socketMock.VerifySet(m => m.DualMode = false, Times.Once);
_tcpListenerMock.Verify(m => m.Start(), Times.Once); _tcpListenerMock.Verify(m => m.Start(), Times.Once);
_tcpListenerMock.Verify(m => m.Stop(), Times.Once); _tcpListenerMock.Verify(m => m.Stop(), Times.Once);
@@ -1569,10 +1522,8 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
await Task.Delay(100); await Task.Delay(100);
// Assert // Assert
_tcpListenerMock.VerifyGet(m => m.Socket, Times.Once);
_tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once); _tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once);
_ipEndPointMock.VerifyGet(m => m.Address, Times.Once); _ipEndPointMock.VerifyGet(m => m.Address, Times.Once);
_socketMock.VerifySet(m => m.DualMode = false, Times.Once);
_tcpListenerMock.Verify(m => m.Start(), Times.Once); _tcpListenerMock.Verify(m => m.Start(), Times.Once);
_tcpListenerMock.Verify(m => m.Stop(), Times.Once); _tcpListenerMock.Verify(m => m.Stop(), Times.Once);
@@ -1616,10 +1567,8 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
await Task.Delay(100); await Task.Delay(100);
// Assert // Assert
_tcpListenerMock.VerifyGet(m => m.Socket, Times.Once);
_tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once); _tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once);
_ipEndPointMock.VerifyGet(m => m.Address, Times.Once); _ipEndPointMock.VerifyGet(m => m.Address, Times.Once);
_socketMock.VerifySet(m => m.DualMode = false, Times.Once);
_tcpListenerMock.Verify(m => m.Start(), Times.Once); _tcpListenerMock.Verify(m => m.Start(), Times.Once);
_tcpListenerMock.Verify(m => m.Stop(), Times.Once); _tcpListenerMock.Verify(m => m.Stop(), Times.Once);
@@ -1662,10 +1611,8 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
await Task.Delay(100); await Task.Delay(100);
// Assert // Assert
_tcpListenerMock.VerifyGet(m => m.Socket, Times.Once);
_tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once); _tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once);
_ipEndPointMock.VerifyGet(m => m.Address, Times.Once); _ipEndPointMock.VerifyGet(m => m.Address, Times.Once);
_socketMock.VerifySet(m => m.DualMode = false, Times.Once);
_tcpListenerMock.Verify(m => m.Start(), Times.Once); _tcpListenerMock.Verify(m => m.Start(), Times.Once);
_tcpListenerMock.Verify(m => m.Stop(), Times.Once); _tcpListenerMock.Verify(m => m.Stop(), Times.Once);
@@ -1707,10 +1654,8 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
await Task.Delay(100); await Task.Delay(100);
// Assert // Assert
_tcpListenerMock.VerifyGet(m => m.Socket, Times.Once);
_tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once); _tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once);
_ipEndPointMock.VerifyGet(m => m.Address, Times.Once); _ipEndPointMock.VerifyGet(m => m.Address, Times.Once);
_socketMock.VerifySet(m => m.DualMode = false, Times.Once);
_tcpListenerMock.Verify(m => m.Start(), Times.Once); _tcpListenerMock.Verify(m => m.Start(), Times.Once);
_tcpListenerMock.Verify(m => m.Stop(), Times.Once); _tcpListenerMock.Verify(m => m.Stop(), Times.Once);
@@ -1739,10 +1684,8 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
await Task.Delay(100); await Task.Delay(100);
// Assert // Assert
_tcpListenerMock.VerifyGet(m => m.Socket, Times.Once);
_tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once); _tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once);
_ipEndPointMock.VerifyGet(m => m.Address, Times.Once); _ipEndPointMock.VerifyGet(m => m.Address, Times.Once);
_socketMock.VerifySet(m => m.DualMode = false, Times.Once);
_tcpListenerMock.Verify(m => m.Start(), Times.Once); _tcpListenerMock.Verify(m => m.Start(), Times.Once);
_tcpListenerMock.Verify(m => m.Stop(), Times.Once); _tcpListenerMock.Verify(m => m.Stop(), Times.Once);
@@ -1775,10 +1718,8 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
await Task.Delay(100); await Task.Delay(100);
// Assert // Assert
_tcpListenerMock.VerifyGet(m => m.Socket, Times.Once);
_tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once); _tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once);
_ipEndPointMock.VerifyGet(m => m.Address, Times.Once); _ipEndPointMock.VerifyGet(m => m.Address, Times.Once);
_socketMock.VerifySet(m => m.DualMode = false, Times.Once);
_tcpListenerMock.Verify(m => m.Start(), Times.Once); _tcpListenerMock.Verify(m => m.Start(), Times.Once);
_tcpListenerMock.Verify(m => m.Stop(), Times.Once); _tcpListenerMock.Verify(m => m.Stop(), Times.Once);
@@ -1826,10 +1767,8 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
await Task.Delay(100); await Task.Delay(100);
// Assert // Assert
_tcpListenerMock.VerifyGet(m => m.Socket, Times.Once);
_tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once); _tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once);
_ipEndPointMock.VerifyGet(m => m.Address, Times.Once); _ipEndPointMock.VerifyGet(m => m.Address, Times.Once);
_socketMock.VerifySet(m => m.DualMode = false, Times.Once);
_tcpListenerMock.Verify(m => m.Start(), Times.Once); _tcpListenerMock.Verify(m => m.Start(), Times.Once);
_tcpListenerMock.Verify(m => m.Stop(), Times.Once); _tcpListenerMock.Verify(m => m.Stop(), Times.Once);
@@ -1876,10 +1815,8 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
await Task.Delay(100); await Task.Delay(100);
// Assert // Assert
_tcpListenerMock.VerifyGet(m => m.Socket, Times.Once);
_tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once); _tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once);
_ipEndPointMock.VerifyGet(m => m.Address, Times.Once); _ipEndPointMock.VerifyGet(m => m.Address, Times.Once);
_socketMock.VerifySet(m => m.DualMode = false, Times.Once);
_tcpListenerMock.Verify(m => m.Start(), Times.Once); _tcpListenerMock.Verify(m => m.Start(), Times.Once);
_tcpListenerMock.Verify(m => m.Stop(), Times.Once); _tcpListenerMock.Verify(m => m.Stop(), Times.Once);
@@ -1921,10 +1858,8 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
await Task.Delay(100); await Task.Delay(100);
// Assert // Assert
_tcpListenerMock.VerifyGet(m => m.Socket, Times.Once);
_tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once); _tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once);
_ipEndPointMock.VerifyGet(m => m.Address, Times.Once); _ipEndPointMock.VerifyGet(m => m.Address, Times.Once);
_socketMock.VerifySet(m => m.DualMode = false, Times.Once);
_tcpListenerMock.Verify(m => m.Start(), Times.Once); _tcpListenerMock.Verify(m => m.Start(), Times.Once);
_tcpListenerMock.Verify(m => m.Stop(), Times.Once); _tcpListenerMock.Verify(m => m.Stop(), Times.Once);
@@ -1953,10 +1888,8 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
await Task.Delay(100); await Task.Delay(100);
// Assert // Assert
_tcpListenerMock.VerifyGet(m => m.Socket, Times.Once);
_tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once); _tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once);
_ipEndPointMock.VerifyGet(m => m.Address, Times.Once); _ipEndPointMock.VerifyGet(m => m.Address, Times.Once);
_socketMock.VerifySet(m => m.DualMode = false, Times.Once);
_tcpListenerMock.Verify(m => m.Start(), Times.Once); _tcpListenerMock.Verify(m => m.Start(), Times.Once);
_tcpListenerMock.Verify(m => m.Stop(), Times.Once); _tcpListenerMock.Verify(m => m.Stop(), Times.Once);
@@ -1989,10 +1922,8 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
await Task.Delay(100); await Task.Delay(100);
// Assert // Assert
_tcpListenerMock.VerifyGet(m => m.Socket, Times.Once);
_tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once); _tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once);
_ipEndPointMock.VerifyGet(m => m.Address, Times.Once); _ipEndPointMock.VerifyGet(m => m.Address, Times.Once);
_socketMock.VerifySet(m => m.DualMode = false, Times.Once);
_tcpListenerMock.Verify(m => m.Start(), Times.Once); _tcpListenerMock.Verify(m => m.Start(), Times.Once);
_tcpListenerMock.Verify(m => m.Stop(), Times.Once); _tcpListenerMock.Verify(m => m.Stop(), Times.Once);
@@ -2040,10 +1971,8 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
await Task.Delay(100); await Task.Delay(100);
// Assert // Assert
_tcpListenerMock.VerifyGet(m => m.Socket, Times.Once);
_tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once); _tcpListenerMock.VerifyGet(m => m.LocalIPEndPoint, Times.Once);
_ipEndPointMock.VerifyGet(m => m.Address, Times.Once); _ipEndPointMock.VerifyGet(m => m.Address, Times.Once);
_socketMock.VerifySet(m => m.DualMode = false, Times.Once);
_tcpListenerMock.Verify(m => m.Start(), Times.Once); _tcpListenerMock.Verify(m => m.Start(), Times.Once);
_tcpListenerMock.Verify(m => m.Stop(), Times.Once); _tcpListenerMock.Verify(m => m.Stop(), Times.Once);
@@ -2099,9 +2028,9 @@ namespace AMWD.Protocols.Modbus.Tests.Tcp
return [.. CreateHeader(request), .. request]; return [.. CreateHeader(request), .. request];
} }
private ModbusTcpProxy GetProxy() private ModbusTcpProxy GetProxy(IPAddress localAddress = null)
{ {
var localAddress = IPAddress.Loopback; localAddress ??= IPAddress.Loopback;
int localPort = 502; int localPort = 502;
var connection = new Mock<IModbusConnection>(); var connection = new Mock<IModbusConnection>();

View File

@@ -0,0 +1,2 @@
TCP Client 127.0.0.1
Port: 502

View File

@@ -0,0 +1,9 @@
DeviceIdentification
VendorName: VendorName
ProductCode: ProductCode
MajorMinorRevision: MajorMinorRevision
VendorUrl:
ProductName:
ModelName:
UserApplicationName:
IsIndividualAccessAllowed: False

View File

@@ -10,6 +10,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
_nothing changed yet_ _nothing changed yet_
## [v0.4.2] (2025-02-07)
### Fixed
- Fixing issue with R/W timeouts while processing client requests on the `ModbusTcpProxy`.
## [v0.4.1] (2025-02-06)
### Changed
- Async methods do not return on captured context anymore (`Task.ConfigureAwait(false)`).
### Fixed
- Set `Socket.DualMode` on IPv4 network address is not allowed (`ModbusTcpProxy`).
## [v0.4.0] (2025-01-29) ## [v0.4.0] (2025-01-29)
### Added ### Added
@@ -77,7 +95,9 @@ So this tag is only here for documentation purposes of the NuGet Gallery.
[Unreleased]: https://github.com/AM-WD/AMWD.Protocols.Modbus/compare/v0.4.0...HEAD [Unreleased]: https://github.com/AM-WD/AMWD.Protocols.Modbus/compare/v0.4.2...HEAD
[v0.4.2]: https://github.com/AM-WD/AMWD.Protocols.Modbus/compare/v0.4.1...v0.4.2
[v0.4.1]: https://github.com/AM-WD/AMWD.Protocols.Modbus/compare/v0.4.0...v0.4.1
[v0.4.0]: https://github.com/AM-WD/AMWD.Protocols.Modbus/compare/v0.3.2...v0.4.0 [v0.4.0]: https://github.com/AM-WD/AMWD.Protocols.Modbus/compare/v0.3.2...v0.4.0
[v0.3.2]: https://github.com/AM-WD/AMWD.Protocols.Modbus/compare/v0.3.1...v0.3.2 [v0.3.2]: https://github.com/AM-WD/AMWD.Protocols.Modbus/compare/v0.3.1...v0.3.2
[v0.3.1]: https://github.com/AM-WD/AMWD.Protocols.Modbus/compare/v0.3.0...v0.3.1 [v0.3.1]: https://github.com/AM-WD/AMWD.Protocols.Modbus/compare/v0.3.0...v0.3.1

View File

@@ -19,6 +19,7 @@
<ItemGroup> <ItemGroup>
<None Remove="$(SolutionDir)/package-icon.png" /> <None Remove="$(SolutionDir)/package-icon.png" />
<None Remove="$(SolutionDir)/LICENSE.txt" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@@ -43,7 +43,7 @@ namespace AMWD.Protocols.Modbus.CliClient
{ {
if (!ParseArguments(args)) if (!ParseArguments(args))
{ {
Console.WriteLine("Could not parse arguments."); Console.Error.WriteLine("Could not parse arguments.");
return 1; return 1;
} }
@@ -55,13 +55,13 @@ namespace AMWD.Protocols.Modbus.CliClient
if (string.IsNullOrWhiteSpace(_target)) if (string.IsNullOrWhiteSpace(_target))
{ {
Console.WriteLine("No serial port or tcp host specified."); Console.Error.WriteLine("No serial port or tcp host specified.");
return 1; return 1;
} }
if (!_typeOption.IsSet) if (!_typeOption.IsSet)
{ {
Console.WriteLine("No type specified."); Console.Error.WriteLine("No type specified.");
return 1; return 1;
} }
@@ -79,7 +79,7 @@ namespace AMWD.Protocols.Modbus.CliClient
{ {
try try
{ {
Console.Write("."); Console.Error.Write(".");
await Task.Delay(1000, cts.Token); await Task.Delay(1000, cts.Token);
} }
catch (OperationCanceledException) catch (OperationCanceledException)
@@ -87,7 +87,7 @@ namespace AMWD.Protocols.Modbus.CliClient
return 0; return 0;
} }
} }
Console.WriteLine(); Console.Error.WriteLine();
} }
using var client = CreateClient(); using var client = CreateClient();

View File

@@ -19,6 +19,7 @@
<ItemGroup> <ItemGroup>
<None Remove="$(SolutionDir)/package-icon.png" /> <None Remove="$(SolutionDir)/package-icon.png" />
<None Remove="$(SolutionDir)/LICENSE.txt" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@@ -57,7 +57,7 @@ namespace AMWD.Protocols.Modbus.CliProxy
{ {
if (!ParseArguments(args)) if (!ParseArguments(args))
{ {
Console.WriteLine("Could not parse arguments."); Console.Error.WriteLine("Could not parse arguments.");
return 1; return 1;
} }
@@ -81,7 +81,7 @@ namespace AMWD.Protocols.Modbus.CliProxy
{ {
try try
{ {
Console.Write("."); Console.Error.Write(".");
await Task.Delay(1000, cts.Token); await Task.Delay(1000, cts.Token);
} }
catch (OperationCanceledException) catch (OperationCanceledException)
@@ -89,12 +89,15 @@ namespace AMWD.Protocols.Modbus.CliProxy
return 0; return 0;
} }
} }
Console.WriteLine(); Console.Error.WriteLine();
} }
try try
{ {
using var client = CreateClient(); using var client = CreateClient();
Console.WriteLine(client);
Console.WriteLine();
if (_clientProtocolOption.IsSet) if (_clientProtocolOption.IsSet)
{ {
switch (_clientProtocolOption.Value.ToLower()) switch (_clientProtocolOption.Value.ToLower())
@@ -105,10 +108,13 @@ namespace AMWD.Protocols.Modbus.CliProxy
} }
} }
using var proxy = CreateProxy(client); using var proxy = CreateProxy(client);
Console.WriteLine(proxy);
Console.WriteLine();
await proxy.StartAsync(cts.Token); await proxy.StartAsync(cts.Token);
try try
{ {
Console.WriteLine("Running proxy. Press Ctrl+C to stop.");
await Task.Delay(Timeout.Infinite, cts.Token); await Task.Delay(Timeout.Infinite, cts.Token);
} }
finally finally

View File

@@ -18,12 +18,12 @@
<PackageIcon>package-icon.png</PackageIcon> <PackageIcon>package-icon.png</PackageIcon>
<PackageReadmeFile>README.md</PackageReadmeFile> <PackageReadmeFile>README.md</PackageReadmeFile>
<PackageLicenseFile>LICENSE.txt</PackageLicenseFile>
<Title>Modbus Protocol for .NET</Title> <Title>Modbus Protocol for .NET</Title>
<Company>AM.WD</Company> <Company>AM.WD</Company>
<Authors>Andreas Müller</Authors> <Authors>Andreas Müller</Authors>
<Copyright>© {copyright:2018-} AM.WD</Copyright> <Copyright>© {copyright:2018-} AM.WD</Copyright>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<SignAssembly>true</SignAssembly> <SignAssembly>true</SignAssembly>
<AssemblyOriginatorKeyFile>$(SolutionDir)/AMWD.Protocols.Modbus.snk</AssemblyOriginatorKeyFile> <AssemblyOriginatorKeyFile>$(SolutionDir)/AMWD.Protocols.Modbus.snk</AssemblyOriginatorKeyFile>
@@ -52,6 +52,7 @@
<ItemGroup> <ItemGroup>
<None Include="$(SolutionDir)/package-icon.png" Pack="true" PackagePath="/" /> <None Include="$(SolutionDir)/package-icon.png" Pack="true" PackagePath="/" />
<None Include="$(SolutionDir)/LICENSE.txt" Pack="true" PackagePath="/" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@@ -2,9 +2,12 @@
Here you can find a basic implementation of the Modbus protocol. Here you can find a basic implementation of the Modbus protocol.
![NuGet Version](https://shields.io/nuget/v/AMWD.Protocols.Modbus.Common?style=flat&logo=nuget)
![Test Coverage](https://git.am-wd.de/am-wd/amwd.protocols.modbus/badges/main/coverage.svg?style=flat)
## Overview ## Overview
The project is divided into four parts. The project is divided into multiple parts.
To be mentioned at the beginning: To be mentioned at the beginning:
Only the clients are build very modular to fit any requirement reached on the first implementation back in 2018 ([see here]). Only the clients are build very modular to fit any requirement reached on the first implementation back in 2018 ([see here]).
@@ -35,7 +38,7 @@ It uses a specific TCP connection implementation and plugs all things from the C
--- ---
Published under [MIT License] (see [choose a license]) Published under [MIT License] (see [choose a license])
[![Buy me a Coffee](https://shields.am-wd.de/badge/PayPal-Buy_me_a_Coffee-yellow?style=flat&logo=paypal)](https://link.am-wd.de/donate) [![Buy me a Coffee](https://shields.io/badge/PayPal-Buy_me_a_Coffee-yellow?style=flat&logo=paypal)](https://link.am-wd.de/donate)
[![built with Codeium](https://codeium.com/badges/main)](https://link.am-wd.de/codeium) [![built with Codeium](https://codeium.com/badges/main)](https://link.am-wd.de/codeium)