diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..20aa534 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,19 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true +indent_style = space +indent_size = 4 + +[*.{csproj,slnx,yml,json}] +indent_size = 2 + +[*.cs] +csharp_style_namespace_declarations = file_scoped:suggestion +csharp_preserve_single_line_blocks = true +csharp_preserve_single_line_statements = true +dotnet_style_qualification_for_field = false:suggestion +dotnet_style_qualification_for_property = false:suggestion diff --git a/.gitattributes b/.gitattributes index 1ff0c42..1a2fd1e 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,63 +1,9 @@ -############################################################################### -# Set default behavior to automatically normalize line endings. -############################################################################### * text=auto - -############################################################################### -# Set default behavior for command prompt diff. -# -# This is need for earlier builds of msysgit that does not have it on by -# default for csharp files. -# Note: This is only used by command line -############################################################################### -#*.cs diff=csharp - -############################################################################### -# Set the merge driver for project and solution files -# -# Merging from the command prompt will add diff markers to the files if there -# are conflicts (Merging from VS is not affected by the settings below, in VS -# the diff markers are never inserted). Diff markers may cause the following -# file extensions to fail to load in VS. An alternative would be to treat -# these files as binary and thus will always conflict and require user -# intervention with every merge. To do so, just uncomment the entries below -############################################################################### -#*.sln merge=binary -#*.csproj merge=binary -#*.vbproj merge=binary -#*.vcxproj merge=binary -#*.vcproj merge=binary -#*.dbproj merge=binary -#*.fsproj merge=binary -#*.lsproj merge=binary -#*.wixproj merge=binary -#*.modelproj merge=binary -#*.sqlproj merge=binary -#*.wwaproj merge=binary - -############################################################################### -# behavior for image files -# -# image files are treated as binary by default. -############################################################################### -#*.jpg binary -#*.png binary -#*.gif binary - -############################################################################### -# diff behavior for common document formats -# -# Convert binary document formats to text before diffing them. This feature -# is only available from the command line. Turn it on by uncommenting the -# entries below. -############################################################################### -#*.doc diff=astextplain -#*.DOC diff=astextplain -#*.docx diff=astextplain -#*.DOCX diff=astextplain -#*.dot diff=astextplain -#*.DOT diff=astextplain -#*.pdf diff=astextplain -#*.PDF diff=astextplain -#*.rtf diff=astextplain -#*.RTF diff=astextplain +*.cs text eol=lf +*.csproj text eol=lf +*.props text eol=lf +*.targets text eol=lf +*.slnx text eol=lf +*.md text eol=lf +*.json text eol=lf +*.yml text eol=lf diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml new file mode 100644 index 0000000..5f487a6 --- /dev/null +++ b/.github/workflows/dotnet.yml @@ -0,0 +1,23 @@ +name: .NET 10 + +on: [push, pull_request] + +permissions: + contents: read + +jobs: + build-and-test: + strategy: + matrix: + os: [ubuntu-latest, windows-latest] + runs-on: ${{ matrix.os }} + timeout-minutes: 10 + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-dotnet@v6 + with: + dotnet-version: '10.0.x' + - run: dotnet restore EasyModbus.slnx + - run: dotnet build EasyModbus.slnx --configuration Release --no-restore + - run: dotnet test EasyModbus.slnx --configuration Release --no-build --no-restore --blame-hang-timeout 30s + - run: dotnet run --project ConsoleAppStd --configuration Release --no-build diff --git a/ConsoleAppStd/ConsoleAppStd.csproj b/ConsoleAppStd/ConsoleAppStd.csproj index 820f23d..46adb72 100644 --- a/ConsoleAppStd/ConsoleAppStd.csproj +++ b/ConsoleAppStd/ConsoleAppStd.csproj @@ -1,12 +1,12 @@ - - + Exe - net5.0 + net10.0 + enable + enable + true - - + - diff --git a/ConsoleAppStd/Program.cs b/ConsoleAppStd/Program.cs index 423e386..4abe00f 100644 --- a/ConsoleAppStd/Program.cs +++ b/ConsoleAppStd/Program.cs @@ -1,22 +1,34 @@ -using System; +using System.Globalization; +using System.Net; +using EasyModbus; -namespace ConsoleAppStd +if (args.Length > 2) { - class Program - { - - static void Main(string[] args) - { - Console.WriteLine("Hello World!"); - - EasyModbus.ModbusClient modbusClient = new EasyModbus.ModbusClient(); - modbusClient.Connect("127.0.0.1", 502); - bool[] response = modbusClient.ReadDiscreteInputs(0, 2); + Console.Error.WriteLine("Usage: ConsoleAppStd [host [port]]"); + return 1; +} - modbusClient.Disconnect(); - Console.WriteLine("Value of Discrete Input #1: " + response[0].ToString()); - Console.WriteLine("Value of Discrete Input #2: " + response[1].ToString()); - Console.ReadKey(); - } +using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5)); +await using var server = args.Length == 0 ? new ModbusServer { LocalIPAddress = IPAddress.Loopback, Port = 0 } : null; +try +{ + if (server is not null) + { + server.holdingRegisters[1] = 123; + server.holdingRegisters[2] = 456; + server.Listen(); } + var host = args.Length > 0 ? args[0] : "127.0.0.1"; + var port = args.Length > 1 ? int.Parse(args[1], CultureInfo.InvariantCulture) : server?.Port ?? 502; + await using var client = new ModbusClient(host, port); + await client.ConnectAsync(timeout.Token); + var values = await client.ReadHoldingRegistersAsync(0, 2, timeout.Token); + Console.WriteLine($"Holding registers 0 and 1: {string.Join(", ", values)}"); + return 0; +} +catch (Exception exception) when (exception is IOException or System.Net.Sockets.SocketException or OperationCanceledException or + EasyModbus.Exceptions.ModbusException or ArgumentException or FormatException or OverflowException) +{ + Console.Error.WriteLine(exception.Message); + return 1; } diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 0000000..f7dd7c8 --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,3 @@ + + + diff --git a/Directory.Build.targets b/Directory.Build.targets new file mode 100644 index 0000000..498457c --- /dev/null +++ b/Directory.Build.targets @@ -0,0 +1,3 @@ + + + diff --git a/EasyModbus.sln b/EasyModbus.sln deleted file mode 100644 index f19c59c..0000000 --- a/EasyModbus.sln +++ /dev/null @@ -1,392 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.3.32811.315 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EasyModbus_Net40", "EasyModbus\EasyModbus_Net40.csproj", "{7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EasyModbusServerSimulator", "EasyModbusServerSimulator\EasyModbusServerSimulator.csproj", "{871BD4C1-69F0-45B9-8807-1620E6A896A9}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EasyModbusClientExample", "EasyModbusClientExample\EasyModbusClientExample.csproj", "{9412077F-7DFF-45D0-AFF9-7D5303118EA7}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EasyModbusAdvancedClient", "EasyModbusAdvancedClient\EasyModbusAdvancedClient.csproj", "{3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ConsoleAppStd", "ConsoleAppStd\ConsoleAppStd.csproj", "{62AFCA11-8005-4D14-9F29-89DED1076335}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EasyModbus_V5.0", "EasyModbus_NET5\EasyModbus_V5.0.csproj", "{83AFFC60-BC95-46B1-861F-B1F80270FBFA}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EasyModbus_Net60", "EasyModbus_Net60\EasyModbus_Net60.csproj", "{6BD5A885-D0A3-44C0-BF73-E2118519EAFE}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Debug|ARM = Debug|ARM - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - DebugCommercial|Any CPU = DebugCommercial|Any CPU - DebugCommercial|ARM = DebugCommercial|ARM - DebugCommercial|x64 = DebugCommercial|x64 - DebugCommercial|x86 = DebugCommercial|x86 - DebugCommercial1|Any CPU = DebugCommercial1|Any CPU - DebugCommercial1|ARM = DebugCommercial1|ARM - DebugCommercial1|x64 = DebugCommercial1|x64 - DebugCommercial1|x86 = DebugCommercial1|x86 - DebugCommercial2|Any CPU = DebugCommercial2|Any CPU - DebugCommercial2|ARM = DebugCommercial2|ARM - DebugCommercial2|x64 = DebugCommercial2|x64 - DebugCommercial2|x86 = DebugCommercial2|x86 - DebugCommercial3|Any CPU = DebugCommercial3|Any CPU - DebugCommercial3|ARM = DebugCommercial3|ARM - DebugCommercial3|x64 = DebugCommercial3|x64 - DebugCommercial3|x86 = DebugCommercial3|x86 - Release|Any CPU = Release|Any CPU - Release|ARM = Release|ARM - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}.Debug|Any CPU.Build.0 = Debug|Any CPU - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}.Debug|ARM.ActiveCfg = Debug|Any CPU - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}.Debug|ARM.Build.0 = Debug|Any CPU - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}.Debug|x64.ActiveCfg = Debug|Any CPU - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}.Debug|x64.Build.0 = Debug|Any CPU - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}.Debug|x86.ActiveCfg = Debug|Any CPU - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}.Debug|x86.Build.0 = Debug|Any CPU - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}.DebugCommercial|Any CPU.ActiveCfg = DebugCommercial|Any CPU - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}.DebugCommercial|Any CPU.Build.0 = DebugCommercial|Any CPU - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}.DebugCommercial|ARM.ActiveCfg = DebugCommercial|Any CPU - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}.DebugCommercial|ARM.Build.0 = DebugCommercial|Any CPU - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}.DebugCommercial|x64.ActiveCfg = DebugCommercial|Any CPU - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}.DebugCommercial|x64.Build.0 = DebugCommercial|Any CPU - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}.DebugCommercial|x86.ActiveCfg = DebugCommercial|Any CPU - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}.DebugCommercial|x86.Build.0 = DebugCommercial|Any CPU - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}.DebugCommercial1|Any CPU.ActiveCfg = DebugCommercial|Any CPU - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}.DebugCommercial1|Any CPU.Build.0 = DebugCommercial|Any CPU - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}.DebugCommercial1|ARM.ActiveCfg = DebugCommercial|Any CPU - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}.DebugCommercial1|ARM.Build.0 = DebugCommercial|Any CPU - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}.DebugCommercial1|x64.ActiveCfg = DebugCommercial|Any CPU - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}.DebugCommercial1|x64.Build.0 = DebugCommercial|Any CPU - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}.DebugCommercial1|x86.ActiveCfg = DebugCommercial|Any CPU - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}.DebugCommercial1|x86.Build.0 = DebugCommercial|Any CPU - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}.DebugCommercial2|Any CPU.ActiveCfg = DebugCommercial|Any CPU - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}.DebugCommercial2|Any CPU.Build.0 = DebugCommercial|Any CPU - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}.DebugCommercial2|ARM.ActiveCfg = DebugCommercial|Any CPU - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}.DebugCommercial2|ARM.Build.0 = DebugCommercial|Any CPU - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}.DebugCommercial2|x64.ActiveCfg = DebugCommercial|Any CPU - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}.DebugCommercial2|x64.Build.0 = DebugCommercial|Any CPU - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}.DebugCommercial2|x86.ActiveCfg = DebugCommercial|Any CPU - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}.DebugCommercial2|x86.Build.0 = DebugCommercial|Any CPU - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}.DebugCommercial3|Any CPU.ActiveCfg = DebugCommercial|Any CPU - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}.DebugCommercial3|Any CPU.Build.0 = DebugCommercial|Any CPU - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}.DebugCommercial3|ARM.ActiveCfg = DebugCommercial|Any CPU - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}.DebugCommercial3|ARM.Build.0 = DebugCommercial|Any CPU - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}.DebugCommercial3|x64.ActiveCfg = DebugCommercial|Any CPU - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}.DebugCommercial3|x64.Build.0 = DebugCommercial|Any CPU - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}.DebugCommercial3|x86.ActiveCfg = DebugCommercial|Any CPU - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}.DebugCommercial3|x86.Build.0 = DebugCommercial|Any CPU - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}.Release|Any CPU.ActiveCfg = Release|Any CPU - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}.Release|Any CPU.Build.0 = Release|Any CPU - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}.Release|ARM.ActiveCfg = Release|Any CPU - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}.Release|ARM.Build.0 = Release|Any CPU - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}.Release|x64.ActiveCfg = Release|Any CPU - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}.Release|x64.Build.0 = Release|Any CPU - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}.Release|x86.ActiveCfg = Release|Any CPU - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}.Release|x86.Build.0 = Release|Any CPU - {871BD4C1-69F0-45B9-8807-1620E6A896A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {871BD4C1-69F0-45B9-8807-1620E6A896A9}.Debug|Any CPU.Build.0 = Debug|Any CPU - {871BD4C1-69F0-45B9-8807-1620E6A896A9}.Debug|ARM.ActiveCfg = Debug|Any CPU - {871BD4C1-69F0-45B9-8807-1620E6A896A9}.Debug|ARM.Build.0 = Debug|Any CPU - {871BD4C1-69F0-45B9-8807-1620E6A896A9}.Debug|x64.ActiveCfg = Debug|Any CPU - {871BD4C1-69F0-45B9-8807-1620E6A896A9}.Debug|x64.Build.0 = Debug|Any CPU - {871BD4C1-69F0-45B9-8807-1620E6A896A9}.Debug|x86.ActiveCfg = Debug|Any CPU - {871BD4C1-69F0-45B9-8807-1620E6A896A9}.Debug|x86.Build.0 = Debug|Any CPU - {871BD4C1-69F0-45B9-8807-1620E6A896A9}.DebugCommercial|Any CPU.ActiveCfg = DebugCommercial3|Any CPU - {871BD4C1-69F0-45B9-8807-1620E6A896A9}.DebugCommercial|Any CPU.Build.0 = DebugCommercial3|Any CPU - {871BD4C1-69F0-45B9-8807-1620E6A896A9}.DebugCommercial|ARM.ActiveCfg = DebugCommercial3|Any CPU - {871BD4C1-69F0-45B9-8807-1620E6A896A9}.DebugCommercial|ARM.Build.0 = DebugCommercial3|Any CPU - {871BD4C1-69F0-45B9-8807-1620E6A896A9}.DebugCommercial|x64.ActiveCfg = DebugCommercial3|Any CPU - {871BD4C1-69F0-45B9-8807-1620E6A896A9}.DebugCommercial|x64.Build.0 = DebugCommercial3|Any CPU - {871BD4C1-69F0-45B9-8807-1620E6A896A9}.DebugCommercial|x86.ActiveCfg = DebugCommercial3|Any CPU - {871BD4C1-69F0-45B9-8807-1620E6A896A9}.DebugCommercial|x86.Build.0 = DebugCommercial3|Any CPU - {871BD4C1-69F0-45B9-8807-1620E6A896A9}.DebugCommercial1|Any CPU.ActiveCfg = Debug|Any CPU - {871BD4C1-69F0-45B9-8807-1620E6A896A9}.DebugCommercial1|Any CPU.Build.0 = Debug|Any CPU - {871BD4C1-69F0-45B9-8807-1620E6A896A9}.DebugCommercial1|ARM.ActiveCfg = DebugCommercial3|Any CPU - {871BD4C1-69F0-45B9-8807-1620E6A896A9}.DebugCommercial1|ARM.Build.0 = DebugCommercial3|Any CPU - {871BD4C1-69F0-45B9-8807-1620E6A896A9}.DebugCommercial1|x64.ActiveCfg = DebugCommercial3|Any CPU - {871BD4C1-69F0-45B9-8807-1620E6A896A9}.DebugCommercial1|x64.Build.0 = DebugCommercial3|Any CPU - {871BD4C1-69F0-45B9-8807-1620E6A896A9}.DebugCommercial1|x86.ActiveCfg = DebugCommercial3|Any CPU - {871BD4C1-69F0-45B9-8807-1620E6A896A9}.DebugCommercial1|x86.Build.0 = DebugCommercial3|Any CPU - {871BD4C1-69F0-45B9-8807-1620E6A896A9}.DebugCommercial2|Any CPU.ActiveCfg = Debug|Any CPU - {871BD4C1-69F0-45B9-8807-1620E6A896A9}.DebugCommercial2|Any CPU.Build.0 = Debug|Any CPU - {871BD4C1-69F0-45B9-8807-1620E6A896A9}.DebugCommercial2|ARM.ActiveCfg = DebugCommercial3|Any CPU - {871BD4C1-69F0-45B9-8807-1620E6A896A9}.DebugCommercial2|ARM.Build.0 = DebugCommercial3|Any CPU - {871BD4C1-69F0-45B9-8807-1620E6A896A9}.DebugCommercial2|x64.ActiveCfg = DebugCommercial3|Any CPU - {871BD4C1-69F0-45B9-8807-1620E6A896A9}.DebugCommercial2|x64.Build.0 = DebugCommercial3|Any CPU - {871BD4C1-69F0-45B9-8807-1620E6A896A9}.DebugCommercial2|x86.ActiveCfg = DebugCommercial3|Any CPU - {871BD4C1-69F0-45B9-8807-1620E6A896A9}.DebugCommercial2|x86.Build.0 = DebugCommercial3|Any CPU - {871BD4C1-69F0-45B9-8807-1620E6A896A9}.DebugCommercial3|Any CPU.ActiveCfg = DebugCommercial3|Any CPU - {871BD4C1-69F0-45B9-8807-1620E6A896A9}.DebugCommercial3|Any CPU.Build.0 = DebugCommercial3|Any CPU - {871BD4C1-69F0-45B9-8807-1620E6A896A9}.DebugCommercial3|ARM.ActiveCfg = DebugCommercial3|Any CPU - {871BD4C1-69F0-45B9-8807-1620E6A896A9}.DebugCommercial3|ARM.Build.0 = DebugCommercial3|Any CPU - {871BD4C1-69F0-45B9-8807-1620E6A896A9}.DebugCommercial3|x64.ActiveCfg = DebugCommercial3|Any CPU - {871BD4C1-69F0-45B9-8807-1620E6A896A9}.DebugCommercial3|x64.Build.0 = DebugCommercial3|Any CPU - {871BD4C1-69F0-45B9-8807-1620E6A896A9}.DebugCommercial3|x86.ActiveCfg = DebugCommercial3|Any CPU - {871BD4C1-69F0-45B9-8807-1620E6A896A9}.DebugCommercial3|x86.Build.0 = DebugCommercial3|Any CPU - {871BD4C1-69F0-45B9-8807-1620E6A896A9}.Release|Any CPU.ActiveCfg = Release|Any CPU - {871BD4C1-69F0-45B9-8807-1620E6A896A9}.Release|Any CPU.Build.0 = Release|Any CPU - {871BD4C1-69F0-45B9-8807-1620E6A896A9}.Release|ARM.ActiveCfg = Release|Any CPU - {871BD4C1-69F0-45B9-8807-1620E6A896A9}.Release|ARM.Build.0 = Release|Any CPU - {871BD4C1-69F0-45B9-8807-1620E6A896A9}.Release|x64.ActiveCfg = Release|Any CPU - {871BD4C1-69F0-45B9-8807-1620E6A896A9}.Release|x64.Build.0 = Release|Any CPU - {871BD4C1-69F0-45B9-8807-1620E6A896A9}.Release|x86.ActiveCfg = Release|Any CPU - {871BD4C1-69F0-45B9-8807-1620E6A896A9}.Release|x86.Build.0 = Release|Any CPU - {9412077F-7DFF-45D0-AFF9-7D5303118EA7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {9412077F-7DFF-45D0-AFF9-7D5303118EA7}.Debug|Any CPU.Build.0 = Debug|Any CPU - {9412077F-7DFF-45D0-AFF9-7D5303118EA7}.Debug|ARM.ActiveCfg = Debug|Any CPU - {9412077F-7DFF-45D0-AFF9-7D5303118EA7}.Debug|ARM.Build.0 = Debug|Any CPU - {9412077F-7DFF-45D0-AFF9-7D5303118EA7}.Debug|x64.ActiveCfg = Debug|Any CPU - {9412077F-7DFF-45D0-AFF9-7D5303118EA7}.Debug|x64.Build.0 = Debug|Any CPU - {9412077F-7DFF-45D0-AFF9-7D5303118EA7}.Debug|x86.ActiveCfg = Debug|Any CPU - {9412077F-7DFF-45D0-AFF9-7D5303118EA7}.Debug|x86.Build.0 = Debug|Any CPU - {9412077F-7DFF-45D0-AFF9-7D5303118EA7}.DebugCommercial|Any CPU.ActiveCfg = DebugCommercial2|Any CPU - {9412077F-7DFF-45D0-AFF9-7D5303118EA7}.DebugCommercial|Any CPU.Build.0 = DebugCommercial2|Any CPU - {9412077F-7DFF-45D0-AFF9-7D5303118EA7}.DebugCommercial|ARM.ActiveCfg = DebugCommercial2|Any CPU - {9412077F-7DFF-45D0-AFF9-7D5303118EA7}.DebugCommercial|ARM.Build.0 = DebugCommercial2|Any CPU - {9412077F-7DFF-45D0-AFF9-7D5303118EA7}.DebugCommercial|x64.ActiveCfg = DebugCommercial2|Any CPU - {9412077F-7DFF-45D0-AFF9-7D5303118EA7}.DebugCommercial|x64.Build.0 = DebugCommercial2|Any CPU - {9412077F-7DFF-45D0-AFF9-7D5303118EA7}.DebugCommercial|x86.ActiveCfg = DebugCommercial2|Any CPU - {9412077F-7DFF-45D0-AFF9-7D5303118EA7}.DebugCommercial|x86.Build.0 = DebugCommercial2|Any CPU - {9412077F-7DFF-45D0-AFF9-7D5303118EA7}.DebugCommercial1|Any CPU.ActiveCfg = Debug|Any CPU - {9412077F-7DFF-45D0-AFF9-7D5303118EA7}.DebugCommercial1|Any CPU.Build.0 = Debug|Any CPU - {9412077F-7DFF-45D0-AFF9-7D5303118EA7}.DebugCommercial1|ARM.ActiveCfg = DebugCommercial2|Any CPU - {9412077F-7DFF-45D0-AFF9-7D5303118EA7}.DebugCommercial1|ARM.Build.0 = DebugCommercial2|Any CPU - {9412077F-7DFF-45D0-AFF9-7D5303118EA7}.DebugCommercial1|x64.ActiveCfg = DebugCommercial2|Any CPU - {9412077F-7DFF-45D0-AFF9-7D5303118EA7}.DebugCommercial1|x64.Build.0 = DebugCommercial2|Any CPU - {9412077F-7DFF-45D0-AFF9-7D5303118EA7}.DebugCommercial1|x86.ActiveCfg = DebugCommercial2|Any CPU - {9412077F-7DFF-45D0-AFF9-7D5303118EA7}.DebugCommercial1|x86.Build.0 = DebugCommercial2|Any CPU - {9412077F-7DFF-45D0-AFF9-7D5303118EA7}.DebugCommercial2|Any CPU.ActiveCfg = DebugCommercial2|Any CPU - {9412077F-7DFF-45D0-AFF9-7D5303118EA7}.DebugCommercial2|Any CPU.Build.0 = DebugCommercial2|Any CPU - {9412077F-7DFF-45D0-AFF9-7D5303118EA7}.DebugCommercial2|ARM.ActiveCfg = DebugCommercial2|Any CPU - {9412077F-7DFF-45D0-AFF9-7D5303118EA7}.DebugCommercial2|ARM.Build.0 = DebugCommercial2|Any CPU - {9412077F-7DFF-45D0-AFF9-7D5303118EA7}.DebugCommercial2|x64.ActiveCfg = DebugCommercial2|Any CPU - {9412077F-7DFF-45D0-AFF9-7D5303118EA7}.DebugCommercial2|x64.Build.0 = DebugCommercial2|Any CPU - {9412077F-7DFF-45D0-AFF9-7D5303118EA7}.DebugCommercial2|x86.ActiveCfg = DebugCommercial2|Any CPU - {9412077F-7DFF-45D0-AFF9-7D5303118EA7}.DebugCommercial2|x86.Build.0 = DebugCommercial2|Any CPU - {9412077F-7DFF-45D0-AFF9-7D5303118EA7}.DebugCommercial3|Any CPU.ActiveCfg = DebugCommercial2|Any CPU - {9412077F-7DFF-45D0-AFF9-7D5303118EA7}.DebugCommercial3|Any CPU.Build.0 = DebugCommercial2|Any CPU - {9412077F-7DFF-45D0-AFF9-7D5303118EA7}.DebugCommercial3|ARM.ActiveCfg = DebugCommercial2|Any CPU - {9412077F-7DFF-45D0-AFF9-7D5303118EA7}.DebugCommercial3|ARM.Build.0 = DebugCommercial2|Any CPU - {9412077F-7DFF-45D0-AFF9-7D5303118EA7}.DebugCommercial3|x64.ActiveCfg = DebugCommercial2|Any CPU - {9412077F-7DFF-45D0-AFF9-7D5303118EA7}.DebugCommercial3|x64.Build.0 = DebugCommercial2|Any CPU - {9412077F-7DFF-45D0-AFF9-7D5303118EA7}.DebugCommercial3|x86.ActiveCfg = DebugCommercial2|Any CPU - {9412077F-7DFF-45D0-AFF9-7D5303118EA7}.DebugCommercial3|x86.Build.0 = DebugCommercial2|Any CPU - {9412077F-7DFF-45D0-AFF9-7D5303118EA7}.Release|Any CPU.ActiveCfg = Release|Any CPU - {9412077F-7DFF-45D0-AFF9-7D5303118EA7}.Release|Any CPU.Build.0 = Release|Any CPU - {9412077F-7DFF-45D0-AFF9-7D5303118EA7}.Release|ARM.ActiveCfg = Release|Any CPU - {9412077F-7DFF-45D0-AFF9-7D5303118EA7}.Release|ARM.Build.0 = Release|Any CPU - {9412077F-7DFF-45D0-AFF9-7D5303118EA7}.Release|x64.ActiveCfg = Release|Any CPU - {9412077F-7DFF-45D0-AFF9-7D5303118EA7}.Release|x64.Build.0 = Release|Any CPU - {9412077F-7DFF-45D0-AFF9-7D5303118EA7}.Release|x86.ActiveCfg = Release|Any CPU - {9412077F-7DFF-45D0-AFF9-7D5303118EA7}.Release|x86.Build.0 = Release|Any CPU - {3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}.Debug|Any CPU.Build.0 = Debug|Any CPU - {3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}.Debug|ARM.ActiveCfg = Debug|Any CPU - {3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}.Debug|ARM.Build.0 = Debug|Any CPU - {3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}.Debug|x64.ActiveCfg = Debug|Any CPU - {3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}.Debug|x64.Build.0 = Debug|Any CPU - {3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}.Debug|x86.ActiveCfg = Debug|Any CPU - {3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}.Debug|x86.Build.0 = Debug|Any CPU - {3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}.DebugCommercial|Any CPU.ActiveCfg = DebugCommercial1|Any CPU - {3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}.DebugCommercial|Any CPU.Build.0 = DebugCommercial1|Any CPU - {3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}.DebugCommercial|ARM.ActiveCfg = DebugCommercial1|Any CPU - {3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}.DebugCommercial|ARM.Build.0 = DebugCommercial1|Any CPU - {3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}.DebugCommercial|x64.ActiveCfg = DebugCommercial1|Any CPU - {3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}.DebugCommercial|x64.Build.0 = DebugCommercial1|Any CPU - {3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}.DebugCommercial|x86.ActiveCfg = DebugCommercial1|Any CPU - {3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}.DebugCommercial|x86.Build.0 = DebugCommercial1|Any CPU - {3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}.DebugCommercial1|Any CPU.ActiveCfg = DebugCommercial1|Any CPU - {3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}.DebugCommercial1|Any CPU.Build.0 = DebugCommercial1|Any CPU - {3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}.DebugCommercial1|ARM.ActiveCfg = DebugCommercial1|Any CPU - {3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}.DebugCommercial1|ARM.Build.0 = DebugCommercial1|Any CPU - {3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}.DebugCommercial1|x64.ActiveCfg = DebugCommercial1|Any CPU - {3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}.DebugCommercial1|x64.Build.0 = DebugCommercial1|Any CPU - {3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}.DebugCommercial1|x86.ActiveCfg = DebugCommercial1|Any CPU - {3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}.DebugCommercial1|x86.Build.0 = DebugCommercial1|Any CPU - {3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}.DebugCommercial2|Any CPU.ActiveCfg = DebugCommercial1|Any CPU - {3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}.DebugCommercial2|Any CPU.Build.0 = DebugCommercial1|Any CPU - {3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}.DebugCommercial2|ARM.ActiveCfg = DebugCommercial1|Any CPU - {3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}.DebugCommercial2|ARM.Build.0 = DebugCommercial1|Any CPU - {3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}.DebugCommercial2|x64.ActiveCfg = DebugCommercial1|Any CPU - {3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}.DebugCommercial2|x64.Build.0 = DebugCommercial1|Any CPU - {3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}.DebugCommercial2|x86.ActiveCfg = DebugCommercial1|Any CPU - {3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}.DebugCommercial2|x86.Build.0 = DebugCommercial1|Any CPU - {3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}.DebugCommercial3|Any CPU.ActiveCfg = DebugCommercial1|Any CPU - {3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}.DebugCommercial3|Any CPU.Build.0 = DebugCommercial1|Any CPU - {3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}.DebugCommercial3|ARM.ActiveCfg = DebugCommercial1|Any CPU - {3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}.DebugCommercial3|ARM.Build.0 = DebugCommercial1|Any CPU - {3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}.DebugCommercial3|x64.ActiveCfg = DebugCommercial1|Any CPU - {3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}.DebugCommercial3|x64.Build.0 = DebugCommercial1|Any CPU - {3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}.DebugCommercial3|x86.ActiveCfg = DebugCommercial1|Any CPU - {3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}.DebugCommercial3|x86.Build.0 = DebugCommercial1|Any CPU - {3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}.Release|Any CPU.ActiveCfg = Release|Any CPU - {3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}.Release|Any CPU.Build.0 = Release|Any CPU - {3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}.Release|ARM.ActiveCfg = Release|Any CPU - {3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}.Release|ARM.Build.0 = Release|Any CPU - {3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}.Release|x64.ActiveCfg = Release|Any CPU - {3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}.Release|x64.Build.0 = Release|Any CPU - {3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}.Release|x86.ActiveCfg = Release|Any CPU - {3398AAF9-F5A5-4F3B-9A02-14A6B2359DC4}.Release|x86.Build.0 = Release|Any CPU - {62AFCA11-8005-4D14-9F29-89DED1076335}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {62AFCA11-8005-4D14-9F29-89DED1076335}.Debug|Any CPU.Build.0 = Debug|Any CPU - {62AFCA11-8005-4D14-9F29-89DED1076335}.Debug|ARM.ActiveCfg = Debug|Any CPU - {62AFCA11-8005-4D14-9F29-89DED1076335}.Debug|ARM.Build.0 = Debug|Any CPU - {62AFCA11-8005-4D14-9F29-89DED1076335}.Debug|x64.ActiveCfg = Debug|Any CPU - {62AFCA11-8005-4D14-9F29-89DED1076335}.Debug|x64.Build.0 = Debug|Any CPU - {62AFCA11-8005-4D14-9F29-89DED1076335}.Debug|x86.ActiveCfg = Debug|Any CPU - {62AFCA11-8005-4D14-9F29-89DED1076335}.Debug|x86.Build.0 = Debug|Any CPU - {62AFCA11-8005-4D14-9F29-89DED1076335}.DebugCommercial|Any CPU.ActiveCfg = Debug|Any CPU - {62AFCA11-8005-4D14-9F29-89DED1076335}.DebugCommercial|Any CPU.Build.0 = Debug|Any CPU - {62AFCA11-8005-4D14-9F29-89DED1076335}.DebugCommercial|ARM.ActiveCfg = Debug|Any CPU - {62AFCA11-8005-4D14-9F29-89DED1076335}.DebugCommercial|ARM.Build.0 = Debug|Any CPU - {62AFCA11-8005-4D14-9F29-89DED1076335}.DebugCommercial|x64.ActiveCfg = Debug|Any CPU - {62AFCA11-8005-4D14-9F29-89DED1076335}.DebugCommercial|x64.Build.0 = Debug|Any CPU - {62AFCA11-8005-4D14-9F29-89DED1076335}.DebugCommercial|x86.ActiveCfg = Debug|Any CPU - {62AFCA11-8005-4D14-9F29-89DED1076335}.DebugCommercial|x86.Build.0 = Debug|Any CPU - {62AFCA11-8005-4D14-9F29-89DED1076335}.DebugCommercial1|Any CPU.ActiveCfg = Debug|Any CPU - {62AFCA11-8005-4D14-9F29-89DED1076335}.DebugCommercial1|Any CPU.Build.0 = Debug|Any CPU - {62AFCA11-8005-4D14-9F29-89DED1076335}.DebugCommercial1|ARM.ActiveCfg = Debug|Any CPU - {62AFCA11-8005-4D14-9F29-89DED1076335}.DebugCommercial1|ARM.Build.0 = Debug|Any CPU - {62AFCA11-8005-4D14-9F29-89DED1076335}.DebugCommercial1|x64.ActiveCfg = Debug|Any CPU - {62AFCA11-8005-4D14-9F29-89DED1076335}.DebugCommercial1|x64.Build.0 = Debug|Any CPU - {62AFCA11-8005-4D14-9F29-89DED1076335}.DebugCommercial1|x86.ActiveCfg = Debug|Any CPU - {62AFCA11-8005-4D14-9F29-89DED1076335}.DebugCommercial1|x86.Build.0 = Debug|Any CPU - {62AFCA11-8005-4D14-9F29-89DED1076335}.DebugCommercial2|Any CPU.ActiveCfg = Debug|Any CPU - {62AFCA11-8005-4D14-9F29-89DED1076335}.DebugCommercial2|Any CPU.Build.0 = Debug|Any CPU - {62AFCA11-8005-4D14-9F29-89DED1076335}.DebugCommercial2|ARM.ActiveCfg = Debug|Any CPU - {62AFCA11-8005-4D14-9F29-89DED1076335}.DebugCommercial2|ARM.Build.0 = Debug|Any CPU - {62AFCA11-8005-4D14-9F29-89DED1076335}.DebugCommercial2|x64.ActiveCfg = Debug|Any CPU - {62AFCA11-8005-4D14-9F29-89DED1076335}.DebugCommercial2|x64.Build.0 = Debug|Any CPU - {62AFCA11-8005-4D14-9F29-89DED1076335}.DebugCommercial2|x86.ActiveCfg = Debug|Any CPU - {62AFCA11-8005-4D14-9F29-89DED1076335}.DebugCommercial2|x86.Build.0 = Debug|Any CPU - {62AFCA11-8005-4D14-9F29-89DED1076335}.DebugCommercial3|Any CPU.ActiveCfg = Debug|Any CPU - {62AFCA11-8005-4D14-9F29-89DED1076335}.DebugCommercial3|Any CPU.Build.0 = Debug|Any CPU - {62AFCA11-8005-4D14-9F29-89DED1076335}.DebugCommercial3|ARM.ActiveCfg = Debug|Any CPU - {62AFCA11-8005-4D14-9F29-89DED1076335}.DebugCommercial3|ARM.Build.0 = Debug|Any CPU - {62AFCA11-8005-4D14-9F29-89DED1076335}.DebugCommercial3|x64.ActiveCfg = Debug|Any CPU - {62AFCA11-8005-4D14-9F29-89DED1076335}.DebugCommercial3|x64.Build.0 = Debug|Any CPU - {62AFCA11-8005-4D14-9F29-89DED1076335}.DebugCommercial3|x86.ActiveCfg = Debug|Any CPU - {62AFCA11-8005-4D14-9F29-89DED1076335}.DebugCommercial3|x86.Build.0 = Debug|Any CPU - {62AFCA11-8005-4D14-9F29-89DED1076335}.Release|Any CPU.ActiveCfg = Release|Any CPU - {62AFCA11-8005-4D14-9F29-89DED1076335}.Release|Any CPU.Build.0 = Release|Any CPU - {62AFCA11-8005-4D14-9F29-89DED1076335}.Release|ARM.ActiveCfg = Release|Any CPU - {62AFCA11-8005-4D14-9F29-89DED1076335}.Release|ARM.Build.0 = Release|Any CPU - {62AFCA11-8005-4D14-9F29-89DED1076335}.Release|x64.ActiveCfg = Release|Any CPU - {62AFCA11-8005-4D14-9F29-89DED1076335}.Release|x64.Build.0 = Release|Any CPU - {62AFCA11-8005-4D14-9F29-89DED1076335}.Release|x86.ActiveCfg = Release|Any CPU - {62AFCA11-8005-4D14-9F29-89DED1076335}.Release|x86.Build.0 = Release|Any CPU - {83AFFC60-BC95-46B1-861F-B1F80270FBFA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {83AFFC60-BC95-46B1-861F-B1F80270FBFA}.Debug|Any CPU.Build.0 = Debug|Any CPU - {83AFFC60-BC95-46B1-861F-B1F80270FBFA}.Debug|ARM.ActiveCfg = Debug|Any CPU - {83AFFC60-BC95-46B1-861F-B1F80270FBFA}.Debug|ARM.Build.0 = Debug|Any CPU - {83AFFC60-BC95-46B1-861F-B1F80270FBFA}.Debug|x64.ActiveCfg = Debug|Any CPU - {83AFFC60-BC95-46B1-861F-B1F80270FBFA}.Debug|x64.Build.0 = Debug|Any CPU - {83AFFC60-BC95-46B1-861F-B1F80270FBFA}.Debug|x86.ActiveCfg = Debug|Any CPU - {83AFFC60-BC95-46B1-861F-B1F80270FBFA}.Debug|x86.Build.0 = Debug|Any CPU - {83AFFC60-BC95-46B1-861F-B1F80270FBFA}.DebugCommercial|Any CPU.ActiveCfg = Debug|Any CPU - {83AFFC60-BC95-46B1-861F-B1F80270FBFA}.DebugCommercial|Any CPU.Build.0 = Debug|Any CPU - {83AFFC60-BC95-46B1-861F-B1F80270FBFA}.DebugCommercial|ARM.ActiveCfg = Debug|Any CPU - {83AFFC60-BC95-46B1-861F-B1F80270FBFA}.DebugCommercial|ARM.Build.0 = Debug|Any CPU - {83AFFC60-BC95-46B1-861F-B1F80270FBFA}.DebugCommercial|x64.ActiveCfg = Debug|Any CPU - {83AFFC60-BC95-46B1-861F-B1F80270FBFA}.DebugCommercial|x64.Build.0 = Debug|Any CPU - {83AFFC60-BC95-46B1-861F-B1F80270FBFA}.DebugCommercial|x86.ActiveCfg = Debug|Any CPU - {83AFFC60-BC95-46B1-861F-B1F80270FBFA}.DebugCommercial|x86.Build.0 = Debug|Any CPU - {83AFFC60-BC95-46B1-861F-B1F80270FBFA}.DebugCommercial1|Any CPU.ActiveCfg = Debug|Any CPU - {83AFFC60-BC95-46B1-861F-B1F80270FBFA}.DebugCommercial1|Any CPU.Build.0 = Debug|Any CPU - {83AFFC60-BC95-46B1-861F-B1F80270FBFA}.DebugCommercial1|ARM.ActiveCfg = Debug|Any CPU - {83AFFC60-BC95-46B1-861F-B1F80270FBFA}.DebugCommercial1|ARM.Build.0 = Debug|Any CPU - {83AFFC60-BC95-46B1-861F-B1F80270FBFA}.DebugCommercial1|x64.ActiveCfg = Debug|Any CPU - {83AFFC60-BC95-46B1-861F-B1F80270FBFA}.DebugCommercial1|x64.Build.0 = Debug|Any CPU - {83AFFC60-BC95-46B1-861F-B1F80270FBFA}.DebugCommercial1|x86.ActiveCfg = Debug|Any CPU - {83AFFC60-BC95-46B1-861F-B1F80270FBFA}.DebugCommercial1|x86.Build.0 = Debug|Any CPU - {83AFFC60-BC95-46B1-861F-B1F80270FBFA}.DebugCommercial2|Any CPU.ActiveCfg = Debug|Any CPU - {83AFFC60-BC95-46B1-861F-B1F80270FBFA}.DebugCommercial2|Any CPU.Build.0 = Debug|Any CPU - {83AFFC60-BC95-46B1-861F-B1F80270FBFA}.DebugCommercial2|ARM.ActiveCfg = Debug|Any CPU - {83AFFC60-BC95-46B1-861F-B1F80270FBFA}.DebugCommercial2|ARM.Build.0 = Debug|Any CPU - {83AFFC60-BC95-46B1-861F-B1F80270FBFA}.DebugCommercial2|x64.ActiveCfg = Debug|Any CPU - {83AFFC60-BC95-46B1-861F-B1F80270FBFA}.DebugCommercial2|x64.Build.0 = Debug|Any CPU - {83AFFC60-BC95-46B1-861F-B1F80270FBFA}.DebugCommercial2|x86.ActiveCfg = Debug|Any CPU - {83AFFC60-BC95-46B1-861F-B1F80270FBFA}.DebugCommercial2|x86.Build.0 = Debug|Any CPU - {83AFFC60-BC95-46B1-861F-B1F80270FBFA}.DebugCommercial3|Any CPU.ActiveCfg = Debug|Any CPU - {83AFFC60-BC95-46B1-861F-B1F80270FBFA}.DebugCommercial3|Any CPU.Build.0 = Debug|Any CPU - {83AFFC60-BC95-46B1-861F-B1F80270FBFA}.DebugCommercial3|ARM.ActiveCfg = Debug|Any CPU - {83AFFC60-BC95-46B1-861F-B1F80270FBFA}.DebugCommercial3|ARM.Build.0 = Debug|Any CPU - {83AFFC60-BC95-46B1-861F-B1F80270FBFA}.DebugCommercial3|x64.ActiveCfg = Debug|Any CPU - {83AFFC60-BC95-46B1-861F-B1F80270FBFA}.DebugCommercial3|x64.Build.0 = Debug|Any CPU - {83AFFC60-BC95-46B1-861F-B1F80270FBFA}.DebugCommercial3|x86.ActiveCfg = Debug|Any CPU - {83AFFC60-BC95-46B1-861F-B1F80270FBFA}.DebugCommercial3|x86.Build.0 = Debug|Any CPU - {83AFFC60-BC95-46B1-861F-B1F80270FBFA}.Release|Any CPU.ActiveCfg = Release|Any CPU - {83AFFC60-BC95-46B1-861F-B1F80270FBFA}.Release|Any CPU.Build.0 = Release|Any CPU - {83AFFC60-BC95-46B1-861F-B1F80270FBFA}.Release|ARM.ActiveCfg = Release|Any CPU - {83AFFC60-BC95-46B1-861F-B1F80270FBFA}.Release|ARM.Build.0 = Release|Any CPU - {83AFFC60-BC95-46B1-861F-B1F80270FBFA}.Release|x64.ActiveCfg = Release|Any CPU - {83AFFC60-BC95-46B1-861F-B1F80270FBFA}.Release|x64.Build.0 = Release|Any CPU - {83AFFC60-BC95-46B1-861F-B1F80270FBFA}.Release|x86.ActiveCfg = Release|Any CPU - {83AFFC60-BC95-46B1-861F-B1F80270FBFA}.Release|x86.Build.0 = Release|Any CPU - {6BD5A885-D0A3-44C0-BF73-E2118519EAFE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {6BD5A885-D0A3-44C0-BF73-E2118519EAFE}.Debug|Any CPU.Build.0 = Debug|Any CPU - {6BD5A885-D0A3-44C0-BF73-E2118519EAFE}.Debug|ARM.ActiveCfg = Debug|Any CPU - {6BD5A885-D0A3-44C0-BF73-E2118519EAFE}.Debug|ARM.Build.0 = Debug|Any CPU - {6BD5A885-D0A3-44C0-BF73-E2118519EAFE}.Debug|x64.ActiveCfg = Debug|Any CPU - {6BD5A885-D0A3-44C0-BF73-E2118519EAFE}.Debug|x64.Build.0 = Debug|Any CPU - {6BD5A885-D0A3-44C0-BF73-E2118519EAFE}.Debug|x86.ActiveCfg = Debug|Any CPU - {6BD5A885-D0A3-44C0-BF73-E2118519EAFE}.Debug|x86.Build.0 = Debug|Any CPU - {6BD5A885-D0A3-44C0-BF73-E2118519EAFE}.DebugCommercial|Any CPU.ActiveCfg = Debug|Any CPU - {6BD5A885-D0A3-44C0-BF73-E2118519EAFE}.DebugCommercial|Any CPU.Build.0 = Debug|Any CPU - {6BD5A885-D0A3-44C0-BF73-E2118519EAFE}.DebugCommercial|ARM.ActiveCfg = Debug|Any CPU - {6BD5A885-D0A3-44C0-BF73-E2118519EAFE}.DebugCommercial|ARM.Build.0 = Debug|Any CPU - {6BD5A885-D0A3-44C0-BF73-E2118519EAFE}.DebugCommercial|x64.ActiveCfg = Debug|Any CPU - {6BD5A885-D0A3-44C0-BF73-E2118519EAFE}.DebugCommercial|x64.Build.0 = Debug|Any CPU - {6BD5A885-D0A3-44C0-BF73-E2118519EAFE}.DebugCommercial|x86.ActiveCfg = Debug|Any CPU - {6BD5A885-D0A3-44C0-BF73-E2118519EAFE}.DebugCommercial|x86.Build.0 = Debug|Any CPU - {6BD5A885-D0A3-44C0-BF73-E2118519EAFE}.DebugCommercial1|Any CPU.ActiveCfg = Debug|Any CPU - {6BD5A885-D0A3-44C0-BF73-E2118519EAFE}.DebugCommercial1|Any CPU.Build.0 = Debug|Any CPU - {6BD5A885-D0A3-44C0-BF73-E2118519EAFE}.DebugCommercial1|ARM.ActiveCfg = Debug|Any CPU - {6BD5A885-D0A3-44C0-BF73-E2118519EAFE}.DebugCommercial1|ARM.Build.0 = Debug|Any CPU - {6BD5A885-D0A3-44C0-BF73-E2118519EAFE}.DebugCommercial1|x64.ActiveCfg = Debug|Any CPU - {6BD5A885-D0A3-44C0-BF73-E2118519EAFE}.DebugCommercial1|x64.Build.0 = Debug|Any CPU - {6BD5A885-D0A3-44C0-BF73-E2118519EAFE}.DebugCommercial1|x86.ActiveCfg = Debug|Any CPU - {6BD5A885-D0A3-44C0-BF73-E2118519EAFE}.DebugCommercial1|x86.Build.0 = Debug|Any CPU - {6BD5A885-D0A3-44C0-BF73-E2118519EAFE}.DebugCommercial2|Any CPU.ActiveCfg = Debug|Any CPU - {6BD5A885-D0A3-44C0-BF73-E2118519EAFE}.DebugCommercial2|Any CPU.Build.0 = Debug|Any CPU - {6BD5A885-D0A3-44C0-BF73-E2118519EAFE}.DebugCommercial2|ARM.ActiveCfg = Debug|Any CPU - {6BD5A885-D0A3-44C0-BF73-E2118519EAFE}.DebugCommercial2|ARM.Build.0 = Debug|Any CPU - {6BD5A885-D0A3-44C0-BF73-E2118519EAFE}.DebugCommercial2|x64.ActiveCfg = Debug|Any CPU - {6BD5A885-D0A3-44C0-BF73-E2118519EAFE}.DebugCommercial2|x64.Build.0 = Debug|Any CPU - {6BD5A885-D0A3-44C0-BF73-E2118519EAFE}.DebugCommercial2|x86.ActiveCfg = Debug|Any CPU - {6BD5A885-D0A3-44C0-BF73-E2118519EAFE}.DebugCommercial2|x86.Build.0 = Debug|Any CPU - {6BD5A885-D0A3-44C0-BF73-E2118519EAFE}.DebugCommercial3|Any CPU.ActiveCfg = Debug|Any CPU - {6BD5A885-D0A3-44C0-BF73-E2118519EAFE}.DebugCommercial3|Any CPU.Build.0 = Debug|Any CPU - {6BD5A885-D0A3-44C0-BF73-E2118519EAFE}.DebugCommercial3|ARM.ActiveCfg = Debug|Any CPU - {6BD5A885-D0A3-44C0-BF73-E2118519EAFE}.DebugCommercial3|ARM.Build.0 = Debug|Any CPU - {6BD5A885-D0A3-44C0-BF73-E2118519EAFE}.DebugCommercial3|x64.ActiveCfg = Debug|Any CPU - {6BD5A885-D0A3-44C0-BF73-E2118519EAFE}.DebugCommercial3|x64.Build.0 = Debug|Any CPU - {6BD5A885-D0A3-44C0-BF73-E2118519EAFE}.DebugCommercial3|x86.ActiveCfg = Debug|Any CPU - {6BD5A885-D0A3-44C0-BF73-E2118519EAFE}.DebugCommercial3|x86.Build.0 = Debug|Any CPU - {6BD5A885-D0A3-44C0-BF73-E2118519EAFE}.Release|Any CPU.ActiveCfg = Release|Any CPU - {6BD5A885-D0A3-44C0-BF73-E2118519EAFE}.Release|Any CPU.Build.0 = Release|Any CPU - {6BD5A885-D0A3-44C0-BF73-E2118519EAFE}.Release|ARM.ActiveCfg = Release|Any CPU - {6BD5A885-D0A3-44C0-BF73-E2118519EAFE}.Release|ARM.Build.0 = Release|Any CPU - {6BD5A885-D0A3-44C0-BF73-E2118519EAFE}.Release|x64.ActiveCfg = Release|Any CPU - {6BD5A885-D0A3-44C0-BF73-E2118519EAFE}.Release|x64.Build.0 = Release|Any CPU - {6BD5A885-D0A3-44C0-BF73-E2118519EAFE}.Release|x86.ActiveCfg = Release|Any CPU - {6BD5A885-D0A3-44C0-BF73-E2118519EAFE}.Release|x86.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - VisualSVNWorkingCopyRoot = . - SolutionGuid = {7628B1C9-8DDB-4DBD-A71D-D369A4A166DE} - EndGlobalSection -EndGlobal diff --git a/EasyModbus.slnx b/EasyModbus.slnx new file mode 100644 index 0000000..ca1d431 --- /dev/null +++ b/EasyModbus.slnx @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/EasyModbus/AdvancedModbusClient.cs b/EasyModbus/AdvancedModbusClient.cs deleted file mode 100644 index 2c322f0..0000000 --- a/EasyModbus/AdvancedModbusClient.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace EasyModbus -{ - public partial class ModbusClient - { - /* - public enum DataType { Short = 0, UShort = 1, Long = 2, ULong = 3, Float = 4, Double = 5 }; - public object[] ReadHoldingRegisters(int startingAddress, int quantity, DataType dataType, RegisterOrder registerOrder) - { - int quantityToRead = quantity; - if (dataType == DataType.Long | dataType == DataType.ULong | dataType == DataType.Float) - quantityToRead = quantity * 2; - if (dataType == DataType.Float) - quantityToRead = quantity * 4; - int[] response = this.ReadHoldingRegisters(startingAddress, quantityToRead); - switch (dataType) - { - case DataType.Short: return response.Cast().ToArray(); - break; - default: return response.Cast().ToArray(); - break; - - } - - - } - */ - } -} diff --git a/EasyModbus/AssemblyInfo.cs b/EasyModbus/AssemblyInfo.cs new file mode 100644 index 0000000..ce565d0 --- /dev/null +++ b/EasyModbus/AssemblyInfo.cs @@ -0,0 +1,3 @@ +using System.Runtime.InteropServices; + +[assembly: ComVisible(false)] diff --git a/EasyModbus/EasyModbus.csproj b/EasyModbus/EasyModbus.csproj new file mode 100644 index 0000000..a72edc8 --- /dev/null +++ b/EasyModbus/EasyModbus.csproj @@ -0,0 +1,27 @@ + + + net10.0 + EasyModbus + EasyModbus + 5.6.0 + enable + enable + true + Modbus TCP, UDP, and RTU client/server library for .NET 10. + Stefan Rossmann Engineering Solutions + Copyright (c) 2018-2020 Rossmann-Engineering + MIT + https://github.com/rjjong1/EasyModbusTCP.NET + README.md + Debug;Release;Plugins + + + true + none + false + + + + + + diff --git a/EasyModbus/EasyModbus_Net40.csproj b/EasyModbus/EasyModbus_Net40.csproj deleted file mode 100644 index 41db91d..0000000 --- a/EasyModbus/EasyModbus_Net40.csproj +++ /dev/null @@ -1,81 +0,0 @@ - - - - {7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B} - Debug - AnyCPU - Library - EasyModbus - EasyModbus - v4.0 - - - Properties - - - - - 3.5 - - - AnyCPU - - - bin\Debug\ - True - Full - False - True - DEBUG;TRACE - - - bin\Release\ - False - None - True - False - TRACE - - - true - bin\DebugCommercial\ - TRACE;DEBUG;COMMERCIAL - true - Full - AnyCPU - MinimumRecommendedRules.ruleset - false - - - TRACE;DEBUG;SSL - false - 0 - bin\Debug\EasyModbus.xml - - - false - - - - - - 3.5 - - - - 3.5 - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/EasyModbus/EasyModbus_Net40.nuspec b/EasyModbus/EasyModbus_Net40.nuspec deleted file mode 100644 index 2e96d5a..0000000 --- a/EasyModbus/EasyModbus_Net40.nuspec +++ /dev/null @@ -1,20 +0,0 @@ - - - - EasyModbusTCP - 5.6 - EasyModbusTCP - Stefan Roßmann - false - MIT - http://www.EasyModbusTCP.net - http://easymodbustcp.net/wp-content/uploads/2020/06/medium-e1592036520465.png - Modbus TCP, Modbus UDP and Modbus RTU client/server library for .NET implementations - Update to version 5.6 - Rossmann Engineering 2018-2020 - Modbus TCP RTU EasyModbusTCP - - - - - \ No newline at end of file diff --git a/EasyModbus/Exceptions/Exceptions.cs b/EasyModbus/Exceptions/Exceptions.cs index 8d1db4f..2b3e2e9 100644 --- a/EasyModbus/Exceptions/Exceptions.cs +++ b/EasyModbus/Exceptions/Exceptions.cs @@ -1,211 +1,188 @@ -/* +/* Copyright (c) 2018-2020 Rossmann-Engineering -Permission is hereby granted, free of charge, +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), -to deal in the Software without restriction, -including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, -and/or sell copies of the Software, and to permit -persons to whom the Software is furnished to do so, +to deal in the Software without restriction, +including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, subject to the following conditions: -The above copyright notice and this permission +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, -ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Runtime.Serialization; -namespace EasyModbus.Exceptions +namespace EasyModbus.Exceptions; + +/// +/// Exception to be thrown if serial port is not opened +/// +public class SerialPortNotOpenedException : ModbusException +{ + public SerialPortNotOpenedException() : base() + { + } + + public SerialPortNotOpenedException(string? message) : base(message) + { + } + + public SerialPortNotOpenedException(string? message, Exception? innerException) : base(message, innerException) + { + } + + [Obsolete("Formatter-based exception serialization is obsolete.", DiagnosticId = "SYSLIB0051")] + protected SerialPortNotOpenedException(SerializationInfo info, StreamingContext context) : base(info, context) + { + } +} + +/// +/// Exception to be thrown if Connection to Modbus device failed +/// +public class ConnectionException : ModbusException +{ + public ConnectionException() : base() + { + } + + public ConnectionException(string? message) : base(message) + { + } + + public ConnectionException(string? message, Exception? innerException) : base(message, innerException) + { + } + + [Obsolete("Formatter-based exception serialization is obsolete.", DiagnosticId = "SYSLIB0051")] + protected ConnectionException(SerializationInfo info, StreamingContext context) : base(info, context) + { + } +} + +/// +/// Exception to be thrown if Modbus Server returns error code "Function code not supported" +/// +public class FunctionCodeNotSupportedException : ModbusException +{ + public FunctionCodeNotSupportedException() : base() + { + } + + public FunctionCodeNotSupportedException(string? message) : base(message) + { + } + + public FunctionCodeNotSupportedException(string? message, Exception? innerException) : base(message, innerException) + { + } + + [Obsolete("Formatter-based exception serialization is obsolete.", DiagnosticId = "SYSLIB0051")] + protected FunctionCodeNotSupportedException(SerializationInfo info, StreamingContext context) : base(info, context) + { + } +} + +/// +/// Exception to be thrown if Modbus Server returns error code "quantity invalid" +/// +public class QuantityInvalidException : ModbusException +{ + public QuantityInvalidException() : base() + { + } + + public QuantityInvalidException(string? message) : base(message) + { + } + + public QuantityInvalidException(string? message, Exception? innerException) : base(message, innerException) + { + } + + [Obsolete("Formatter-based exception serialization is obsolete.", DiagnosticId = "SYSLIB0051")] + protected QuantityInvalidException(SerializationInfo info, StreamingContext context) : base(info, context) + { + } +} + +/// +/// Exception to be thrown if Modbus Server returns error code "starting adddress and quantity invalid" +/// +public class StartingAddressInvalidException : ModbusException +{ + public StartingAddressInvalidException() : base() + { + } + + public StartingAddressInvalidException(string? message) : base(message) + { + } + + public StartingAddressInvalidException(string? message, Exception? innerException) : base(message, innerException) + { + } + + [Obsolete("Formatter-based exception serialization is obsolete.", DiagnosticId = "SYSLIB0051")] + protected StartingAddressInvalidException(SerializationInfo info, StreamingContext context) : base(info, context) + { + } +} + +/// +/// Exception to be thrown if Modbus Server returns error code "Function Code not executed (0x04)" +/// +public class ModbusException : Exception +{ + public ModbusException() : base() + { + } + + public ModbusException(string? message) : base(message) + { + } + + public ModbusException(string? message, Exception? innerException) : base(message, innerException) + { + } + + [Obsolete("Formatter-based exception serialization is obsolete.", DiagnosticId = "SYSLIB0051")] + protected ModbusException(SerializationInfo info, StreamingContext context) : base(info, context) + { + } +} + +/// +/// Exception to be thrown if CRC Check failed +/// +public class CRCCheckFailedException : ModbusException { - /// - /// Exception to be thrown if serial port is not opened - /// - public class SerialPortNotOpenedException : ModbusException - { - public SerialPortNotOpenedException() - : base() - { - } - - public SerialPortNotOpenedException(string message) - : base(message) - { - } - - public SerialPortNotOpenedException(string message, Exception innerException) - : base(message, innerException) - { - } - - protected SerialPortNotOpenedException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } - } - - /// - /// Exception to be thrown if Connection to Modbus device failed - /// - public class ConnectionException : ModbusException - { - public ConnectionException() - : base() - { - } - - public ConnectionException(string message) - : base(message) - { - } - - public ConnectionException(string message, Exception innerException) - : base(message, innerException) - { - } - - protected ConnectionException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } - } - - /// - /// Exception to be thrown if Modbus Server returns error code "Function code not supported" - /// - public class FunctionCodeNotSupportedException : ModbusException - { - public FunctionCodeNotSupportedException() - : base() - { - } - - public FunctionCodeNotSupportedException(string message) - : base(message) - { - } - - public FunctionCodeNotSupportedException(string message, Exception innerException) - : base(message, innerException) - { - } - - protected FunctionCodeNotSupportedException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } - } - - /// - /// Exception to be thrown if Modbus Server returns error code "quantity invalid" - /// - public class QuantityInvalidException : ModbusException - { - public QuantityInvalidException() - : base() - { - } - - public QuantityInvalidException(string message) - : base(message) - { - } - - public QuantityInvalidException(string message, Exception innerException) - : base(message, innerException) - { - } - - protected QuantityInvalidException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } - } - - /// - /// Exception to be thrown if Modbus Server returns error code "starting adddress and quantity invalid" - /// - public class StartingAddressInvalidException : ModbusException - { - public StartingAddressInvalidException() - : base() - { - } - - public StartingAddressInvalidException(string message) - : base(message) - { - } - - public StartingAddressInvalidException(string message, Exception innerException) - : base(message, innerException) - { - } - - protected StartingAddressInvalidException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } - } - - /// - /// Exception to be thrown if Modbus Server returns error code "Function Code not executed (0x04)" - /// - public class ModbusException : Exception - { - public ModbusException() - : base() - { - } - - public ModbusException(string message) - : base(message) - { - } - - public ModbusException(string message, Exception innerException) - : base(message, innerException) - { - } - - protected ModbusException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } - } - - /// - /// Exception to be thrown if CRC Check failed - /// - public class CRCCheckFailedException : ModbusException - { - public CRCCheckFailedException() - : base() - { - } - - public CRCCheckFailedException(string message) - : base(message) - { - } - - public CRCCheckFailedException(string message, Exception innerException) - : base(message, innerException) - { - } - - protected CRCCheckFailedException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } - } - + public CRCCheckFailedException() : base() + { + } + + public CRCCheckFailedException(string? message) : base(message) + { + } + + public CRCCheckFailedException(string? message, Exception? innerException) : base(message, innerException) + { + } + + [Obsolete("Formatter-based exception serialization is obsolete.", DiagnosticId = "SYSLIB0051")] + protected CRCCheckFailedException(SerializationInfo info, StreamingContext context) : base(info, context) + { + } } diff --git a/EasyModbus/ModbusClient.Conversions.cs b/EasyModbus/ModbusClient.Conversions.cs new file mode 100644 index 0000000..beb8993 --- /dev/null +++ b/EasyModbus/ModbusClient.Conversions.cs @@ -0,0 +1,97 @@ +using System.Buffers.Binary; +using System.Text; + +namespace EasyModbus; + +public partial class ModbusClient +{ + public static float ConvertRegistersToFloat(int[] registers) => ConvertRegistersToFloat(registers, RegisterOrder.LowHigh); + public static float ConvertRegistersToFloat(int[] registers, RegisterOrder registerOrder) => BitConverter.Int32BitsToSingle(ConvertRegistersToInt(registers, registerOrder)); + public static int ConvertRegistersToInt(int[] registers) => ConvertRegistersToInt(registers, RegisterOrder.LowHigh); + public static int ConvertRegistersToInt(int[] registers, RegisterOrder registerOrder) => unchecked((int)ReadRegisterBits(registers, 2, registerOrder)); + public static long ConvertRegistersToLong(int[] registers) => ConvertRegistersToLong(registers, RegisterOrder.LowHigh); + public static long ConvertRegistersToLong(int[] registers, RegisterOrder registerOrder) => unchecked((long)ReadRegisterBits(registers, 4, registerOrder)); + public static double ConvertRegistersToDouble(int[] registers) => ConvertRegistersToDouble(registers, RegisterOrder.LowHigh); + public static double ConvertRegistersToDouble(int[] registers, RegisterOrder registerOrder) => BitConverter.Int64BitsToDouble(ConvertRegistersToLong(registers, registerOrder)); + + public static int[] ConvertFloatToRegisters(float floatValue) => ConvertFloatToRegisters(floatValue, RegisterOrder.LowHigh); + public static int[] ConvertFloatToRegisters(float floatValue, RegisterOrder registerOrder) => ConvertIntToRegisters(BitConverter.SingleToInt32Bits(floatValue), registerOrder); + public static int[] ConvertIntToRegisters(int intValue) => ConvertIntToRegisters(intValue, RegisterOrder.LowHigh); + public static int[] ConvertIntToRegisters(int intValue, RegisterOrder registerOrder) => WriteRegisterBits(unchecked((uint)intValue), 2, registerOrder); + public static int[] ConvertLongToRegisters(long longValue) => ConvertLongToRegisters(longValue, RegisterOrder.LowHigh); + public static int[] ConvertLongToRegisters(long longValue, RegisterOrder registerOrder) => WriteRegisterBits(unchecked((ulong)longValue), 4, registerOrder); + public static int[] ConvertDoubleToRegisters(double doubleValue) => ConvertDoubleToRegisters(doubleValue, RegisterOrder.LowHigh); + public static int[] ConvertDoubleToRegisters(double doubleValue, RegisterOrder registerOrder) => ConvertLongToRegisters(BitConverter.DoubleToInt64Bits(doubleValue), registerOrder); + + private static ulong ReadRegisterBits(int[] registers, int count, RegisterOrder order) + { + ArgumentNullException.ThrowIfNull(registers); + if (registers.Length != count) + throw new ArgumentException($"Expected exactly {count} registers.", nameof(registers)); + ValidateRegisterOrder(order); + ulong value = 0; + for (var index = 0; index < count; index++) + { + var register = order == RegisterOrder.LowHigh ? index : count - index - 1; + value |= (ulong)(ushort)registers[register] << (index * 16); + } + return value; + } + + private static int[] WriteRegisterBits(ulong value, int count, RegisterOrder order) + { + ValidateRegisterOrder(order); + var registers = new int[count]; + for (var index = 0; index < count; index++) + registers[order == RegisterOrder.LowHigh ? index : count - index - 1] = (ushort)(value >> (index * 16)); + return registers; + } + + private static void ValidateRegisterOrder(RegisterOrder order) + { + if (order is not RegisterOrder.LowHigh and not RegisterOrder.HighLow) + throw new ArgumentOutOfRangeException(nameof(order)); + } + + /// Decodes ASCII register bytes, low byte first. Length is in characters. + public static string ConvertRegistersToString(int[] registers, int offset, int stringLength) + { + ArgumentNullException.ThrowIfNull(registers); + ArgumentOutOfRangeException.ThrowIfNegative(offset); + ArgumentOutOfRangeException.ThrowIfGreaterThan(offset, registers.Length); + ArgumentOutOfRangeException.ThrowIfNegative(stringLength); + if (stringLength > (registers.Length - offset) * 2L) + throw new ArgumentOutOfRangeException(nameof(stringLength)); + Span bytes = stringLength <= 256 ? stackalloc byte[stringLength] : new byte[stringLength]; + for (var index = 0; index < bytes.Length; index++) + bytes[index] = (byte)(registers[offset + index / 2] >> (index % 2 * 8)); + return Encoding.ASCII.GetString(bytes); + } + + public static int[] ConvertStringToRegisters(string stringToConvert) + { + ArgumentNullException.ThrowIfNull(stringToConvert); + var bytes = Encoding.ASCII.GetBytes(stringToConvert); + var registers = new int[(bytes.Length + 1) / 2]; + for (var index = 0; index < bytes.Length; index++) + registers[index / 2] |= bytes[index] << (index % 2 * 8); + return registers; + } + + public static ushort CalculateCRC(byte[] data, ushort numberOfBytes, int startByte) + { + ArgumentNullException.ThrowIfNull(data); + return ModbusFrame.CalculateCrc(data.AsSpan(startByte, numberOfBytes)); + } + + public static ushort CalculateCRC(ReadOnlySpan data) => ModbusFrame.CalculateCrc(data); + + public static bool DetectValidModbusFrame(byte[] readBuffer, int length) + { + ArgumentNullException.ThrowIfNull(readBuffer); + if (length < 4 || length > Math.Min(readBuffer.Length, 256)) + return false; + return ModbusFrame.CalculateCrc(readBuffer.AsSpan(0, length - 2)) == + BinaryPrimitives.ReadUInt16LittleEndian(readBuffer.AsSpan(length - 2, 2)); + } +} diff --git a/EasyModbus/ModbusClient.Protocol.cs b/EasyModbus/ModbusClient.Protocol.cs new file mode 100644 index 0000000..c4b4c73 --- /dev/null +++ b/EasyModbus/ModbusClient.Protocol.cs @@ -0,0 +1,322 @@ +using System.Buffers.Binary; +using EasyModbus.Exceptions; + +namespace EasyModbus; + +public partial class ModbusClient +{ + public bool[] ReadCoils(int startingAddress, int quantity) => ReadCoilsAsync(startingAddress, quantity).GetAwaiter().GetResult(); + public bool[] ReadDiscreteInputs(int startingAddress, int quantity) => ReadDiscreteInputsAsync(startingAddress, quantity).GetAwaiter().GetResult(); + public int[] ReadHoldingRegisters(int startingAddress, int quantity) => ReadHoldingRegistersAsync(startingAddress, quantity).GetAwaiter().GetResult(); + public int[] ReadInputRegisters(int startingAddress, int quantity) => ReadInputRegistersAsync(startingAddress, quantity).GetAwaiter().GetResult(); + public void WriteSingleCoil(int startingAddress, bool value) => WriteSingleCoilAsync(startingAddress, value).GetAwaiter().GetResult(); + public void WriteSingleRegister(int startingAddress, int value) => WriteSingleRegisterAsync(startingAddress, value).GetAwaiter().GetResult(); + public void WriteMultipleCoils(int startingAddress, bool[] values) => WriteMultipleCoilsAsync(startingAddress, values).GetAwaiter().GetResult(); + public void WriteMultipleRegisters(int startingAddress, int[] values) => WriteMultipleRegistersAsync(startingAddress, values).GetAwaiter().GetResult(); + public int[] ReadWriteMultipleRegisters(int startingAddressRead, int quantityRead, int startingAddressWrite, int[] values) => ReadWriteMultipleRegistersAsync(startingAddressRead, quantityRead, startingAddressWrite, values).GetAwaiter().GetResult(); + + public Task ReadCoilsAsync(int startingAddress, int quantity, CancellationToken cancellationToken = default) => ReadBitsAsync(1, startingAddress, quantity, cancellationToken); + public Task ReadDiscreteInputsAsync(int startingAddress, int quantity, CancellationToken cancellationToken = default) => ReadBitsAsync(2, startingAddress, quantity, cancellationToken); + public Task ReadHoldingRegistersAsync(int startingAddress, int quantity, CancellationToken cancellationToken = default) => ReadRegistersAsync(3, startingAddress, quantity, cancellationToken); + public Task ReadInputRegistersAsync(int startingAddress, int quantity, CancellationToken cancellationToken = default) => ReadRegistersAsync(4, startingAddress, quantity, cancellationToken); + + private async Task ReadBitsAsync(byte function, int address, int quantity, CancellationToken cancellationToken) + { + ValidateRange(address, quantity, 2000); + var response = await ExecuteAsync(CreateRequest(function, address, quantity), cancellationToken).ConfigureAwait(false); + ValidateReadResponse(response, (quantity + 7) / 8); + var values = new bool[quantity]; + for (var index = 0; index < values.Length; index++) + values[index] = (response[2 + index / 8] & (1 << (index % 8))) != 0; + + return values; + } + + private async Task ReadRegistersAsync(byte function, int address, int quantity, CancellationToken cancellationToken) + { + ValidateRange(address, quantity, 125); + var response = await ExecuteAsync(CreateRequest(function, address, quantity), cancellationToken).ConfigureAwait(false); + return DecodeRegisters(response, quantity); + } + + public Task WriteSingleCoilAsync(int startingAddress, bool value, CancellationToken cancellationToken = default) => + WriteSingleAsync(5, startingAddress, value ? 0xFF00 : 0, cancellationToken); + + public Task WriteSingleRegisterAsync(int startingAddress, int value, CancellationToken cancellationToken = default) + { + ValidateRegisterValue(value); + return WriteSingleAsync(6, startingAddress, value, cancellationToken); + } + + private async Task WriteSingleAsync(byte function, int address, int value, CancellationToken cancellationToken) + { + ValidateRange(address, 1, 1); + var request = CreateRequest(function, address, value); + var response = await ExecuteAsync(request, cancellationToken).ConfigureAwait(false); + if (!request.AsSpan().SequenceEqual(response)) + throw new InvalidDataException("The Modbus write acknowledgement does not match the request."); + } + + public async Task WriteMultipleCoilsAsync(int startingAddress, bool[] values, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(values); + ValidateRange(startingAddress, values.Length, 1968); + var request = new byte[6 + (values.Length + 7) / 8]; + CreateRequest(15, startingAddress, values.Length).CopyTo(request, 0); + request[5] = (byte)(request.Length - 6); + for (var index = 0; index < values.Length; index++) + if (values[index]) + request[6 + index / 8] |= (byte)(1 << (index % 8)); + + var response = await ExecuteAsync(request, cancellationToken).ConfigureAwait(false); + ValidateWriteResponse(request, response); + } + + public async Task WriteMultipleRegistersAsync(int startingAddress, int[] values, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(values); + ValidateRange(startingAddress, values.Length, 123); + var request = new byte[6 + values.Length * 2]; + CreateRequest(16, startingAddress, values.Length).CopyTo(request, 0); + request[5] = (byte)(values.Length * 2); + EncodeRegisters(values, request.AsSpan(6)); + var response = await ExecuteAsync(request, cancellationToken).ConfigureAwait(false); + ValidateWriteResponse(request, response); + } + + public async Task ReadWriteMultipleRegistersAsync(int startingAddressRead, int quantityRead, int startingAddressWrite, int[] values, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(values); + ValidateRange(startingAddressRead, quantityRead, 125); + ValidateRange(startingAddressWrite, values.Length, 121); + var request = new byte[10 + values.Length * 2]; + CreateRequest(23, startingAddressRead, quantityRead).CopyTo(request, 0); + BinaryPrimitives.WriteUInt16BigEndian(request.AsSpan(5), (ushort)startingAddressWrite); + BinaryPrimitives.WriteUInt16BigEndian(request.AsSpan(7), (ushort)values.Length); + request[9] = (byte)(values.Length * 2); + EncodeRegisters(values, request.AsSpan(10)); + var response = await ExecuteAsync(request, cancellationToken).ConfigureAwait(false); + return DecodeRegisters(response, quantityRead); + } + + private static byte[] CreateRequest(byte function, int address, int value) + { + var request = new byte[5]; + request[0] = function; + BinaryPrimitives.WriteUInt16BigEndian(request.AsSpan(1), (ushort)address); + BinaryPrimitives.WriteUInt16BigEndian(request.AsSpan(3), unchecked((ushort)value)); + return request; + } + + private static void ValidateRange(int address, int quantity, int maxQuantity) + { + ArgumentOutOfRangeException.ThrowIfNegative(address); + ArgumentOutOfRangeException.ThrowIfGreaterThan(address, 65535); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(quantity); + ArgumentOutOfRangeException.ThrowIfGreaterThan(quantity, maxQuantity); + if ((long)address + quantity > 65536) + throw new ArgumentOutOfRangeException(nameof(quantity), "The requested range exceeds the Modbus address space."); + } + + private static void ValidateRegisterValue(int value) + { + if (value is < short.MinValue or > ushort.MaxValue) + throw new ArgumentOutOfRangeException(nameof(value), "A register must fit in a signed or unsigned 16-bit value."); + } + + private static void EncodeRegisters(ReadOnlySpan values, Span destination) + { + for (var index = 0; index < values.Length; index++) + { + ValidateRegisterValue(values[index]); + BinaryPrimitives.WriteUInt16BigEndian(destination[(index * 2)..], unchecked((ushort)values[index])); + } + } + + private static int[] DecodeRegisters(byte[] response, int quantity) + { + ValidateReadResponse(response, quantity * 2); + var values = new int[quantity]; + for (var index = 0; index < quantity; index++) + values[index] = BinaryPrimitives.ReadInt16BigEndian(response.AsSpan(2 + index * 2)); + + return values; + } + + private static void ValidateReadResponse(byte[] response, int expectedBytes) + { + if (response.Length != expectedBytes + 2 || response[1] != expectedBytes) + throw new InvalidDataException("The Modbus response byte count does not match the request."); + } + + private static void ValidateWriteResponse(byte[] request, byte[] response) + { + if (!request.AsSpan(0, 5).SequenceEqual(response)) + throw new InvalidDataException("The Modbus write acknowledgement does not match the request."); + } + + private async Task ExecuteAsync(byte[] pdu, CancellationToken cancellationToken) + { + await _operationLock.WaitAsync(cancellationToken).ConfigureAwait(false); + + var sent = false; + var received = false; + var wasConnected = Connected; + try + { + ObjectDisposedException.ThrowIf(_disposed, this); + if (!Connected) + throw _serialport is not null ? new SerialPortNotOpenedException("The serial port is not open.") : + new ConnectionException("The Modbus client is not connected."); + + for (var attempt = 0; ; attempt++) + { + cancellationToken.ThrowIfCancellationRequested(); + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeout.CancelAfter(ConnectionTimeout); + try + { + byte[] response; + if (_serialport is not null) + { + if (!_serialport.IsOpen) + { + ConfigureSerialPort(); + _serialport.Open(); + } + response = await ExchangeSerialAsync(pdu, timeout.Token).ConfigureAwait(false); + } + else + { + var transaction = unchecked(++_transactionIdentifier); + _sendData = ModbusFrame.Create(transaction, UnitIdentifier, pdu); + sent = true; + StoreLogData.Instance.Store($"Send: {Convert.ToHexString(_sendData)}", DateTime.Now); + if (_udpClient is not null) + { + await _udpClient.SendAsync(_sendData, timeout.Token).ConfigureAwait(false); + _receiveData = (await _udpClient.ReceiveAsync(timeout.Token).ConfigureAwait(false)).Buffer; + } + else + { + await _stream!.WriteAsync(_sendData, timeout.Token).ConfigureAwait(false); + _receiveData = await ModbusFrame.ReadAsync(_stream, timeout.Token).ConfigureAwait(false); + } + + received = true; + ModbusFrame.Validate(_receiveData); + if (BinaryPrimitives.ReadUInt16BigEndian(_receiveData) != transaction || _receiveData[6] != UnitIdentifier) + throw new InvalidDataException("The response transaction or unit identifier does not match the request."); + + response = _receiveData[7..]; + } + + sent = received = true; + StoreLogData.Instance.Store($"Receive: {Convert.ToHexString(_receiveData)}", DateTime.Now); + ValidateFunction(response, pdu[0]); + return response; + } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested && _serialport is not null && attempt < NumberOfRetries) + { + CloseTransport(); + } + catch (CRCCheckFailedException) when (_serialport is not null && attempt < NumberOfRetries) + { + _serialport.DiscardInBuffer(); + } + catch (OperationCanceledException exception) + { + CloseTransport(); + cancellationToken.ThrowIfCancellationRequested(); + throw new TimeoutException("The Modbus request timed out.", exception); + } + } + } + catch (IOException exception) + { + CloseTransport(); + throw new ConnectionException("The Modbus connection closed before a complete response was received.", exception); + } + catch (System.Net.Sockets.SocketException exception) + { + CloseTransport(); + throw new ConnectionException("The Modbus transport failed.", exception); + } + catch (InvalidDataException) + { + CloseTransport(); + throw; + } + finally + { + _operationLock.Release(); + if (sent) + SendDataChanged?.Invoke(this); + if (received) + ReceiveDataChanged?.Invoke(this); + if (wasConnected && !Connected) + ConnectedChanged?.Invoke(this); + } + } + + private async Task ExchangeSerialAsync(byte[] pdu, CancellationToken cancellationToken) + { + var serial = _serialport!; + _sendData = new byte[pdu.Length + 3]; + _sendData[0] = UnitIdentifier; + pdu.CopyTo(_sendData, 1); + BinaryPrimitives.WriteUInt16LittleEndian(_sendData.AsSpan(_sendData.Length - 2), ModbusFrame.CalculateCrc(_sendData.AsSpan(0, _sendData.Length - 2))); + serial.DiscardInBuffer(); + + // Closing the port also cancels drivers that do not honor async read cancellation. + using var registration = cancellationToken.Register(serial.Close); + try + { + await serial.BaseStream.WriteAsync(_sendData, cancellationToken).ConfigureAwait(false); + var header = new byte[3]; + await serial.BaseStream.ReadExactlyAsync(header, cancellationToken).ConfigureAwait(false); + var remaining = (header[1] & 0x80) != 0 ? 2 : header[1] is 5 or 6 or 15 or 16 ? 5 : header[2] + 2; + if (remaining + 3 > 256) + throw new InvalidDataException("The RTU response is too large."); + + _receiveData = new byte[3 + remaining]; + header.CopyTo(_receiveData, 0); + await serial.BaseStream.ReadExactlyAsync(_receiveData.AsMemory(3), cancellationToken).ConfigureAwait(false); + if (!DetectValidModbusFrame(_receiveData, _receiveData.Length)) + throw new CRCCheckFailedException("The RTU response CRC is invalid."); + + if (_receiveData[0] != UnitIdentifier) + throw new InvalidDataException("The RTU response unit identifier does not match the request."); + + return _receiveData[1..^2]; + } + catch (Exception exception) when (cancellationToken.IsCancellationRequested && exception is IOException or InvalidOperationException or ObjectDisposedException) + { + throw new OperationCanceledException("The serial operation was canceled.", exception, cancellationToken); + } + } + + private static void ValidateFunction(byte[] response, byte function) + { + if (response.Length == 0) + throw new InvalidDataException("The Modbus response is empty."); + + if (response[0] == (function | 0x80)) + { + if (response.Length != 2) + throw new InvalidDataException("Invalid Modbus exception response length."); + + throw response[1] switch + { + 1 => new FunctionCodeNotSupportedException("The server does not support the function code."), + 2 => new StartingAddressInvalidException("The server rejected the address range."), + 3 => new QuantityInvalidException("The server rejected the quantity or value."), + _ => new ModbusException($"The server returned Modbus exception 0x{response[1]:X2}.") + }; + } + + if (response[0] != function) + throw new InvalidDataException("The response function code does not match the request."); + } +} diff --git a/EasyModbus/ModbusClient.cs b/EasyModbus/ModbusClient.cs index b9e0285..fc7bf4b 100644 --- a/EasyModbus/ModbusClient.cs +++ b/EasyModbus/ModbusClient.cs @@ -1,2876 +1,267 @@ -/* -Copyright (c) 2018-2020 Rossmann-Engineering -Permission is hereby granted, free of charge, -to any person obtaining a copy of this software -and associated documentation files (the "Software"), -to deal in the Software without restriction, -including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, -and/or sell copies of the Software, and to permit -persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission -notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, -ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE -OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ -using System; -using System.Net.Sockets; -using System.Net; -using System.IO.Ports; -using System.Reflection; -using System.Text; -using System.Collections.Generic; -using System.Threading; - -namespace EasyModbus -{ - /// - /// Implements a ModbusClient. - /// - public partial class ModbusClient - { - public enum RegisterOrder { LowHigh = 0, HighLow = 1 }; - private bool debug=false; - private TcpClient tcpClient; - private string ipAddress = "127.0.0.1"; - private int port = 502; - private uint transactionIdentifierInternal = 0; - private byte [] transactionIdentifier = new byte[2]; - private byte [] protocolIdentifier = new byte[2]; - private byte[] crc = new byte[2]; - private byte [] length = new byte[2]; - private byte unitIdentifier = 0x01; - private byte functionCode; - private byte [] startingAddress = new byte[2]; - private byte [] quantity = new byte[2]; - private bool udpFlag = false; - private int portOut; - private int baudRate = 9600; - private int connectTimeout = 1000; - public byte[] receiveData; - public byte[] sendData; - private SerialPort serialport; - private Parity parity = Parity.Even; - private StopBits stopBits = StopBits.One; - private bool connected = false; - public int NumberOfRetries { get; set; } = 3; - private int countRetries = 0; - - public delegate void ReceiveDataChangedHandler(object sender); - public event ReceiveDataChangedHandler ReceiveDataChanged; - - public delegate void SendDataChangedHandler(object sender); - public event SendDataChangedHandler SendDataChanged; - - public delegate void ConnectedChangedHandler(object sender); - public event ConnectedChangedHandler ConnectedChanged; - - NetworkStream stream; - - /// - /// Constructor which determines the Master ip-address and the Master Port. - /// - /// IP-Address of the Master device - /// Listening port of the Master device (should be 502) - public ModbusClient(string ipAddress, int port) - { - if (debug) StoreLogData.Instance.Store("EasyModbus library initialized for Modbus-TCP, IPAddress: " + ipAddress + ", Port: "+port ,System.DateTime.Now); -#if (!COMMERCIAL) - Console.WriteLine("EasyModbus Client Library Version: " + Assembly.GetExecutingAssembly().GetName().Version.ToString()); - Console.WriteLine("Copyright (c) Stefan Rossmann Engineering Solutions"); - Console.WriteLine(); -#endif - this.ipAddress = ipAddress; - this.port = port; - } - - /// - /// Constructor which determines the Serial-Port - /// - /// Serial-Port Name e.G. "COM1" - public ModbusClient(string serialPort) - { - if (debug) StoreLogData.Instance.Store("EasyModbus library initialized for Modbus-RTU, COM-Port: " + serialPort ,System.DateTime.Now); -#if (!COMMERCIAL) - Console.WriteLine("EasyModbus Client Library Version: " + Assembly.GetExecutingAssembly().GetName().Version.ToString()); - Console.WriteLine("Copyright (c) Stefan Rossmann Engineering Solutions"); - Console.WriteLine(); -#endif - this.serialport = new SerialPort(); - serialport.PortName = serialPort; - serialport.BaudRate = baudRate; - serialport.Parity = parity; - serialport.StopBits = stopBits; - serialport.WriteTimeout = 10000; - serialport.ReadTimeout = connectTimeout; - - serialport.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler); - } - - /// - /// Parameterless constructor - /// - public ModbusClient() - { - if (debug) StoreLogData.Instance.Store("EasyModbus library initialized for Modbus-TCP" ,System.DateTime.Now); -#if (!COMMERCIAL) - Console.WriteLine("EasyModbus Client Library Version: " + Assembly.GetExecutingAssembly().GetName().Version.ToString()); - Console.WriteLine("Copyright (c) Stefan Rossmann Engineering Solutions"); - Console.WriteLine(); -#endif - } - - /// - /// Establish connection to Master device in case of Modbus TCP. Opens COM-Port in case of Modbus RTU - /// - public void Connect() - { - if (serialport != null) - { - if (!serialport.IsOpen) - { - if (debug) StoreLogData.Instance.Store("Open Serial port " + serialport.PortName,System.DateTime.Now); - serialport.BaudRate = baudRate; - serialport.Parity = parity; - serialport.StopBits = stopBits; - serialport.WriteTimeout = 10000; - serialport.ReadTimeout = connectTimeout; - serialport.Open(); - connected = true; - - - } - if (ConnectedChanged != null) - try - { - ConnectedChanged(this); - } - catch - { - - } - return; - } - if (!udpFlag) - { - if (debug) StoreLogData.Instance.Store("Open TCP-Socket, IP-Address: " + ipAddress + ", Port: " + port, System.DateTime.Now); - tcpClient = new TcpClient(); - var result = tcpClient.BeginConnect(ipAddress, port, null, null); - var success = result.AsyncWaitHandle.WaitOne(connectTimeout); - if (!success) - { - throw new EasyModbus.Exceptions.ConnectionException("connection timed out"); - } - tcpClient.EndConnect(result); - - //tcpClient = new TcpClient(ipAddress, port); - stream = tcpClient.GetStream(); - stream.ReadTimeout = connectTimeout; - connected = true; - } - else - { - tcpClient = new TcpClient(); - connected = true; - } - if (ConnectedChanged != null) - try - { - ConnectedChanged(this); - } - catch - { - - } - } - - /// - /// Establish connection to Master device in case of Modbus TCP. - /// - public void Connect(string ipAddress, int port) - { - if (!udpFlag) - { - if (debug) StoreLogData.Instance.Store("Open TCP-Socket, IP-Address: " + ipAddress + ", Port: " + port, System.DateTime.Now); - tcpClient = new TcpClient(); - var result = tcpClient.BeginConnect(ipAddress, port, null, null); - var success = result.AsyncWaitHandle.WaitOne(connectTimeout); - if (!success) - { - throw new EasyModbus.Exceptions.ConnectionException("connection timed out"); - } - tcpClient.EndConnect(result); - - //tcpClient = new TcpClient(ipAddress, port); - stream = tcpClient.GetStream(); - stream.ReadTimeout = connectTimeout; - connected = true; - } - else - { - tcpClient = new TcpClient(); - connected = true; - } - - if (ConnectedChanged != null) - ConnectedChanged(this); - } - - /// - /// Converts two ModbusRegisters to Float - Example: EasyModbus.ModbusClient.ConvertRegistersToFloat(modbusClient.ReadHoldingRegisters(19,2)) - /// - /// Two Register values received from Modbus - /// Connected float value - public static float ConvertRegistersToFloat(int[] registers) - { - if (registers.Length != 2) - throw new ArgumentException("Input Array length invalid - Array langth must be '2'"); - int highRegister = registers[1]; - int lowRegister = registers[0]; - byte[] highRegisterBytes = BitConverter.GetBytes(highRegister); - byte[] lowRegisterBytes = BitConverter.GetBytes(lowRegister); - byte[] floatBytes = { - lowRegisterBytes[0], - lowRegisterBytes[1], - highRegisterBytes[0], - highRegisterBytes[1] - }; - return BitConverter.ToSingle(floatBytes, 0); - } - - /// - /// Converts two ModbusRegisters to Float, Registers can by swapped - /// - /// Two Register values received from Modbus - /// Desired Word Order (Low Register first or High Register first - /// Connected float value - public static float ConvertRegistersToFloat(int[] registers, RegisterOrder registerOrder) - { - int [] swappedRegisters = {registers[0],registers[1]}; - if (registerOrder == RegisterOrder.HighLow) - swappedRegisters = new int[] {registers[1],registers[0]}; - return ConvertRegistersToFloat(swappedRegisters); - } - - /// - /// Converts two ModbusRegisters to 32 Bit Integer value - /// - /// Two Register values received from Modbus - /// Connected 32 Bit Integer value - public static Int32 ConvertRegistersToInt(int[] registers) - { - if (registers.Length != 2) - throw new ArgumentException("Input Array length invalid - Array langth must be '2'"); - int highRegister = registers[1]; - int lowRegister = registers[0]; - byte[] highRegisterBytes = BitConverter.GetBytes(highRegister); - byte[] lowRegisterBytes = BitConverter.GetBytes(lowRegister); - byte[] doubleBytes = { - lowRegisterBytes[0], - lowRegisterBytes[1], - highRegisterBytes[0], - highRegisterBytes[1] - }; - return BitConverter.ToInt32(doubleBytes, 0); - } - - /// - /// Converts two ModbusRegisters to 32 Bit Integer Value - Registers can be swapped - /// - /// Two Register values received from Modbus - /// Desired Word Order (Low Register first or High Register first - /// Connecteds 32 Bit Integer value - public static Int32 ConvertRegistersToInt(int[] registers, RegisterOrder registerOrder) - { - int[] swappedRegisters = { registers[0], registers[1] }; - if (registerOrder == RegisterOrder.HighLow) - swappedRegisters = new int[] { registers[1], registers[0] }; - return ConvertRegistersToInt(swappedRegisters); - } - - /// - /// Convert four 16 Bit Registers to 64 Bit Integer value Register Order "LowHigh": Reg0: Low Word.....Reg3: High Word, "HighLow": Reg0: High Word.....Reg3: Low Word - /// - /// four Register values received from Modbus - /// 64 bit value - public static Int64 ConvertRegistersToLong(int[] registers) - { - if (registers.Length != 4) - throw new ArgumentException("Input Array length invalid - Array langth must be '4'"); - int highRegister = registers[3]; - int highLowRegister = registers[2]; - int lowHighRegister = registers[1]; - int lowRegister = registers[0]; - byte[] highRegisterBytes = BitConverter.GetBytes(highRegister); - byte[] highLowRegisterBytes = BitConverter.GetBytes(highLowRegister); - byte[] lowHighRegisterBytes = BitConverter.GetBytes(lowHighRegister); - byte[] lowRegisterBytes = BitConverter.GetBytes(lowRegister); - byte[] longBytes = { - lowRegisterBytes[0], - lowRegisterBytes[1], - lowHighRegisterBytes[0], - lowHighRegisterBytes[1], - highLowRegisterBytes[0], - highLowRegisterBytes[1], - highRegisterBytes[0], - highRegisterBytes[1] - }; - return BitConverter.ToInt64(longBytes, 0); - } - - /// - /// Convert four 16 Bit Registers to 64 Bit Integer value - Registers can be swapped - /// - /// four Register values received from Modbus - /// Desired Word Order (Low Register first or High Register first - /// Connected 64 Bit Integer value - public static Int64 ConvertRegistersToLong(int[] registers, RegisterOrder registerOrder) - { - if (registers.Length != 4) - throw new ArgumentException("Input Array length invalid - Array langth must be '4'"); - int[] swappedRegisters = { registers[0], registers[1], registers[2], registers[3] }; - if (registerOrder == RegisterOrder.HighLow) - swappedRegisters = new int[] { registers[3], registers[2], registers[1], registers[0] }; - return ConvertRegistersToLong(swappedRegisters); - } - - /// - /// Convert four 16 Bit Registers to 64 Bit double prec. value Register Order "LowHigh": Reg0: Low Word.....Reg3: High Word, "HighLow": Reg0: High Word.....Reg3: Low Word - /// - /// four Register values received from Modbus - /// 64 bit value - public static double ConvertRegistersToDouble(int[] registers) - { - if (registers.Length != 4) - throw new ArgumentException("Input Array length invalid - Array langth must be '4'"); - int highRegister = registers[3]; - int highLowRegister = registers[2]; - int lowHighRegister = registers[1]; - int lowRegister = registers[0]; - byte[] highRegisterBytes = BitConverter.GetBytes(highRegister); - byte[] highLowRegisterBytes = BitConverter.GetBytes(highLowRegister); - byte[] lowHighRegisterBytes = BitConverter.GetBytes(lowHighRegister); - byte[] lowRegisterBytes = BitConverter.GetBytes(lowRegister); - byte[] longBytes = { - lowRegisterBytes[0], - lowRegisterBytes[1], - lowHighRegisterBytes[0], - lowHighRegisterBytes[1], - highLowRegisterBytes[0], - highLowRegisterBytes[1], - highRegisterBytes[0], - highRegisterBytes[1] - }; - return BitConverter.ToDouble(longBytes, 0); - } - - /// - /// Convert four 16 Bit Registers to 64 Bit double prec. value - Registers can be swapped - /// - /// four Register values received from Modbus - /// Desired Word Order (Low Register first or High Register first - /// Connected double prec. float value - public static double ConvertRegistersToDouble(int[] registers, RegisterOrder registerOrder) - { - if (registers.Length != 4) - throw new ArgumentException("Input Array length invalid - Array langth must be '4'"); - int[] swappedRegisters = { registers[0], registers[1], registers[2], registers[3] }; - if (registerOrder == RegisterOrder.HighLow) - swappedRegisters = new int[] { registers[3], registers[2], registers[1], registers[0] }; - return ConvertRegistersToDouble(swappedRegisters); - } - - /// - /// Converts float to two ModbusRegisters - Example: modbusClient.WriteMultipleRegisters(24, EasyModbus.ModbusClient.ConvertFloatToTwoRegisters((float)1.22)); - /// - /// Float value which has to be converted into two registers - /// Register values - public static int[] ConvertFloatToRegisters(float floatValue) - { - byte[] floatBytes = BitConverter.GetBytes(floatValue); - byte[] highRegisterBytes = - { - floatBytes[2], - floatBytes[3], - 0, - 0 - }; - byte[] lowRegisterBytes = - { - - floatBytes[0], - floatBytes[1], - 0, - 0 - }; - int[] returnValue = - { - BitConverter.ToInt32(lowRegisterBytes,0), - BitConverter.ToInt32(highRegisterBytes,0) - }; - return returnValue; - } - - /// - /// Converts float to two ModbusRegisters Registers - Registers can be swapped - /// - /// Float value which has to be converted into two registers - /// Desired Word Order (Low Register first or High Register first - /// Register values - public static int[] ConvertFloatToRegisters(float floatValue, RegisterOrder registerOrder) - { - int[] registerValues = ConvertFloatToRegisters(floatValue); - int[] returnValue = registerValues; - if (registerOrder == RegisterOrder.HighLow) - returnValue = new Int32[] { registerValues[1], registerValues[0] }; - return returnValue; - } - - /// - /// Converts 32 Bit Value to two ModbusRegisters - /// - /// Int value which has to be converted into two registers - /// Register values - public static int[] ConvertIntToRegisters(Int32 intValue) - { - byte[] doubleBytes = BitConverter.GetBytes(intValue); - byte[] highRegisterBytes = - { - doubleBytes[2], - doubleBytes[3], - 0, - 0 - }; - byte[] lowRegisterBytes = - { - - doubleBytes[0], - doubleBytes[1], - 0, - 0 - }; - int[] returnValue = - { - BitConverter.ToInt32(lowRegisterBytes,0), - BitConverter.ToInt32(highRegisterBytes,0) - }; - return returnValue; - } - - /// - /// Converts 32 Bit Value to two ModbusRegisters Registers - Registers can be swapped - /// - /// Double value which has to be converted into two registers - /// Desired Word Order (Low Register first or High Register first - /// Register values - public static int[] ConvertIntToRegisters(Int32 intValue, RegisterOrder registerOrder) - { - int[] registerValues = ConvertIntToRegisters(intValue); - int[] returnValue = registerValues; - if (registerOrder == RegisterOrder.HighLow) - returnValue = new Int32[] { registerValues[1], registerValues[0] }; - return returnValue; - } - - /// - /// Converts 64 Bit Value to four ModbusRegisters - /// - /// long value which has to be converted into four registers - /// Register values - public static int[] ConvertLongToRegisters(Int64 longValue) - { - byte[] longBytes = BitConverter.GetBytes(longValue); - byte[] highRegisterBytes = - { - longBytes[6], - longBytes[7], - 0, - 0 - }; - byte[] highLowRegisterBytes = - { - longBytes[4], - longBytes[5], - 0, - 0 - }; - byte[] lowHighRegisterBytes = - { - longBytes[2], - longBytes[3], - 0, - 0 - }; - byte[] lowRegisterBytes = - { - - longBytes[0], - longBytes[1], - 0, - 0 - }; - int[] returnValue = - { - BitConverter.ToInt32(lowRegisterBytes,0), - BitConverter.ToInt32(lowHighRegisterBytes,0), - BitConverter.ToInt32(highLowRegisterBytes,0), - BitConverter.ToInt32(highRegisterBytes,0) - }; - return returnValue; - } - - /// - /// Converts 64 Bit Value to four ModbusRegisters - Registers can be swapped - /// - /// long value which has to be converted into four registers - /// Desired Word Order (Low Register first or High Register first - /// Register values - public static int[] ConvertLongToRegisters(Int64 longValue, RegisterOrder registerOrder) - { - int[] registerValues = ConvertLongToRegisters(longValue); - int[] returnValue = registerValues; - if (registerOrder == RegisterOrder.HighLow) - returnValue = new int[] { registerValues[3], registerValues[2], registerValues[1], registerValues[0] }; - return returnValue; - } - - /// - /// Converts 64 Bit double prec Value to four ModbusRegisters - /// - /// double value which has to be converted into four registers - /// Register values - public static int[] ConvertDoubleToRegisters(double doubleValue) - { - byte[] doubleBytes = BitConverter.GetBytes(doubleValue); - byte[] highRegisterBytes = - { - doubleBytes[6], - doubleBytes[7], - 0, - 0 - }; - byte[] highLowRegisterBytes = - { - doubleBytes[4], - doubleBytes[5], - 0, - 0 - }; - byte[] lowHighRegisterBytes = - { - doubleBytes[2], - doubleBytes[3], - 0, - 0 - }; - byte[] lowRegisterBytes = - { - - doubleBytes[0], - doubleBytes[1], - 0, - 0 - }; - int[] returnValue = - { - BitConverter.ToInt32(lowRegisterBytes,0), - BitConverter.ToInt32(lowHighRegisterBytes,0), - BitConverter.ToInt32(highLowRegisterBytes,0), - BitConverter.ToInt32(highRegisterBytes,0) - }; - return returnValue; - } - - /// - /// Converts 64 Bit double prec. Value to four ModbusRegisters - Registers can be swapped - /// - /// double value which has to be converted into four registers - /// Desired Word Order (Low Register first or High Register first - /// Register values - public static int[] ConvertDoubleToRegisters(double doubleValue, RegisterOrder registerOrder) - { - int[] registerValues = ConvertDoubleToRegisters(doubleValue); - int[] returnValue = registerValues; - if (registerOrder == RegisterOrder.HighLow) - returnValue = new int[] { registerValues[3], registerValues[2], registerValues[1], registerValues[0] }; - return returnValue; - } - - /// - /// Converts 16 - Bit Register values to String - /// - /// Register array received via Modbus - /// First Register containing the String to convert - /// number of characters in String (must be even) - /// Converted String - public static string ConvertRegistersToString(int[] registers, int offset, int stringLength) - { - byte[] result = new byte[stringLength]; - byte[] registerResult = new byte[2]; - - for (int i = 0; i < stringLength/2; i++) - { - registerResult = BitConverter.GetBytes(registers[offset + i]); - result[i * 2] = registerResult[0]; - result[i * 2 + 1] = registerResult[1]; - } - return System.Text.Encoding.Default.GetString(result); - } - - /// - /// Converts a String to 16 - Bit Registers - /// - /// Register array received via Modbus - /// Converted String - public static int[] ConvertStringToRegisters(string stringToConvert) - { - byte[] array = System.Text.Encoding.ASCII.GetBytes(stringToConvert); - int[] returnarray = new int[stringToConvert.Length / 2 + stringToConvert.Length % 2]; - for (int i = 0; i < returnarray.Length; i++) - { - returnarray[i] = array[i * 2]; - if (i*2 +1< array.Length) - { - returnarray[i] = returnarray[i] | ((int)array[i * 2 + 1] << 8); - } - } - return returnarray; - } - - - /// - /// Calculates the CRC16 for Modbus-RTU - /// - /// Byte buffer to send - /// Number of bytes to calculate CRC - /// First byte in buffer to start calculating CRC - public static UInt16 calculateCRC(byte[] data, UInt16 numberOfBytes, int startByte) - { - byte[] auchCRCHi = { - 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, - 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, - 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, - 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, - 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, - 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, - 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, - 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, - 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, - 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, - 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, - 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, - 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, - 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, - 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, - 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, - 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, - 0x40 - }; - - byte[] auchCRCLo = { - 0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06, 0x07, 0xC7, 0x05, 0xC5, 0xC4, - 0x04, 0xCC, 0x0C, 0x0D, 0xCD, 0x0F, 0xCF, 0xCE, 0x0E, 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09, - 0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9, 0x1B, 0xDB, 0xDA, 0x1A, 0x1E, 0xDE, 0xDF, 0x1F, 0xDD, - 0x1D, 0x1C, 0xDC, 0x14, 0xD4, 0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3, - 0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3, 0xF2, 0x32, 0x36, 0xF6, 0xF7, - 0x37, 0xF5, 0x35, 0x34, 0xF4, 0x3C, 0xFC, 0xFD, 0x3D, 0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A, - 0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38, 0x28, 0xE8, 0xE9, 0x29, 0xEB, 0x2B, 0x2A, 0xEA, 0xEE, - 0x2E, 0x2F, 0xEF, 0x2D, 0xED, 0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26, - 0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60, 0x61, 0xA1, 0x63, 0xA3, 0xA2, - 0x62, 0x66, 0xA6, 0xA7, 0x67, 0xA5, 0x65, 0x64, 0xA4, 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F, - 0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB, 0x69, 0xA9, 0xA8, 0x68, 0x78, 0xB8, 0xB9, 0x79, 0xBB, - 0x7B, 0x7A, 0xBA, 0xBE, 0x7E, 0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5, - 0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71, 0x70, 0xB0, 0x50, 0x90, 0x91, - 0x51, 0x93, 0x53, 0x52, 0x92, 0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C, - 0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, 0x5A, 0x9A, 0x9B, 0x5B, 0x99, 0x59, 0x58, 0x98, 0x88, - 0x48, 0x49, 0x89, 0x4B, 0x8B, 0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C, - 0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42, 0x43, 0x83, 0x41, 0x81, 0x80, - 0x40 - }; - UInt16 usDataLen = numberOfBytes; - byte uchCRCHi = 0xFF ; - byte uchCRCLo = 0xFF ; - int i = 0; - int uIndex ; - while (usDataLen>0) - { - usDataLen--; - if ((i + startByte) < data.Length) - { - uIndex = uchCRCLo ^ data[i + startByte]; - uchCRCLo = (byte)(uchCRCHi ^ auchCRCHi[uIndex]); - uchCRCHi = auchCRCLo[uIndex]; - } - i++; - } - return (UInt16)((UInt16)uchCRCHi << 8 | uchCRCLo); - } - - private bool dataReceived = false; - private bool receiveActive = false; - private byte[] readBuffer = new byte[256]; - private int bytesToRead = 0; - private int akjjjctualPositionToRead = 0; - DateTime dateTimeLastRead; -/* - private void DataReceivedHandler(object sender, - SerialDataReceivedEventArgs e) - { - long ticksWait = TimeSpan.TicksPerMillisecond * 2000; - SerialPort sp = (SerialPort)sender; - - if (bytesToRead == 0 || sp.BytesToRead == 0) - { - actualPositionToRead = 0; - sp.DiscardInBuffer(); - dataReceived = false; - receiveActive = false; - return; - } - - if (actualPositionToRead == 0 && !dataReceived) - readBuffer = new byte[256]; - - //if ((DateTime.Now.Ticks - dateTimeLastRead.Ticks) > ticksWait) - //{ - // readBuffer = new byte[256]; - // actualPositionToRead = 0; - //} - int numberOfBytesInBuffer = sp.BytesToRead; - sp.Read(readBuffer, actualPositionToRead, ((numberOfBytesInBuffer + actualPositionToRead) > readBuffer.Length) ? 0 : numberOfBytesInBuffer); - actualPositionToRead = actualPositionToRead + numberOfBytesInBuffer; - //sp.DiscardInBuffer(); - //if (DetectValidModbusFrame(readBuffer, (actualPositionToRead < readBuffer.Length) ? actualPositionToRead : readBuffer.Length) | bytesToRead <= actualPositionToRead) - if (actualPositionToRead >= bytesToRead) - { - - dataReceived = true; - bytesToRead = 0; - actualPositionToRead = 0; - if (debug) StoreLogData.Instance.Store("Received Serial-Data: " + BitConverter.ToString(readBuffer), System.DateTime.Now); - - } - - - //dateTimeLastRead = DateTime.Now; - } - */ - - - private void DataReceivedHandler(object sender, - SerialDataReceivedEventArgs e) - { - serialport.DataReceived -= DataReceivedHandler; - - //while (receiveActive | dataReceived) - // System.Threading.Thread.Sleep(10); - receiveActive = true; - - const long ticksWait = TimeSpan.TicksPerMillisecond * 2000;//((40*10000000) / this.baudRate); - - - SerialPort sp = (SerialPort)sender; - if (bytesToRead == 0) - { - sp.DiscardInBuffer(); - receiveActive = false; - serialport.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler); - return; - } - readBuffer = new byte[256]; - int numbytes=0; - int actualPositionToRead = 0; - DateTime dateTimeLastRead = DateTime.Now; - do{ - try { - dateTimeLastRead = DateTime.Now; - while ((sp.BytesToRead) == 0) - { - System.Threading.Thread.Sleep(10); - if ((DateTime.Now.Ticks - dateTimeLastRead.Ticks) > ticksWait) - break; - } - numbytes=sp.BytesToRead; - - - byte[] rxbytearray = new byte[numbytes]; - sp.Read(rxbytearray, 0, numbytes); - Array.Copy(rxbytearray,0, readBuffer,actualPositionToRead, (actualPositionToRead + rxbytearray.Length) <= bytesToRead ? rxbytearray.Length : bytesToRead - actualPositionToRead); - - actualPositionToRead = actualPositionToRead + rxbytearray.Length; - - } - catch (Exception){ - - } - - if (bytesToRead <= actualPositionToRead) - break; - - if (DetectValidModbusFrame(readBuffer, (actualPositionToRead < readBuffer.Length) ? actualPositionToRead : readBuffer.Length) | bytesToRead <= actualPositionToRead) - break; - } - while ((DateTime.Now.Ticks - dateTimeLastRead.Ticks) < ticksWait) ; - - //10.000 Ticks in 1 ms - - receiveData = new byte[actualPositionToRead]; - Array.Copy(readBuffer, 0, receiveData, 0, (actualPositionToRead < readBuffer.Length) ? actualPositionToRead: readBuffer.Length); - if (debug) StoreLogData.Instance.Store("Received Serial-Data: "+BitConverter.ToString(readBuffer) ,System.DateTime.Now); - bytesToRead = 0; - - - - - dataReceived = true; - receiveActive = false; - serialport.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler); - if (ReceiveDataChanged != null) - { - - ReceiveDataChanged(this); - - } - - //sp.DiscardInBuffer(); - } - - public static bool DetectValidModbusFrame(byte[] readBuffer, int length) - { - // minimum length 6 bytes - if (length < 6) - return false; - //SlaveID correct - if ((readBuffer[0] < 1) | (readBuffer[0] > 247)) - return false; - //CRC correct? - byte[] crc = new byte[2]; - crc = BitConverter.GetBytes(calculateCRC(readBuffer, (ushort)(length-2), 0)); - if (crc[0] != readBuffer[length-2] | crc[1] != readBuffer[length-1]) - return false; - return true; - } - - - - /// - /// Read Discrete Inputs from Server device (FC2). - /// - /// First discrete input to read - /// Number of discrete Inputs to read - /// Boolean Array which contains the discrete Inputs - public bool[] ReadDiscreteInputs(int startingAddress, int quantity) - { - if (debug) StoreLogData.Instance.Store("FC2 (Read Discrete Inputs from Master device), StartingAddress: "+ startingAddress+", Quantity: " +quantity, System.DateTime.Now); - transactionIdentifierInternal ++; - if (serialport != null) - if (!serialport.IsOpen) - { - if (debug) StoreLogData.Instance.Store("SerialPortNotOpenedException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.SerialPortNotOpenedException("serial port not opened"); - } - if (tcpClient == null & !udpFlag & serialport==null) - { - if (debug) StoreLogData.Instance.Store("ConnectionException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.ConnectionException("connection error"); - } - if (startingAddress > 65535 | quantity >2000) - { - if (debug) StoreLogData.Instance.Store("ArgumentException Throwed", System.DateTime.Now); - throw new ArgumentException("Starting address must be 0 - 65535; quantity must be 0 - 2000"); - } - bool[] response; - this.transactionIdentifier = BitConverter.GetBytes((uint)transactionIdentifierInternal); - this.protocolIdentifier = BitConverter.GetBytes((int) 0x0000); - this.length = BitConverter.GetBytes((int)0x0006); - this.functionCode = 0x02; - this.startingAddress = BitConverter.GetBytes(startingAddress); - this.quantity = BitConverter.GetBytes(quantity); - Byte[] data = new byte[] - { - this.transactionIdentifier[1], - this.transactionIdentifier[0], - this.protocolIdentifier[1], - this.protocolIdentifier[0], - this.length[1], - this.length[0], - this.unitIdentifier, - this.functionCode, - this.startingAddress[1], - this.startingAddress[0], - this.quantity[1], - this.quantity[0], - this.crc[0], - this.crc[1] - }; - crc = BitConverter.GetBytes(calculateCRC(data, 6, 6)); - data[12] = crc[0]; - data[13] = crc[1]; - - if (serialport != null) - { - dataReceived = false; - if (quantity % 8 == 0) - bytesToRead = 5 + quantity / 8; - else - bytesToRead = 6 + quantity / 8; - // serialport.ReceivedBytesThreshold = bytesToRead; - serialport.Write(data, 6, 8); - if (debug) - { - byte [] debugData = new byte[8]; - Array.Copy(data, 6, debugData, 0, 8); - if (debug) StoreLogData.Instance.Store("Send Serial-Data: "+BitConverter.ToString(debugData) ,System.DateTime.Now); - } - if (SendDataChanged != null) - { - sendData = new byte[8]; - Array.Copy(data, 6, sendData, 0, 8); - SendDataChanged(this); - - } - data = new byte[2100]; - readBuffer = new byte[256]; - DateTime dateTimeSend = DateTime.Now; - byte receivedUnitIdentifier = 0xFF; - - SpinWait sw_delay = new SpinWait(); - while (receivedUnitIdentifier != this.unitIdentifier & !((DateTime.Now.Ticks - dateTimeSend.Ticks) > TimeSpan.TicksPerMillisecond * this.connectTimeout)) - { - while (dataReceived == false & !((DateTime.Now.Ticks - dateTimeSend.Ticks) > TimeSpan.TicksPerMillisecond * this.connectTimeout)) - sw_delay.SpinOnce(); - - data = new byte[2100]; - Array.Copy(readBuffer, 0, data, 6, readBuffer.Length); - receivedUnitIdentifier = data[6]; - } - if (receivedUnitIdentifier != this.unitIdentifier) - data = new byte[2100]; - else - countRetries = 0; - } - else if (tcpClient.Client.Connected | udpFlag) - { - if (udpFlag) - { - UdpClient udpClient = new UdpClient(); - IPEndPoint endPoint = new IPEndPoint(System.Net.IPAddress.Parse(ipAddress), port); - udpClient.Send(data, data.Length-2, endPoint); - portOut = ((IPEndPoint)udpClient.Client.LocalEndPoint).Port; - udpClient.Client.ReceiveTimeout = 5000; - endPoint = new IPEndPoint(System.Net.IPAddress.Parse(ipAddress), portOut); - data = udpClient.Receive(ref endPoint); - } - else - { - stream.Write(data, 0, data.Length-2); - if (debug) - { - byte [] debugData = new byte[data.Length-2]; - Array.Copy(data, 0, debugData, 0, data.Length-2); - if (debug) StoreLogData.Instance.Store("Send ModbusTCP-Data: "+BitConverter.ToString(debugData) ,System.DateTime.Now); - } - if (SendDataChanged != null) - { - sendData = new byte[data.Length-2]; - Array.Copy(data, 0, sendData, 0, data.Length-2); - SendDataChanged(this); - } - data = new Byte[2100]; - int NumberOfBytes = stream.Read(data, 0, data.Length); - if (ReceiveDataChanged != null) - { - receiveData = new byte[NumberOfBytes]; - Array.Copy(data, 0, receiveData, 0, NumberOfBytes); - if (debug) StoreLogData.Instance.Store("Receive ModbusTCP-Data: " + BitConverter.ToString(receiveData), System.DateTime.Now); - ReceiveDataChanged(this); - } - } - } - if (data[7] == 0x82 & data[8] == 0x01) - { - if (debug) StoreLogData.Instance.Store("FunctionCodeNotSupportedException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.FunctionCodeNotSupportedException("Function code not supported by master"); - } - if (data[7] == 0x82 & data[8] == 0x02) - { - if (debug) StoreLogData.Instance.Store("StartingAddressInvalidException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.StartingAddressInvalidException("Starting address invalid or starting address + quantity invalid"); - } - if (data[7] == 0x82 & data[8] == 0x03) - { - if (debug) StoreLogData.Instance.Store("QuantityInvalidException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.QuantityInvalidException("quantity invalid"); - } - if (data[7] == 0x82 & data[8] == 0x04) - { - if (debug) StoreLogData.Instance.Store("ModbusException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.ModbusException("error reading"); - } - if (serialport != null) - { - crc = BitConverter.GetBytes(calculateCRC(data, (ushort)(data[8]+3), 6)); - if ((crc[0] != data[data[8] + 9] | crc[1] != data[data[8] + 10]) & dataReceived) - { - if (debug) StoreLogData.Instance.Store("CRCCheckFailedException Throwed", System.DateTime.Now); - if (NumberOfRetries <= countRetries) - { - countRetries = 0; - throw new EasyModbus.Exceptions.CRCCheckFailedException("Response CRC check failed"); - } - else - { - countRetries++; - return ReadDiscreteInputs(startingAddress, quantity); - } - } - else if (!dataReceived) - { - if (debug) StoreLogData.Instance.Store("TimeoutException Throwed", System.DateTime.Now); - if (NumberOfRetries <= countRetries) - { - countRetries = 0; - throw new TimeoutException("No Response from Modbus Slave"); - } - else - { - countRetries++; - return ReadDiscreteInputs(startingAddress, quantity); - } - } - } - response = new bool[quantity]; - for (int i = 0; i < quantity; i++) - { - int intData = data[9+i/8]; - int mask = Convert.ToInt32(Math.Pow(2, (i%8))); - response[i] = Convert.ToBoolean((intData & mask)/mask); - } - return (response); - } - - - /// - /// Read Coils from Server device (FC1). - /// - /// First coil to read - /// Numer of coils to read - /// Boolean Array which contains the coils - public bool[] ReadCoils(int startingAddress, int quantity) - { - if (debug) StoreLogData.Instance.Store("FC1 (Read Coils from Master device), StartingAddress: "+ startingAddress+", Quantity: " +quantity, System.DateTime.Now); - transactionIdentifierInternal++; - if (serialport != null) - if (!serialport.IsOpen) - { - if (debug) StoreLogData.Instance.Store("SerialPortNotOpenedException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.SerialPortNotOpenedException("serial port not opened"); - } - if (tcpClient == null & !udpFlag & serialport == null) - { - if (debug) StoreLogData.Instance.Store("ConnectionException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.ConnectionException("connection error"); - } - if (startingAddress > 65535 | quantity >2000) - { - if (debug) StoreLogData.Instance.Store("ArgumentException Throwed", System.DateTime.Now); - throw new ArgumentException("Starting address must be 0 - 65535; quantity must be 0 - 2000"); - } - bool[] response; - this.transactionIdentifier = BitConverter.GetBytes((uint)transactionIdentifierInternal); - this.protocolIdentifier = BitConverter.GetBytes((int) 0x0000); - this.length = BitConverter.GetBytes((int)0x0006); - this.functionCode = 0x01; - this.startingAddress = BitConverter.GetBytes(startingAddress); - this.quantity = BitConverter.GetBytes(quantity); - Byte[] data = new byte[]{ - this.transactionIdentifier[1], - this.transactionIdentifier[0], - this.protocolIdentifier[1], - this.protocolIdentifier[0], - this.length[1], - this.length[0], - this.unitIdentifier, - this.functionCode, - this.startingAddress[1], - this.startingAddress[0], - this.quantity[1], - this.quantity[0], - this.crc[0], - this.crc[1] - }; - - crc = BitConverter.GetBytes(calculateCRC(data, 6, 6)); - data[12] = crc[0]; - data[13] = crc[1]; - if (serialport != null) - { - dataReceived = false; - if (quantity % 8 == 0) - bytesToRead = 5 + quantity/8; - else - bytesToRead = 6 + quantity/8; - // serialport.ReceivedBytesThreshold = bytesToRead; - serialport.Write(data, 6, 8); - if (debug) - { - byte [] debugData = new byte[8]; - Array.Copy(data, 6, debugData, 0, 8); - if (debug) StoreLogData.Instance.Store("Send Serial-Data: "+BitConverter.ToString(debugData) ,System.DateTime.Now); - } - if (SendDataChanged != null) - { - sendData = new byte[8]; - Array.Copy(data, 6, sendData, 0, 8); - SendDataChanged(this); - - } - data = new byte[2100]; - readBuffer = new byte[256]; - DateTime dateTimeSend = DateTime.Now; - byte receivedUnitIdentifier = 0xFF; - - SpinWait sw_delay = new SpinWait(); - while (receivedUnitIdentifier != this.unitIdentifier & !((DateTime.Now.Ticks - dateTimeSend.Ticks) > TimeSpan.TicksPerMillisecond * this.connectTimeout)) - { - while (dataReceived == false & !((DateTime.Now.Ticks - dateTimeSend.Ticks) > TimeSpan.TicksPerMillisecond * this.connectTimeout)) - sw_delay.SpinOnce(); - - data = new byte[2100]; - - Array.Copy(readBuffer, 0, data, 6, readBuffer.Length); - receivedUnitIdentifier = data[6]; - } - if (receivedUnitIdentifier != this.unitIdentifier) - data = new byte[2100]; - else - countRetries = 0; - } - else if (tcpClient.Client.Connected | udpFlag) - { - if (udpFlag) - { - UdpClient udpClient = new UdpClient(); - IPEndPoint endPoint = new IPEndPoint(System.Net.IPAddress.Parse(ipAddress), port); - udpClient.Send(data, data.Length-2, endPoint); - portOut = ((IPEndPoint)udpClient.Client.LocalEndPoint).Port; - udpClient.Client.ReceiveTimeout = 5000; - endPoint = new IPEndPoint(System.Net.IPAddress.Parse(ipAddress), portOut); - data = udpClient.Receive(ref endPoint); - } - else - { - stream.Write(data, 0, data.Length-2); - if (debug) - { - byte [] debugData = new byte[data.Length-2]; - Array.Copy(data, 0, debugData, 0, data.Length-2); - if (debug) StoreLogData.Instance.Store("Send MocbusTCP-Data: "+BitConverter.ToString(debugData) ,System.DateTime.Now); - } - if (SendDataChanged != null) - { - sendData = new byte[data.Length-2]; - Array.Copy(data, 0, sendData, 0, data.Length-2); - SendDataChanged(this); - - } - data = new Byte[2100]; - int NumberOfBytes = stream.Read(data, 0, data.Length); - if (ReceiveDataChanged != null) - { - receiveData = new byte[NumberOfBytes]; - Array.Copy(data, 0, receiveData, 0, NumberOfBytes); - if (debug) StoreLogData.Instance.Store("Receive ModbusTCP-Data: " + BitConverter.ToString(receiveData), System.DateTime.Now); - ReceiveDataChanged(this); - } - } - } - if (data[7] == 0x81 & data[8] == 0x01) - { - if (debug) StoreLogData.Instance.Store("FunctionCodeNotSupportedException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.FunctionCodeNotSupportedException("Function code not supported by master"); - } - if (data[7] == 0x81 & data[8] == 0x02) - { - if (debug) StoreLogData.Instance.Store("StartingAddressInvalidException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.StartingAddressInvalidException("Starting address invalid or starting address + quantity invalid"); - } - if (data[7] == 0x81 & data[8] == 0x03) - { - if (debug) StoreLogData.Instance.Store("QuantityInvalidException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.QuantityInvalidException("quantity invalid"); - } - if (data[7] == 0x81 & data[8] == 0x04) - { - if (debug) StoreLogData.Instance.Store("ModbusException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.ModbusException("error reading"); - } - if (serialport != null) - { - crc = BitConverter.GetBytes(calculateCRC(data, (ushort)(data[8]+3), 6)); - if ((crc[0] != data[data[8]+9] | crc[1] != data[data[8]+10]) & dataReceived) - { - if (debug) StoreLogData.Instance.Store("CRCCheckFailedException Throwed", System.DateTime.Now); - if (NumberOfRetries <= countRetries) - { - countRetries = 0; - throw new EasyModbus.Exceptions.CRCCheckFailedException("Response CRC check failed"); - } - else - { - countRetries++; - return ReadCoils(startingAddress, quantity); - } - } - else if (!dataReceived) - { - if (debug) StoreLogData.Instance.Store("TimeoutException Throwed", System.DateTime.Now); - if (NumberOfRetries <= countRetries) - { - countRetries = 0; - throw new TimeoutException("No Response from Modbus Slave"); - } - else - { - countRetries++; - return ReadCoils(startingAddress, quantity); - } - } - } - response = new bool[quantity]; - for (int i = 0; i < quantity; i++) - { - int intData = data[9+i/8]; - int mask = Convert.ToInt32(Math.Pow(2, (i%8))); - response[i] = Convert.ToBoolean((intData & mask)/mask); - } - return (response); - } - - - /// - /// Read Holding Registers from Master device (FC3). - /// - /// First holding register to be read - /// Number of holding registers to be read - /// Int Array which contains the holding registers - public int[] ReadHoldingRegisters(int startingAddress, int quantity) - { - if (debug) StoreLogData.Instance.Store("FC3 (Read Holding Registers from Master device), StartingAddress: "+ startingAddress+", Quantity: " +quantity, System.DateTime.Now); - transactionIdentifierInternal++; - if (serialport != null) - if (!serialport.IsOpen) - { - if (debug) StoreLogData.Instance.Store("SerialPortNotOpenedException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.SerialPortNotOpenedException("serial port not opened"); - } - if (tcpClient == null & !udpFlag & serialport == null) - { - if (debug) StoreLogData.Instance.Store("ConnectionException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.ConnectionException("connection error"); - } - if (startingAddress > 65535 | quantity >125) - { - if (debug) StoreLogData.Instance.Store("ArgumentException Throwed", System.DateTime.Now); - throw new ArgumentException("Starting address must be 0 - 65535; quantity must be 0 - 125"); - } - int[] response; - this.transactionIdentifier = BitConverter.GetBytes((uint)transactionIdentifierInternal); - this.protocolIdentifier = BitConverter.GetBytes((int) 0x0000); - this.length = BitConverter.GetBytes((int)0x0006); - this.functionCode = 0x03; - this.startingAddress = BitConverter.GetBytes(startingAddress); - this.quantity = BitConverter.GetBytes(quantity); - Byte[] data = new byte[]{ this.transactionIdentifier[1], - this.transactionIdentifier[0], - this.protocolIdentifier[1], - this.protocolIdentifier[0], - this.length[1], - this.length[0], - this.unitIdentifier, - this.functionCode, - this.startingAddress[1], - this.startingAddress[0], - this.quantity[1], - this.quantity[0], - this.crc[0], - this.crc[1] - }; - crc = BitConverter.GetBytes(calculateCRC(data, 6, 6)); - data[12] = crc[0]; - data[13] = crc[1]; - if (serialport != null) - { - dataReceived = false; - bytesToRead = 5 + 2 * quantity; -// serialport.ReceivedBytesThreshold = bytesToRead; - serialport.Write(data, 6, 8); - if (debug) - { - byte [] debugData = new byte[8]; - Array.Copy(data, 6, debugData, 0, 8); - if (debug) StoreLogData.Instance.Store("Send Serial-Data: "+BitConverter.ToString(debugData) ,System.DateTime.Now); - } - if (SendDataChanged != null) - { - sendData = new byte[8]; - Array.Copy(data, 6, sendData, 0, 8); - SendDataChanged(this); - - } - data = new byte[2100]; - readBuffer = new byte[256]; - - DateTime dateTimeSend = DateTime.Now; - byte receivedUnitIdentifier = 0xFF; - - SpinWait sw_delay = new SpinWait(); - while (receivedUnitIdentifier != this.unitIdentifier & !((DateTime.Now.Ticks - dateTimeSend.Ticks) > TimeSpan.TicksPerMillisecond * this.connectTimeout)) - { - while (dataReceived == false & !((DateTime.Now.Ticks - dateTimeSend.Ticks) > TimeSpan.TicksPerMillisecond * this.connectTimeout)) - sw_delay.SpinOnce(); - - data = new byte[2100]; - Array.Copy(readBuffer, 0, data, 6, readBuffer.Length); - - receivedUnitIdentifier = data[6]; - } - if (receivedUnitIdentifier != this.unitIdentifier) - data = new byte[2100]; - else - countRetries = 0; - } - else if (tcpClient.Client.Connected | udpFlag) - { - if (udpFlag) - { - UdpClient udpClient = new UdpClient(); - IPEndPoint endPoint = new IPEndPoint(System.Net.IPAddress.Parse(ipAddress), port); - udpClient.Send(data, data.Length-2, endPoint); - portOut = ((IPEndPoint)udpClient.Client.LocalEndPoint).Port; - udpClient.Client.ReceiveTimeout = 5000; - endPoint = new IPEndPoint(System.Net.IPAddress.Parse(ipAddress), portOut); - data = udpClient.Receive(ref endPoint); - } - else - { - stream.Write(data, 0, data.Length-2); - if (debug) - { - byte [] debugData = new byte[data.Length-2]; - Array.Copy(data, 0, debugData, 0, data.Length-2); - if (debug) StoreLogData.Instance.Store("Send ModbusTCP-Data: "+BitConverter.ToString(debugData) ,System.DateTime.Now); - } - if (SendDataChanged != null) - { - sendData = new byte[data.Length-2]; - Array.Copy(data, 0, sendData, 0, data.Length-2); - SendDataChanged(this); - - } - data = new Byte[256]; - int NumberOfBytes = stream.Read(data, 0, data.Length); - if (ReceiveDataChanged != null) - { - receiveData = new byte[NumberOfBytes]; - Array.Copy(data, 0, receiveData, 0, NumberOfBytes); - if (debug) StoreLogData.Instance.Store("Receive ModbusTCP-Data: " + BitConverter.ToString(receiveData), System.DateTime.Now); - ReceiveDataChanged(this); - } - } - } - if (data[7] == 0x83 & data[8] == 0x01) - { - if (debug) StoreLogData.Instance.Store("FunctionCodeNotSupportedException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.FunctionCodeNotSupportedException("Function code not supported by master"); - } - if (data[7] == 0x83 & data[8] == 0x02) - { - if (debug) StoreLogData.Instance.Store("StartingAddressInvalidException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.StartingAddressInvalidException("Starting address invalid or starting address + quantity invalid"); - } - if (data[7] == 0x83 & data[8] == 0x03) - { - if (debug) StoreLogData.Instance.Store("QuantityInvalidException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.QuantityInvalidException("quantity invalid"); - } - if (data[7] == 0x83 & data[8] == 0x04) - { - if (debug) StoreLogData.Instance.Store("ModbusException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.ModbusException("error reading"); - } - if (serialport != null) - { - crc = BitConverter.GetBytes(calculateCRC(data, (ushort)(data[8]+3), 6)); - if ((crc[0] != data[data[8]+9] | crc[1] != data[data[8]+10])& dataReceived) - { - if (debug) StoreLogData.Instance.Store("CRCCheckFailedException Throwed", System.DateTime.Now); - if (NumberOfRetries <= countRetries) - { - countRetries = 0; - throw new EasyModbus.Exceptions.CRCCheckFailedException("Response CRC check failed"); - } - else - { - countRetries++; - return ReadHoldingRegisters(startingAddress, quantity); - } - } - else if (!dataReceived) - { - if (debug) StoreLogData.Instance.Store("TimeoutException Throwed", System.DateTime.Now); - if (NumberOfRetries <= countRetries) - { - countRetries = 0; - throw new TimeoutException("No Response from Modbus Slave"); - } - else - { - countRetries++; - return ReadHoldingRegisters(startingAddress, quantity); - } - - - } - } - response = new int[quantity]; - for (int i = 0; i < quantity; i++) - { - byte lowByte; - byte highByte; - highByte = data[9+i*2]; - lowByte = data[9+i*2+1]; - - data[9+i*2] = lowByte; - data[9+i*2+1] = highByte; - - response[i] = BitConverter.ToInt16(data,(9+i*2)); - } - return (response); - } - - - - /// - /// Read Input Registers from Master device (FC4). - /// - /// First input register to be read - /// Number of input registers to be read - /// Int Array which contains the input registers - public int[] ReadInputRegisters(int startingAddress, int quantity) - { - - if (debug) StoreLogData.Instance.Store("FC4 (Read Input Registers from Master device), StartingAddress: "+ startingAddress+", Quantity: " +quantity, System.DateTime.Now); - transactionIdentifierInternal++; - if (serialport != null) - if (!serialport.IsOpen) - { - if (debug) StoreLogData.Instance.Store("SerialPortNotOpenedException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.SerialPortNotOpenedException("serial port not opened"); - } - if (tcpClient == null & !udpFlag & serialport == null) - { - if (debug) StoreLogData.Instance.Store("ConnectionException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.ConnectionException("connection error"); - } - if (startingAddress > 65535 | quantity >125) - { - if (debug) StoreLogData.Instance.Store("ArgumentException Throwed", System.DateTime.Now); - throw new ArgumentException("Starting address must be 0 - 65535; quantity must be 0 - 125"); - } - int[] response; - this.transactionIdentifier = BitConverter.GetBytes((uint)transactionIdentifierInternal); - this.protocolIdentifier = BitConverter.GetBytes((int) 0x0000); - this.length = BitConverter.GetBytes((int)0x0006); - this.functionCode = 0x04; - this.startingAddress = BitConverter.GetBytes(startingAddress); - this.quantity = BitConverter.GetBytes(quantity); - Byte[] data = new byte[]{ this.transactionIdentifier[1], - this.transactionIdentifier[0], - this.protocolIdentifier[1], - this.protocolIdentifier[0], - this.length[1], - this.length[0], - this.unitIdentifier, - this.functionCode, - this.startingAddress[1], - this.startingAddress[0], - this.quantity[1], - this.quantity[0], - this.crc[0], - this.crc[1] - }; - crc = BitConverter.GetBytes(calculateCRC(data, 6, 6)); - data[12] = crc[0]; - data[13] = crc[1]; - if (serialport != null) - { - dataReceived = false; - bytesToRead = 5 + 2 * quantity; - - - // serialport.ReceivedBytesThreshold = bytesToRead; - serialport.Write(data, 6, 8); - if (debug) - { - byte [] debugData = new byte[8]; - Array.Copy(data, 6, debugData, 0, 8); - if (debug) StoreLogData.Instance.Store("Send Serial-Data: "+BitConverter.ToString(debugData) ,System.DateTime.Now); - } - if (SendDataChanged != null) - { - sendData = new byte[8]; - Array.Copy(data, 6, sendData, 0, 8); - SendDataChanged(this); - - } - data = new byte[2100]; - readBuffer = new byte[256]; - DateTime dateTimeSend = DateTime.Now; - byte receivedUnitIdentifier = 0xFF; - - SpinWait sw_delay = new SpinWait(); - while (receivedUnitIdentifier != this.unitIdentifier & !((DateTime.Now.Ticks - dateTimeSend.Ticks) > TimeSpan.TicksPerMillisecond * this.connectTimeout)) - { - while (dataReceived == false & !((DateTime.Now.Ticks - dateTimeSend.Ticks) > TimeSpan.TicksPerMillisecond * this.connectTimeout)) - sw_delay.SpinOnce(); - - data = new byte[2100]; - Array.Copy(readBuffer, 0, data, 6, readBuffer.Length); - receivedUnitIdentifier = data[6]; - } - - if (receivedUnitIdentifier != this.unitIdentifier) - data = new byte[2100]; - else - countRetries = 0; - } - else if (tcpClient.Client.Connected | udpFlag) - { - if (udpFlag) - { - UdpClient udpClient = new UdpClient(); - IPEndPoint endPoint = new IPEndPoint(System.Net.IPAddress.Parse(ipAddress), port); - udpClient.Send(data, data.Length-2, endPoint); - portOut = ((IPEndPoint)udpClient.Client.LocalEndPoint).Port; - udpClient.Client.ReceiveTimeout = 5000; - endPoint = new IPEndPoint(System.Net.IPAddress.Parse(ipAddress), portOut); - data = udpClient.Receive(ref endPoint); - } - else - { - stream.Write(data, 0, data.Length-2); - if (debug) - { - byte [] debugData = new byte[data.Length-2]; - Array.Copy(data, 0, debugData, 0, data.Length-2); - if (debug) StoreLogData.Instance.Store("Send ModbusTCP-Data: "+BitConverter.ToString(debugData) ,System.DateTime.Now); - } - if (SendDataChanged != null) - { - sendData = new byte[data.Length-2]; - Array.Copy(data, 0, sendData, 0, data.Length-2); - SendDataChanged(this); - } - data = new Byte[2100]; - int NumberOfBytes = stream.Read(data, 0, data.Length); - if (ReceiveDataChanged != null) - { - receiveData = new byte[NumberOfBytes]; - Array.Copy(data, 0, receiveData, 0, NumberOfBytes); - if (debug) StoreLogData.Instance.Store("Receive ModbusTCP-Data: " + BitConverter.ToString(receiveData), System.DateTime.Now); - ReceiveDataChanged(this); - } - - } - } - if (data[7] == 0x84 & data[8] == 0x01) - { - if (debug) StoreLogData.Instance.Store("FunctionCodeNotSupportedException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.FunctionCodeNotSupportedException("Function code not supported by master"); - } - if (data[7] == 0x84 & data[8] == 0x02) - { - if (debug) StoreLogData.Instance.Store("StartingAddressInvalidException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.StartingAddressInvalidException("Starting address invalid or starting address + quantity invalid"); - } - if (data[7] == 0x84 & data[8] == 0x03) - { - if (debug) StoreLogData.Instance.Store("QuantityInvalidException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.QuantityInvalidException("quantity invalid"); - } - if (data[7] == 0x84 & data[8] == 0x04) - { - if (debug) StoreLogData.Instance.Store("ModbusException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.ModbusException("error reading"); - } - if (serialport != null) - { - crc = BitConverter.GetBytes(calculateCRC(data, (ushort)(data[8]+3), 6)); - if ((crc[0] != data[data[8]+9] | crc[1] != data[data[8]+10]) & dataReceived) - { - if (debug) StoreLogData.Instance.Store("CRCCheckFailedException Throwed", System.DateTime.Now); - if (NumberOfRetries <= countRetries) - { - countRetries = 0; - throw new EasyModbus.Exceptions.CRCCheckFailedException("Response CRC check failed"); - } - else - { - countRetries++; - return ReadInputRegisters(startingAddress, quantity); - } - } - else if (!dataReceived) - { - if (debug) StoreLogData.Instance.Store("TimeoutException Throwed", System.DateTime.Now); - if (NumberOfRetries <= countRetries) - { - countRetries = 0; - throw new TimeoutException("No Response from Modbus Slave"); - - } - else - { - countRetries++; - return ReadInputRegisters(startingAddress, quantity); - } - - } - } - response = new int[quantity]; - for (int i = 0; i < quantity; i++) - { - byte lowByte; - byte highByte; - highByte = data[9+i*2]; - lowByte = data[9+i*2+1]; - - data[9+i*2] = lowByte; - data[9+i*2+1] = highByte; - - response[i] = BitConverter.ToInt16(data,(9+i*2)); - } - return (response); - } - - - /// - /// Write single Coil to Master device (FC5). - /// - /// Coil to be written - /// Coil Value to be written - public void WriteSingleCoil(int startingAddress, bool value) - { - - if (debug) StoreLogData.Instance.Store("FC5 (Write single coil to Master device), StartingAddress: "+ startingAddress+", Value: " + value, System.DateTime.Now); - transactionIdentifierInternal++; - if (serialport != null) - if (!serialport.IsOpen) - { - if (debug) StoreLogData.Instance.Store("SerialPortNotOpenedException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.SerialPortNotOpenedException("serial port not opened"); - } - if (tcpClient == null & !udpFlag & serialport == null) - { - if (debug) StoreLogData.Instance.Store("ConnectionException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.ConnectionException("connection error"); - } - byte[] coilValue = new byte[2]; - this.transactionIdentifier = BitConverter.GetBytes((uint)transactionIdentifierInternal); - this.protocolIdentifier = BitConverter.GetBytes((int)0x0000); - this.length = BitConverter.GetBytes((int)0x0006); - this.functionCode = 0x05; - this.startingAddress = BitConverter.GetBytes(startingAddress); - if (value == true) - { - coilValue = BitConverter.GetBytes((int)0xFF00); - } - else - { - coilValue = BitConverter.GetBytes((int)0x0000); - } - Byte[] data = new byte[]{ this.transactionIdentifier[1], - this.transactionIdentifier[0], - this.protocolIdentifier[1], - this.protocolIdentifier[0], - this.length[1], - this.length[0], - this.unitIdentifier, - this.functionCode, - this.startingAddress[1], - this.startingAddress[0], - coilValue[1], - coilValue[0], - this.crc[0], - this.crc[1] - }; - crc = BitConverter.GetBytes(calculateCRC(data, 6, 6)); - data[12] = crc[0]; - data[13] = crc[1]; - if (serialport != null) - { - dataReceived = false; - bytesToRead = 8; - // serialport.ReceivedBytesThreshold = bytesToRead; - serialport.Write(data, 6, 8); - if (debug) - { - byte [] debugData = new byte[8]; - Array.Copy(data, 6, debugData, 0, 8); - if (debug) StoreLogData.Instance.Store("Send Serial-Data: "+BitConverter.ToString(debugData) ,System.DateTime.Now); - } - if (SendDataChanged != null) - { - sendData = new byte[8]; - Array.Copy(data, 6, sendData, 0, 8); - SendDataChanged(this); - - } - data = new byte[2100]; - readBuffer = new byte[256]; - DateTime dateTimeSend = DateTime.Now; - byte receivedUnitIdentifier = 0xFF; - - SpinWait sw_delay = new SpinWait(); - while (receivedUnitIdentifier != this.unitIdentifier & !((DateTime.Now.Ticks - dateTimeSend.Ticks) > TimeSpan.TicksPerMillisecond * this.connectTimeout)) - { - while (dataReceived == false & !((DateTime.Now.Ticks - dateTimeSend.Ticks) > TimeSpan.TicksPerMillisecond * this.connectTimeout)) - sw_delay.SpinOnce(); - - data = new byte[2100]; - Array.Copy(readBuffer, 0, data, 6, readBuffer.Length); - receivedUnitIdentifier = data[6]; - } +using System.IO.Ports; +using System.Net.NetworkInformation; +using System.Net.Sockets; +using EasyModbus.Exceptions; - if (receivedUnitIdentifier != this.unitIdentifier) - data = new byte[2100]; - else - countRetries = 0; +namespace EasyModbus; - } - else if (tcpClient.Client.Connected | udpFlag) - { - if (udpFlag) - { - UdpClient udpClient = new UdpClient(); - IPEndPoint endPoint = new IPEndPoint(System.Net.IPAddress.Parse(ipAddress), port); - udpClient.Send(data, data.Length - 2, endPoint); - portOut = ((IPEndPoint)udpClient.Client.LocalEndPoint).Port; - udpClient.Client.ReceiveTimeout = 5000; - endPoint = new IPEndPoint(System.Net.IPAddress.Parse(ipAddress), portOut); - data = udpClient.Receive(ref endPoint); - } - else - { - stream.Write(data, 0, data.Length - 2); - if (debug) - { - byte [] debugData = new byte[data.Length-2]; - Array.Copy(data, 0, debugData, 0, data.Length-2); - if (debug) StoreLogData.Instance.Store("Send ModbusTCP-Data: "+BitConverter.ToString(debugData) ,System.DateTime.Now); - } - if (SendDataChanged != null) - { - sendData = new byte[data.Length-2]; - Array.Copy(data, 0, sendData, 0, data.Length-2); - SendDataChanged(this); - - } - data = new Byte[2100]; - int NumberOfBytes = stream.Read(data, 0, data.Length); - if (ReceiveDataChanged != null) - { - receiveData = new byte[NumberOfBytes]; - Array.Copy(data, 0, receiveData, 0, NumberOfBytes); - if (debug) StoreLogData.Instance.Store("Receive ModbusTCP-Data: " + BitConverter.ToString(receiveData), System.DateTime.Now); - ReceiveDataChanged(this); - } - } - } - if (data[7] == 0x85 & data[8] == 0x01) - { - if (debug) StoreLogData.Instance.Store("FunctionCodeNotSupportedException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.FunctionCodeNotSupportedException("Function code not supported by master"); - } - if (data[7] == 0x85 & data[8] == 0x02) - { - if (debug) StoreLogData.Instance.Store("StartingAddressInvalidException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.StartingAddressInvalidException("Starting address invalid or starting address + quantity invalid"); - } - if (data[7] == 0x85 & data[8] == 0x03) - { - if (debug) StoreLogData.Instance.Store("QuantityInvalidException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.QuantityInvalidException("quantity invalid"); - } - if (data[7] == 0x85 & data[8] == 0x04) - { - if (debug) StoreLogData.Instance.Store("ModbusException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.ModbusException("error reading"); - } - if (serialport != null) - { - crc = BitConverter.GetBytes(calculateCRC(data, 6, 6)); - if ((crc[0] != data[12] | crc[1] != data[13]) & dataReceived) - { - if (debug) StoreLogData.Instance.Store("CRCCheckFailedException Throwed", System.DateTime.Now); - if (NumberOfRetries <= countRetries) - { - countRetries = 0; - throw new EasyModbus.Exceptions.CRCCheckFailedException("Response CRC check failed"); - } - else - { - countRetries++; - WriteSingleCoil(startingAddress, value); - } - } - else if (!dataReceived) - { - if (debug) StoreLogData.Instance.Store("TimeoutException Throwed", System.DateTime.Now); - if (NumberOfRetries <= countRetries) - { - countRetries = 0; - throw new TimeoutException("No Response from Modbus Slave"); +/// A serialized Modbus TCP, UDP, or RTU client. Dispose after use. +public partial class ModbusClient : IDisposable, IAsyncDisposable +{ + public enum RegisterOrder + { + LowHigh, HighLow + } - } - else - { - countRetries++; - WriteSingleCoil(startingAddress, value); - } - } - } + private readonly SemaphoreSlim _operationLock = new(1, 1); + private TcpClient? _tcpClient; + private UdpClient? _udpClient; + private SerialPort? _serialport; + private NetworkStream? _stream; + private bool _disposed; + private ushort _transactionIdentifier; + private byte[] _receiveData = []; + private byte[] _sendData = []; + + public delegate void ReceiveDataChangedHandler(object sender); + public delegate void SendDataChangedHandler(object sender); + public delegate void ConnectedChangedHandler(object sender); + public event ReceiveDataChangedHandler? ReceiveDataChanged; + public event SendDataChangedHandler? SendDataChanged; + public event ConnectedChangedHandler? ConnectedChanged; + + public ReadOnlyMemory ReceivedData => _receiveData; + public ReadOnlyMemory SentData => _sendData; + public bool Connected => _serialport?.IsOpen ?? (_udpClient is not null || _tcpClient?.Connected == true); + public string IPAddress { + get; + set { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + field = value; + } + } = "127.0.0.1"; + public int Port { + get; + set { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(value); + ArgumentOutOfRangeException.ThrowIfGreaterThan(value, 65535); + field = value; + } + } = 502; + public int ConnectionTimeout { + get; + set { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(value); + field = value; + } + } = 1000; + public int NumberOfRetries { + get; + set { + ArgumentOutOfRangeException.ThrowIfNegative(value); + field = value; + } + } = 3; + public bool UDPFlag { + get; set; + } + public byte UnitIdentifier { get; set; } = 1; + public int Baudrate { + get; + set { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(value); + field = value; } - - - /// - /// Write single Register to Master device (FC6). - /// - /// Register to be written - /// Register Value to be written - public void WriteSingleRegister(int startingAddress, int value) - { - if (debug) StoreLogData.Instance.Store("FC6 (Write single register to Master device), StartingAddress: "+ startingAddress+", Value: " + value, System.DateTime.Now); - transactionIdentifierInternal++; - if (serialport != null) - if (!serialport.IsOpen) - { - if (debug) StoreLogData.Instance.Store("SerialPortNotOpenedException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.SerialPortNotOpenedException("serial port not opened"); - } - if (tcpClient == null & !udpFlag & serialport == null) - { - if (debug) StoreLogData.Instance.Store("ConnectionException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.ConnectionException("connection error"); - } - byte[] registerValue = new byte[2]; - this.transactionIdentifier = BitConverter.GetBytes((uint)transactionIdentifierInternal); - this.protocolIdentifier = BitConverter.GetBytes((int)0x0000); - this.length = BitConverter.GetBytes((int)0x0006); - this.functionCode = 0x06; - this.startingAddress = BitConverter.GetBytes(startingAddress); - registerValue = BitConverter.GetBytes((int)value); - - Byte[] data = new byte[]{ this.transactionIdentifier[1], - this.transactionIdentifier[0], - this.protocolIdentifier[1], - this.protocolIdentifier[0], - this.length[1], - this.length[0], - this.unitIdentifier, - this.functionCode, - this.startingAddress[1], - this.startingAddress[0], - registerValue[1], - registerValue[0], - this.crc[0], - this.crc[1] - }; - crc = BitConverter.GetBytes(calculateCRC(data, 6, 6)); - data[12] = crc[0]; - data[13] = crc[1]; - if (serialport != null) - { - dataReceived = false; - bytesToRead = 8; -// serialport.ReceivedBytesThreshold = bytesToRead; - serialport.Write(data, 6, 8); - if (debug) - { - byte [] debugData = new byte[8]; - Array.Copy(data, 6, debugData, 0, 8); - if (debug) StoreLogData.Instance.Store("Send Serial-Data: "+BitConverter.ToString(debugData) ,System.DateTime.Now); - } - if (SendDataChanged != null) - { - sendData = new byte[8]; - Array.Copy(data, 6, sendData, 0, 8); - SendDataChanged(this); - - } - data = new byte[2100]; - readBuffer = new byte[256]; - DateTime dateTimeSend = DateTime.Now; - byte receivedUnitIdentifier = 0xFF; - - SpinWait sw_delay = new SpinWait(); - while (receivedUnitIdentifier != this.unitIdentifier & !((DateTime.Now.Ticks - dateTimeSend.Ticks) > TimeSpan.TicksPerMillisecond * this.connectTimeout)) - { - while (dataReceived == false & !((DateTime.Now.Ticks - dateTimeSend.Ticks) > TimeSpan.TicksPerMillisecond * this.connectTimeout)) - sw_delay.SpinOnce(); - - data = new byte[2100]; - Array.Copy(readBuffer, 0, data, 6, readBuffer.Length); - receivedUnitIdentifier = data[6]; - } - if (receivedUnitIdentifier != this.unitIdentifier) - data = new byte[2100]; - else - countRetries = 0; - } - else if (tcpClient.Client.Connected | udpFlag) - { - if (udpFlag) - { - UdpClient udpClient = new UdpClient(); - IPEndPoint endPoint = new IPEndPoint(System.Net.IPAddress.Parse(ipAddress), port); - udpClient.Send(data, data.Length - 2, endPoint); - portOut = ((IPEndPoint)udpClient.Client.LocalEndPoint).Port; - udpClient.Client.ReceiveTimeout = 5000; - endPoint = new IPEndPoint(System.Net.IPAddress.Parse(ipAddress), portOut); - data = udpClient.Receive(ref endPoint); - } - else - { - stream.Write(data, 0, data.Length - 2); - if (debug) - { - byte [] debugData = new byte[data.Length-2]; - Array.Copy(data, 0, debugData, 0, data.Length-2); - if (debug) StoreLogData.Instance.Store("Send ModbusTCP-Data: "+BitConverter.ToString(debugData) ,System.DateTime.Now); - } - if (SendDataChanged != null) - { - sendData = new byte[data.Length-2]; - Array.Copy(data, 0, sendData, 0, data.Length-2); - SendDataChanged(this); - - } - data = new Byte[2100]; - int NumberOfBytes = stream.Read(data, 0, data.Length); - if (ReceiveDataChanged != null) - { - receiveData = new byte[NumberOfBytes]; - Array.Copy(data, 0, receiveData, 0, NumberOfBytes); - if (debug) StoreLogData.Instance.Store("Receive ModbusTCP-Data: " + BitConverter.ToString(receiveData), System.DateTime.Now); - ReceiveDataChanged(this); - } - } - } - if (data[7] == 0x86 & data[8] == 0x01) - { - if (debug) StoreLogData.Instance.Store("FunctionCodeNotSupportedException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.FunctionCodeNotSupportedException("Function code not supported by master"); - } - if (data[7] == 0x86 & data[8] == 0x02) + } = 9600; + public Parity Parity { get; set; } = Parity.Even; + public StopBits StopBits { get; set; } = StopBits.One; + public string? SerialPort { + get => _serialport?.PortName; + set { + _operationLock.Wait(); + try { - if (debug) StoreLogData.Instance.Store("StartingAddressInvalidException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.StartingAddressInvalidException("Starting address invalid or starting address + quantity invalid"); + ObjectDisposedException.ThrowIf(_disposed, this); + CloseTransport(); + _serialport?.Dispose(); + _serialport = value is null ? null : new SerialPort(value); } - if (data[7] == 0x86 & data[8] == 0x03) + finally { - if (debug) StoreLogData.Instance.Store("QuantityInvalidException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.QuantityInvalidException("quantity invalid"); - } - if (data[7] == 0x86 & data[8] == 0x04) - { - if (debug) StoreLogData.Instance.Store("ModbusException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.ModbusException("error reading"); - } - if (serialport != null) - { - crc = BitConverter.GetBytes(calculateCRC(data, 6, 6)); - if ((crc[0] != data[12] | crc[1] != data[13]) & dataReceived) - { - if (debug) StoreLogData.Instance.Store("CRCCheckFailedException Throwed", System.DateTime.Now); - if (NumberOfRetries <= countRetries) - { - countRetries = 0; - throw new EasyModbus.Exceptions.CRCCheckFailedException("Response CRC check failed"); - } - else - { - countRetries++; - WriteSingleRegister(startingAddress, value); - } - } - else if (!dataReceived) - { - if (debug) StoreLogData.Instance.Store("TimeoutException Throwed", System.DateTime.Now); - if (NumberOfRetries <= countRetries) - { - countRetries = 0; - throw new TimeoutException("No Response from Modbus Slave"); - - } - else - { - countRetries++; - WriteSingleRegister(startingAddress, value); - } - } + _operationLock.Release(); } } + } - /// - /// Write multiple coils to Master device (FC15). - /// - /// First coil to be written - /// Coil Values to be written - public void WriteMultipleCoils(int startingAddress, bool[] values) - { - string debugString = ""; - for (int i = 0; i < values.Length;i++) - debugString = debugString + values[i] + " "; - if (debug) StoreLogData.Instance.Store("FC15 (Write multiple coils to Master device), StartingAddress: "+ startingAddress+", Values: " + debugString, System.DateTime.Now); - transactionIdentifierInternal++; - byte byteCount = (byte)((values.Length % 8 != 0 ? values.Length / 8 + 1: (values.Length / 8))); - byte[] quantityOfOutputs = BitConverter.GetBytes((int)values.Length); - byte singleCoilValue = 0; - if (serialport != null) - if (!serialport.IsOpen) - { - if (debug) StoreLogData.Instance.Store("SerialPortNotOpenedException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.SerialPortNotOpenedException("serial port not opened"); - } - if (tcpClient == null & !udpFlag & serialport == null) - { - if (debug) StoreLogData.Instance.Store("ConnectionException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.ConnectionException("connection error"); - } - this.transactionIdentifier = BitConverter.GetBytes((uint)transactionIdentifierInternal); - this.protocolIdentifier = BitConverter.GetBytes((int)0x0000); - this.length = BitConverter.GetBytes((int)(7+(byteCount))); - this.functionCode = 0x0F; - this.startingAddress = BitConverter.GetBytes(startingAddress); - - + public ModbusClient() + { - Byte[] data = new byte[14 +2 + (values.Length % 8 != 0 ? values.Length/8 : (values.Length / 8)-1)]; - data[0] = this.transactionIdentifier[1]; - data[1] = this.transactionIdentifier[0]; - data[2] = this.protocolIdentifier[1]; - data[3] = this.protocolIdentifier[0]; - data[4] = this.length[1]; - data[5] = this.length[0]; - data[6] = this.unitIdentifier; - data[7] = this.functionCode; - data[8] = this.startingAddress[1]; - data[9] = this.startingAddress[0]; - data[10] = quantityOfOutputs[1]; - data[11] = quantityOfOutputs[0]; - data[12] = byteCount; - for (int i = 0; i < values.Length; i++) - { - if ((i % 8) == 0) - singleCoilValue = 0; - byte CoilValue; - if (values[i] == true) - CoilValue = 1; - else - CoilValue = 0; + } + public ModbusClient(string ipAddress, int port) + { + IPAddress = ipAddress; + Port = port; + } - singleCoilValue = (byte)((int)CoilValue<<(i%8) | (int)singleCoilValue); + public ModbusClient(string serialPort) + { + ArgumentException.ThrowIfNullOrWhiteSpace(serialPort); + SerialPort = serialPort; + } - data[13 + (i / 8)] = singleCoilValue; - } - crc = BitConverter.GetBytes(calculateCRC(data, (ushort)(data.Length - 8), 6)); - data[data.Length - 2] = crc[0]; - data[data.Length - 1] = crc[1]; - if (serialport != null) - { - dataReceived = false; - bytesToRead = 8; - // serialport.ReceivedBytesThreshold = bytesToRead; - serialport.Write(data, 6, data.Length - 6); - if (debug) - { - byte [] debugData = new byte[data.Length - 6]; - Array.Copy(data, 6, debugData, 0, data.Length - 6); - if (debug) StoreLogData.Instance.Store("Send Serial-Data: "+BitConverter.ToString(debugData) ,System.DateTime.Now); - } - if (SendDataChanged != null) - { - sendData = new byte[data.Length - 6]; - Array.Copy(data, 6, sendData, 0, data.Length - 6); - SendDataChanged(this); - - } - data = new byte[2100]; - readBuffer = new byte[256]; - DateTime dateTimeSend = DateTime.Now; - byte receivedUnitIdentifier = 0xFF; + public void Connect() => ConnectAsync().GetAwaiter().GetResult(); + public void Connect(string ipAddress, int port) => ConnectAsync(ipAddress, port).GetAwaiter().GetResult(); - SpinWait sw_delay = new SpinWait(); - while (receivedUnitIdentifier != this.unitIdentifier & !((DateTime.Now.Ticks - dateTimeSend.Ticks) > TimeSpan.TicksPerMillisecond * this.connectTimeout)) - { - while (dataReceived == false & !((DateTime.Now.Ticks - dateTimeSend.Ticks) > TimeSpan.TicksPerMillisecond * this.connectTimeout)) - sw_delay.SpinOnce(); + public async Task ConnectAsync(string ipAddress, int port, CancellationToken cancellationToken = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(ipAddress); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(port); + ArgumentOutOfRangeException.ThrowIfGreaterThan(port, 65535); + await ConnectCoreAsync(ipAddress, port, cancellationToken).ConfigureAwait(false); + } - data = new byte[2100]; - Array.Copy(readBuffer, 0, data, 6, readBuffer.Length); - receivedUnitIdentifier = data[6]; - } - if (receivedUnitIdentifier != this.unitIdentifier) - data = new byte[2100]; - else - countRetries = 0; - } - else if (tcpClient.Client.Connected | udpFlag) - { - if (udpFlag) - { - UdpClient udpClient = new UdpClient(); - IPEndPoint endPoint = new IPEndPoint(System.Net.IPAddress.Parse(ipAddress), port); - udpClient.Send(data, data.Length-2, endPoint); - portOut = ((IPEndPoint)udpClient.Client.LocalEndPoint).Port; - udpClient.Client.ReceiveTimeout = 5000; - endPoint = new IPEndPoint(System.Net.IPAddress.Parse(ipAddress), portOut); - data = udpClient.Receive(ref endPoint); - } - else - { - stream.Write(data, 0, data.Length-2); - if (debug) - { - byte [] debugData = new byte[data.Length-2]; - Array.Copy(data, 0, debugData, 0, data.Length-2); - if (debug) StoreLogData.Instance.Store("Send ModbusTCP-Data: "+BitConverter.ToString(debugData) ,System.DateTime.Now); - } - if (SendDataChanged != null) - { - sendData = new byte[data.Length-2]; - Array.Copy(data, 0, sendData, 0, data.Length-2); - SendDataChanged(this); - - } - data = new Byte[2100]; - int NumberOfBytes = stream.Read(data, 0, data.Length); - if (ReceiveDataChanged != null) - { - receiveData = new byte[NumberOfBytes]; - Array.Copy(data, 0, receiveData, 0, NumberOfBytes); - if (debug) StoreLogData.Instance.Store("Receive ModbusTCP-Data: " + BitConverter.ToString(receiveData), System.DateTime.Now); - ReceiveDataChanged(this); - } - } - } - if (data[7] == 0x8F & data[8] == 0x01) - { - if (debug) StoreLogData.Instance.Store("FunctionCodeNotSupportedException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.FunctionCodeNotSupportedException("Function code not supported by master"); - } - if (data[7] == 0x8F & data[8] == 0x02) - { - if (debug) StoreLogData.Instance.Store("StartingAddressInvalidException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.StartingAddressInvalidException("Starting address invalid or starting address + quantity invalid"); - } - if (data[7] == 0x8F & data[8] == 0x03) - { - if (debug) StoreLogData.Instance.Store("QuantityInvalidException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.QuantityInvalidException("quantity invalid"); - } - if (data[7] == 0x8F & data[8] == 0x04) - { - if (debug) StoreLogData.Instance.Store("ModbusException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.ModbusException("error reading"); - } - if (serialport != null) - { - crc = BitConverter.GetBytes(calculateCRC(data, 6, 6)); - if ((crc[0] != data[12] | crc[1] != data[13]) & dataReceived) - { - if (debug) StoreLogData.Instance.Store("CRCCheckFailedException Throwed", System.DateTime.Now); - if (NumberOfRetries <= countRetries) - { - countRetries = 0; - throw new EasyModbus.Exceptions.CRCCheckFailedException("Response CRC check failed"); - } - else - { - countRetries++; - WriteMultipleCoils(startingAddress, values); - } - } - else if (!dataReceived) - { - if (debug) StoreLogData.Instance.Store("TimeoutException Throwed", System.DateTime.Now); - if (NumberOfRetries <= countRetries) - { - countRetries = 0; - throw new TimeoutException("No Response from Modbus Slave"); + public Task ConnectAsync(CancellationToken cancellationToken = default) => ConnectCoreAsync(IPAddress, Port, cancellationToken); - } - else - { - countRetries++; - WriteMultipleCoils(startingAddress, values); - } - } - } - } + private async Task ConnectCoreAsync(string ipAddress, int port, CancellationToken cancellationToken) + { + await _operationLock.WaitAsync(cancellationToken).ConfigureAwait(false); - /// - /// Write multiple registers to Master device (FC16). - /// - /// First register to be written - /// register Values to be written - public void WriteMultipleRegisters(int startingAddress, int[] values) + try { - string debugString = ""; - for (int i = 0; i < values.Length;i++) - debugString = debugString + values[i] + " "; - if (debug) StoreLogData.Instance.Store("FC16 (Write multiple Registers to Server device), StartingAddress: "+ startingAddress+", Values: " + debugString, System.DateTime.Now); - transactionIdentifierInternal++; - byte byteCount = (byte)(values.Length * 2); - byte[] quantityOfOutputs = BitConverter.GetBytes((int)values.Length); - if (serialport != null) - if (!serialport.IsOpen) - { - if (debug) StoreLogData.Instance.Store("SerialPortNotOpenedException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.SerialPortNotOpenedException("serial port not opened"); - } - if (tcpClient == null & !udpFlag & serialport == null) - { - if (debug) StoreLogData.Instance.Store("ConnectionException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.ConnectionException("connection error"); - } - this.transactionIdentifier = BitConverter.GetBytes((uint)transactionIdentifierInternal); - this.protocolIdentifier = BitConverter.GetBytes((int)0x0000); - this.length = BitConverter.GetBytes((int)(7+values.Length*2)); - this.functionCode = 0x10; - this.startingAddress = BitConverter.GetBytes(startingAddress); - - Byte[] data = new byte[13+2 + values.Length*2]; - data[0] = this.transactionIdentifier[1]; - data[1] = this.transactionIdentifier[0]; - data[2] = this.protocolIdentifier[1]; - data[3] = this.protocolIdentifier[0]; - data[4] = this.length[1]; - data[5] = this.length[0]; - data[6] = this.unitIdentifier; - data[7] = this.functionCode; - data[8] = this.startingAddress[1]; - data[9] = this.startingAddress[0]; - data[10] = quantityOfOutputs[1]; - data[11] = quantityOfOutputs[0]; - data[12] = byteCount; - for (int i = 0; i < values.Length; i++) - { - byte[] singleRegisterValue = BitConverter.GetBytes((int)values[i]); - data[13 + i*2] = singleRegisterValue[1]; - data[14 + i*2] = singleRegisterValue[0]; - } - crc = BitConverter.GetBytes(calculateCRC(data, (ushort)(data.Length - 8), 6)); - data[data.Length - 2] = crc[0]; - data[data.Length - 1] = crc[1]; - if (serialport != null) + ObjectDisposedException.ThrowIf(_disposed, this); + CloseTransport(); + IPAddress = ipAddress; + Port = port; + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeout.CancelAfter(ConnectionTimeout); + try { - dataReceived = false; - bytesToRead = 8; -// serialport.ReceivedBytesThreshold = bytesToRead; - serialport.Write(data, 6, data.Length - 6); - - if (debug) - { - byte [] debugData = new byte[data.Length - 6]; - Array.Copy(data, 6, debugData, 0, data.Length - 6); - if (debug) StoreLogData.Instance.Store("Send Serial-Data: "+BitConverter.ToString(debugData) ,System.DateTime.Now); - } - if (SendDataChanged != null) - { - sendData = new byte[data.Length - 6]; - Array.Copy(data, 6, sendData, 0, data.Length - 6); - SendDataChanged(this); - - } - data = new byte[2100]; - readBuffer = new byte[256]; - DateTime dateTimeSend = DateTime.Now; - byte receivedUnitIdentifier = 0xFF; - - SpinWait sw_delay = new SpinWait(); - while (receivedUnitIdentifier != this.unitIdentifier & !((DateTime.Now.Ticks - dateTimeSend.Ticks) > TimeSpan.TicksPerMillisecond * this.connectTimeout)) + if (_serialport is not null) { - while (dataReceived == false & !((DateTime.Now.Ticks - dateTimeSend.Ticks) > TimeSpan.TicksPerMillisecond * this.connectTimeout)) - sw_delay.SpinOnce(); - - data = new byte[2100]; - Array.Copy(readBuffer, 0, data, 6, readBuffer.Length); - receivedUnitIdentifier = data[6]; + ConfigureSerialPort(); + _serialport.Open(); } - if (receivedUnitIdentifier != this.unitIdentifier) - data = new byte[2100]; - else - countRetries = 0; - } - else if (tcpClient.Client.Connected | udpFlag) - { - if (udpFlag) + else if (UDPFlag) { - UdpClient udpClient = new UdpClient(); - IPEndPoint endPoint = new IPEndPoint(System.Net.IPAddress.Parse(ipAddress), port); - udpClient.Send(data, data.Length-2, endPoint); - portOut = ((IPEndPoint)udpClient.Client.LocalEndPoint).Port; - udpClient.Client.ReceiveTimeout = 5000; - endPoint = new IPEndPoint(System.Net.IPAddress.Parse(ipAddress), portOut); - data = udpClient.Receive(ref endPoint); + var addresses = await System.Net.Dns.GetHostAddressesAsync(ipAddress, timeout.Token).ConfigureAwait(false); + _udpClient = new UdpClient(addresses[0].AddressFamily); + _udpClient.Connect(addresses[0], port); } else { - stream.Write(data, 0, data.Length-2); - if (debug) - { - byte [] debugData = new byte[data.Length-2]; - Array.Copy(data, 0, debugData, 0, data.Length-2); - if (debug) StoreLogData.Instance.Store("Send ModbusTCP-Data: "+BitConverter.ToString(debugData) ,System.DateTime.Now); - } - if (SendDataChanged != null) - { - sendData = new byte[data.Length-2]; - Array.Copy(data, 0, sendData, 0, data.Length-2); - SendDataChanged(this); - } - data = new Byte[2100]; - int NumberOfBytes = stream.Read(data, 0, data.Length); - if (ReceiveDataChanged != null) - { - receiveData = new byte[NumberOfBytes]; - Array.Copy(data, 0, receiveData, 0, NumberOfBytes); - if (debug) StoreLogData.Instance.Store("Receive ModbusTCP-Data: " + BitConverter.ToString(receiveData), System.DateTime.Now); - ReceiveDataChanged(this); - } + _tcpClient = new TcpClient { NoDelay = true }; + await _tcpClient.ConnectAsync(ipAddress, port, timeout.Token).ConfigureAwait(false); + _stream = _tcpClient.GetStream(); } } - if (data[7] == 0x90 & data[8] == 0x01) + catch (OperationCanceledException exception) when (!cancellationToken.IsCancellationRequested) { - if (debug) StoreLogData.Instance.Store("FunctionCodeNotSupportedException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.FunctionCodeNotSupportedException("Function code not supported by master"); + CloseTransport(); + throw new ConnectionException("The Modbus connection timed out.", exception); } - if (data[7] == 0x90 & data[8] == 0x02) + catch { - if (debug) StoreLogData.Instance.Store("StartingAddressInvalidException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.StartingAddressInvalidException("Starting address invalid or starting address + quantity invalid"); - } - if (data[7] == 0x90 & data[8] == 0x03) - { - if (debug) StoreLogData.Instance.Store("QuantityInvalidException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.QuantityInvalidException("quantity invalid"); - } - if (data[7] == 0x90 & data[8] == 0x04) - { - if (debug) StoreLogData.Instance.Store("ModbusException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.ModbusException("error reading"); - } - if (serialport != null) - { - crc = BitConverter.GetBytes(calculateCRC(data, 6, 6)); - if ((crc[0] != data[12] | crc[1] != data[13]) &dataReceived) - { - if (debug) StoreLogData.Instance.Store("CRCCheckFailedException Throwed", System.DateTime.Now); - if (NumberOfRetries <= countRetries) - { - countRetries = 0; - throw new EasyModbus.Exceptions.CRCCheckFailedException("Response CRC check failed"); - } - else - { - countRetries++; - WriteMultipleRegisters(startingAddress, values); - } - } - else if (!dataReceived) - { - if (debug) StoreLogData.Instance.Store("TimeoutException Throwed", System.DateTime.Now); - if (NumberOfRetries <= countRetries) - { - countRetries = 0; - throw new TimeoutException("No Response from Modbus Slave"); - - } - else - { - countRetries++; - WriteMultipleRegisters(startingAddress, values); - } - } + CloseTransport(); + throw; } } - - /// - /// Read/Write Multiple Registers (FC23). - /// - /// First input register to read - /// Number of input registers to read - /// First input register to write - /// Values to write - /// Int Array which contains the Holding registers - public int[] ReadWriteMultipleRegisters(int startingAddressRead, int quantityRead, int startingAddressWrite, int[] values) + finally { - - string debugString = ""; - for (int i = 0; i < values.Length;i++) - debugString = debugString + values[i] + " "; - if (debug) StoreLogData.Instance.Store("FC23 (Read and Write multiple Registers to Server device), StartingAddress Read: "+ startingAddressRead+ ", Quantity Read: "+quantityRead+", startingAddressWrite: " + startingAddressWrite +", Values: " + debugString, System.DateTime.Now); - transactionIdentifierInternal++; - byte [] startingAddressReadLocal = new byte[2]; - byte [] quantityReadLocal = new byte[2]; - byte[] startingAddressWriteLocal = new byte[2]; - byte[] quantityWriteLocal = new byte[2]; - byte writeByteCountLocal = 0; - if (serialport != null) - if (!serialport.IsOpen) - { - if (debug) StoreLogData.Instance.Store("SerialPortNotOpenedException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.SerialPortNotOpenedException("serial port not opened"); - } - if (tcpClient == null & !udpFlag & serialport == null) - { - if (debug) StoreLogData.Instance.Store("ConnectionException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.ConnectionException("connection error"); - } - if (startingAddressRead > 65535 | quantityRead > 125 | startingAddressWrite > 65535 | values.Length > 121) - { - if (debug) StoreLogData.Instance.Store("ArgumentException Throwed", System.DateTime.Now); - throw new ArgumentException("Starting address must be 0 - 65535; quantity must be 0 - 2000"); - } - int[] response; - this.transactionIdentifier = BitConverter.GetBytes((uint)transactionIdentifierInternal); - this.protocolIdentifier = BitConverter.GetBytes((int)0x0000); - this.length = BitConverter.GetBytes((int)11 + values.Length * 2); - this.functionCode = 0x17; - startingAddressReadLocal = BitConverter.GetBytes(startingAddressRead); - quantityReadLocal = BitConverter.GetBytes(quantityRead); - startingAddressWriteLocal = BitConverter.GetBytes(startingAddressWrite); - quantityWriteLocal = BitConverter.GetBytes(values.Length); - writeByteCountLocal = Convert.ToByte(values.Length * 2); - Byte[] data = new byte[17 +2+ values.Length*2]; - data[0] = this.transactionIdentifier[1]; - data[1] = this.transactionIdentifier[0]; - data[2] = this.protocolIdentifier[1]; - data[3] = this.protocolIdentifier[0]; - data[4] = this.length[1]; - data[5] = this.length[0]; - data[6] = this.unitIdentifier; - data[7] = this.functionCode; - data[8] = startingAddressReadLocal[1]; - data[9] = startingAddressReadLocal[0]; - data[10] = quantityReadLocal[1]; - data[11] = quantityReadLocal[0]; - data[12] = startingAddressWriteLocal[1]; - data[13] = startingAddressWriteLocal[0]; - data[14] = quantityWriteLocal[1]; - data[15] = quantityWriteLocal[0]; - data[16] = writeByteCountLocal; - - for (int i = 0; i < values.Length; i++) - { - byte[] singleRegisterValue = BitConverter.GetBytes((int)values[i]); - data[17 + i*2] = singleRegisterValue[1]; - data[18 + i*2] = singleRegisterValue[0]; - } - crc = BitConverter.GetBytes(calculateCRC(data, (ushort)(data.Length - 8), 6)); - data[data.Length - 2] = crc[0]; - data[data.Length - 1] = crc[1]; - if (serialport != null) - { - dataReceived = false; - bytesToRead = 5 + 2*quantityRead; - // serialport.ReceivedBytesThreshold = bytesToRead; - serialport.Write(data, 6, data.Length - 6); - if (debug) - { - byte [] debugData = new byte[data.Length - 6]; - Array.Copy(data, 6, debugData, 0, data.Length - 6); - if (debug) StoreLogData.Instance.Store("Send Serial-Data: "+BitConverter.ToString(debugData) ,System.DateTime.Now); - } - if (SendDataChanged != null) - { - sendData = new byte[data.Length - 6]; - Array.Copy(data, 6, sendData, 0, data.Length - 6); - SendDataChanged(this); - } - data = new byte[2100]; - readBuffer = new byte[256]; - DateTime dateTimeSend = DateTime.Now; - byte receivedUnitIdentifier = 0xFF; - - SpinWait sw_delay = new SpinWait(); - while (receivedUnitIdentifier != this.unitIdentifier & !((DateTime.Now.Ticks - dateTimeSend.Ticks) > TimeSpan.TicksPerMillisecond * this.connectTimeout)) - { - while (dataReceived == false & !((DateTime.Now.Ticks - dateTimeSend.Ticks) > TimeSpan.TicksPerMillisecond * this.connectTimeout)) - sw_delay.SpinOnce(); - - data = new byte[2100]; - Array.Copy(readBuffer, 0, data, 6, readBuffer.Length); - receivedUnitIdentifier = data[6]; - } - if (receivedUnitIdentifier != this.unitIdentifier) - data = new byte[2100]; - else - countRetries = 0; - } - else if (tcpClient.Client.Connected | udpFlag) - { - if (udpFlag) - { - UdpClient udpClient = new UdpClient(); - IPEndPoint endPoint = new IPEndPoint(System.Net.IPAddress.Parse(ipAddress), port); - udpClient.Send(data, data.Length-2, endPoint); - portOut = ((IPEndPoint)udpClient.Client.LocalEndPoint).Port; - udpClient.Client.ReceiveTimeout = 5000; - endPoint = new IPEndPoint(System.Net.IPAddress.Parse(ipAddress), portOut); - data = udpClient.Receive(ref endPoint); - } - else - { - stream.Write(data, 0, data.Length-2); - if (debug) - { - byte [] debugData = new byte[data.Length-2]; - Array.Copy(data, 0, debugData, 0, data.Length-2); - if (debug) StoreLogData.Instance.Store("Send ModbusTCP-Data: "+BitConverter.ToString(debugData) ,System.DateTime.Now); - } - if (SendDataChanged != null) - { - sendData = new byte[data.Length-2]; - Array.Copy(data, 0, sendData, 0, data.Length-2); - SendDataChanged(this); - - } - data = new Byte[2100]; - int NumberOfBytes = stream.Read(data, 0, data.Length); - if (ReceiveDataChanged != null) - { - receiveData = new byte[NumberOfBytes]; - Array.Copy(data, 0, receiveData, 0, NumberOfBytes); - if (debug) StoreLogData.Instance.Store("Receive ModbusTCP-Data: " + BitConverter.ToString(receiveData), System.DateTime.Now); - ReceiveDataChanged(this); - } - } - } - if (data[7] == 0x97 & data[8] == 0x01) - { - if (debug) StoreLogData.Instance.Store("FunctionCodeNotSupportedException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.FunctionCodeNotSupportedException("Function code not supported by master"); - } - if (data[7] == 0x97 & data[8] == 0x02) - { - if (debug) StoreLogData.Instance.Store("StartingAddressInvalidException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.StartingAddressInvalidException("Starting address invalid or starting address + quantity invalid"); - } - if (data[7] == 0x97 & data[8] == 0x03) - { - if (debug) StoreLogData.Instance.Store("QuantityInvalidException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.QuantityInvalidException("quantity invalid"); - } - if (data[7] == 0x97 & data[8] == 0x04) - { - if (debug) StoreLogData.Instance.Store("ModbusException Throwed", System.DateTime.Now); - throw new EasyModbus.Exceptions.ModbusException("error reading"); - } - response = new int[quantityRead]; - for (int i = 0; i < quantityRead; i++) - { - byte lowByte; - byte highByte; - highByte = data[9 + i * 2]; - lowByte = data[9 + i * 2 + 1]; - - data[9 + i * 2] = lowByte; - data[9 + i * 2 + 1] = highByte; - - response[i] = BitConverter.ToInt16(data, (9 + i * 2)); - } - return (response); - } - - /// - /// Close connection to Master Device. - /// - public void Disconnect() - { - if (debug) StoreLogData.Instance.Store("Disconnect", System.DateTime.Now); - if (serialport != null) - { - if (serialport.IsOpen & !this.receiveActive) - serialport.Close(); - if (ConnectedChanged != null) - ConnectedChanged(this); - return; - } - if (stream != null) - stream.Close(); - if (tcpClient != null) - tcpClient.Close(); - connected = false; - if (ConnectedChanged != null) - ConnectedChanged(this); - + _operationLock.Release(); } - /// - /// Destructor - Close connection to Master Device. - /// - ~ ModbusClient() - { - if (debug) StoreLogData.Instance.Store("Destructor called - automatically disconnect", System.DateTime.Now); - if (serialport != null) - { - if (serialport.IsOpen) - serialport.Close(); - return; - } - if (tcpClient != null & !udpFlag) - { - if (stream !=null) - stream.Close(); - tcpClient.Close(); - } - } - - /// - /// Returns "TRUE" if Client is connected to Server and "FALSE" if not. In case of Modbus RTU returns if COM-Port is opened - /// - public bool Connected - { - get - { - if (serialport != null) - { - return (serialport.IsOpen); - } - - if (udpFlag & tcpClient != null) - return true; - if (tcpClient == null) - return false; - else - { - return connected; - - } + ConnectedChanged?.Invoke(this); + } - } - } + public void Disconnect() + { + _operationLock.Wait(); - public bool Available(int timeout) + try { - // Ping's the local machine. - System.Net.NetworkInformation.Ping pingSender = new System.Net.NetworkInformation.Ping(); - IPAddress address = System.Net.IPAddress.Parse(ipAddress); - - // Create a buffer of 32 bytes of data to be transmitted. - string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; - byte[] buffer = System.Text.Encoding.ASCII.GetBytes(data); - - // Wait 10 seconds for a reply. - System.Net.NetworkInformation.PingReply reply = pingSender.Send(address, timeout, buffer); - - if (reply.Status == System.Net.NetworkInformation.IPStatus.Success) - return true; - else - return false; + CloseTransport(); + } + finally + { + _operationLock.Release(); } - /// - /// Gets or Sets the IP-Address of the Server. - /// - public string IPAddress - { - get - { - return ipAddress; - } - set - { - ipAddress = value; - } - } + ConnectedChanged?.Invoke(this); + } - /// - /// Gets or Sets the Port were the Modbus-TCP Server is reachable (Standard is 502). - /// - public int Port - { - get - { - return port; - } - set - { - port = value; - } - } + public bool Available(int timeout) + { + ObjectDisposedException.ThrowIf(_disposed, this); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(timeout); + using var ping = new Ping(); + return ping.Send(IPAddress, timeout)?.Status == IPStatus.Success; + } - /// - /// Gets or Sets the UDP-Flag to activate Modbus UDP. - /// - public bool UDPFlag - { - get - { - return udpFlag; - } - set - { - udpFlag = value; - } - } + private void ConfigureSerialPort() + { + var serial = _serialport ?? throw new SerialPortNotOpenedException("No serial port is configured."); + serial.BaudRate = Baudrate; + serial.Parity = Parity; + serial.StopBits = StopBits; + serial.ReadTimeout = ConnectionTimeout; + serial.WriteTimeout = ConnectionTimeout; + } - /// - /// Gets or Sets the Unit identifier in case of serial connection (Default = 0) - /// - public byte UnitIdentifier - { - get - { - return unitIdentifier; - } - set - { - unitIdentifier = value; - } - } + private void CloseTransport() + { + _stream?.Dispose(); + _stream = null; + _tcpClient?.Dispose(); + _tcpClient = null; + _udpClient?.Dispose(); + _udpClient = null; + if (_serialport?.IsOpen == true) + _serialport.Close(); + } + public void Dispose() + { + _operationLock.Wait(); - /// - /// Gets or Sets the Baudrate for serial connection (Default = 9600) - /// - public int Baudrate + try { - get - { - return baudRate; - } - set - { - baudRate = value; - } + DisposeCore(); } - - /// - /// Gets or Sets the of Parity in case of serial connection - /// - public Parity Parity + finally { - get - { - if (serialport != null) - return parity; - else - return Parity.Even; - } - set - { - if (serialport != null) - parity = value; - } + _operationLock.Release(); } + GC.SuppressFinalize(this); + } - /// - /// Gets or Sets the number of stopbits in case of serial connection - /// - public StopBits StopBits - { - get - { - if (serialport != null) - return stopBits; - else - return StopBits.One; - } - set - { - if (serialport != null) - stopBits = value; - } - } + public async ValueTask DisposeAsync() + { + await _operationLock.WaitAsync().ConfigureAwait(false); - /// - /// Gets or Sets the connection Timeout in case of ModbusTCP connection - /// - public int ConnectionTimeout + try { - get - { - return connectTimeout; - } - set - { - connectTimeout = value; - } + DisposeCore(); } - - /// - /// Gets or Sets the serial Port - /// - public string SerialPort + finally { - get - { - - return serialport.PortName; - } - set - { - if (value == null) - { - serialport = null; - return; - } - if (serialport != null) - serialport.Close(); - this.serialport = new SerialPort(); - this.serialport.PortName = value; - serialport.BaudRate = baudRate; - serialport.Parity = parity; - serialport.StopBits = stopBits; - serialport.WriteTimeout = 10000; - serialport.ReadTimeout = connectTimeout; - serialport.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler); - } + _operationLock.Release(); } - /// - /// Gets or Sets the Filename for the LogFile - /// - public string LogFileFilename - { - get - { - return StoreLogData.Instance.Filename; - } - set - { - StoreLogData.Instance.Filename = value; - if (StoreLogData.Instance.Filename != null) - debug = true; - else - debug = false; - } - } + GC.SuppressFinalize(this); + } + private void DisposeCore() + { + if (_disposed) + return; + + _disposed = true; + CloseTransport(); + _serialport?.Dispose(); + _serialport = null; + // Keep the managed semaphore alive so callers already waiting on it can + // enter, observe disposal, and leave without a release/disposal race. } } diff --git a/EasyModbus/ModbusFrame.cs b/EasyModbus/ModbusFrame.cs new file mode 100644 index 0000000..d7868fd --- /dev/null +++ b/EasyModbus/ModbusFrame.cs @@ -0,0 +1,51 @@ +using System.Buffers.Binary; + +namespace EasyModbus; + +internal static class ModbusFrame +{ + internal const int MaxLength = 260; + + internal static byte[] Create(ushort transaction, byte unit, ReadOnlySpan pdu) + { + var frame = new byte[7 + pdu.Length]; + BinaryPrimitives.WriteUInt16BigEndian(frame, transaction); + BinaryPrimitives.WriteUInt16BigEndian(frame.AsSpan(4), (ushort)(pdu.Length + 1)); + frame[6] = unit; + pdu.CopyTo(frame.AsSpan(7)); + return frame; + } + + internal static void Validate(ReadOnlySpan frame) + { + if (frame.Length is < 8 or > MaxLength || BinaryPrimitives.ReadUInt16BigEndian(frame[2..]) != 0 || + BinaryPrimitives.ReadUInt16BigEndian(frame[4..]) != frame.Length - 6) + throw new InvalidDataException("Invalid Modbus TCP/UDP frame header or length."); + } + + internal static async ValueTask ReadAsync(Stream stream, CancellationToken cancellationToken) + { + var header = new byte[7]; + await stream.ReadExactlyAsync(header, cancellationToken).ConfigureAwait(false); + var length = BinaryPrimitives.ReadUInt16BigEndian(header.AsSpan(4)); + if (length is < 2 or > 254 || BinaryPrimitives.ReadUInt16BigEndian(header.AsSpan(2)) != 0) + throw new InvalidDataException("Invalid Modbus TCP frame header or length."); + + var frame = new byte[6 + length]; + header.CopyTo(frame, 0); + await stream.ReadExactlyAsync(frame.AsMemory(7), cancellationToken).ConfigureAwait(false); + return frame; + } + + internal static ushort CalculateCrc(ReadOnlySpan data) + { + ushort crc = 0xFFFF; + foreach (var value in data) + { + crc ^= value; + for (var bit = 0; bit < 8; bit++) + crc = (ushort)((crc & 1) != 0 ? (crc >> 1) ^ 0xA001 : crc >> 1); + } + return crc; + } +} diff --git a/EasyModbus/ModbusProtocol.cs b/EasyModbus/ModbusProtocol.cs new file mode 100644 index 0000000..2617b2c --- /dev/null +++ b/EasyModbus/ModbusProtocol.cs @@ -0,0 +1,34 @@ +namespace EasyModbus; + +public class ModbusProtocol +{ + public enum ProtocolType + { + ModbusTCP = 0, + ModbusUDP = 1, + ModbusRTU = 2 + }; + + public DateTime TimeStamp; + public bool Request; + public bool Response; + public ushort TransactionIdentifier; + public ushort ProtocolIdentifier; + public ushort Length; + public byte UnitIdentifier; + public byte FunctionCode; + public ushort StartingAdress; + public ushort StartingAddressRead; + public ushort StartingAddressWrite; + public ushort Quantity; + public ushort QuantityRead; + public ushort QuantityWrite; + public byte ByteCount; + public byte ExceptionCode; + public byte ErrorCode; + public ushort[] ReceiveCoilValues = []; + public ushort[] ReceiveRegisterValues = []; + public short[] SendRegisterValues = []; + public bool[] SendCoilValues = []; + public ushort Crc; +} diff --git a/EasyModbus/ModbusServer.Protocol.cs b/EasyModbus/ModbusServer.Protocol.cs new file mode 100644 index 0000000..1ec1629 --- /dev/null +++ b/EasyModbus/ModbusServer.Protocol.cs @@ -0,0 +1,243 @@ +using System.Buffers.Binary; + +namespace EasyModbus; + +public partial class ModbusServer +{ + private byte[]? ProcessRequest(byte[] frame) + { + ModbusFrame.Validate(frame); + if (frame[6] != UnitIdentifier && frame[6] != 0) + return null; + + var previous = _processingRequest.Value; + _processingRequest.Value = true; + try + { + byte[] response; + (int Address, int Count, bool Coils)? change; + lock (_stateLock) + { + var pdu = HandlePdu(frame.AsSpan(7), out change); + response = ModbusFrame.Create(BinaryPrimitives.ReadUInt16BigEndian(frame), frame[6], pdu); + Array.Copy(_modbusLogData, 0, _modbusLogData, 2, _modbusLogData.Length - 2); + _modbusLogData[0] = CreateLog(frame, true); + _modbusLogData[1] = CreateLog(response, false); + } + + StoreLogData.Instance.Store($"Request: {Convert.ToHexString(frame)}; response: {Convert.ToHexString(response)}", DateTime.Now); + if (change is { } updated) + { + if (updated.Coils) + CoilsChanged?.Invoke(updated.Address + 1, updated.Count); + else + HoldingRegistersChanged?.Invoke(updated.Address + 1, updated.Count); + } + + LogDataChanged?.Invoke(); + return response; + } + finally + { + _processingRequest.Value = previous; + } + } + + private byte[] HandlePdu(ReadOnlySpan pdu, out (int Address, int Count, bool Coils)? change) + { + change = null; + var function = pdu[0]; + var disabled = function switch + { + 1 => FunctionCode1Disabled, + 2 => FunctionCode2Disabled, + 3 => FunctionCode3Disabled, + 4 => FunctionCode4Disabled, + 5 => FunctionCode5Disabled, + 6 => FunctionCode6Disabled, + 15 => FunctionCode15Disabled, + 16 => FunctionCode16Disabled, + 23 => FunctionCode23Disabled, + _ => true + }; + + if (disabled) + return Error(function, 1); + + if (pdu.Length < 5) + return Error(function, 3); + + var address = BinaryPrimitives.ReadUInt16BigEndian(pdu[1..]); + var quantity = BinaryPrimitives.ReadUInt16BigEndian(pdu[3..]); + + if (function is >= 1 and <= 4) + { + if (pdu.Length != 5 || quantity == 0 || quantity > (function <= 2 ? 2000 : 125)) + return Error(function, 3); + + if (!ValidRange(address, quantity)) + return Error(function, 2); + + if (function <= 2) + { + var table = function == 1 ? Coils._localArray : DiscreteInputs._localArray; + var result = new byte[2 + (quantity + 7) / 8]; + result[0] = function; + result[1] = (byte)(result.Length - 2); + for (var index = 0; index < quantity; index++) + if (table[address + index + 1]) + result[2 + index / 8] |= (byte)(1 << (index % 8)); + + return result; + } + + return ReadRegisterResponse(function, address, quantity, function == 3 ? HoldingRegisters._localArray : InputRegisters._localArray); + } + + if (function is 5 or 6) + { + if (pdu.Length != 5 || (function == 5 && quantity is not 0 and not 0xFF00)) + return Error(function, 3); + + if (function == 5) + Coils._localArray[address + 1] = quantity != 0; + else + HoldingRegisters._localArray[address + 1] = unchecked((short)quantity); + + change = (address, 1, function == 5); + return pdu.ToArray(); + } + + if (function is 15 or 16) + { + if (pdu.Length < 6 || quantity == 0 || quantity > (function == 15 ? 1968 : 123)) + return Error(function, 3); + + var byteCount = function == 15 ? (quantity + 7) / 8 : quantity * 2; + if (pdu[5] != byteCount || pdu.Length != byteCount + 6) + return Error(function, 3); + + if (!ValidRange(address, quantity)) + return Error(function, 2); + + for (var index = 0; index < quantity; index++) + { + if (function == 15) + Coils._localArray[address + index + 1] = (pdu[6 + index / 8] & (1 << (index % 8))) != 0; + else + HoldingRegisters._localArray[address + index + 1] = BinaryPrimitives.ReadInt16BigEndian(pdu[(6 + index * 2)..]); + } + + change = (address, quantity, function == 15); + return pdu[..5].ToArray(); + } + + if (pdu.Length < 10) + return Error(function, 3); + + var writeAddress = BinaryPrimitives.ReadUInt16BigEndian(pdu[5..]); + var writeQuantity = BinaryPrimitives.ReadUInt16BigEndian(pdu[7..]); + if (quantity is 0 or > 125 || writeQuantity is 0 or > 121 || pdu[9] != writeQuantity * 2 || pdu.Length != 10 + writeQuantity * 2) + return Error(function, 3); + + if (!ValidRange(address, quantity) || !ValidRange(writeAddress, writeQuantity)) + return Error(function, 2); + + for (var index = 0; index < writeQuantity; index++) + HoldingRegisters._localArray[writeAddress + index + 1] = BinaryPrimitives.ReadInt16BigEndian(pdu[(10 + index * 2)..]); + + change = (writeAddress, writeQuantity, false); + return ReadRegisterResponse(function, address, quantity, HoldingRegisters._localArray); + } + + private static bool ValidRange(int address, int quantity) => address + quantity <= 65536; + private static byte[] Error(byte function, byte code) => [(byte)(function | 0x80), code]; + + private static byte[] ReadRegisterResponse(byte function, int address, int quantity, short[] table) + { + var response = new byte[2 + quantity * 2]; + response[0] = function; + response[1] = (byte)(quantity * 2); + for (var index = 0; index < quantity; index++) + BinaryPrimitives.WriteInt16BigEndian(response.AsSpan(2 + index * 2), table[address + index + 1]); + + return response; + } + + private static ModbusProtocol CreateLog(byte[] frame, bool request) + { + var pdu = frame.AsSpan(7); + var result = new ModbusProtocol + { + TimeStamp = DateTime.Now, + Request = request, + Response = !request, + TransactionIdentifier = BinaryPrimitives.ReadUInt16BigEndian(frame), + Length = (ushort)(frame.Length - 6), + UnitIdentifier = frame[6], + FunctionCode = pdu[0] + }; + + if ((pdu[0] & 0x80) != 0 && pdu.Length >= 2) + { + result.ErrorCode = pdu[0]; + result.ExceptionCode = pdu[1]; + } + else if (request && pdu.Length >= 5) + { + result.StartingAdress = BinaryPrimitives.ReadUInt16BigEndian(pdu[1..]); + result.Quantity = BinaryPrimitives.ReadUInt16BigEndian(pdu[3..]); + if (pdu[0] == 5) + result.ReceiveCoilValues = [result.Quantity]; + + if (pdu[0] == 6) + result.ReceiveRegisterValues = [result.Quantity]; + + if (pdu[0] is 16 or 23) + { + var offset = pdu[0] == 16 ? 6 : 10; + if (pdu.Length < offset) + return result; + + result.ByteCount = pdu[offset - 1]; + result.ReceiveRegisterValues = new ushort[(pdu.Length - offset) / 2]; + for (var index = 0; index < result.ReceiveRegisterValues.Length; index++) + result.ReceiveRegisterValues[index] = BinaryPrimitives.ReadUInt16BigEndian(pdu[(offset + index * 2)..]); + + if (pdu[0] == 23) + { + result.StartingAddressRead = result.StartingAdress; + result.QuantityRead = result.Quantity; + result.StartingAddressWrite = BinaryPrimitives.ReadUInt16BigEndian(pdu[5..]); + result.QuantityWrite = BinaryPrimitives.ReadUInt16BigEndian(pdu[7..]); + } + } + + if (pdu[0] == 15 && pdu.Length >= 6) + { + result.ByteCount = pdu[5]; + result.ReceiveCoilValues = new ushort[(pdu.Length - 6 + 1) / 2]; + for (var index = 6; index < pdu.Length; index++) + result.ReceiveCoilValues[(index - 6) / 2] |= (ushort)(pdu[index] << ((index - 6) % 2 * 8)); + } + } + else if (!request && pdu[0] is 1 or 2 or 3 or 4 or 23) + { + result.ByteCount = pdu[1]; + if (pdu[0] is 1 or 2) + { + result.SendCoilValues = new bool[result.ByteCount * 8]; + for (var index = 0; index < result.SendCoilValues.Length; index++) + result.SendCoilValues[index] = (pdu[2 + index / 8] & (1 << (index % 8))) != 0; + } + else + { + result.SendRegisterValues = new short[result.ByteCount / 2]; + for (var index = 0; index < result.SendRegisterValues.Length; index++) + result.SendRegisterValues[index] = BinaryPrimitives.ReadInt16BigEndian(pdu[(2 + index * 2)..]); + } + } + + return result; + } +} diff --git a/EasyModbus/ModbusServer.Registers.cs b/EasyModbus/ModbusServer.Registers.cs new file mode 100644 index 0000000..62d8d64 --- /dev/null +++ b/EasyModbus/ModbusServer.Registers.cs @@ -0,0 +1,77 @@ +namespace EasyModbus; + +public partial class ModbusServer +{ + // Wire addresses 0..65535 map to the legacy local indices 1..65536. + public class HoldingRegisterCollection(ModbusServer modbusServer) + { + internal readonly short[] _localArray = new short[65537]; + public short this[int index] + { + get + { + lock (modbusServer._stateLock) + return _localArray[index]; + } + set + { + lock (modbusServer._stateLock) + _localArray[index] = value; + } + } + } + + public class InputRegisterCollection(ModbusServer modbusServer) + { + internal readonly short[] _localArray = new short[65537]; + public short this[int index] + { + get + { + lock (modbusServer._stateLock) + return _localArray[index]; + } + set + { + lock (modbusServer._stateLock) + _localArray[index] = value; + } + } + } + + public class CoilCollection(ModbusServer modbusServer) + { + internal readonly bool[] _localArray = new bool[65537]; + public bool this[int index] + { + get + { + lock (modbusServer._stateLock) + return _localArray[index]; + } + set + { + lock (modbusServer._stateLock) + _localArray[index] = value; + } + } + } + + public class DiscreteInputCollection(ModbusServer modbusServer) + { + internal readonly bool[] _localArray = new bool[65537]; + public bool this[int index] + { + get + { + lock (modbusServer._stateLock) + return _localArray[index]; + } + set + { + lock (modbusServer._stateLock) + _localArray[index] = value; + } + } + } +} diff --git a/EasyModbus/ModbusServer.cs b/EasyModbus/ModbusServer.cs index 13374cd..a5572db 100644 --- a/EasyModbus/ModbusServer.cs +++ b/EasyModbus/ModbusServer.cs @@ -1,2266 +1,375 @@ -/* -Copyright (c) 2018-2020 Rossmann-Engineering -Permission is hereby granted, free of charge, -to any person obtaining a copy of this software -and associated documentation files (the "Software"), -to deal in the Software without restriction, -including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, -and/or sell copies of the Software, and to permit -persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission -notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, -ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE -OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ - -using System; -using System.Collections.Generic; -using System.Text; -using System.Net.Sockets; -using System.Net; -using System.Threading; -using System.Net.NetworkInformation; +using System.Collections.Concurrent; +using System.Diagnostics; using System.IO.Ports; +using System.Net; +using System.Net.Sockets; + +namespace EasyModbus; -namespace EasyModbus +/// A disposable Modbus server with one-based local register tables. +public partial class ModbusServer : IDisposable, IAsyncDisposable { -#region class ModbusProtocol - /// - /// Modbus Protocol informations. - /// - public class ModbusProtocol + private readonly Lock _lifecycleLock = new(); + private readonly Lock _stateLock = new(); + private readonly AsyncLocal _processingRequest = new(); + private Session? _session; + private bool _disposed; + private int _numberOfConnections; + private readonly ModbusProtocol?[] _modbusLogData = new ModbusProtocol?[100]; + + public HoldingRegisterCollection HoldingRegisters; + public InputRegisterCollection InputRegisters; + public CoilCollection Coils; + public DiscreteInputCollection DiscreteInputs; + + public ModbusServer() { - public enum ProtocolType { ModbusTCP = 0, ModbusUDP = 1, ModbusRTU = 2}; - public DateTime timeStamp; - public bool request; - public bool response; - public UInt16 transactionIdentifier; - public UInt16 protocolIdentifier; - public UInt16 length; - public byte unitIdentifier; - public byte functionCode; - public UInt16 startingAdress; - public UInt16 startingAddressRead; - public UInt16 startingAddressWrite; - public UInt16 quantity; - public UInt16 quantityRead; - public UInt16 quantityWrite; - public byte byteCount; - public byte exceptionCode; - public byte errorCode; - public UInt16[] receiveCoilValues; - public UInt16[] receiveRegisterValues; - public Int16[] sendRegisterValues; - public bool[] sendCoilValues; - public UInt16 crc; + HoldingRegisters = new(this); + InputRegisters = new(this); + Coils = new(this); + DiscreteInputs = new(this); } -#endregion -#region structs - struct NetworkConnectionParameter - { - public NetworkStream stream; //For TCP-Connection only - public Byte[] bytes; - public int portIn; //For UDP-Connection only - public IPAddress ipAddressIn; //For UDP-Connection only + public delegate void CoilsChangedHandler(int coil, int numberOfCoils); + public delegate void HoldingRegistersChangedHandler(int register, int numberOfRegisters); + public delegate void NumberOfConnectedClientsChangedHandler(); + public delegate void LogDataChangedHandler(); + public event CoilsChangedHandler? CoilsChanged; + public event HoldingRegistersChangedHandler? HoldingRegistersChanged; + public event NumberOfConnectedClientsChangedHandler? NumberOfConnectedClientsChanged; + public event LogDataChangedHandler? LogDataChanged; + + public bool FunctionCode1Disabled { get; set; } + public bool FunctionCode2Disabled { get; set; } + public bool FunctionCode3Disabled { get; set; } + public bool FunctionCode4Disabled { get; set; } + public bool FunctionCode5Disabled { get; set; } + public bool FunctionCode6Disabled { get; set; } + public bool FunctionCode15Disabled { get; set; } + public bool FunctionCode16Disabled { get; set; } + public bool FunctionCode23Disabled { get; set; } + public bool PortChanged { get; set; } + public IPAddress LocalIPAddress { get; set; } = IPAddress.Any; + public int Port { get; set; } = 502; + public bool UDPFlag { get; set; } + public bool SerialFlag { get; set; } + public int Baudrate { get; set; } = 9600; + public Parity Parity { get; set; } = Parity.Even; + public StopBits StopBits { get; set; } = StopBits.One; + public byte UnitIdentifier { get; set; } = 1; + public string? SerialPort { + get; + set + { + field = value; + SerialFlag = value is not null; + } + } = "COM1"; + public string? LogFileFilename { + get => StoreLogData.Instance.Filename; + set => StoreLogData.Instance.Filename = value; } -#endregion - -#region TCPHandler class - internal class TCPHandler + public int NumberOfConnections => Volatile.Read(ref _numberOfConnections); + public bool IsListening { - public delegate void DataChanged(object networkConnectionParameter); - public event DataChanged dataChanged; - - public delegate void NumberOfClientsChanged(); - public event NumberOfClientsChanged numberOfClientsChanged; - - TcpListener server = null; - - - private List tcpClientLastRequestList = new List(); - - public int NumberOfConnectedClients { get; set; } - - public string ipAddress = null; - - /// When making a server TCP listen socket, will listen to this IP address. - public IPAddress LocalIPAddress { - get { return localIPAddress; } - } - private IPAddress localIPAddress = IPAddress.Any; - - /// - /// Listen to all network interfaces. - /// - /// TCP port to listen - public TCPHandler(int port) + get { - server = new TcpListener(LocalIPAddress, port); - server.Start(); - server.BeginAcceptTcpClient(AcceptTcpClientCallback, null); + lock (_lifecycleLock) + return _session is not null; } - - /// - /// Listen to a specific network interface. - /// - /// IP address of network interface to listen - /// TCP port to listen - public TCPHandler(IPAddress localIPAddress, int port) + } + public ModbusProtocol?[] ModbusLogData + { + get { - this.localIPAddress = localIPAddress; - server = new TcpListener(LocalIPAddress, port); - server.Start(); - server.BeginAcceptTcpClient(AcceptTcpClientCallback, null); + lock (_stateLock) + return (ModbusProtocol?[])_modbusLogData.Clone(); } + } - - private void AcceptTcpClientCallback(IAsyncResult asyncResult) - { - TcpClient tcpClient = new TcpClient(); + /// Binds before returning, so startup failures are reported to the caller. + public void Listen() + { + lock (_lifecycleLock) + { + ObjectDisposedException.ThrowIf(_disposed, this); + if (_session is not null) + throw new InvalidOperationException("The Modbus server is already listening."); + ArgumentNullException.ThrowIfNull(LocalIPAddress); + ArgumentOutOfRangeException.ThrowIfNegative(Port); + ArgumentOutOfRangeException.ThrowIfGreaterThan(Port, 65535); + var session = new Session(); try { - tcpClient = server.EndAcceptTcpClient(asyncResult); - tcpClient.ReceiveTimeout = 4000; - if (ipAddress != null) + if (SerialFlag) { - string ipEndpoint = tcpClient.Client.RemoteEndPoint.ToString(); - ipEndpoint = ipEndpoint.Split(':')[0]; - if (ipEndpoint != ipAddress) + session.Serial = new SerialPort(SerialPort ?? throw new InvalidOperationException("A serial port is required."), Baudrate, Parity, 8, StopBits) { - tcpClient.Client.Disconnect(false); - return; - } + ReadTimeout = 1000, + WriteTimeout = 1000 + }; + session.SerialHandler = (_, _) => ReceiveSerial(session); + session.Serial.DataReceived += session.SerialHandler; + session.Serial.Open(); } - } - catch (Exception) { } - try - { - server.BeginAcceptTcpClient(AcceptTcpClientCallback, null); - Client client = new Client(tcpClient); - NetworkStream networkStream = client.NetworkStream; - networkStream.ReadTimeout = 4000; - networkStream.BeginRead(client.Buffer, 0, client.Buffer.Length, ReadCallback, client); - } - catch (Exception) { } - } - - private int GetAndCleanNumberOfConnectedClients(Client client) - { - lock (this) - { - int i = 0; - bool objetExists = false; - foreach (Client clientLoop in tcpClientLastRequestList) + else if (UDPFlag) { - if (client.Equals(clientLoop)) - objetExists = true; + session.Udp = new UdpClient(new IPEndPoint(LocalIPAddress, Port)); + Port = ((IPEndPoint)session.Udp.Client.LocalEndPoint!).Port; } - try + else { - tcpClientLastRequestList.RemoveAll(delegate (Client c) - { - return ((DateTime.Now.Ticks - c.Ticks) > 40000000); - } - - ); + session.Listener = new TcpListener(LocalIPAddress, Port); + session.Listener.Start(); + Port = ((IPEndPoint)session.Listener.LocalEndpoint).Port; } - catch (Exception) { } - if (!objetExists) - tcpClientLastRequestList.Add(client); - - - return tcpClientLastRequestList.Count; + _session = session; + session.Worker = session.Udp is not null ? ReceiveUdpAsync(session) : + session.Listener is not null ? AcceptClientsAsync(session) : Task.CompletedTask; + PortChanged = false; } - } - - private void ReadCallback(IAsyncResult asyncResult) - { - NetworkConnectionParameter networkConnectionParameter = new NetworkConnectionParameter(); - Client client = asyncResult.AsyncState as Client; - client.Ticks = DateTime.Now.Ticks; - NumberOfConnectedClients = GetAndCleanNumberOfConnectedClients(client); - if (numberOfClientsChanged != null) - numberOfClientsChanged(); - if (client != null) + catch { - int read; - NetworkStream networkStream = null; - try - { - networkStream = client.NetworkStream; - - read = networkStream.EndRead(asyncResult); - } - catch (Exception ex) - { - return; - } - - - if (read == 0) - { - //OnClientDisconnected(client.TcpClient); - //connectedClients.Remove(client); - return; - } - byte[] data = new byte[read]; - Buffer.BlockCopy(client.Buffer, 0, data, 0, read); - networkConnectionParameter.bytes = data; - networkConnectionParameter.stream = networkStream; - if (dataChanged != null) - dataChanged(networkConnectionParameter); - try - { - networkStream.BeginRead(client.Buffer, 0, client.Buffer.Length, ReadCallback, client); - } - catch (Exception) - { - } + session.RequestStop(); + session.Cancellation.Dispose(); + throw; } } + } + + public void StopListening() => StopListeningAsync().GetAwaiter().GetResult(); - public void Disconnect() + public Task StopListeningAsync(CancellationToken cancellationToken = default) + { + Session? session; + lock (_lifecycleLock) { - try - { - foreach (Client clientLoop in tcpClientLastRequestList) - { - clientLoop.NetworkStream.Close(00); - } - } - catch (Exception) { } - server.Stop(); - + session = _session; + _session = null; } + if (session is null) + return Task.CompletedTask; + session.RequestStop(); + var stopped = FinishStopAsync(session); + // A synchronous event handler may stop its own server. The transports + // are already closed; let that request unwind before joining its task. + return _processingRequest.Value ? Task.CompletedTask : stopped.WaitAsync(cancellationToken); + } - internal class Client + private static async Task FinishStopAsync(Session session) + { + try { - private readonly TcpClient tcpClient; - private readonly byte[] buffer; - public long Ticks { get; set; } - - public Client(TcpClient tcpClient) - { - this.tcpClient = tcpClient; - int bufferSize = tcpClient.ReceiveBufferSize; - buffer = new byte[bufferSize]; - } - - public TcpClient TcpClient + try { - get { return tcpClient; } + await session.Worker.ConfigureAwait(false); } - - public byte[] Buffer + finally { - get { return buffer; } + await Task.WhenAll(session.Clients.Values.Select(connection => connection.Worker)).ConfigureAwait(false); } + } + catch (Exception exception) { Trace.TraceError($"Modbus server stopped after an error: {exception}"); } + finally { session.Cancellation.Dispose(); } + } - public NetworkStream NetworkStream + private async Task AcceptClientsAsync(Session session) + { + try + { + while (!session.Cancellation.IsCancellationRequested) { - get { - - return tcpClient.GetStream(); - - } + var client = await session.Listener!.AcceptTcpClientAsync(session.Cancellation.Token).ConfigureAwait(false); + client.NoDelay = true; + var connection = new ClientConnection(client); + session.Clients.TryAdd(client, connection); + connection.Worker = HandleClientAsync(session, connection); } } + catch (Exception exception) when (session.Cancellation.IsCancellationRequested && exception is OperationCanceledException or SocketException or ObjectDisposedException) { } + catch (Exception exception) { Trace.TraceError($"Modbus accept failed: {exception}"); } } -#endregion - - /// - /// Modbus TCP Server. - /// - public class ModbusServer - { - private bool debug = false; - Int32 port = 502; - ModbusProtocol receiveData; - ModbusProtocol sendData = new ModbusProtocol(); - Byte[] bytes = new Byte[2100]; - //public Int16[] _holdingRegisters = new Int16[65535]; - public HoldingRegisters holdingRegisters; - public InputRegisters inputRegisters; - public Coils coils; - public DiscreteInputs discreteInputs; - private int numberOfConnections = 0; - private bool udpFlag; - private bool serialFlag; - private int baudrate = 9600; - private System.IO.Ports.Parity parity = Parity.Even; - private System.IO.Ports.StopBits stopBits = StopBits.One; - private string serialPort = "COM1"; - private SerialPort serialport; - private byte unitIdentifier = 1; - private int portIn; - private IPAddress ipAddressIn; - private UdpClient udpClient; - private IPEndPoint iPEndPoint; - private TCPHandler tcpHandler; - Thread listenerThread; - Thread clientConnectionThread; - private ModbusProtocol[] modbusLogData = new ModbusProtocol[100]; - public bool FunctionCode1Disabled {get; set;} - public bool FunctionCode2Disabled { get; set; } - public bool FunctionCode3Disabled { get; set; } - public bool FunctionCode4Disabled { get; set; } - public bool FunctionCode5Disabled { get; set; } - public bool FunctionCode6Disabled { get; set; } - public bool FunctionCode15Disabled { get; set; } - public bool FunctionCode16Disabled { get; set; } - public bool FunctionCode23Disabled { get; set; } - public bool PortChanged { get; set; } - object lockCoils = new object(); - object lockHoldingRegisters = new object(); - private volatile bool shouldStop; - - private IPAddress localIPAddress = IPAddress.Any; - /// - /// When creating a TCP or UDP socket, the local IP address to attach to. - /// - public IPAddress LocalIPAddress + private async Task HandleClientAsync(Session session, ClientConnection connection) + { + Interlocked.Increment(ref _numberOfConnections); + try { - get { return localIPAddress; } - set { if (listenerThread == null) localIPAddress = value; } + NotifyConnectedClientsChanged(); + var stream = connection.Client.GetStream(); + while (!session.Cancellation.IsCancellationRequested) + { + var request = await ModbusFrame.ReadAsync(stream, session.Cancellation.Token).ConfigureAwait(false); + var response = ProcessRequest(request); + if (response is not null) + await stream.WriteAsync(response, session.Cancellation.Token).ConfigureAwait(false); + } } - - public ModbusServer() + catch (Exception exception) when (exception is EndOfStreamException or IOException or SocketException or OperationCanceledException or ObjectDisposedException or InvalidDataException) { - holdingRegisters = new HoldingRegisters(this); - inputRegisters = new InputRegisters(this); - coils = new Coils(this); - discreteInputs = new DiscreteInputs(this); - + if (!session.Cancellation.IsCancellationRequested && exception is not EndOfStreamException) + Trace.TraceWarning($"Modbus client disconnected: {exception.Message}"); } - - #region events - public delegate void CoilsChangedHandler(int coil, int numberOfCoils); - public event CoilsChangedHandler CoilsChanged; - - public delegate void HoldingRegistersChangedHandler(int register, int numberOfRegisters); - public event HoldingRegistersChangedHandler HoldingRegistersChanged; - - public delegate void NumberOfConnectedClientsChangedHandler(); - public event NumberOfConnectedClientsChangedHandler NumberOfConnectedClientsChanged; - - public delegate void LogDataChangedHandler(); - public event LogDataChangedHandler LogDataChanged; - #endregion - - public void Listen() + catch (Exception exception) { - - listenerThread = new Thread(ListenerThread); - listenerThread.Start(); + Trace.TraceError($"Modbus client failed: {exception}"); } - - public void StopListening() + finally { - if (SerialFlag & (serialport != null)) - { - if (serialport.IsOpen) - serialport.Close(); - shouldStop = true; - } + connection.Client.Dispose(); + session.Clients.TryRemove(connection.Client, out _); + Interlocked.Decrement(ref _numberOfConnections); try { - tcpHandler.Disconnect(); - listenerThread.Abort(); - + NotifyConnectedClientsChanged(); } - catch (Exception) { } - listenerThread.Join(); - try + catch (Exception exception) { - - clientConnectionThread.Abort(); + Trace.TraceError($"Modbus client notification failed: {exception}"); } - catch (Exception) { } } - - private void ListenerThread() - { - if (!udpFlag & !serialFlag) - { - if (udpClient != null) - { - try - { - udpClient.Close(); - } - catch (Exception) { } - } - tcpHandler = new TCPHandler(LocalIPAddress, port); - if (debug) StoreLogData.Instance.Store($"EasyModbus Server listing for incomming data at Port {port}, local IP {LocalIPAddress}", System.DateTime.Now); - tcpHandler.dataChanged += new TCPHandler.DataChanged(ProcessReceivedData); - tcpHandler.numberOfClientsChanged += new TCPHandler.NumberOfClientsChanged(numberOfClientsChanged); - } - else if (serialFlag) - { - if (serialport == null) - { - if (debug) StoreLogData.Instance.Store("EasyModbus RTU-Server listing for incomming data at Serial Port " + serialPort, System.DateTime.Now); - serialport = new SerialPort(); - serialport.PortName = serialPort; - serialport.BaudRate = this.baudrate; - serialport.Parity = this.parity; - serialport.StopBits = stopBits; - serialport.WriteTimeout = 10000; - serialport.ReadTimeout = 1000; - serialport.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler); - serialport.Open(); - } - } - else - while (!shouldStop) - { - if (udpFlag) - { - if (udpClient == null | PortChanged) - { - IPEndPoint localEndoint = new IPEndPoint(LocalIPAddress, port); - udpClient = new UdpClient(localEndoint); - if (debug) StoreLogData.Instance.Store($"EasyModbus Server listing for incomming data at Port {port}, local IP {LocalIPAddress}", System.DateTime.Now); - udpClient.Client.ReceiveTimeout = 1000; - iPEndPoint = new IPEndPoint(IPAddress.Any, port); - PortChanged = false; - } - if (tcpHandler != null) - tcpHandler.Disconnect(); - try - { - bytes = udpClient.Receive(ref iPEndPoint); - portIn = iPEndPoint.Port; - NetworkConnectionParameter networkConnectionParameter = new NetworkConnectionParameter(); - networkConnectionParameter.bytes = bytes; - ipAddressIn = iPEndPoint.Address; - networkConnectionParameter.portIn = portIn; - networkConnectionParameter.ipAddressIn = ipAddressIn; - ParameterizedThreadStart pts = new ParameterizedThreadStart(this.ProcessReceivedData); - Thread processDataThread = new Thread(pts); - processDataThread.Start(networkConnectionParameter); - } - catch (Exception) - { - } - } + } - } - } - - #region SerialHandler - private bool dataReceived = false; - private byte[] readBuffer = new byte[2094]; - private DateTime lastReceive; - private int nextSign = 0; - private void DataReceivedHandler(object sender, - SerialDataReceivedEventArgs e) + private void NotifyConnectedClientsChanged() + { + var previous = _processingRequest.Value; + _processingRequest.Value = true; + try { - int silence = 4000 / baudrate; - if ((DateTime.Now.Ticks - lastReceive.Ticks) > TimeSpan.TicksPerMillisecond*silence) - nextSign = 0; - - - SerialPort sp = (SerialPort)sender; - - int numbytes = sp.BytesToRead; - byte[] rxbytearray = new byte[numbytes]; - - sp.Read(rxbytearray, 0, numbytes); - - Array.Copy(rxbytearray, 0, readBuffer, nextSign, rxbytearray.Length); - lastReceive= DateTime.Now; - nextSign = numbytes+ nextSign; - if (ModbusClient.DetectValidModbusFrame(readBuffer, nextSign)) - { - - dataReceived = true; - nextSign= 0; - - NetworkConnectionParameter networkConnectionParameter = new NetworkConnectionParameter(); - networkConnectionParameter.bytes = readBuffer; - ParameterizedThreadStart pts = new ParameterizedThreadStart(this.ProcessReceivedData); - Thread processDataThread = new Thread(pts); - processDataThread.Start(networkConnectionParameter); - dataReceived = false; - - } - else - dataReceived = false; + NumberOfConnectedClientsChanged?.Invoke(); } - #endregion - - #region Method numberOfClientsChanged - private void numberOfClientsChanged() + finally { - numberOfConnections = tcpHandler.NumberOfConnectedClients; - if (NumberOfConnectedClientsChanged != null) - NumberOfConnectedClientsChanged(); + _processingRequest.Value = previous; } - #endregion + } - object lockProcessReceivedData = new object(); - #region Method ProcessReceivedData - private void ProcessReceivedData(object networkConnectionParameter) + private async Task ReceiveUdpAsync(Session session) + { + try { - lock (lockProcessReceivedData) + while (!session.Cancellation.IsCancellationRequested) { - Byte[] bytes = new byte[((NetworkConnectionParameter)networkConnectionParameter).bytes.Length]; - if (debug) StoreLogData.Instance.Store("Received Data: " + BitConverter.ToString(bytes), System.DateTime.Now); - NetworkStream stream = ((NetworkConnectionParameter)networkConnectionParameter).stream; - int portIn = ((NetworkConnectionParameter)networkConnectionParameter).portIn; - IPAddress ipAddressIn = ((NetworkConnectionParameter)networkConnectionParameter).ipAddressIn; - - - Array.Copy(((NetworkConnectionParameter)networkConnectionParameter).bytes, 0, bytes, 0, ((NetworkConnectionParameter)networkConnectionParameter).bytes.Length); - - ModbusProtocol receiveDataThread = new ModbusProtocol(); - ModbusProtocol sendDataThread = new ModbusProtocol(); - + var datagram = await session.Udp!.ReceiveAsync(session.Cancellation.Token).ConfigureAwait(false); try { - UInt16[] wordData = new UInt16[1]; - byte[] byteData = new byte[2]; - receiveDataThread.timeStamp = DateTime.Now; - receiveDataThread.request = true; - if (!serialFlag) - { - //Lese Transaction identifier - byteData[1] = bytes[0]; - byteData[0] = bytes[1]; - Buffer.BlockCopy(byteData, 0, wordData, 0, 2); - receiveDataThread.transactionIdentifier = wordData[0]; - - //Lese Protocol identifier - byteData[1] = bytes[2]; - byteData[0] = bytes[3]; - Buffer.BlockCopy(byteData, 0, wordData, 0, 2); - receiveDataThread.protocolIdentifier = wordData[0]; - - //Lese length - byteData[1] = bytes[4]; - byteData[0] = bytes[5]; - Buffer.BlockCopy(byteData, 0, wordData, 0, 2); - receiveDataThread.length = wordData[0]; - } - - //Lese unit identifier - receiveDataThread.unitIdentifier = bytes[6 - 6 * Convert.ToInt32(serialFlag)]; - //Check UnitIdentifier - if ((receiveDataThread.unitIdentifier != this.unitIdentifier) & (receiveDataThread.unitIdentifier != 0)) - return; - - // Lese function code - receiveDataThread.functionCode = bytes[7 - 6 * Convert.ToInt32(serialFlag)]; - - // Lese starting address - byteData[1] = bytes[8 - 6 * Convert.ToInt32(serialFlag)]; - byteData[0] = bytes[9 - 6 * Convert.ToInt32(serialFlag)]; - Buffer.BlockCopy(byteData, 0, wordData, 0, 2); - receiveDataThread.startingAdress = wordData[0]; - - if (receiveDataThread.functionCode <= 4) - { - // Lese quantity - byteData[1] = bytes[10 - 6 * Convert.ToInt32(serialFlag)]; - byteData[0] = bytes[11 - 6 * Convert.ToInt32(serialFlag)]; - Buffer.BlockCopy(byteData, 0, wordData, 0, 2); - receiveDataThread.quantity = wordData[0]; - } - if (receiveDataThread.functionCode == 5) - { - receiveDataThread.receiveCoilValues = new ushort[1]; - // Lese Value - byteData[1] = bytes[10 - 6 * Convert.ToInt32(serialFlag)]; - byteData[0] = bytes[11 - 6 * Convert.ToInt32(serialFlag)]; - Buffer.BlockCopy(byteData, 0, receiveDataThread.receiveCoilValues, 0, 2); - } - if (receiveDataThread.functionCode == 6) - { - receiveDataThread.receiveRegisterValues = new ushort[1]; - // Lese Value - byteData[1] = bytes[10 - 6 * Convert.ToInt32(serialFlag)]; - byteData[0] = bytes[11 - 6 * Convert.ToInt32(serialFlag)]; - Buffer.BlockCopy(byteData, 0, receiveDataThread.receiveRegisterValues, 0, 2); - } - if (receiveDataThread.functionCode == 15) - { - // Lese quantity - byteData[1] = bytes[10 - 6 * Convert.ToInt32(serialFlag)]; - byteData[0] = bytes[11 - 6 * Convert.ToInt32(serialFlag)]; - Buffer.BlockCopy(byteData, 0, wordData, 0, 2); - receiveDataThread.quantity = wordData[0]; - - receiveDataThread.byteCount = bytes[12 - 6 * Convert.ToInt32(serialFlag)]; - - if ((receiveDataThread.byteCount % 2) != 0) - receiveDataThread.receiveCoilValues = new ushort[receiveDataThread.byteCount / 2 + 1]; - else - receiveDataThread.receiveCoilValues = new ushort[receiveDataThread.byteCount / 2]; - // Lese Value - Buffer.BlockCopy(bytes, 13 - 6 * Convert.ToInt32(serialFlag), receiveDataThread.receiveCoilValues, 0, receiveDataThread.byteCount); - } - if (receiveDataThread.functionCode == 16) - { - // Lese quantity - byteData[1] = bytes[10 - 6 * Convert.ToInt32(serialFlag)]; - byteData[0] = bytes[11 - 6 * Convert.ToInt32(serialFlag)]; - Buffer.BlockCopy(byteData, 0, wordData, 0, 2); - receiveDataThread.quantity = wordData[0]; - - receiveDataThread.byteCount = bytes[12 - 6 * Convert.ToInt32(serialFlag)]; - receiveDataThread.receiveRegisterValues = new ushort[receiveDataThread.quantity]; - for (int i = 0; i < receiveDataThread.quantity; i++) - { - // Lese Value - byteData[1] = bytes[13 + i * 2 - 6 * Convert.ToInt32(serialFlag)]; - byteData[0] = bytes[14 + i * 2 - 6 * Convert.ToInt32(serialFlag)]; - Buffer.BlockCopy(byteData, 0, receiveDataThread.receiveRegisterValues, i * 2, 2); - } - - } - if (receiveDataThread.functionCode == 23) - { - // Lese starting Address Read - byteData[1] = bytes[8 - 6 * Convert.ToInt32(serialFlag)]; - byteData[0] = bytes[9 - 6 * Convert.ToInt32(serialFlag)]; - Buffer.BlockCopy(byteData, 0, wordData, 0, 2); - receiveDataThread.startingAddressRead = wordData[0]; - // Lese quantity Read - byteData[1] = bytes[10 - 6 * Convert.ToInt32(serialFlag)]; - byteData[0] = bytes[11 - 6 * Convert.ToInt32(serialFlag)]; - Buffer.BlockCopy(byteData, 0, wordData, 0, 2); - receiveDataThread.quantityRead = wordData[0]; - // Lese starting Address Write - byteData[1] = bytes[12 - 6 * Convert.ToInt32(serialFlag)]; - byteData[0] = bytes[13 - 6 * Convert.ToInt32(serialFlag)]; - Buffer.BlockCopy(byteData, 0, wordData, 0, 2); - receiveDataThread.startingAddressWrite = wordData[0]; - // Lese quantity Write - byteData[1] = bytes[14 - 6 * Convert.ToInt32(serialFlag)]; - byteData[0] = bytes[15 - 6 * Convert.ToInt32(serialFlag)]; - Buffer.BlockCopy(byteData, 0, wordData, 0, 2); - receiveDataThread.quantityWrite = wordData[0]; - - receiveDataThread.byteCount = bytes[16 - 6 * Convert.ToInt32(serialFlag)]; - receiveDataThread.receiveRegisterValues = new ushort[receiveDataThread.quantityWrite]; - for (int i = 0; i < receiveDataThread.quantityWrite; i++) - { - // Lese Value - byteData[1] = bytes[17 + i * 2 - 6 * Convert.ToInt32(serialFlag)]; - byteData[0] = bytes[18 + i * 2 - 6 * Convert.ToInt32(serialFlag)]; - Buffer.BlockCopy(byteData, 0, receiveDataThread.receiveRegisterValues, i * 2, 2); - } - } + ModbusFrame.Validate(datagram.Buffer); + var response = ProcessRequest(datagram.Buffer); + if (response is not null) + await session.Udp.SendAsync(response, datagram.RemoteEndPoint, session.Cancellation.Token).ConfigureAwait(false); + } + catch (InvalidDataException exception) + { + Trace.TraceWarning($"Ignored invalid Modbus UDP frame: {exception.Message}"); + } + catch (Exception exception) when (!session.Cancellation.IsCancellationRequested && exception is not OperationCanceledException) + { + Trace.TraceError($"Modbus UDP request failed: {exception}"); } - catch (Exception exc) - { } - this.CreateAnswer(receiveDataThread, sendDataThread, stream, portIn, ipAddressIn); - //this.sendAnswer(); - this.CreateLogData(receiveDataThread, sendDataThread); - - if (LogDataChanged != null) - LogDataChanged(); } } - #endregion - - #region Method CreateAnswer - private void CreateAnswer(ModbusProtocol receiveData, ModbusProtocol sendData, NetworkStream stream, int portIn, IPAddress ipAddressIn) - { - - switch (receiveData.functionCode) - { - // Read Coils - case 1: - if (!FunctionCode1Disabled) - this.ReadCoils(receiveData, sendData, stream, portIn, ipAddressIn); - else - { - sendData.errorCode = (byte)(receiveData.functionCode + 0x80); - sendData.exceptionCode = 1; - sendException(sendData.errorCode, sendData.exceptionCode, receiveData, sendData, stream, portIn, ipAddressIn); - } - break; - // Read Input Registers - case 2: - if (!FunctionCode2Disabled) - this.ReadDiscreteInputs(receiveData, sendData, stream, portIn, ipAddressIn); - else - { - sendData.errorCode = (byte)(receiveData.functionCode + 0x80); - sendData.exceptionCode = 1; - sendException(sendData.errorCode, sendData.exceptionCode, receiveData, sendData, stream, portIn, ipAddressIn); - } - - break; - // Read Holding Registers - case 3: - if (!FunctionCode3Disabled) - this.ReadHoldingRegisters(receiveData, sendData, stream, portIn, ipAddressIn); - else - { - sendData.errorCode = (byte)(receiveData.functionCode + 0x80); - sendData.exceptionCode = 1; - sendException(sendData.errorCode, sendData.exceptionCode, receiveData, sendData, stream, portIn, ipAddressIn); - } - - break; - // Read Input Registers - case 4: - if (!FunctionCode4Disabled) - this.ReadInputRegisters(receiveData, sendData, stream, portIn, ipAddressIn); - else - { - sendData.errorCode = (byte)(receiveData.functionCode + 0x80); - sendData.exceptionCode = 1; - sendException(sendData.errorCode, sendData.exceptionCode, receiveData, sendData, stream, portIn, ipAddressIn); - } - - break; - // Write single coil - case 5: - if (!FunctionCode5Disabled) - this.WriteSingleCoil(receiveData, sendData, stream, portIn, ipAddressIn); - else - { - sendData.errorCode = (byte)(receiveData.functionCode + 0x80); - sendData.exceptionCode = 1; - sendException(sendData.errorCode, sendData.exceptionCode, receiveData, sendData, stream, portIn, ipAddressIn); - } - - break; - // Write single register - case 6: - if (!FunctionCode6Disabled) - this.WriteSingleRegister(receiveData, sendData, stream, portIn, ipAddressIn); - else - { - sendData.errorCode = (byte)(receiveData.functionCode + 0x80); - sendData.exceptionCode = 1; - sendException(sendData.errorCode, sendData.exceptionCode, receiveData, sendData, stream, portIn, ipAddressIn); - } - - break; - // Write Multiple coils - case 15: - if (!FunctionCode15Disabled) - this.WriteMultipleCoils(receiveData, sendData, stream, portIn, ipAddressIn); - else - { - sendData.errorCode = (byte)(receiveData.functionCode + 0x80); - sendData.exceptionCode = 1; - sendException(sendData.errorCode, sendData.exceptionCode, receiveData, sendData, stream, portIn, ipAddressIn); - } - - break; - // Write Multiple registers - case 16: - if (!FunctionCode16Disabled) - this.WriteMultipleRegisters(receiveData, sendData, stream, portIn, ipAddressIn); - else - { - sendData.errorCode = (byte)(receiveData.functionCode + 0x80); - sendData.exceptionCode = 1; - sendException(sendData.errorCode, sendData.exceptionCode, receiveData, sendData, stream, portIn, ipAddressIn); - } - - break; - // Error: Function Code not supported - case 23: - if (!FunctionCode23Disabled) - this.ReadWriteMultipleRegisters(receiveData, sendData, stream, portIn, ipAddressIn); - else - { - sendData.errorCode = (byte)(receiveData.functionCode + 0x80); - sendData.exceptionCode = 1; - sendException(sendData.errorCode, sendData.exceptionCode, receiveData, sendData, stream, portIn, ipAddressIn); - } + catch (Exception exception) when (session.Cancellation.IsCancellationRequested && exception is OperationCanceledException or SocketException or ObjectDisposedException) { } + catch (Exception exception) { Trace.TraceError($"Modbus UDP receive failed: {exception}"); } + } - break; - // Error: Function Code not supported - default: sendData.errorCode = (byte) (receiveData.functionCode + 0x80); - sendData.exceptionCode = 1; - sendException(sendData.errorCode, sendData.exceptionCode, receiveData, sendData, stream, portIn, ipAddressIn); - break; - } - sendData.timeStamp = DateTime.Now; - } - #endregion - - private void ReadCoils(ModbusProtocol receiveData, ModbusProtocol sendData, NetworkStream stream, int portIn, IPAddress ipAddressIn) + private void ReceiveSerial(Session session) + { + lock (session.SerialLock) { - sendData.response = true; - - sendData.transactionIdentifier = receiveData.transactionIdentifier; - sendData.protocolIdentifier = receiveData.protocolIdentifier; - - sendData.unitIdentifier = this.unitIdentifier; - sendData.functionCode = receiveData.functionCode; - if ((receiveData.quantity < 1) | (receiveData.quantity > 0x07D0)) //Invalid quantity - { - sendData.errorCode = (byte)(receiveData.functionCode + 0x80); - sendData.exceptionCode = 3; - } - if (((receiveData.startingAdress + 1 + receiveData.quantity) > 65535) | (receiveData.startingAdress < 0)) //Invalid Starting adress or Starting address + quantity - { - sendData.errorCode = (byte)(receiveData.functionCode + 0x80); - sendData.exceptionCode = 2; - } - if (sendData.exceptionCode == 0) - { - if ((receiveData.quantity % 8) == 0) - sendData.byteCount = (byte)(receiveData.quantity / 8); - else - sendData.byteCount = (byte)(receiveData.quantity / 8 + 1); - - sendData.sendCoilValues = new bool[receiveData.quantity]; - lock (lockCoils) - Array.Copy(coils.localArray, receiveData.startingAdress + 1, sendData.sendCoilValues, 0, receiveData.quantity); - } - if (true) + var serial = session.Serial!; + try { - Byte[] data; - - if (sendData.exceptionCode > 0) - data = new byte[9 + 2*Convert.ToInt32(serialFlag)]; - else - data = new byte[9 + sendData.byteCount+ 2*Convert.ToInt32(serialFlag)]; - - Byte[] byteData = new byte[2]; - - sendData.length = (byte)(data.Length - 6); - - //Send Transaction identifier - byteData = BitConverter.GetBytes((int)sendData.transactionIdentifier); - data[0] = byteData[1]; - data[1] = byteData[0]; - - //Send Protocol identifier - byteData = BitConverter.GetBytes((int)sendData.protocolIdentifier); - data[2] = byteData[1]; - data[3] = byteData[0]; - - //Send length - byteData = BitConverter.GetBytes((int)sendData.length); - data[4] = byteData[1]; - data[5] = byteData[0]; - //Unit Identifier - data[6] = sendData.unitIdentifier; - - //Function Code - data[7] = sendData.functionCode; - - //ByteCount - data[8] = sendData.byteCount; - - if (sendData.exceptionCode > 0) + while (serial.IsOpen && serial.BytesToRead > 0) { - data[7] = sendData.errorCode; - data[8] = sendData.exceptionCode; - sendData.sendCoilValues = null; - } - - if (sendData.sendCoilValues != null) - for (int i = 0; i < (sendData.byteCount); i++) - { - byteData = new byte[2]; - for (int j = 0; j < 8; j++) - { + session.SerialBuffer.Add((byte)serial.ReadByte()); + if (session.SerialBuffer.Count < 8) + continue; - byte boolValue; - if (sendData.sendCoilValues[i * 8 + j] == true) - boolValue = 1; - else - boolValue = 0; - byteData[1] = (byte)((byteData[1]) | (boolValue << j)); - if ((i * 8 + j + 1) >= sendData.sendCoilValues.Length) - break; - } - data[9 + i] = byteData[1]; - } - try - { - if (serialFlag) + var bytes = session.SerialBuffer; + var length = bytes[1] is 15 or 16 ? 9 + bytes[6] : bytes[1] == 23 ? bytes.Count < 11 ? 11 : 13 + bytes[10] : 8; + if (length > 256) { - if (!serialport.IsOpen) - throw new EasyModbus.Exceptions.SerialPortNotOpenedException("serial port not opened"); - //Create CRC - sendData.crc = ModbusClient.calculateCRC(data, Convert.ToUInt16(data.Length - 8), 6); - byteData = BitConverter.GetBytes((int)sendData.crc); - data[data.Length - 2] = byteData[0]; - data[data.Length - 1] = byteData[1]; - serialport.Write(data, 6, data.Length - 6); - if (debug) - { - byte[] debugData = new byte[data.Length - 6]; - Array.Copy(data, 6, debugData, 0, data.Length - 6); - if (debug) StoreLogData.Instance.Store("Send Serial-Data: " + BitConverter.ToString(debugData), System.DateTime.Now); - } + bytes.Clear(); + continue; } - else if (udpFlag) - { - //UdpClient udpClient = new UdpClient(); - IPEndPoint endPoint = new IPEndPoint(ipAddressIn, portIn); - if (debug) StoreLogData.Instance.Store("Send Data: " + BitConverter.ToString(data), System.DateTime.Now); - udpClient.Send(data, data.Length, endPoint); - } - else - { - stream.Write(data, 0, data.Length); - if (debug) StoreLogData.Instance.Store("Send Data: " + BitConverter.ToString(data), System.DateTime.Now); - } - } - catch (Exception) { } - } - } + if (bytes.Count < length) + continue; - private void ReadDiscreteInputs(ModbusProtocol receiveData, ModbusProtocol sendData, NetworkStream stream, int portIn, IPAddress ipAddressIn) - { - sendData.response = true; + var frame = bytes.GetRange(0, length).ToArray(); + bytes.RemoveRange(0, length); + if (!ModbusClient.DetectValidModbusFrame(frame, frame.Length)) + continue; - sendData.transactionIdentifier = receiveData.transactionIdentifier; - sendData.protocolIdentifier = receiveData.protocolIdentifier; + var response = ProcessRequest(ModbusFrame.Create(0, frame[0], frame.AsSpan(1, frame.Length - 3))); + if (response is null || frame[0] == 0) + continue; - sendData.unitIdentifier = this.unitIdentifier; - sendData.functionCode = receiveData.functionCode; - if ((receiveData.quantity < 1) | (receiveData.quantity > 0x07D0)) //Invalid quantity - { - sendData.errorCode = (byte)(receiveData.functionCode + 0x80); - sendData.exceptionCode = 3; - } - if (((receiveData.startingAdress + 1 + receiveData.quantity) > 65535) | (receiveData.startingAdress < 0)) //Invalid Starting adress or Starting address + quantity - { - sendData.errorCode = (byte)(receiveData.functionCode + 0x80); - sendData.exceptionCode = 2; + var result = new byte[response.Length - 4]; + response.AsSpan(6).CopyTo(result); + System.Buffers.Binary.BinaryPrimitives.WriteUInt16LittleEndian(result.AsSpan(result.Length - 2), ModbusFrame.CalculateCrc(result.AsSpan(0, result.Length - 2))); + if (serial.IsOpen) + serial.Write(result, 0, result.Length); + } } - if (sendData.exceptionCode == 0) + catch (Exception exception) when (exception is IOException or InvalidOperationException or TimeoutException) { - if ((receiveData.quantity % 8) == 0) - sendData.byteCount = (byte)(receiveData.quantity / 8); - else - sendData.byteCount = (byte)(receiveData.quantity / 8 + 1); - - sendData.sendCoilValues = new bool[receiveData.quantity]; - Array.Copy(discreteInputs.localArray, receiveData.startingAdress + 1, sendData.sendCoilValues, 0, receiveData.quantity); + if (!session.Cancellation.IsCancellationRequested) + Trace.TraceError($"Modbus serial receive failed: {exception}"); } - if (true) - { - Byte[] data; - if (sendData.exceptionCode > 0) - data = new byte[9 + 2 * Convert.ToInt32(serialFlag)]; - else - data = new byte[9 + sendData.byteCount + 2 * Convert.ToInt32(serialFlag)]; - Byte[] byteData = new byte[2]; - sendData.length = (byte)(data.Length - 6); - - //Send Transaction identifier - byteData = BitConverter.GetBytes((int)sendData.transactionIdentifier); - data[0] = byteData[1]; - data[1] = byteData[0]; - - //Send Protocol identifier - byteData = BitConverter.GetBytes((int)sendData.protocolIdentifier); - data[2] = byteData[1]; - data[3] = byteData[0]; - - //Send length - byteData = BitConverter.GetBytes((int)sendData.length); - data[4] = byteData[1]; - data[5] = byteData[0]; - - //Unit Identifier - data[6] = sendData.unitIdentifier; - - //Function Code - data[7] = sendData.functionCode; - - //ByteCount - data[8] = sendData.byteCount; - - - if (sendData.exceptionCode > 0) - { - data[7] = sendData.errorCode; - data[8] = sendData.exceptionCode; - sendData.sendCoilValues = null; - } - - if (sendData.sendCoilValues != null) - for (int i = 0; i < (sendData.byteCount); i++) - { - byteData = new byte[2]; - for (int j = 0; j < 8; j++) - { + } + } - byte boolValue; - if (sendData.sendCoilValues[i * 8 + j] == true) - boolValue = 1; - else - boolValue = 0; - byteData[1] = (byte)((byteData[1]) | (boolValue << j)); - if ((i * 8 + j + 1) >= sendData.sendCoilValues.Length) - break; - } - data[9 + i] = byteData[1]; - } + public void Dispose() + { + lock (_lifecycleLock) + _disposed = true; - try - { - if (serialFlag) - { - if (!serialport.IsOpen) - throw new EasyModbus.Exceptions.SerialPortNotOpenedException("serial port not opened"); - //Create CRC - sendData.crc = ModbusClient.calculateCRC(data, Convert.ToUInt16(data.Length - 8), 6); - byteData = BitConverter.GetBytes((int)sendData.crc); - data[data.Length - 2] = byteData[0]; - data[data.Length - 1] = byteData[1]; - serialport.Write(data, 6, data.Length - 6); - if (debug) - { - byte[] debugData = new byte[data.Length - 6]; - Array.Copy(data, 6, debugData, 0, data.Length - 6); - if (debug) StoreLogData.Instance.Store("Send Serial-Data: " + BitConverter.ToString(debugData), System.DateTime.Now); - } - } - else if (udpFlag) - { - //UdpClient udpClient = new UdpClient(); - IPEndPoint endPoint = new IPEndPoint(ipAddressIn, portIn); - udpClient.Send(data, data.Length, endPoint); + StopListening(); + GC.SuppressFinalize(this); + } - } - else - { - stream.Write(data, 0, data.Length); - if(debug) StoreLogData.Instance.Store("Send Data: " + BitConverter.ToString(data), System.DateTime.Now); - } - } - catch (Exception) { } - } - } + public async ValueTask DisposeAsync() + { + lock (_lifecycleLock) + _disposed = true; - private void ReadHoldingRegisters(ModbusProtocol receiveData, ModbusProtocol sendData, NetworkStream stream, int portIn, IPAddress ipAddressIn) - { - sendData.response = true; + await StopListeningAsync().ConfigureAwait(false); + GC.SuppressFinalize(this); + } - sendData.transactionIdentifier = receiveData.transactionIdentifier; - sendData.protocolIdentifier = receiveData.protocolIdentifier; + private sealed class ClientConnection(TcpClient client) + { + internal TcpClient Client { get; } = client; + internal Task Worker { get; set; } = Task.CompletedTask; + } - sendData.unitIdentifier = this.unitIdentifier; - sendData.functionCode = receiveData.functionCode; - if ((receiveData.quantity < 1) | (receiveData.quantity > 0x007D)) //Invalid quantity - { - sendData.errorCode = (byte)(receiveData.functionCode + 0x80); - sendData.exceptionCode = 3; - } - if (((receiveData.startingAdress + 1 + receiveData.quantity) > 65535) | (receiveData.startingAdress < 0)) //Invalid Starting adress or Starting address + quantity - { - sendData.errorCode = (byte)(receiveData.functionCode + 0x80); - sendData.exceptionCode = 2; + private sealed class Session + { + internal CancellationTokenSource Cancellation { get; } = new(); + internal ConcurrentDictionary Clients { get; } = new(); + internal TcpListener? Listener { get; set; } + internal UdpClient? Udp { get; set; } + internal SerialPort? Serial { get; set; } + internal SerialDataReceivedEventHandler? SerialHandler { get; set; } + internal Task Worker { get; set; } = Task.CompletedTask; + internal Lock SerialLock { get; } = new(); + internal List SerialBuffer { get; } = []; + internal void RequestStop() + { + Cancellation.Cancel(); + Listener?.Stop(); + Udp?.Dispose(); + foreach (var client in Clients.Keys) + client.Dispose(); + + if (Serial is not null) + { + if (SerialHandler is not null) + Serial.DataReceived -= SerialHandler; + Serial.Dispose(); } - if (sendData.exceptionCode == 0) - { - sendData.byteCount = (byte)(2 * receiveData.quantity); - sendData.sendRegisterValues = new Int16[receiveData.quantity]; - lock (lockHoldingRegisters) - Buffer.BlockCopy(holdingRegisters.localArray, receiveData.startingAdress * 2 + 2, sendData.sendRegisterValues, 0, receiveData.quantity * 2); - } - if (sendData.exceptionCode > 0) - sendData.length = 0x03; - else - sendData.length = (ushort)(0x03 + sendData.byteCount); - - if (true) - { - Byte[] data; - if (sendData.exceptionCode > 0) - data = new byte[9 + 2 * Convert.ToInt32(serialFlag)]; - else - data = new byte[9 + sendData.byteCount + 2 * Convert.ToInt32(serialFlag)]; - Byte[] byteData = new byte[2]; - sendData.length = (byte)(data.Length - 6); - - //Send Transaction identifier - byteData = BitConverter.GetBytes((int)sendData.transactionIdentifier); - data[0] = byteData[1]; - data[1] = byteData[0]; - - //Send Protocol identifier - byteData = BitConverter.GetBytes((int)sendData.protocolIdentifier); - data[2] = byteData[1]; - data[3] = byteData[0]; - - //Send length - byteData = BitConverter.GetBytes((int)sendData.length); - data[4] = byteData[1]; - data[5] = byteData[0]; - - //Unit Identifier - data[6] = sendData.unitIdentifier; - - //Function Code - data[7] = sendData.functionCode; - - //ByteCount - data[8] = sendData.byteCount; - - if (sendData.exceptionCode > 0) - { - data[7] = sendData.errorCode; - data[8] = sendData.exceptionCode; - sendData.sendRegisterValues = null; - } - - - if (sendData.sendRegisterValues != null) - for (int i = 0; i < (sendData.byteCount / 2); i++) - { - byteData = BitConverter.GetBytes((Int16)sendData.sendRegisterValues[i]); - data[9 + i * 2] = byteData[1]; - data[10 + i * 2] = byteData[0]; - } - try - { - if (serialFlag) - { - if (!serialport.IsOpen) - throw new EasyModbus.Exceptions.SerialPortNotOpenedException("serial port not opened"); - //Create CRC - sendData.crc = ModbusClient.calculateCRC(data, Convert.ToUInt16(data.Length - 8), 6); - byteData = BitConverter.GetBytes((int)sendData.crc); - data[data.Length - 2] = byteData[0]; - data[data.Length - 1] = byteData[1]; - serialport.Write(data, 6, data.Length - 6); - if (debug) - { - byte[] debugData = new byte[data.Length - 6]; - Array.Copy(data, 6, debugData, 0, data.Length - 6); - if (debug) StoreLogData.Instance.Store("Send Serial-Data: " + BitConverter.ToString(debugData), System.DateTime.Now); - } - } - else if (udpFlag) - { - //UdpClient udpClient = new UdpClient(); - IPEndPoint endPoint = new IPEndPoint(ipAddressIn, portIn); - udpClient.Send(data, data.Length, endPoint); - - } - else - { - stream.Write(data, 0, data.Length); - if (debug) StoreLogData.Instance.Store("Send Data: " + BitConverter.ToString(data), System.DateTime.Now); - } - } - catch (Exception) { } - } - } - - private void ReadInputRegisters(ModbusProtocol receiveData, ModbusProtocol sendData, NetworkStream stream, int portIn, IPAddress ipAddressIn) - { - sendData.response = true; - - sendData.transactionIdentifier = receiveData.transactionIdentifier; - sendData.protocolIdentifier = receiveData.protocolIdentifier; - - sendData.unitIdentifier = this.unitIdentifier; - sendData.functionCode = receiveData.functionCode; - if ((receiveData.quantity < 1) | (receiveData.quantity > 0x007D)) //Invalid quantity - { - sendData.errorCode = (byte)(receiveData.functionCode + 0x80); - sendData.exceptionCode = 3; - } - if (((receiveData.startingAdress + 1 + receiveData.quantity) > 65535) | (receiveData.startingAdress < 0)) //Invalid Starting adress or Starting address + quantity - { - sendData.errorCode = (byte)(receiveData.functionCode + 0x80); - sendData.exceptionCode = 2; - } - if (sendData.exceptionCode == 0) - { - sendData.byteCount = (byte)(2 * receiveData.quantity); - sendData.sendRegisterValues = new Int16[receiveData.quantity]; - Buffer.BlockCopy(inputRegisters.localArray, receiveData.startingAdress * 2 + 2, sendData.sendRegisterValues, 0, receiveData.quantity * 2); - } - if (sendData.exceptionCode > 0) - sendData.length = 0x03; - else - sendData.length = (ushort)(0x03 + sendData.byteCount); - - if (true) - { - Byte[] data; - if (sendData.exceptionCode > 0) - data = new byte[9 + 2 * Convert.ToInt32(serialFlag)]; - else - data = new byte[9 + sendData.byteCount + 2 * Convert.ToInt32(serialFlag)]; - Byte[] byteData = new byte[2]; - sendData.length = (byte)(data.Length - 6); - - //Send Transaction identifier - byteData = BitConverter.GetBytes((int)sendData.transactionIdentifier); - data[0] = byteData[1]; - data[1] = byteData[0]; - - //Send Protocol identifier - byteData = BitConverter.GetBytes((int)sendData.protocolIdentifier); - data[2] = byteData[1]; - data[3] = byteData[0]; - - //Send length - byteData = BitConverter.GetBytes((int)sendData.length); - data[4] = byteData[1]; - data[5] = byteData[0]; - - //Unit Identifier - data[6] = sendData.unitIdentifier; - - //Function Code - data[7] = sendData.functionCode; - - //ByteCount - data[8] = sendData.byteCount; - - - if (sendData.exceptionCode > 0) - { - data[7] = sendData.errorCode; - data[8] = sendData.exceptionCode; - sendData.sendRegisterValues = null; - } - - - if (sendData.sendRegisterValues != null) - for (int i = 0; i < (sendData.byteCount / 2); i++) - { - byteData = BitConverter.GetBytes((Int16)sendData.sendRegisterValues[i]); - data[9 + i * 2] = byteData[1]; - data[10 + i * 2] = byteData[0]; - } - try - { - if (serialFlag) - { - if (!serialport.IsOpen) - throw new EasyModbus.Exceptions.SerialPortNotOpenedException("serial port not opened"); - //Create CRC - sendData.crc = ModbusClient.calculateCRC(data, Convert.ToUInt16(data.Length - 8), 6); - byteData = BitConverter.GetBytes((int)sendData.crc); - data[data.Length - 2] = byteData[0]; - data[data.Length - 1] = byteData[1]; - serialport.Write(data, 6, data.Length - 6); - if (debug) - { - byte[] debugData = new byte[data.Length - 6]; - Array.Copy(data, 6, debugData, 0, data.Length - 6); - if (debug) StoreLogData.Instance.Store("Send Serial-Data: " + BitConverter.ToString(debugData), System.DateTime.Now); - } - - } - else if (udpFlag) - { - //UdpClient udpClient = new UdpClient(); - IPEndPoint endPoint = new IPEndPoint(ipAddressIn, portIn); - udpClient.Send(data, data.Length, endPoint); - - } - else - { - stream.Write(data, 0, data.Length); - if (debug) StoreLogData.Instance.Store("Send Data: " + BitConverter.ToString(data), System.DateTime.Now); - } - } - catch (Exception) { } - } - } - - private void WriteSingleCoil(ModbusProtocol receiveData, ModbusProtocol sendData, NetworkStream stream, int portIn, IPAddress ipAddressIn) - { - sendData.response = true; - - sendData.transactionIdentifier = receiveData.transactionIdentifier; - sendData.protocolIdentifier = receiveData.protocolIdentifier; - - sendData.unitIdentifier = this.unitIdentifier; - sendData.functionCode = receiveData.functionCode; - sendData.startingAdress = receiveData.startingAdress; - sendData.receiveCoilValues = receiveData.receiveCoilValues; - if ((receiveData.receiveCoilValues[0] != 0x0000) & (receiveData.receiveCoilValues[0] != 0xFF00)) //Invalid Value - { - sendData.errorCode = (byte)(receiveData.functionCode + 0x80); - sendData.exceptionCode = 3; - } - if (((receiveData.startingAdress + 1) > 65535) | (receiveData.startingAdress < 0)) //Invalid Starting adress or Starting address + quantity - { - sendData.errorCode = (byte)(receiveData.functionCode + 0x80); - sendData.exceptionCode = 2; - } - if (sendData.exceptionCode == 0) - { - if (receiveData.receiveCoilValues[0] == 0xFF00) - { - lock (lockCoils) - coils[receiveData.startingAdress + 1] = true; - } - if (receiveData.receiveCoilValues[0] == 0x0000) - { - lock (lockCoils) - coils[receiveData.startingAdress + 1] = false; - } - } - if (sendData.exceptionCode > 0) - sendData.length = 0x03; - else - sendData.length = 0x06; - - if (true) - { - Byte[] data; - if (sendData.exceptionCode > 0) - data = new byte[9 + 2 * Convert.ToInt32(serialFlag)]; - else - data = new byte[12 + 2 * Convert.ToInt32(serialFlag)]; - - Byte[] byteData = new byte[2]; - sendData.length = (byte)(data.Length - 6); - - //Send Transaction identifier - byteData = BitConverter.GetBytes((int)sendData.transactionIdentifier); - data[0] = byteData[1]; - data[1] = byteData[0]; - - //Send Protocol identifier - byteData = BitConverter.GetBytes((int)sendData.protocolIdentifier); - data[2] = byteData[1]; - data[3] = byteData[0]; - - //Send length - byteData = BitConverter.GetBytes((int)sendData.length); - data[4] = byteData[1]; - data[5] = byteData[0]; - - //Unit Identifier - data[6] = sendData.unitIdentifier; - - //Function Code - data[7] = sendData.functionCode; - - - - if (sendData.exceptionCode > 0) - { - data[7] = sendData.errorCode; - data[8] = sendData.exceptionCode; - sendData.sendRegisterValues = null; - } - else - { - byteData = BitConverter.GetBytes((int)receiveData.startingAdress); - data[8] = byteData[1]; - data[9] = byteData[0]; - byteData = BitConverter.GetBytes((int)receiveData.receiveCoilValues[0]); - data[10] = byteData[1]; - data[11] = byteData[0]; - } - - - try - { - if (serialFlag) - { - if (!serialport.IsOpen) - throw new EasyModbus.Exceptions.SerialPortNotOpenedException("serial port not opened"); - //Create CRC - sendData.crc = ModbusClient.calculateCRC(data, Convert.ToUInt16(data.Length - 8), 6); - byteData = BitConverter.GetBytes((int)sendData.crc); - data[data.Length - 2] = byteData[0]; - data[data.Length - 1] = byteData[1]; - serialport.Write(data, 6, data.Length - 6); - if (debug) - { - byte[] debugData = new byte[data.Length - 6]; - Array.Copy(data, 6, debugData, 0, data.Length - 6); - if (debug) StoreLogData.Instance.Store("Send Serial-Data: " + BitConverter.ToString(debugData), System.DateTime.Now); - } - - } - else if (udpFlag) - { - //UdpClient udpClient = new UdpClient(); - IPEndPoint endPoint = new IPEndPoint(ipAddressIn, portIn); - udpClient.Send(data, data.Length, endPoint); - - } - else - { - stream.Write(data, 0, data.Length); - if (debug) StoreLogData.Instance.Store("Send Data: " + BitConverter.ToString(data), System.DateTime.Now); - } - } - catch (Exception) { } - if (CoilsChanged != null) - CoilsChanged(receiveData.startingAdress+1, 1); - } - } - - private void WriteSingleRegister(ModbusProtocol receiveData, ModbusProtocol sendData, NetworkStream stream, int portIn, IPAddress ipAddressIn) - { - sendData.response = true; - - sendData.transactionIdentifier = receiveData.transactionIdentifier; - sendData.protocolIdentifier = receiveData.protocolIdentifier; - - sendData.unitIdentifier = this.unitIdentifier; - sendData.functionCode = receiveData.functionCode; - sendData.startingAdress = receiveData.startingAdress; - sendData.receiveRegisterValues = receiveData.receiveRegisterValues; - - if ((receiveData.receiveRegisterValues[0] < 0x0000) | (receiveData.receiveRegisterValues[0] > 0xFFFF)) //Invalid Value - { - sendData.errorCode = (byte)(receiveData.functionCode + 0x80); - sendData.exceptionCode = 3; - } - if (((receiveData.startingAdress + 1) > 65535) | (receiveData.startingAdress < 0)) //Invalid Starting adress or Starting address + quantity - { - sendData.errorCode = (byte)(receiveData.functionCode + 0x80); - sendData.exceptionCode = 2; - } - if (sendData.exceptionCode == 0) - { - lock (lockHoldingRegisters) - holdingRegisters[receiveData.startingAdress + 1] = unchecked((short)receiveData.receiveRegisterValues[0]); - } - if (sendData.exceptionCode > 0) - sendData.length = 0x03; - else - sendData.length = 0x06; - - if (true) - { - Byte[] data; - if (sendData.exceptionCode > 0) - data = new byte[9 + 2 * Convert.ToInt32(serialFlag)]; - else - data = new byte[12 + 2 * Convert.ToInt32(serialFlag)]; - - Byte[] byteData = new byte[2]; - sendData.length = (byte)(data.Length - 6); - - - //Send Transaction identifier - byteData = BitConverter.GetBytes((int)sendData.transactionIdentifier); - data[0] = byteData[1]; - data[1] = byteData[0]; - - //Send Protocol identifier - byteData = BitConverter.GetBytes((int)sendData.protocolIdentifier); - data[2] = byteData[1]; - data[3] = byteData[0]; - - //Send length - byteData = BitConverter.GetBytes((int)sendData.length); - data[4] = byteData[1]; - data[5] = byteData[0]; - - //Unit Identifier - data[6] = sendData.unitIdentifier; - - //Function Code - data[7] = sendData.functionCode; - - - - if (sendData.exceptionCode > 0) - { - data[7] = sendData.errorCode; - data[8] = sendData.exceptionCode; - sendData.sendRegisterValues = null; - } - else - { - byteData = BitConverter.GetBytes((int)receiveData.startingAdress); - data[8] = byteData[1]; - data[9] = byteData[0]; - byteData = BitConverter.GetBytes((int)receiveData.receiveRegisterValues[0]); - data[10] = byteData[1]; - data[11] = byteData[0]; - } - - - try - { - if (serialFlag) - { - if (!serialport.IsOpen) - throw new EasyModbus.Exceptions.SerialPortNotOpenedException("serial port not opened"); - //Create CRC - sendData.crc = ModbusClient.calculateCRC(data, Convert.ToUInt16(data.Length - 8), 6); - byteData = BitConverter.GetBytes((int)sendData.crc); - data[data.Length - 2] = byteData[0]; - data[data.Length - 1] = byteData[1]; - serialport.Write(data, 6, data.Length - 6); - if (debug) - { - byte[] debugData = new byte[data.Length - 6]; - Array.Copy(data, 6, debugData, 0, data.Length - 6); - if (debug) StoreLogData.Instance.Store("Send Serial-Data: " + BitConverter.ToString(debugData), System.DateTime.Now); - } - - } - else if (udpFlag) - { - //UdpClient udpClient = new UdpClient(); - IPEndPoint endPoint = new IPEndPoint(ipAddressIn, portIn); - udpClient.Send(data, data.Length, endPoint); - - } - else - { - stream.Write(data, 0, data.Length); - if (debug) StoreLogData.Instance.Store("Send Data: " + BitConverter.ToString(data), System.DateTime.Now); - } - } - catch (Exception) { } - if (HoldingRegistersChanged != null) - HoldingRegistersChanged(receiveData.startingAdress+1, 1); - } - } - - private void WriteMultipleCoils(ModbusProtocol receiveData, ModbusProtocol sendData, NetworkStream stream, int portIn, IPAddress ipAddressIn) - { - sendData.response = true; - - sendData.transactionIdentifier = receiveData.transactionIdentifier; - sendData.protocolIdentifier = receiveData.protocolIdentifier; - - sendData.unitIdentifier = this.unitIdentifier; - sendData.functionCode = receiveData.functionCode; - sendData.startingAdress = receiveData.startingAdress; - sendData.quantity = receiveData.quantity; - - if ((receiveData.quantity == 0x0000) | (receiveData.quantity > 0x07B0)) //Invalid Quantity - { - sendData.errorCode = (byte)(receiveData.functionCode + 0x80); - sendData.exceptionCode = 3; - } - if ((((int)receiveData.startingAdress + 1 + (int)receiveData.quantity) > 65535) | (receiveData.startingAdress < 0)) //Invalid Starting adress or Starting address + quantity - { - sendData.errorCode = (byte)(receiveData.functionCode + 0x80); - sendData.exceptionCode = 2; - } - if (sendData.exceptionCode == 0) - { - lock (lockCoils) - for (int i = 0; i < receiveData.quantity; i++) - { - int shift = i % 16; - /* if ((i == receiveData.quantity - 1) & (receiveData.quantity % 2 != 0)) - { - if (shift < 8) - shift = shift + 8; - else - shift = shift - 8; - }*/ - int mask = 0x1; - mask = mask << (shift); - if ((receiveData.receiveCoilValues[i / 16] & (ushort)mask) == 0) - - coils[receiveData.startingAdress + i + 1] = false; - else - - coils[receiveData.startingAdress + i + 1] = true; - - } - } - if (sendData.exceptionCode > 0) - sendData.length = 0x03; - else - sendData.length = 0x06; - if (true) - { - Byte[] data; - if (sendData.exceptionCode > 0) - data = new byte[9 + 2 * Convert.ToInt32(serialFlag)]; - else - data = new byte[12 + 2 * Convert.ToInt32(serialFlag)]; - - Byte[] byteData = new byte[2]; - sendData.length = (byte)(data.Length - 6); - - //Send Transaction identifier - byteData = BitConverter.GetBytes((int)sendData.transactionIdentifier); - data[0] = byteData[1]; - data[1] = byteData[0]; - - //Send Protocol identifier - byteData = BitConverter.GetBytes((int)sendData.protocolIdentifier); - data[2] = byteData[1]; - data[3] = byteData[0]; - - //Send length - byteData = BitConverter.GetBytes((int)sendData.length); - data[4] = byteData[1]; - data[5] = byteData[0]; - - //Unit Identifier - data[6] = sendData.unitIdentifier; - - //Function Code - data[7] = sendData.functionCode; - - - - if (sendData.exceptionCode > 0) - { - data[7] = sendData.errorCode; - data[8] = sendData.exceptionCode; - sendData.sendRegisterValues = null; - } - else - { - byteData = BitConverter.GetBytes((int)receiveData.startingAdress); - data[8] = byteData[1]; - data[9] = byteData[0]; - byteData = BitConverter.GetBytes((int)receiveData.quantity); - data[10] = byteData[1]; - data[11] = byteData[0]; - } - - - try - { - if (serialFlag) - { - if (!serialport.IsOpen) - throw new EasyModbus.Exceptions.SerialPortNotOpenedException("serial port not opened"); - //Create CRC - sendData.crc = ModbusClient.calculateCRC(data, Convert.ToUInt16(data.Length - 8), 6); - byteData = BitConverter.GetBytes((int)sendData.crc); - data[data.Length - 2] = byteData[0]; - data[data.Length - 1] = byteData[1]; - serialport.Write(data, 6, data.Length - 6); - if (debug) - { - byte[] debugData = new byte[data.Length - 6]; - Array.Copy(data, 6, debugData, 0, data.Length - 6); - if (debug) StoreLogData.Instance.Store("Send Serial-Data: " + BitConverter.ToString(debugData), System.DateTime.Now); - } - - } - else if (udpFlag) - { - //UdpClient udpClient = new UdpClient(); - IPEndPoint endPoint = new IPEndPoint(ipAddressIn, portIn); - udpClient.Send(data, data.Length, endPoint); - - } - else - { - stream.Write(data, 0, data.Length); - if (debug) StoreLogData.Instance.Store("Send Data: " + BitConverter.ToString(data), System.DateTime.Now); - } - } - catch (Exception) { } - if (CoilsChanged != null) - CoilsChanged(receiveData.startingAdress+1, receiveData.quantity); - } - } - - private void WriteMultipleRegisters(ModbusProtocol receiveData, ModbusProtocol sendData, NetworkStream stream, int portIn, IPAddress ipAddressIn) - { - sendData.response = true; - - sendData.transactionIdentifier = receiveData.transactionIdentifier; - sendData.protocolIdentifier = receiveData.protocolIdentifier; - - sendData.unitIdentifier = this.unitIdentifier; - sendData.functionCode = receiveData.functionCode; - sendData.startingAdress = receiveData.startingAdress; - sendData.quantity = receiveData.quantity; - - if ((receiveData.quantity == 0x0000) | (receiveData.quantity > 0x07B0)) //Invalid Quantity - { - sendData.errorCode = (byte)(receiveData.functionCode + 0x80); - sendData.exceptionCode = 3; - } - if ((((int)receiveData.startingAdress + 1 + (int)receiveData.quantity) > 65535) | (receiveData.startingAdress < 0)) //Invalid Starting adress or Starting address + quantity - { - sendData.errorCode = (byte)(receiveData.functionCode + 0x80); - sendData.exceptionCode = 2; - } - if (sendData.exceptionCode == 0) - { - lock (lockHoldingRegisters) - for (int i = 0; i < receiveData.quantity; i++) - { - holdingRegisters[receiveData.startingAdress + i + 1] = unchecked((short)receiveData.receiveRegisterValues[i]); - } - } - if (sendData.exceptionCode > 0) - sendData.length = 0x03; - else - sendData.length = 0x06; - if (true) - { - Byte[] data; - if (sendData.exceptionCode > 0) - data = new byte[9 + 2 * Convert.ToInt32(serialFlag)]; - else - data = new byte[12 + 2 * Convert.ToInt32(serialFlag)]; - - Byte[] byteData = new byte[2]; - sendData.length = (byte)(data.Length - 6); - - //Send Transaction identifier - byteData = BitConverter.GetBytes((int)sendData.transactionIdentifier); - data[0] = byteData[1]; - data[1] = byteData[0]; - - //Send Protocol identifier - byteData = BitConverter.GetBytes((int)sendData.protocolIdentifier); - data[2] = byteData[1]; - data[3] = byteData[0]; - - //Send length - byteData = BitConverter.GetBytes((int)sendData.length); - data[4] = byteData[1]; - data[5] = byteData[0]; - - //Unit Identifier - data[6] = sendData.unitIdentifier; - - //Function Code - data[7] = sendData.functionCode; - - - - if (sendData.exceptionCode > 0) - { - data[7] = sendData.errorCode; - data[8] = sendData.exceptionCode; - sendData.sendRegisterValues = null; - } - else - { - byteData = BitConverter.GetBytes((int)receiveData.startingAdress); - data[8] = byteData[1]; - data[9] = byteData[0]; - byteData = BitConverter.GetBytes((int)receiveData.quantity); - data[10] = byteData[1]; - data[11] = byteData[0]; - } - - - try - { - if (serialFlag) - { - if (!serialport.IsOpen) - throw new EasyModbus.Exceptions.SerialPortNotOpenedException("serial port not opened"); - //Create CRC - sendData.crc = ModbusClient.calculateCRC(data, Convert.ToUInt16(data.Length - 8), 6); - byteData = BitConverter.GetBytes((int)sendData.crc); - data[data.Length - 2] = byteData[0]; - data[data.Length - 1] = byteData[1]; - serialport.Write(data, 6, data.Length - 6); - if (debug) - { - byte[] debugData = new byte[data.Length - 6]; - Array.Copy(data, 6, debugData, 0, data.Length - 6); - if (debug) StoreLogData.Instance.Store("Send Serial-Data: " + BitConverter.ToString(debugData), System.DateTime.Now); - } - - } - else if (udpFlag) - { - //UdpClient udpClient = new UdpClient(); - IPEndPoint endPoint = new IPEndPoint(ipAddressIn, portIn); - udpClient.Send(data, data.Length, endPoint); - - } - else - { - stream.Write(data, 0, data.Length); - if (debug) StoreLogData.Instance.Store("Send Data: " + BitConverter.ToString(data), System.DateTime.Now); - } - } - catch (Exception) { } - if (HoldingRegistersChanged != null) - HoldingRegistersChanged(receiveData.startingAdress+1, receiveData.quantity); - } - } - - private void ReadWriteMultipleRegisters(ModbusProtocol receiveData, ModbusProtocol sendData, NetworkStream stream, int portIn, IPAddress ipAddressIn) - { - sendData.response = true; - - sendData.transactionIdentifier = receiveData.transactionIdentifier; - sendData.protocolIdentifier = receiveData.protocolIdentifier; - - sendData.unitIdentifier = this.unitIdentifier; - sendData.functionCode = receiveData.functionCode; - - - if ((receiveData.quantityRead < 0x0001) | (receiveData.quantityRead > 0x007D) | (receiveData.quantityWrite < 0x0001) | (receiveData.quantityWrite > 0x0079) | (receiveData.byteCount != (receiveData.quantityWrite * 2))) //Invalid Quantity - { - sendData.errorCode = (byte)(receiveData.functionCode + 0x80); - sendData.exceptionCode = 3; - } - if ((((int)receiveData.startingAddressRead + 1 + (int)receiveData.quantityRead) > 65535) | (((int)receiveData.startingAddressWrite + 1 + (int)receiveData.quantityWrite) > 65535) | (receiveData.quantityWrite < 0) | (receiveData.quantityRead < 0)) //Invalid Starting adress or Starting address + quantity - { - sendData.errorCode = (byte)(receiveData.functionCode + 0x80); - sendData.exceptionCode = 2; - } - if (sendData.exceptionCode == 0) - { - sendData.sendRegisterValues = new Int16[receiveData.quantityRead]; - lock (lockHoldingRegisters) - Buffer.BlockCopy(holdingRegisters.localArray, receiveData.startingAddressRead * 2 + 2, sendData.sendRegisterValues, 0, receiveData.quantityRead * 2); - - lock (holdingRegisters) - for (int i = 0; i < receiveData.quantityWrite; i++) - { - holdingRegisters[receiveData.startingAddressWrite + i + 1] = unchecked((short)receiveData.receiveRegisterValues[i]); - } - sendData.byteCount = (byte)(2 * receiveData.quantityRead); - } - if (sendData.exceptionCode > 0) - sendData.length = 0x03; - else - sendData.length = Convert.ToUInt16(3 + 2 * receiveData.quantityRead); - if (true) - { - Byte[] data; - if (sendData.exceptionCode > 0) - data = new byte[9 + 2 * Convert.ToInt32(serialFlag)]; - else - data = new byte[9 + sendData.byteCount + 2 * Convert.ToInt32(serialFlag)]; - - Byte[] byteData = new byte[2]; - - //Send Transaction identifier - byteData = BitConverter.GetBytes((int)sendData.transactionIdentifier); - data[0] = byteData[1]; - data[1] = byteData[0]; - - //Send Protocol identifier - byteData = BitConverter.GetBytes((int)sendData.protocolIdentifier); - data[2] = byteData[1]; - data[3] = byteData[0]; - - //Send length - byteData = BitConverter.GetBytes((int)sendData.length); - data[4] = byteData[1]; - data[5] = byteData[0]; - - //Unit Identifier - data[6] = sendData.unitIdentifier; - - //Function Code - data[7] = sendData.functionCode; - - //ByteCount - data[8] = sendData.byteCount; - - - if (sendData.exceptionCode > 0) - { - data[7] = sendData.errorCode; - data[8] = sendData.exceptionCode; - sendData.sendRegisterValues = null; - } - else - { - if (sendData.sendRegisterValues != null) - for (int i = 0; i < (sendData.byteCount / 2); i++) - { - byteData = BitConverter.GetBytes((Int16)sendData.sendRegisterValues[i]); - data[9 + i * 2] = byteData[1]; - data[10 + i * 2] = byteData[0]; - } - - } - - - try - { - if (serialFlag) - { - if (!serialport.IsOpen) - throw new EasyModbus.Exceptions.SerialPortNotOpenedException("serial port not opened"); - //Create CRC - sendData.crc = ModbusClient.calculateCRC(data, Convert.ToUInt16(data.Length - 8), 6); - byteData = BitConverter.GetBytes((int)sendData.crc); - data[data.Length - 2] = byteData[0]; - data[data.Length - 1] = byteData[1]; - serialport.Write(data, 6, data.Length - 6); - if (debug) - { - byte[] debugData = new byte[data.Length - 6]; - Array.Copy(data, 6, debugData, 0, data.Length - 6); - if (debug) StoreLogData.Instance.Store("Send Serial-Data: " + BitConverter.ToString(debugData), System.DateTime.Now); - } - - } - else if (udpFlag) - { - //UdpClient udpClient = new UdpClient(); - IPEndPoint endPoint = new IPEndPoint(ipAddressIn, portIn); - udpClient.Send(data, data.Length, endPoint); - - } - else - { - stream.Write(data, 0, data.Length); - if (debug) StoreLogData.Instance.Store("Send Data: " + BitConverter.ToString(data), System.DateTime.Now); - } - } - catch (Exception) { } - if (HoldingRegistersChanged != null) - HoldingRegistersChanged(receiveData.startingAddressWrite+1, receiveData.quantityWrite); - } - } - - private void sendException(int errorCode, int exceptionCode, ModbusProtocol receiveData, ModbusProtocol sendData, NetworkStream stream, int portIn, IPAddress ipAddressIn) - { - sendData.response = true; - - sendData.transactionIdentifier = receiveData.transactionIdentifier; - sendData.protocolIdentifier = receiveData.protocolIdentifier; - - sendData.unitIdentifier = receiveData.unitIdentifier; - sendData.errorCode = (byte)errorCode; - sendData.exceptionCode = (byte)exceptionCode; - - if (sendData.exceptionCode > 0) - sendData.length = 0x03; - else - sendData.length = (ushort)(0x03 + sendData.byteCount); - - if (true) - { - Byte[] data; - if (sendData.exceptionCode > 0) - data = new byte[9 + 2 * Convert.ToInt32(serialFlag)]; - else - data = new byte[9 + sendData.byteCount + 2 * Convert.ToInt32(serialFlag)]; - Byte[] byteData = new byte[2]; - sendData.length = (byte)(data.Length - 6); - - //Send Transaction identifier - byteData = BitConverter.GetBytes((int)sendData.transactionIdentifier); - data[0] = byteData[1]; - data[1] = byteData[0]; - - //Send Protocol identifier - byteData = BitConverter.GetBytes((int)sendData.protocolIdentifier); - data[2] = byteData[1]; - data[3] = byteData[0]; - - //Send length - byteData = BitConverter.GetBytes((int)sendData.length); - data[4] = byteData[1]; - data[5] = byteData[0]; - - //Unit Identifier - data[6] = sendData.unitIdentifier; - - - data[7] = sendData.errorCode; - data[8] = sendData.exceptionCode; - - - try - { - if (serialFlag) - { - if (!serialport.IsOpen) - throw new EasyModbus.Exceptions.SerialPortNotOpenedException("serial port not opened"); - //Create CRC - sendData.crc = ModbusClient.calculateCRC(data, Convert.ToUInt16(data.Length - 8), 6); - byteData = BitConverter.GetBytes((int)sendData.crc); - data[data.Length - 2] = byteData[0]; - data[data.Length - 1] = byteData[1]; - serialport.Write(data, 6, data.Length - 6); - if (debug) - { - byte[] debugData = new byte[data.Length - 6]; - Array.Copy(data, 6, debugData, 0, data.Length - 6); - if (debug) StoreLogData.Instance.Store("Send Serial-Data: " + BitConverter.ToString(debugData), System.DateTime.Now); - } - } - else if (udpFlag) - { - //UdpClient udpClient = new UdpClient(); - IPEndPoint endPoint = new IPEndPoint(ipAddressIn, portIn); - udpClient.Send(data, data.Length, endPoint); - - } - else - { - stream.Write(data, 0, data.Length); - if (debug) StoreLogData.Instance.Store("Send Data: " + BitConverter.ToString(data), System.DateTime.Now); - } - } - catch (Exception) { } - } - } - - private void CreateLogData(ModbusProtocol receiveData, ModbusProtocol sendData) - { - for (int i = 0; i < 98; i++) - { - modbusLogData[99 - i] = modbusLogData[99 - i - 2]; - - } - modbusLogData[0] = receiveData; - modbusLogData[1] = sendData; - - } - - - - public int NumberOfConnections - { - get - { - return numberOfConnections; - } - } - - public ModbusProtocol[] ModbusLogData - { - get - { - return modbusLogData; - } - } - - public int Port - { - get - { - return port; - } - set - { - port = value; - - - } - } - - public bool UDPFlag - { - get - { - return udpFlag; - } - set - { - udpFlag = value; - } - } - - public bool SerialFlag - { - get - { - return serialFlag; - } - set - { - serialFlag = value; - } - } - - public int Baudrate - { - get - { - return baudrate; - } - set - { - baudrate = value; - } - } - - public System.IO.Ports.Parity Parity - { - get - { - return parity; - } - set - { - parity = value; - } - } - - public System.IO.Ports.StopBits StopBits - { - get - { - return stopBits; - } - set - { - stopBits = value; - } - } - - public string SerialPort - { - get - { - return serialPort; - } - set - { - serialPort = value; - if (serialPort != null) - serialFlag = true; - else - serialFlag = false; - } - } - - public byte UnitIdentifier - { - get - { - return unitIdentifier; - } - set - { - unitIdentifier = value; - } - } - - - - - /// - /// Gets or Sets the Filename for the LogFile - /// - public string LogFileFilename - { - get - { - return StoreLogData.Instance.Filename; - } - set - { - StoreLogData.Instance.Filename = value; - if (StoreLogData.Instance.Filename != null) - debug = true; - else - debug = false; - } - } - - - - - public class HoldingRegisters - { - public Int16[] localArray = new Int16[65535]; - ModbusServer modbusServer; - - public HoldingRegisters(EasyModbus.ModbusServer modbusServer) - { - this.modbusServer = modbusServer; - } - - public Int16 this[int x] - { - get { return this.localArray[x]; } - set - { - this.localArray[x] = value; - - } - } - } - - public class InputRegisters - { - public Int16[] localArray = new Int16[65535]; - ModbusServer modbusServer; - - public InputRegisters(EasyModbus.ModbusServer modbusServer) - { - this.modbusServer = modbusServer; - } - - public Int16 this[int x] - { - get { return this.localArray[x]; } - set - { - this.localArray[x] = value; - - } - } - } - - public class Coils - { - public bool[] localArray = new bool[65535]; - ModbusServer modbusServer; - - public Coils(EasyModbus.ModbusServer modbusServer) - { - this.modbusServer = modbusServer; - } - - public bool this[int x] - { - get { return this.localArray[x]; } - set - { - this.localArray[x] = value; - - } - } - } - - public class DiscreteInputs - { - public bool[] localArray = new bool[65535]; - ModbusServer modbusServer; - - public DiscreteInputs(EasyModbus.ModbusServer modbusServer) - { - this.modbusServer = modbusServer; - } - - public bool this[int x] - { - get { return this.localArray[x]; } - set - { - this.localArray[x] = value; - - } - } - - } } } - \ No newline at end of file diff --git a/EasyModbus/Properties/AssemblyInfo.cs b/EasyModbus/Properties/AssemblyInfo.cs deleted file mode 100644 index 87e63ce..0000000 --- a/EasyModbus/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,31 +0,0 @@ -#region Using directives - -using System; -using System.Reflection; -using System.Runtime.InteropServices; - -#endregion - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("EasyModbus")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Stefan Rossmann Engineering Solutions")] -[assembly: AssemblyProduct("EasyModbus")] -[assembly: AssemblyCopyright("Copyright 2017-2020")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// This sets the default COM visibility of types in the assembly to invisible. -// If you need to expose a type to COM, use [ComVisible(true)] on that type. -[assembly: ComVisible(false)] - -// The assembly version has following format : -// -// Major.Minor.Build.Revision -// -// You can specify all the values or you can use the default the Revision and -// Build Numbers by using the '*' as shown below: -[assembly: AssemblyVersion("5.6.0")] diff --git a/EasyModbus/StoreLogData.cs b/EasyModbus/StoreLogData.cs index 3345038..3c33811 100644 --- a/EasyModbus/StoreLogData.cs +++ b/EasyModbus/StoreLogData.cs @@ -1,120 +1,35 @@ -/* -Copyright (c) 2018-2020 Rossmann-Engineering -Permission is hereby granted, free of charge, -to any person obtaining a copy of this software -and associated documentation files (the "Software"), -to deal in the Software without restriction, -including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, -and/or sell copies of the Software, and to permit -persons to whom the Software is furnished to do so, -subject to the following conditions: +using System.Diagnostics; +using System.Globalization; -The above copyright notice and this permission -notice shall be included in all copies or substantial portions of the Software. +namespace EasyModbus; -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, -ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE -OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ - -using System; -using System.Collections.Generic; -using System.Text; - -namespace EasyModbus +/// Optional process-wide file logging retained for API compatibility. +public sealed class StoreLogData { - /// - /// Store Log-Data in a File - /// - public sealed class StoreLogData + private readonly Lock _writeLock = new(); + public static StoreLogData Instance { get; } = new(); + public string? Filename { - private String filename = null; - private static volatile StoreLogData instance; - private static object syncObject = new Object(); - - /// - /// Private constructor; Ensures the access of the class only via "instance" - /// - private StoreLogData() - { - } - - /// - /// Returns the instance of the class (singleton) - /// - /// instance (Singleton) - public static StoreLogData Instance - { - get - { - if (instance == null) - { - lock (syncObject) - { - if (instance == null) - instance = new StoreLogData(); - } - } - - return instance; - } - } - - /// - /// Store message in Log-File - /// - /// Message to append to the Log-File - public void Store(String message) + get; set; + } + private StoreLogData() + { + } + public void Store(string message) => Write(message); + public void Store(string message, DateTime timestamp) => Write(timestamp.ToString("dd.MM.yyyy H:mm:ss.ff ", CultureInfo.InvariantCulture) + message); + private void Write(string message) + { + var filename = Filename; + if (string.IsNullOrWhiteSpace(filename)) + return; + try { - if (this.filename == null) - return; - - using (System.IO.StreamWriter file = - new System.IO.StreamWriter(Filename, true)) - { - file.WriteLine(message); - } + lock (_writeLock) + File.AppendAllText(filename, message + Environment.NewLine); } - - /// - /// Store message in Log-File including Timestamp - /// - /// Message to append to the Log-File - /// Timestamp to add to the same Row - public void Store(String message, DateTime timestamp) + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or ArgumentException) { - try - { - using (System.IO.StreamWriter file = - new System.IO.StreamWriter(Filename, true)) - { - file.WriteLine(timestamp.ToString("dd.MM.yyyy H:mm:ss.ff ") + message); - } - } - catch (Exception e) - { - - } + Trace.TraceWarning($"Modbus file logging failed: {exception.Message}"); } - - /// - /// Gets or Sets the Filename to Store Strings in a File - /// - public string Filename - { - get - { - return filename; - } - set - { - filename = value; - } - } } } diff --git a/EasyModbus/nuget.exe b/EasyModbus/nuget.exe deleted file mode 100644 index ad35fa4..0000000 Binary files a/EasyModbus/nuget.exe and /dev/null differ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..958ef5d --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018-2020 Rossmann-Engineering + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index e5658f9..0443244 100644 --- a/README.md +++ b/README.md @@ -1,52 +1,134 @@ -# EasyModbusTCP.NET - www.EasyModbusTCP.NET +# EasyModbusTCP.NET for .NET 10 -Modbus TCP, Modbus UDP and Modbus RTU client/server library for .NET
-Industry approved!!
-Fast and secure access from PC or Embedded Systems to many PLC-Systems and other components for industry automation.
-Only a few lines of codes are needed to read or write data from or to a PLC. +A modernized fork of the [Rossmann Engineering EasyModbus library](https://github.com/rossmann-engineering/EasyModbusTCP.NET), +maintained for source integration with Texplorer Suite. The library targets +`net10.0` and supports Modbus TCP, UDP, and RTU clients and servers. -

Implementation Guide and Codesamples: www.easymodbustcp.net

+## Build and test -Additional Software tools e.g. Modbus Server Simulator, makes software development fast and easy. +Install the .NET 10 SDK, then run from the repository root: -Download Library (*.DLL) from NuGet or from: Download EasyModbusTCP/UDP/RTU .NET +```powershell +dotnet build EasyModbus.slnx --configuration Release +dotnet test EasyModbus.slnx --configuration Release +dotnet run --project ConsoleAppStd --configuration Release +``` +The console example starts a loopback server, reads its registers, and disposes +both endpoints. Pass a host and optional port to connect to an existing server: +```powershell +dotnet run --project ConsoleAppStd -- 192.168.0.10 502 +``` -Supported Function Codes: +GitHub Actions builds and tests the solution on Windows and Linux. Regression +tests exercise all supported function codes over TCP and UDP, fragmented and +batched TCP frames, signed values and address boundaries, malformed packets, +timeouts, cancellation, concurrent calls, shutdown, and register conversions. +RTU CRC framing is tested without hardware; serial driver behavior still needs +validation on the intended hardware. -- Read Coils (FC1) -- Read Discrete Inputs (FC2) -- Read Holding Registers (FC3) -- Read Input Registers (FC4) -- Write Single Coil (FC5) -- Write Single Register (FC6) -- Write Multiple Coils (FC15) -- Write Multiple Registers (FC16) -- Read/Write Multiple Registers (FC23) +## Client +```csharp +using EasyModbus; -Modbus TCP, Modbus UDP and Modbus RTU client/server library +await using var client = new ModbusClient("192.168.0.10", 502) +{ + ConnectionTimeout = 2000, + UnitIdentifier = 1 +}; +using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5)); +await client.ConnectAsync(timeout.Token); +int[] registers = await client.ReadHoldingRegistersAsync(0, 2, timeout.Token); +await client.WriteMultipleRegistersAsync(0, [100, 200], timeout.Token); +``` -Copyright (c) 2018-2020 Rossmann-Engineering -Permission is hereby granted, free of charge, -to any person obtaining a copy of this software -and associated documentation files (the "Software"), -to deal in the Software without restriction, -including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, -and/or sell copies of the Software, and to permit -persons to whom the Software is furnished to do so, -subject to the following conditions: +Every supported read/write method has an async counterpart accepting a +`CancellationToken`. Existing synchronous methods call the same protocol core. +Requests on a client are serialized, including mixed synchronous and async calls. +Configure the endpoint and transport while disconnected. -The above copyright notice and this permission -notice shall be included in all copies or substantial portions of the Software. +Set `UDPFlag = true` before connecting to use UDP. For RTU, create +`new ModbusClient("COM3")`, configure `Baudrate`, `Parity`, and `StopBits`, then +connect. `NumberOfRetries` controls RTU retries after a timeout or failed CRC. +TCP and UDP writes are not automatically replayed. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, -ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE -OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +An interrupted in-flight request closes the transport so its delayed response +cannot be mistaken for a later request. Reconnect before making another request. +Canceling a request still queued behind another operation leaves that active +operation and connection intact. Dispose waits for the current operation to end; +cancel that operation's token first when prompt shutdown is needed. + +`ReceivedData` and `SentData` expose the latest wire frames as read-only memory. +The legacy `receiveData`, `sendData`, and `calculateCRC` members remain as obsolete +source compatibility aliases. Data-change callbacks run after releasing the +client operation lock and must not throw exceptions. Callbacks can run on I/O +threads; UI applications should marshal updates to their UI thread. + +This fork is intended for source integration and recompilation. Diagnostic +fields are now snapshot properties, and legacy register array views are +read-only properties exposing mutable arrays. Previously compiled assemblies +that accessed those fields need to be rebuilt against the current library. + +## Server + +```csharp +await using var server = new ModbusServer { Port = 502 }; +server.holdingRegisters[1] = 123; +server.Listen(); +// Serve requests until the application requests shutdown. +await server.StopListeningAsync(); +``` + +`Listen()` binds before returning and reports startup errors directly to the +caller. `StopListening()` and `StopListeningAsync()` cancel pending I/O and close +accepted connections. A stopped server can be restarted. Configure its endpoint +and transport while stopped. `Port = 0` chooses an available port and updates +`Port` with the bound port, which is useful for local tests. + +Wire addresses are **zero-based**. Server tables retain EasyModbus's **one-based** +local indexing: `holdingRegisters[1]` corresponds to wire address `0`. +The complete wire address range `0..65535` is supported. Register reads retain +signed 16-bit values; register writes accept signed or unsigned 16-bit values. +Use table indexers to synchronize local access with protocol requests. Legacy +`localArray` views expose the mutable backing arrays and bypass that locking. + +Protocol logging retains the `ModbusProtocol` model. `ModbusLogData` returns a +snapshot of the latest 100 request/response records, with empty slots represented +by null. Optional `LogFileFilename` logging is process-wide and serialized. + +## Function codes + +| Code | Operation | +| --- | --- | +| 1 | Read coils | +| 2 | Read discrete inputs | +| 3 | Read holding registers | +| 4 | Read input registers | +| 5 | Write single coil | +| 6 | Write single register | +| 15 | Write multiple coils | +| 16 | Write multiple registers | +| 23 | Read/write multiple registers | + +## Repository layout + +`EasyModbus.slnx` is the current solution. The library lives in `EasyModbus`, tests +in `Tests/EasyModbus.Tests`, and the runnable example in `ConsoleAppStd`. The +library uses nullable reference types, C# 14 validated properties, cancellable +socket I/O, deterministic disposal, and explicit byte-order handling. + +Historical upstream Windows Forms applications and the .NET 5 and .NET 6 project +copies are retained as reference material. They are outside +the current solution and are not supported build targets for this fork. Use the +current library project rather than the old projects that link individual source +files. Git retains the original upstream solution and source history. + +When consumed as a Git submodule, repository-local `Directory.Build.props` and +`Directory.Build.targets` isolate the library from the host's product versioning +and deployment rules. Commit and push library changes before updating the host +repository's pinned submodule commit. + +The original upstream copyright and MIT license are preserved in [LICENSE](LICENSE). diff --git a/Tests/EasyModbus.Tests/EasyModbus.Tests.csproj b/Tests/EasyModbus.Tests/EasyModbus.Tests.csproj new file mode 100644 index 0000000..6504ba7 --- /dev/null +++ b/Tests/EasyModbus.Tests/EasyModbus.Tests.csproj @@ -0,0 +1,17 @@ + + + net10.0 + enable + enable + true + false + true + Debug;Release;Plugins + + + + + + + + diff --git a/Tests/EasyModbus.Tests/ModbusLoopbackTests.cs b/Tests/EasyModbus.Tests/ModbusLoopbackTests.cs new file mode 100644 index 0000000..bb94dc8 --- /dev/null +++ b/Tests/EasyModbus.Tests/ModbusLoopbackTests.cs @@ -0,0 +1,153 @@ +using System.Net; +using System.Net.Sockets; +using NUnit.Framework; + +namespace EasyModbus.Tests; + +[TestFixture] +[NonParallelizable] +public class ModbusLoopbackTests +{ + [Test] + [CancelAfter(10000)] + public void TcpClientReadsAndWritesRegistersAndCoils() + { + var server = new ModbusServer { LocalIPAddress = IPAddress.Loopback, Port = GetFreeTcpPort() }; + var client = new ModbusClient("127.0.0.1", server.Port) { ConnectionTimeout = 2000 }; + server.HoldingRegisters[1] = 1234; + server.InputRegisters[1] = 5678; + server.DiscreteInputs[1] = true; + server.Listen(); + + try + { + ConnectWhenReady(client); + Assert.That(client.ReadHoldingRegisters(0, 1), Is.EqualTo(new[] { 1234 })); + Assert.That(client.ReadInputRegisters(0, 1), Is.EqualTo(new[] { 5678 })); + Assert.That(client.ReadDiscreteInputs(0, 1), Is.EqualTo(new[] { true })); + + client.WriteSingleRegister(0, 4321); + Assert.That(client.ReadHoldingRegisters(0, 1), Is.EqualTo(new[] { 4321 })); + client.WriteMultipleRegisters(1, new[] { 100, 200 }); + Assert.That(client.ReadHoldingRegisters(1, 2), Is.EqualTo(new[] { 100, 200 })); + + client.WriteSingleCoil(0, true); + Assert.That(client.ReadCoils(0, 1), Is.EqualTo(new[] { true })); + client.WriteMultipleCoils(1, new[] { true, false, true }); + Assert.That(client.ReadCoils(1, 3), Is.EqualTo(new[] { true, false, true })); + } + finally + { + client.Disconnect(); + server.StopListening(); + } + } + + [Test] + [CancelAfter(10000)] + public void TcpServerCanStopAndRestartOnTheSamePort() + { + var server = new ModbusServer { LocalIPAddress = IPAddress.Loopback, Port = GetFreeTcpPort() }; + server.StopListening(); + + for (var attempt = 0; attempt < 2; attempt++) + { + var client = new ModbusClient("127.0.0.1", server.Port) { ConnectionTimeout = 2000 }; + server.Listen(); + try + { + ConnectWhenReady(client); + Assert.That(client.ReadHoldingRegisters(0, 1), Has.Length.EqualTo(1)); + } + finally + { + client.Disconnect(); + server.StopListening(); + } + } + + server.StopListening(); + var listener = new TcpListener(IPAddress.Loopback, server.Port); + try + { + listener.Start(); + } + finally + { + listener.Stop(); + } + } + + [Test] + [CancelAfter(10000)] + public void IdleUdpServerStopsAndReleasesItsPort() + { + int port; + using (var reservation = new UdpClient(new IPEndPoint(IPAddress.Loopback, 0))) + port = ((IPEndPoint)reservation.Client.LocalEndPoint!).Port; + + var server = new ModbusServer { LocalIPAddress = IPAddress.Loopback, Port = port, UDPFlag = true }; + server.Listen(); + try + { + Assert.That(() => CanBindUdpPort(port), Is.False.After(3000, 20)); + } + finally + { + server.StopListening(); + } + server.StopListening(); + using var rebound = new UdpClient(new IPEndPoint(IPAddress.Loopback, port)); + } + + [Test] + public void RegisterConversionsPreserveTexplorerValues() + { + const int integer = 123456789; + const float real = 123.25f; + Assert.That(ModbusClient.ConvertRegistersToInt(ModbusClient.ConvertIntToRegisters(integer)), Is.EqualTo(integer)); + Assert.That(ModbusClient.ConvertRegistersToFloat(ModbusClient.ConvertFloatToRegisters(real)), Is.EqualTo(real)); + var registers = ModbusClient.ConvertStringToRegisters("Texplorer "); + Assert.That(ModbusClient.ConvertRegistersToString(registers, 0, 10), Is.EqualTo("Texplorer ")); + } + + private static bool CanBindUdpPort(int port) + { + try + { + using var reservation = new UdpClient(new IPEndPoint(IPAddress.Loopback, port)); + return true; + } + catch (SocketException exception) when (exception.SocketErrorCode == SocketError.AddressAlreadyInUse) + { + return false; + } + } + + private static int GetFreeTcpPort() + { + var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + var port = ((IPEndPoint)listener.LocalEndpoint).Port; + listener.Stop(); + return port; + } + + private static void ConnectWhenReady(ModbusClient client) + { + var deadline = DateTime.UtcNow.AddSeconds(3); + while (true) + { + try + { + client.Connect(); + return; + } + catch (SocketException) when (DateTime.UtcNow < deadline) + { + client.Disconnect(); + Thread.Sleep(20); + } + } + } +} diff --git a/Tests/EasyModbus.Tests/ModbusModernizationTests.cs b/Tests/EasyModbus.Tests/ModbusModernizationTests.cs new file mode 100644 index 0000000..3e4ce31 --- /dev/null +++ b/Tests/EasyModbus.Tests/ModbusModernizationTests.cs @@ -0,0 +1,338 @@ +using System.Buffers.Binary; +using System.Net; +using System.Net.Sockets; +using EasyModbus.Exceptions; +using NUnit.Framework; + +namespace EasyModbus.Tests; + +[TestFixture, NonParallelizable, CancelAfter(10000)] +public class ModbusModernizationTests +{ + [TestCase(false)] + [TestCase(true)] + public async Task AsyncClientSupportsEveryFunctionOverTcpAndUdp(bool udp) + { + await using var server = new ModbusServer { LocalIPAddress = IPAddress.Loopback, Port = 0, UDPFlag = udp }; + server.InputRegisters[1] = -123; + server.DiscreteInputs[1] = true; + server.Listen(); + await using var client = new ModbusClient("127.0.0.1", server.Port) { UDPFlag = udp }; + await client.ConnectAsync(); + + Assert.That(await client.ReadInputRegistersAsync(0, 1), Is.EqualTo(new[] { -123 })); + Assert.That(await client.ReadDiscreteInputsAsync(0, 1), Is.EqualTo(new[] { true })); + await client.WriteSingleCoilAsync(0, true); + Assert.That(await client.ReadCoilsAsync(0, 1), Is.EqualTo(new[] { true })); + await client.WriteMultipleCoilsAsync(1, [true, false, true]); + Assert.That(await client.ReadCoilsAsync(1, 3), Is.EqualTo(new[] { true, false, true })); + await client.WriteSingleRegisterAsync(0, -1234); + Assert.That(await client.ReadHoldingRegistersAsync(0, 1), Is.EqualTo(new[] { -1234 })); + await client.WriteMultipleRegistersAsync(1, [123, 456]); + Assert.That(await client.ReadHoldingRegistersAsync(1, 2), Is.EqualTo(new[] { 123, 456 })); + Assert.That(await client.ReadWriteMultipleRegistersAsync(0, 3, 0, [100, 200, 300]), Is.EqualTo(new[] { 100, 200, 300 })); + + await client.WriteSingleRegisterAsync(65535, ushort.MaxValue); + Assert.That(await client.ReadHoldingRegistersAsync(65535, 1), Is.EqualTo(new[] { -1 })); + await client.WriteSingleCoilAsync(65535, true); + Assert.That(await client.ReadCoilsAsync(65535, 1), Is.EqualTo(new[] { true })); + Assert.That(client.ReceivedData.IsEmpty, Is.False); + Assert.That(client.SentData.IsEmpty, Is.False); + } + + [Test] + public async Task ConcurrentAsyncRequestsKeepTheirOwnResponses() + { + await using var server = NewServer(); + server.Listen(); + await using var client = new ModbusClient("127.0.0.1", server.Port); + await client.ConnectAsync(); + await Task.WhenAll(Enumerable.Range(1, 32).Select(async value => + { + var result = await client.ReadWriteMultipleRegistersAsync(0, 1, 0, [value]); + Assert.That(result, Is.EqualTo(new[] { value })); + })); + } + + [Test] + public async Task ClientReassemblesFragmentedResponse() + { + using var listener = StartPeer(); + var peer = ServePeerAsync(listener, async (stream, request) => + { + var response = RegisterReply(request, 0x1234); + foreach (var value in response) + { + await stream.WriteAsync(new[] { value }); + await Task.Delay(2); + } + }); + await using var client = new ModbusClient("127.0.0.1", PeerPort(listener)); + await client.ConnectAsync(); + Assert.That(await client.ReadHoldingRegistersAsync(0, 1), Is.EqualTo(new[] { 0x1234 })); + await peer; + } + + [Test] + public async Task ServerReassemblesFragmentedAndBatchedRequests() + { + await using var server = NewServer(); + server.HoldingRegisters[1] = 0x1234; + server.Listen(); + using var client = new TcpClient(); + await client.ConnectAsync(IPAddress.Loopback, server.Port); + var stream = client.GetStream(); + byte[] request = [0, 1, 0, 0, 0, 6, 1, 3, 0, 0, 0, 1]; + foreach (var value in request) + { + await stream.WriteAsync(new[] { value }); + await Task.Delay(2); + } + Assert.That(await ReadFrameAsync(stream), Is.EqualTo(RegisterReply(request, 0x1234))); + byte[] batch = [.. request, .. request]; + await stream.WriteAsync(batch); + Assert.That(await ReadFrameAsync(stream), Is.EqualTo(RegisterReply(request, 0x1234))); + Assert.That(await ReadFrameAsync(stream), Is.EqualTo(RegisterReply(request, 0x1234))); + } + + [TestCase("transaction")] + [TestCase("unit")] + [TestCase("protocol")] + [TestCase("function")] + [TestCase("count")] + public async Task ClientRejectsInvalidReplies(string field) + { + using var listener = StartPeer(); + var peer = ServePeerAsync(listener, async (stream, request) => + { + var response = RegisterReply(request, 42); + response[field switch + { + "transaction" => 0, + "unit" => 6, + "protocol" => 2, + "function" => 7, + _ => 8 + }] ^= 1; + await stream.WriteAsync(response); + }); + await using var client = new ModbusClient("127.0.0.1", PeerPort(listener)); + await client.ConnectAsync(); + Assert.ThrowsAsync(async () => await client.ReadHoldingRegistersAsync(0, 1)); + await peer; + } + + [Test] + public async Task PeerDisconnectDuringResponseIsReportedAndClosesClient() + { + using var listener = StartPeer(); + var peer = ServePeerAsync(listener, (stream, _) => stream.WriteAsync(new byte[] { 0, 1, 0 }).AsTask()); + await using var client = new ModbusClient("127.0.0.1", PeerPort(listener)); + await client.ConnectAsync(); + Assert.ThrowsAsync(async () => await client.ReadHoldingRegistersAsync(0, 1)); + Assert.That(client.Connected, Is.False); + await peer; + } + + [TestCase(false)] + [TestCase(true)] + public async Task TimeoutAndCancellationCloseIncompleteRequests(bool cancel) + { + using var listener = StartPeer(); + using var peerStop = new CancellationTokenSource(); + var requestArrived = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var peer = ServePeerAsync(listener, async (_, _) => + { + requestArrived.SetResult(); + try + { + await Task.Delay(Timeout.Infinite, peerStop.Token); + } + catch (OperationCanceledException) { } + }); + await using var client = new ModbusClient("127.0.0.1", PeerPort(listener)) { ConnectionTimeout = cancel ? 2000 : 100 }; + await client.ConnectAsync(); + using var cancellation = new CancellationTokenSource(); + var read = client.ReadHoldingRegistersAsync(0, 1, cancellation.Token); + await requestArrived.Task; + if (cancel) + cancellation.Cancel(); + try + { + if (cancel) + Assert.CatchAsync(async () => await read); + else + Assert.ThrowsAsync(async () => await read); + Assert.That(client.Connected, Is.False); + } + finally { peerStop.Cancel(); await peer; } + } + + [Test] + public async Task CancelingQueuedRequestDoesNotInterruptCurrentRequest() + { + using var listener = StartPeer(); + var arrived = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var reply = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var peer = ServePeerAsync(listener, async (stream, request) => + { + arrived.SetResult(); + await reply.Task; + await stream.WriteAsync(RegisterReply(request, 42)); + }); + await using var client = new ModbusClient("127.0.0.1", PeerPort(listener)); + await client.ConnectAsync(); + var current = client.ReadHoldingRegistersAsync(0, 1); + await arrived.Task; + using var cancellation = new CancellationTokenSource(); + var queued = client.ReadHoldingRegistersAsync(1, 1, cancellation.Token); + cancellation.Cancel(); + try + { + Assert.CatchAsync(async () => await queued); + } + finally { reply.TrySetResult(); } + Assert.That(await current, Is.EqualTo(new[] { 42 })); + await peer; + } + + [Test] + public async Task ModbusExceptionsKeepConnectionUsable() + { + await using var server = NewServer(); + server.FunctionCode3Disabled = true; + server.Listen(); + await using var client = new ModbusClient("127.0.0.1", server.Port); + await client.ConnectAsync(); + Assert.ThrowsAsync(async () => await client.ReadHoldingRegistersAsync(0, 1)); + Assert.That(await client.ReadInputRegistersAsync(0, 1), Is.EqualTo(new[] { 0 })); + Assert.That(client.Connected, Is.True); + } + + [Test] + public async Task MalformedWritesDoNotPartiallyChangeRegisters() + { + await using var server = NewServer(); + server.HoldingRegisters[1] = 77; + server.Listen(); + using var client = new TcpClient(); + await client.ConnectAsync(IPAddress.Loopback, server.Port); + var stream = client.GetStream(); + await stream.WriteAsync(new byte[] { 0, 1, 0, 0, 0, 9, 1, 16, 0, 0, 0, 2, 4, 0, 42 }); + Assert.That(await ReadFrameAsync(stream), Is.EqualTo(new byte[] { 0, 1, 0, 0, 0, 3, 1, 0x90, 3 })); + Assert.That(server.HoldingRegisters[1], Is.EqualTo(77)); + await stream.WriteAsync(new byte[] { 0, 2, 0, 0, 0, 2, 1, 0x80 }); + Assert.That(await ReadFrameAsync(stream), Is.EqualTo(new byte[] { 0, 2, 0, 0, 0, 3, 1, 0x80, 1 })); + await stream.WriteAsync(new byte[] { 0, 3, 0, 0, 0, 6, 1, 3, 0, 0, 0, 1 }); + Assert.That((await ReadFrameAsync(stream))[^1], Is.EqualTo(77)); + } + + [Test] + public async Task StoppingServerReleasesIdleConnections() + { + await using var server = NewServer(); + server.Listen(); + using var client = new TcpClient(); + await client.ConnectAsync(IPAddress.Loopback, server.Port); + Assert.That(() => server.NumberOfConnections, Is.EqualTo(1).After(2000, 10)); + await server.StopListeningAsync().WaitAsync(TimeSpan.FromSeconds(2)); + Assert.That(server.IsListening, Is.False); + Assert.That(server.NumberOfConnections, Is.Zero); + Assert.That(await client.GetStream().ReadAsync(new byte[1]), Is.Zero); + } + + [Test] + public void BindFailuresAreSynchronousAndServerCanRetry() + { + using var listener = StartPeer(); + using var server = NewServer(); + server.Port = PeerPort(listener); + Assert.Throws(server.Listen); + Assert.That(server.IsListening, Is.False); + listener.Stop(); + Assert.DoesNotThrow(server.Listen); + } + + [Test] + public async Task NotificationCanStopItsOwnServerWithoutDeadlock() + { + await using var server = NewServer(); + server.HoldingRegistersChanged += (_, _) => server.StopListening(); + server.Listen(); + await using var client = new ModbusClient("127.0.0.1", server.Port); + await client.ConnectAsync(); + Assert.ThrowsAsync(async () => await client.WriteSingleRegisterAsync(0, 42).WaitAsync(TimeSpan.FromSeconds(2))); + Assert.That(server.IsListening, Is.False); + } + + [Test] + public async Task ConnectionNotificationCanStopItsOwnServerWithoutDeadlock() + { + await using var server = NewServer(); + server.NumberOfConnectedClientsChanged += () => + { + if (server.NumberOfConnections == 1) + server.StopListening(); + }; + server.Listen(); + using var client = new TcpClient(); + await client.ConnectAsync(IPAddress.Loopback, server.Port); + Assert.That(await client.GetStream().ReadAsync(new byte[1]).AsTask().WaitAsync(TimeSpan.FromSeconds(2)), Is.Zero); + Assert.That(server.IsListening, Is.False); + } + + [Test] + public async Task DisposalIsIdempotentAndPreventsReconnection() + { + var server = NewServer(); + server.Listen(); + var client = new ModbusClient("127.0.0.1", server.Port); + await client.ConnectAsync(); + await client.DisposeAsync(); + client.Dispose(); + Assert.That(client.Connected, Is.False); + Assert.ThrowsAsync(async () => await client.ConnectAsync()); + Assert.ThrowsAsync(async () => await client.ReadHoldingRegistersAsync(0, 1)); + await server.DisposeAsync(); + server.Dispose(); + Assert.Throws(server.Listen); + } + + [TestCase(-1, 1)] + [TestCase(65536, 1)] + [TestCase(0, 0)] + [TestCase(0, -1)] + [TestCase(0, 126)] + [TestCase(65535, 2)] + public void ClientValidatesAddressRangesBeforeIo(int address, int quantity) + { + using var client = new ModbusClient(); + Assert.ThrowsAsync(async () => await client.ReadHoldingRegistersAsync(address, quantity)); + } + + private static ModbusServer NewServer() => new() { LocalIPAddress = IPAddress.Loopback, Port = 0 }; + private static TcpListener StartPeer() + { + var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + return listener; + } + private static int PeerPort(TcpListener listener) => ((IPEndPoint)listener.LocalEndpoint).Port; + private static async Task ServePeerAsync(TcpListener listener, Func respond) + { + using var connection = await listener.AcceptTcpClientAsync(); + var stream = connection.GetStream(); + await respond(stream, await ReadFrameAsync(stream)); + } + private static byte[] RegisterReply(byte[] request, ushort value) => + [request[0], request[1], 0, 0, 0, 5, request[6], 3, 2, (byte)(value >> 8), (byte)value]; + private static async Task ReadFrameAsync(Stream stream) + { + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(3)); + var header = new byte[6]; + await stream.ReadExactlyAsync(header, timeout.Token); + var payload = new byte[BinaryPrimitives.ReadUInt16BigEndian(header.AsSpan(4))]; + await stream.ReadExactlyAsync(payload, timeout.Token); + return [.. header, .. payload]; + } +} diff --git a/Tests/EasyModbus.Tests/RegisterConversionTests.cs b/Tests/EasyModbus.Tests/RegisterConversionTests.cs new file mode 100644 index 0000000..f3aa66d --- /dev/null +++ b/Tests/EasyModbus.Tests/RegisterConversionTests.cs @@ -0,0 +1,70 @@ +using NUnit.Framework; + +namespace EasyModbus.Tests; + +[TestFixture] +public class RegisterConversionTests +{ + [TestCase(ModbusClient.RegisterOrder.LowHigh)] + [TestCase(ModbusClient.RegisterOrder.HighLow)] + public void NumericConversionsPreserveBitsInEitherWordOrder(ModbusClient.RegisterOrder order) + { + foreach (var value in new[] { int.MinValue, -1, 0, 0x12345678, int.MaxValue }) + Assert.That(ModbusClient.ConvertRegistersToInt(ModbusClient.ConvertIntToRegisters(value, order), order), Is.EqualTo(value)); + foreach (var value in new[] { long.MinValue, -1, 0, 0x123456789ABCDEF0, long.MaxValue }) + Assert.That(ModbusClient.ConvertRegistersToLong(ModbusClient.ConvertLongToRegisters(value, order), order), Is.EqualTo(value)); + foreach (var bits in new[] { int.MinValue, 0, 0x3F800000, 0x7F800000, 0x7FC01234 }) + { + var registers = ModbusClient.ConvertFloatToRegisters(BitConverter.Int32BitsToSingle(bits), order); + Assert.That(BitConverter.SingleToInt32Bits(ModbusClient.ConvertRegistersToFloat(registers, order)), Is.EqualTo(bits)); + } + foreach (var bits in new[] { long.MinValue, 0, 0x3FF0000000000000, 0x7FF0000000000000, 0x7FF8123456789ABC }) + { + var registers = ModbusClient.ConvertDoubleToRegisters(BitConverter.Int64BitsToDouble(bits), order); + Assert.That(BitConverter.DoubleToInt64Bits(ModbusClient.ConvertRegistersToDouble(registers, order)), Is.EqualTo(bits)); + } + } + + [Test] + public void RegisterOrderMatchesKnownWireValues() + { + Assert.That(ModbusClient.ConvertIntToRegisters(0x12345678), Is.EqualTo(new[] { 0x5678, 0x1234 })); + Assert.That(ModbusClient.ConvertIntToRegisters(0x12345678, ModbusClient.RegisterOrder.HighLow), Is.EqualTo(new[] { 0x1234, 0x5678 })); + Assert.That(ModbusClient.ConvertFloatToRegisters(1.0f), Is.EqualTo(new[] { 0, 0x3F80 })); + Assert.That(ModbusClient.ConvertDoubleToRegisters(1.0), Is.EqualTo(new[] { 0, 0, 0, 0x3FF0 })); + Assert.That(ModbusClient.ConvertRegistersToInt([-1, -1]), Is.EqualTo(-1)); + } + + [TestCase("")] + [TestCase("A")] + [TestCase("ABC")] + [TestCase("Texplorer ")] + public void AsciiStringsRoundTripIncludingOddLengths(string text) + { + var registers = ModbusClient.ConvertStringToRegisters(text); + Assert.That(ModbusClient.ConvertRegistersToString(registers, 0, text.Length), Is.EqualTo(text)); + } + + [Test] + public void StringOffsetsAndLengthAreChecked() + { + Assert.That(ModbusClient.ConvertRegistersToString([0, 0x4241, 0x4443], 1, 3), Is.EqualTo("ABC")); + Assert.Throws(() => ModbusClient.ConvertRegistersToString([0], -1, 1)); + Assert.Throws(() => ModbusClient.ConvertRegistersToString([0], 0, 3)); + Assert.Throws(() => ModbusClient.ConvertRegistersToFloat([0])); + Assert.Throws(() => ModbusClient.ConvertRegistersToInt(null!)); + } + + [Test] + public void CrcMatchesPublishedRtuFrameAndRejectsCorruption() + { + byte[] request = [1, 3, 0, 0, 0, 10]; + Assert.That(ModbusClient.CalculateCRC(request), Is.EqualTo(0xCDC5)); + Assert.That(ModbusClient.CalculateCRC(request, 6, 0), Is.EqualTo(0xCDC5)); + byte[] frame = [.. request, 0xC5, 0xCD]; + Assert.That(ModbusClient.DetectValidModbusFrame(frame, frame.Length), Is.True); + frame[3] = 1; + Assert.That(ModbusClient.DetectValidModbusFrame(frame, frame.Length), Is.False); + Assert.That(ModbusClient.DetectValidModbusFrame([], 0), Is.False); + } +} diff --git a/global.json b/global.json new file mode 100644 index 0000000..d46d21e --- /dev/null +++ b/global.json @@ -0,0 +1,7 @@ +{ + "sdk": { + "version": "10.0.100", + "rollForward": "latestFeature", + "allowPrerelease": false + } +}