Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions FluentModbus.sln
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.28803.202
# Visual Studio Version 17
VisualStudioVersion = 17.14.36429.23 d17.14
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{8449A872-2591-4C77-A810-974A20DD0227}"
EndProject
Expand All @@ -17,6 +17,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FluentModbus", "src\FluentM
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FluentModbus.Tests", "tests\FluentModbus.Tests\FluentModbus.Tests.csproj", "{EDA7B16D-17C0-4E4F-8315-A639BE519B26}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ServerRequestsTest", "ServerRequestsTest\ServerRequestsTest.csproj", "{CE748186-3D5E-40EE-BAE9-CA32D81671B9}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -57,6 +59,14 @@ Global
{EDA7B16D-17C0-4E4F-8315-A639BE519B26}.Release|Any CPU.Build.0 = Release|Any CPU
{EDA7B16D-17C0-4E4F-8315-A639BE519B26}.Release|x86.ActiveCfg = Release|Any CPU
{EDA7B16D-17C0-4E4F-8315-A639BE519B26}.Release|x86.Build.0 = Release|Any CPU
{CE748186-3D5E-40EE-BAE9-CA32D81671B9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CE748186-3D5E-40EE-BAE9-CA32D81671B9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CE748186-3D5E-40EE-BAE9-CA32D81671B9}.Debug|x86.ActiveCfg = Debug|Any CPU
{CE748186-3D5E-40EE-BAE9-CA32D81671B9}.Debug|x86.Build.0 = Debug|Any CPU
{CE748186-3D5E-40EE-BAE9-CA32D81671B9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CE748186-3D5E-40EE-BAE9-CA32D81671B9}.Release|Any CPU.Build.0 = Release|Any CPU
{CE748186-3D5E-40EE-BAE9-CA32D81671B9}.Release|x86.ActiveCfg = Release|Any CPU
{CE748186-3D5E-40EE-BAE9-CA32D81671B9}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand All @@ -66,6 +76,7 @@ Global
{ACFCBF6C-4363-47CB-B412-907464C7888F} = {D6452DF6-D009-4A4D-A161-E25DE443C0D8}
{BE6DE3F6-ED5E-4603-AC45-8966CD4EB2D1} = {8449A872-2591-4C77-A810-974A20DD0227}
{EDA7B16D-17C0-4E4F-8315-A639BE519B26} = {2B4BA2BB-B561-4301-A1B9-9E59E58BE8EF}
{CE748186-3D5E-40EE-BAE9-CA32D81671B9} = {D6452DF6-D009-4A4D-A161-E25DE443C0D8}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {F998BD6D-3E2B-4AA0-A7A4-FD84100C45A4}
Expand Down
30 changes: 30 additions & 0 deletions ServerRequestsTest/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
using FluentModbus;
using System.Buffers.Binary;
using System.Net;
using System.Runtime.InteropServices;

namespace ServerRequestsTest;

internal class Program
{
static void Main(string[] args)
{
try
{
ModbusTcpServer server = new ModbusTcpServer();
server.AddUnit(1);
//server.LooseUnitIdMode = true;
Span<short> register = server.GetHoldingRegisters(1);
UInt32 value = 327680;
register.SetLittleEndianSwapped<UInt32>(0, value);
ushort getValue = register.GetLittleEndianSwapped<ushort>(1);
Console.WriteLine($"Get: {getValue}");
server.Start(IPAddress.Parse("192.168.25.201"));
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
}
}
}
14 changes: 14 additions & 0 deletions ServerRequestsTest/ServerRequestsTest.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\src\FluentModbus\FluentModbus.csproj" />
</ItemGroup>

</Project>
21 changes: 21 additions & 0 deletions src/FluentModbus/ModbusUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -269,4 +269,25 @@ public static void SwitchEndianness<T>(Span<T> dataset) where T : unmanaged
}
}
}

public static T SwapBytes<T>(T value) where T : unmanaged
{
Span<T> data = stackalloc T[] { value };
SwapBytes(data);
return data[0];
}

public static void SwapBytes<T>(Span<T> dataset) where T : unmanaged
{
var dataset_bytes = MemoryMarshal.Cast<T, byte>(dataset);

for (int i = 0; i < dataset_bytes.Length; i += 2)
{

var i1 = i;
var i2 = i + 1;

(dataset_bytes[i2], dataset_bytes[i1]) = (dataset_bytes[i1], dataset_bytes[i2]);
}
}
}
12 changes: 12 additions & 0 deletions src/FluentModbus/Properties/PublishProfiles/FolderProfile.pubxml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- https://go.microsoft.com/fwlink/?LinkID=208121. -->
<Project>
<PropertyGroup>
<Configuration>Release</Configuration>
<Platform>Any CPU</Platform>
<PublishDir>C:\ProjetsVS\FluentModbus\artifacts\publish\FluentModbus\release_netstandard2.0\</PublishDir>
<PublishProtocol>FileSystem</PublishProtocol>
<_TargetId>Folder</_TargetId>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
</Project>
9 changes: 9 additions & 0 deletions src/FluentModbus/Server/ModbusRequestHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,15 @@ public void CancelToken()
_cts.Cancel();
}

public void WaitForConnectionToBeClosed()
{
if (!IsResponseRequired)
return;

if (Length == 0)
throw new Exception(ErrorMessage.ModbusTcpRequestHandler_NoValidRequestAvailable);
}

public void WriteResponse()
{
int frameLength;
Expand Down
9 changes: 7 additions & 2 deletions src/FluentModbus/Server/ModbusRtuRequestHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,9 @@ internal override async Task ReceiveRequestAsync()

if (ModbusServer.IsAsynchronous)
WriteResponse();
} else
{
WaitForConnectionToBeClosed();
}
}
catch (Exception ex)
Expand Down Expand Up @@ -127,15 +130,17 @@ private async Task<bool> TryReceiveRequestAsync()
}

// make sure that the incoming frame is actually adressed to this server
if (ModbusServer.UnitIdentifiers.Contains(UnitIdentifier))
if (ModbusServer.LooseUnitIdMode || ModbusServer.UnitIdentifiers.Contains(UnitIdentifier))
{
LastRequest.Restart();
return true;
}

else
{
return false;
//_logger.LogDebug("Incoming request not addressed to this server, the connection will be closed");
//CancelToken();
return false;
}
}

Expand Down
17 changes: 14 additions & 3 deletions src/FluentModbus/Server/ModbusServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,12 @@ protected ModbusServer(bool isAsynchronous, ILogger logger)
/// </summary>
public bool AlwaysRaiseChangedEvent { get; set; } = false;

private bool _looseUnitMode = false;
/// <summary>
/// Accept requests of any Unit Identifier, even if not managed. Default: false.
/// </summary>
public bool LooseUnitIdMode { get { return _looseUnitMode; } set { _looseUnitMode = value; AddUnit(0); } }

/// <summary>
/// Gets the logger.
/// </summary>
Expand Down Expand Up @@ -411,14 +417,14 @@ public void AddUnit(byte unitIdentifer)
if (unitIdentifer == 0)
{
// we are not in single zero unit mode
if (!_unitIdentifiers.Contains(0))
if (!_unitIdentifiers.Contains(0) && !LooseUnitIdMode)
throw new ArgumentException("Zero unit identifier can only be added in single zero unit identifier mode.");
}

else
{
// we are in single zero unit mode -> remove zero unit identifier to leave that mode
if (_unitIdentifiers.Contains(0))
if (!LooseUnitIdMode && _unitIdentifiers.Contains(0))
RemoveUnit(0);
}
}
Expand Down Expand Up @@ -451,7 +457,12 @@ public void RemoveUnit(byte unitIdentifer)

private Span<byte> Find(byte unitIdentifier, Dictionary<byte, byte[]> map)
{
if (!map.TryGetValue(unitIdentifier, out var buffer))
byte unitIdentifierToFind = unitIdentifier;
if(!map.ContainsKey(unitIdentifierToFind) && LooseUnitIdMode)
{
unitIdentifierToFind = 0;
}
if (!map.TryGetValue(unitIdentifierToFind, out var buffer))
throw new KeyNotFoundException(ErrorMessage.ModbusServer_UnitIdentifierNotFound);

return buffer;
Expand Down
9 changes: 7 additions & 2 deletions src/FluentModbus/Server/ModbusTcpRequestHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,9 @@ internal override async Task ReceiveRequestAsync()

if (ModbusServer.IsAsynchronous)
WriteResponse();
} else
{
WaitForConnectionToBeClosed();
}
}
catch (Exception ex)
Expand Down Expand Up @@ -178,15 +181,17 @@ private async Task<bool> TryReceiveRequestAsync()
// Make sure that the incoming frame is actually addressed to this server.
// If we have only one UnitIdentifier, and it is zero, then we accept all
// incoming messages
if (ModbusServer.IsSingleZeroUnitMode || ModbusServer.UnitIdentifiers.Contains(UnitIdentifier))
if (ModbusServer.IsSingleZeroUnitMode || ModbusServer.LooseUnitIdMode || ModbusServer.UnitIdentifiers.Contains(UnitIdentifier))
{
LastRequest.Restart();
return true;
}

else
{
return false;
//_logger.LogDebug("Incoming request not addressed to this server, the connection will be closed");
//CancelToken();
return false;
}
}

Expand Down
108 changes: 108 additions & 0 deletions src/FluentModbus/SpanExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,33 @@ public static void SetLittleEndian<T>(this Span<short> buffer, int address, T va
Unsafe.WriteUnaligned(ref byteBuffer.GetPinnableReference(), value);
}

/// <summary>
/// Writes a single value of type <typeparamref name="T"/> to the registers and converts it to the little-endian bytes swapped representation if necessary.
/// </summary>
/// <typeparam name="T">The type of the value to write.</typeparam>
/// <param name="buffer">The target buffer.</param>
/// <param name="address">The Modbus register address.</param>
/// <param name="value">The value to write.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void SetLittleEndianSwapped<T>(this Span<short> buffer, int address, T value)
where T : unmanaged
{
// CDAB
if (!(0 <= address && address <= ushort.MaxValue))
throw new Exception(ErrorMessage.Modbus_InvalidValueUShort);

var byteBuffer = MemoryMarshal
.AsBytes(buffer)
.Slice(address * 2);

if (!BitConverter.IsLittleEndian)
value = ModbusUtils.SwitchEndianness(value);

value = ModbusUtils.SwapBytes(value);

Unsafe.WriteUnaligned(ref byteBuffer.GetPinnableReference(), value);
}

/// <summary>
/// Writes a single value of type <typeparamref name="T"/> to the registers and converts it to the mid-little-endian representation.
/// </summary>
Expand Down Expand Up @@ -85,6 +112,33 @@ public static void SetBigEndian<T>(this Span<short> buffer, int address, T value
Unsafe.WriteUnaligned(ref byteBuffer.GetPinnableReference(), value);
}

/// <summary>
/// Writes a single value of type <typeparamref name="T"/> to the registers and converts it to the big-endian bytes swapped representation if necessary.
/// </summary>
/// <typeparam name="T">The type of the value to write.</typeparam>
/// <param name="buffer">The target buffer.</param>
/// <param name="address">The Modbus register address.</param>
/// <param name="value">The value to write.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void SetBigEndianSwapped<T>(this Span<short> buffer, int address, T value)
where T : unmanaged
{
// BADC
if (!(0 <= address && address <= ushort.MaxValue))
throw new Exception(ErrorMessage.Modbus_InvalidValueUShort);

var byteBuffer = MemoryMarshal
.AsBytes(buffer)
.Slice(address * 2);

if (BitConverter.IsLittleEndian)
value = ModbusUtils.SwitchEndianness(value);

value = ModbusUtils.SwapBytes(value);

Unsafe.WriteUnaligned(ref byteBuffer.GetPinnableReference(), value);
}

/// <summary>
/// Reads a single little-endian value of type <typeparamref name="T"/> from the registers.
/// </summary>
Expand All @@ -110,6 +164,33 @@ public static T GetLittleEndian<T>(this Span<short> buffer, int address)
return value;
}

/// <summary>
/// Reads a single little-endian bytes swapped value of type <typeparamref name="T"/> from the registers.
/// </summary>
/// <typeparam name="T">The type of the value to read.</typeparam>
/// <param name="buffer">The source buffer.</param>
/// <param name="address">The Modbus register address.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static T GetLittleEndianSwapped<T>(this Span<short> buffer, int address)
where T : unmanaged
{
if (!(0 <= address && address <= ushort.MaxValue))
throw new Exception(ErrorMessage.Modbus_InvalidValueUShort);

var byteBuffer = MemoryMarshal
.AsBytes(buffer)
.Slice(address * 2);

var value = Unsafe.ReadUnaligned<T>(ref byteBuffer.GetPinnableReference());

if (!BitConverter.IsLittleEndian)
value = ModbusUtils.SwitchEndianness(value);

value = ModbusUtils.SwapBytes(value);

return value;
}

/// <summary>
/// Reads a single mid-little-endian value of type <typeparamref name="T"/> from the registers.
/// </summary>
Expand Down Expand Up @@ -161,6 +242,33 @@ public static T GetBigEndian<T>(this Span<short> buffer, int address)
return value;
}

/// <summary>
/// Reads a single big-endian bytes swapped value of type <typeparamref name="T"/> from the registers.
/// </summary>
/// <typeparam name="T">The type of the value to read.</typeparam>
/// <param name="buffer">The source buffer.</param>
/// <param name="address">The Modbus register address.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static T GetBigEndianSwapped<T>(this Span<short> buffer, int address)
where T : unmanaged
{
if (!(0 <= address && address <= ushort.MaxValue))
throw new Exception(ErrorMessage.Modbus_InvalidValueUShort);

var byteBuffer = MemoryMarshal
.AsBytes(buffer)
.Slice(address * 2);

var value = Unsafe.ReadUnaligned<T>(ref byteBuffer.GetPinnableReference());

if (BitConverter.IsLittleEndian)
value = ModbusUtils.SwitchEndianness(value);

value = ModbusUtils.SwapBytes(value);

return value;
}

/// <summary>
/// Writes a single bit to the buffer.
/// </summary>
Expand Down