176 Commits

Author SHA1 Message Date
Michael Croes
ab6308eacd Merge pull request #506 from bonk-dev/s5-date
Add support for reading/writing the legacy DATE (IEC date) datatype
2023-09-07 21:26:25 +02:00
Michael Croes
130eeadbd8 Merge branch 'main' into s5-date 2023-09-07 21:20:54 +02:00
Michael Croes
76a7ea04f7 Merge pull request #507 from mycroes/clock
Add support for reading and writing PLC clock
2023-09-05 21:25:25 +02:00
Michael Croes
4764c997ed refactor: Replace DateTime.Length with Plc.DateTimeLength in Plc.Clock 2023-09-04 22:20:31 +02:00
Michael Croes
cb24e9a046 feat: Implement clock write support 2023-09-04 22:15:52 +02:00
Michael Croes
10315b4b4c style: Add missing space in WriteClockAsync summary 2023-09-04 21:55:34 +02:00
Michael Croes
0774e124bf test: Fix comments in write clock messages 2023-09-04 21:55:06 +02:00
Michael Croes
1ebffe08e7 test: Add Write_Clock_Value test 2023-08-31 19:55:57 +02:00
Michael Croes
f419df4d73 feat: Stub PLC WriteClock methods 2023-08-31 19:55:41 +02:00
Michael Croes
1969aac1b2 refactor: Rename WriteSzlRequestHeader to WriteUserDataRequest 2023-08-31 19:36:00 +02:00
Michael Croes
2f2dcf7281 test: Raise ReadClock timeout to 1 second 2023-08-29 21:38:01 +02:00
Michael Croes
07325db2fa feat: Implement clock reading 2023-08-29 21:34:09 +02:00
Michael Croes
eada47cd24 refactor(PLCHelpers): Extract WriteSzlRequestHeader 2023-08-29 20:41:55 +02:00
Michael Croes
5e1ac8c7bf test(ReadClock): Use template parameters for PDU bytes 2023-08-29 19:42:59 +02:00
Michael Croes
13544a1bcf test: Add ReadClock test 2023-08-23 23:03:45 +02:00
Michael Croes
6fc526b886 Stub PLC ReadClock methods 2023-08-23 22:40:57 +02:00
bonk-dev
f227ad4b53 Expose IecMinDate and IecMaxDate as properties 2023-08-23 12:03:22 +02:00
Dawid Pągowski
e4cc42fa51 Add support for serializing IEC date 2023-08-23 01:04:23 +02:00
Dawid Pągowski
689e7ffd96 Increase the maximum date
The spec goes up to a full 2168 year, but the PLC date type goes up to 2169 June 06 which is represented by 65535 (max ushort value).
2023-08-23 00:53:29 +02:00
Dawid Pągowski
8087b8d315 Change the thrown exceptions to ArgumentOutOfRangeException 2023-08-23 00:43:17 +02:00
Dawid Pągowski
a55ceba679 Add IEC Date VarType support to PLCHelpers.cs 2023-08-23 00:38:24 +02:00
Dawid Pągowski
eb1fad9333 Add IEC date DataType 2023-08-23 00:27:55 +02:00
Michael Croes
0de9364dee Merge pull request #504 from mycroes/remove-appveyor-config
Remove leftover appveyor.yml
2023-08-22 15:49:38 +02:00
Michael Croes
9380ea85c3 chore: Remove leftover appveyor.yml 2023-08-21 21:23:46 +02:00
Michael Croes
22451bc440 Merge pull request #501 from Himmelt/add_set_bit
Add SetBit method to modify one bit of a byte
2023-08-18 20:48:32 +02:00
Himmelt
e98ce005c5 update param description 2023-08-18 16:50:53 +08:00
Himmelt
11a40cc5e3 update summary 2023-08-18 16:37:50 +08:00
Himmelt
f79286b2d0 Apply suggestions from code review
Co-authored-by: Michael Croes <mycroes@gmail.com>
2023-08-18 15:58:35 +08:00
Himmelt
fadd7d0cb3 update params descriptions and change param name from "bitPosition" to "index" 2023-08-17 13:33:07 +08:00
Himmelt
652ff3a9bb Update S7.Net/Conversion.cs
Co-authored-by: Günther Foidl <gue@korporal.at>
2023-08-16 17:19:53 +08:00
Himmelt
9c0fea721a Update S7.Net/Conversion.cs
Co-authored-by: Günther Foidl <gue@korporal.at>
2023-08-16 17:18:33 +08:00
Himmelt
2ec73224c1 Add SetBit method to modify one bit of a byte 2023-08-15 18:08:10 +08:00
Michael Croes
a8ef47b475 Merge pull request #490 from bonk-dev/timespan
Added support for serializing TimeSpan
2023-08-04 08:55:08 +02:00
Michael Croes
55aa06a1fc Merge branch 'main' into timespan 2023-08-03 21:55:20 +02:00
Michael Croes
7e631a713f Merge pull request #498 from S7NetPlus/github-actions-logger
chore: Update GitHubActionsTestLogger
2023-08-03 21:52:03 +02:00
Michael Croes
0797c5858f chore: Update GitHubActionsTestLogger 2023-08-03 21:45:46 +02:00
Michael Croes
f1ae0ea084 Merge pull request #491 from S7NetPlus/plc-status
Plc status
2023-08-02 19:36:58 +02:00
Michael Croes
addf6068bb style(ReadStatusAsync): Move opening brace to new line 2023-08-01 22:56:08 +02:00
Michael Croes
970e9d4395 feat: Add sync version of ReadStatus 2023-08-01 22:55:19 +02:00
Michael Croes
c3934c3493 fix(ReadStatusAsync): Fix index of status in response message 2023-08-01 22:52:44 +02:00
Michael Croes
e5823f2806 doc(ReadStatusAsync): Add missing cancellationToken documentation 2023-08-01 22:52:10 +02:00
Michael Croes
97e27ccc2b chore(ReadStatusAsync): Make cancellationToken optional 2023-08-01 22:51:47 +02:00
Michael Croes
9b1faa0123 test: Add test for reading PLC status 2023-08-01 22:50:50 +02:00
Michael Croes
54dadec75a test: Extract connection open templates 2023-08-01 22:50:21 +02:00
Michael Croes
8b8ad13464 test: Add ConnectionOpen communication test 2023-07-31 23:58:15 +02:00
Michael Croes
714ac62ab1 test: Add CommunicationSequence 2023-07-31 23:57:38 +02:00
Michael Croes
088cd0a4a8 Merge branch 'main' into plc-status 2023-07-29 23:12:22 +02:00
Michael Croes
361db8be9d Merge pull request #494 from S7NetPlus/warnings
Cleanup of warnings
2023-07-29 23:07:23 +02:00
Michael Croes
e26860b0c0 build: Extend NoWarn
- Amend existing NoWarn if set
- Ignore out of support target framework warning
2023-07-28 23:57:55 +02:00
Michael Croes
6e103cea63 fix: Fix warnings in Struct 2023-07-28 23:55:12 +02:00
Michael Croes
c5023c10e4 style: Cleanup line endings in S7String 2023-07-28 23:54:15 +02:00
Michael Croes
b61ac32913 fix: Permit nulls in string ToByteArray conversions 2023-07-28 23:52:57 +02:00
Michael Croes
b27e1c9083 build: Set LangVersion to latest 2023-07-28 23:51:09 +02:00
Michael Croes
71f7f8b400 fix: Fix nullability warning in String.ToByteArray 2023-07-27 00:16:40 +02:00
Michael Croes
4aca9e4e53 fix: Fix remaining nullability warnings in Class 2023-07-27 00:11:18 +02:00
Michael Croes
0bb7c5351a ci: Update actions to Node 16 compatible versions 2023-07-26 23:59:21 +02:00
Michael Croes
c3f86c32a2 fix: Fix nullability warnings in Class.FromBytes 2023-07-26 23:52:28 +02:00
Michael Croes
3d0dd693ba fix: Fix nullability warnings in Class.ToBytes 2023-07-26 23:47:32 +02:00
Michael Croes
8ad25033d5 chore: Fix xmldoc warnings 2023-07-26 23:38:32 +02:00
Michael Croes
12e180ea2d build: Don't warn on missing xmldoc
While definitely desirable, at least temporarily disabled in order to
find other warnings.
2023-07-26 23:14:38 +02:00
Michael Croes
5891a30c5d Merge branch 'main' into plc-status 2023-07-25 23:25:54 +02:00
Michael Croes
b3077b27e7 Merge pull request #493 from S7NetPlus/testing
GitHub actions test improvements
2023-07-25 23:24:43 +02:00
Michael Croes
8126018afd test: Fix target framework*s* specification 2023-07-25 23:17:25 +02:00
Michael Croes
4e4071f07f test: Only target net462 on Windows 2023-07-24 22:04:18 +02:00
Michael Croes
534d9fd69d fix: Remove leftover test-framework in runner name 2023-07-24 21:41:32 +02:00
Michael Croes
8da292ad2f ci: Run tests against all target frameworks on all OS-es 2023-07-24 21:32:49 +02:00
Michael Croes
019aeb26dc Merge branch 'main' into plc-status
# Conflicts:
#	S7.Net.UnitTest/S7.Net.UnitTest.csproj
2023-07-23 23:34:03 +02:00
Michael Croes
670fb70b78 Merge pull request #492 from S7NetPlus/testing
Fix GH actions test runs
2023-07-23 23:29:46 +02:00
Michael Croes
aa15145184 fix: Install dotnet 7.x always 2023-07-23 23:20:18 +02:00
Michael Croes
12ea402769 fix: Remove separate restore step 2023-07-23 23:10:21 +02:00
Michael Croes
18402604d1 feat: Add net462, net6.0 and net7.0 targeting to S7NetPlus
This should be the actual baseline, which is also what the test project
targets now.
2023-07-23 23:04:03 +02:00
Michael Croes
53f651a482 fix: Constrain dotnet restore to matrix runtime 2023-07-23 22:58:53 +02:00
Michael Croes
7558b9a691 fix: Retarget test project to net462, net6.0 and net7.0
These are the frameworks currently used in the GitHub workflow, when
missing the tests aren't executed and the job will succeed nonetheless.
2023-07-23 22:53:11 +02:00
Michael Croes
3185d1fccf fix: Revert Ubuntu target back to 20.04 for snap7 ppa availability 2023-07-23 22:48:52 +02:00
Michael Croes
0d9ccea11b feat: Add Plc.ReadStatusAsync 2023-07-22 22:53:45 +02:00
Michael Croes
1fc6899905 feat: Add WriteSzlReadRequest 2023-07-21 22:28:22 +02:00
Michael Croes
18c3883dc0 feat: Add WriteUserDataHeader 2023-07-21 22:27:30 +02:00
Michael Croes
1f26833244 fix: Add missing xmldoc nodes in PLCHelpers 2023-07-21 21:26:13 +02:00
Michael Croes
7d212134e3 refactor: Rename BuildHeaderPackage to WriteReadHeader 2023-07-21 21:23:00 +02:00
Michael Croes
38b26e0ce1 fix: Update test project target frameworks
Ensures tests are actually run on GitHub
2023-07-20 21:39:58 +02:00
Michael Croes
cf94f8ad11 fix(PLCHelpers): Fix errors from refactors 2023-07-20 21:25:24 +02:00
Michael Croes
8becc562a8 refactor: Cleanup inline math in BuildHeaderPackage
- Remove unnecessary parentheses
- Use constant value first in multiplication
2023-07-19 23:32:00 +02:00
Michael Croes
296ead69c7 refactor: Use Word.ToByteArray in WriteTpktHeader 2023-07-19 23:30:02 +02:00
Michael Croes
ebf3da6280 refactor: Extract WriteS7Header 2023-07-19 23:29:11 +02:00
Michael Croes
42194aa788 refactor: Extract WriteDataHeader 2023-07-19 23:19:32 +02:00
Michael Croes
9c8b453326 refactor: Extract WriteTpktHeader 2023-07-19 23:18:26 +02:00
Dawid Pągowski
49e4d3369a Add TimeSpan serialization to Struct 2023-07-19 21:12:54 +02:00
Dawid Pągowski
ee06bec0fb Fix the documentation 2023-07-19 21:04:07 +02:00
Dawid Pągowski
05ccb05f3a Added TimeSpan tests 2023-07-19 20:57:14 +02:00
Dawid Pągowski
0d2817661e Add S7 Time type (C# TimeSpan)
Adds the S7 TIME (IEC) type (32 bits long)
It is deserialized to C# TimeSpan and serialized as S7 DInt.
2023-07-19 20:30:32 +02:00
Michael Croes
e869d19587 Merge pull request #487 from mycroes/ci
Update ci workflow
2023-06-27 17:08:34 +02:00
Michael Croes
e7194bc470 Update OS, SDK and target versions 2023-06-27 17:00:25 +02:00
Michael Croes
5bc2c6c5e7 Add create_nuget and deploy jobs 2023-06-27 16:49:19 +02:00
Michael Croes
77dcb1778b Merge pull request #485 from dylandrush/484_Public_PLCExceptions
Made all exceptions public
2023-06-19 14:52:02 +02:00
DRUSH12
14053e342a Made all exceptions public 2023-06-19 06:14:14 -04:00
Michael Croes
ab3bd87701 chore: Delete GitVersion configuration
Rely on builtin defaults from now on.
2023-05-30 22:21:12 +02:00
Michael Croes
bc7c27e1d4 Release S7NetPlus 0.18.0
Release highlights:
- Add Memory/Span support from 0.17.0 to < net5 targets
2023-05-30 21:47:40 +02:00
Michael Croes
f0256fd0cb Merge pull request #483 from gfoidl/span-memory
Use System.Memory for < .NET 5 and avoid (some) unnecessary allocations
2023-05-30 21:44:33 +02:00
Günther Foidl
209148ab02 Use System.Memory for < .NET 5 and avoid (some) unnecessary allocations 2023-05-30 17:25:25 +02:00
Michael Croes
2fc9eaade3 Release S7NetPlus 0.17.0
Release highlights:
- Add Read-/WriteBytes overloads for Span<byte> and Memory<byte>
2023-05-30 12:19:39 +02:00
Michael Croes
ab70bfb041 Merge pull request #482 from ArgusMagnus/add_span_overloads
add Read/WriteBytes(Async) overloads accepting Span<byte>/Memory<byte> for .NET5 or greater
2023-05-30 12:14:19 +02:00
ArgusMagnus
e277cf6e6c add Read/WriteBytes(Async) overloads accepting Span<byte>/Memory<byte> for .NET5 or greater 2023-05-30 10:47:38 +02:00
Michael Croes
43b29825a4 Release S7NetPlus 0.16.0
Release highlights:
- Fix UInt32 reads in classes
- Add string support for classes
2022-12-10 21:22:16 +01:00
Michael Croes
6aa0133081 Merge pull request #415 from scamille/fb-fixClassUint32
Fix ReadClass for UInt32
2022-12-10 21:12:28 +01:00
Michael Croes
868e719b78 Merge remote-tracking branch 's7netplus/develop' into fb-fixClassUint32
# Conflicts:
#	S7.Net/Types/Class.cs
2022-12-10 21:09:29 +01:00
Michael Croes
3833d29c0e Merge pull request #459 from mycroes/test-workflow
ci: Run test on ubuntu-20.04 due to lack of snap7 on newer ubuntu
2022-12-10 21:01:21 +01:00
Michael Croes
144f814794 Merge branch 'develop' into test-workflow 2022-12-10 20:58:29 +01:00
Michael Croes
82aaf7e2cb Merge pull request #458 from MCPC10/StringSupportForClass
Added support for string/wstring in a class
2022-12-10 20:58:10 +01:00
Michael Croes
f47918946d ci: Run test on ubuntu-20.04 due to lack of snap7 on newer ubuntu 2022-12-10 20:51:44 +01:00
Mike Cremer
142f1ba90e Added support string/wstring for class type 2022-12-10 18:59:25 +01:00
Michael Croes
d99d0d0e6f Release S7NetPlus 0.15.0
Release highlights:
- Add flowed cancellation to ConnectAsync
2022-11-08 11:22:47 +01:00
Michael Croes
ce9f9f9e08 Merge pull request #423 from gfoidl/openasync_cancellation
Flowed cancellation token to TcpClient.ConnectAsync in .NET 5.0 target
2022-11-08 11:19:37 +01:00
Michael Croes
ea1140314b Merge branch 'develop' into openasync_cancellation 2022-11-08 11:13:25 +01:00
Michael Croes
e3fad0b94f Release S7NetPlus 0.14.0
Release highlights:
- Support setting the Encoding for S7String
2022-06-17 23:14:48 +02:00
Michael Croes
7f76d4fc5a Merge pull request #435 from ismdiego/develop
Allow changing the default Encoding used in S7String
2022-06-17 23:12:43 +02:00
diego
ec554ddb59 Better stringEncoding initialization, as per code review comments 2022-06-17 11:23:58 +02:00
diego
2ecd2c6b49 Changes following code review 2022-06-17 11:08:09 +02:00
diego
d808ea5eb6 Give the option of changing the Encoding used to serialize and deserialize S7String, instead of always using Encoding.ASCII 2022-06-16 17:21:23 +02:00
Günther Foidl
5d3f01e59e Updated AppVeyor image to VS 2022 to allow better conditional compilation 2021-12-26 19:26:44 +01:00
Günther Foidl
9c3f95ce73 Flowed cancellation token to TcpClient.ConnectAsync in .NET 5.0 target 2021-12-26 19:26:04 +01:00
Serge Camille
12281ec802 Fix ReadClass for Uint32
Use consistent DWord conversion for both Int32 and UInt32. Unfortunately there is no Span or even a FromByteArray function accepting a offset, so just use the same Array.Copy falls used for double.
2021-10-04 18:59:05 +02:00
Serge Camille
8df1a9c8cb Add unit test for ReadClass uint32 bug.
https://github.com/S7NetPlus/s7netplus/issues/414
2021-10-04 18:53:13 +02:00
Michael Croes
946536c2d6 Release S7NetPlus 0.13.0
Release highlights:
- Change default TSAP for S7 200
- Add S7 200 Smart support
- Add support for custom TSAP's
- Align data to even bytes when parsing responses from class and struct
  reads
- Close connection on IOException
- Add cancellation for Read/Write
- Set default Read-/WriteTimeout to 10 seconds
- Cleanup of sync helper methods
2021-06-21 21:52:25 +02:00
Michael Croes
b475aee2e7 Merge pull request #401 from scamille/test-ConnectionClose
Add unit test to ensure a connection has been properly closed
2021-06-10 17:04:42 +02:00
Serge Camille
82a745c972 Merge branch 'develop' into test-ConnectionClose 2021-06-08 22:53:30 +02:00
Serge Camille
74fecad48d Remove cancel timeouts. 2021-06-08 22:47:12 +02:00
Michael Croes
37c63cea8e Merge pull request #402 from mycroes/default-timeout
Default ReadTimeout and WriteTimeout to 10 seconds
2021-06-07 22:23:57 +02:00
Michael Croes
36c4564f5e Default ReadTimeout and WriteTimeout to 10 seconds 2021-06-07 22:19:23 +02:00
Michael Croes
0c0200d12d Merge pull request #400 from scamille/tests-taskCanceled
Fix Cancellation test.
2021-06-07 22:03:02 +02:00
Michael Croes
6e861d2f00 Merge branch 'develop' into tests-taskCanceled 2021-06-07 22:00:52 +02:00
Michael Croes
372f4a5dcb Merge pull request #398 from mycroes/cleanup-sync
Cleanup sync
2021-06-07 21:26:41 +02:00
Serge Camille
0d87dbf3c6 Add unit test to ensure a connection has been properly closed
If cancelled during data transmission, #349 adds code to ensure that the connection automatically gets cancelled.

Add inerted test to ensure that cancellation before sending data does not result in a cancellation.
2021-06-07 14:49:06 +02:00
Serge Camille
15f94cd7bf Fix Cancellation test. 2021-06-07 14:13:04 +02:00
Michael Croes
36b59a2926 Cleanup whitespace, usings 2021-06-06 23:20:19 +02:00
Michael Croes
8d081859da Remove unused sync methods 2021-06-06 23:19:56 +02:00
Michael Croes
2302819650 Merge pull request #349 from scamille/closeConnectionIOException
Close connection on IOExceptions.
2021-06-06 22:58:27 +02:00
Michael Croes
d65b83660f Merge branch 'develop' into closeConnectionIOException 2021-06-06 22:56:17 +02:00
Michael Croes
77b2ecfd45 Merge pull request #397 from scamille/multipleVarsAlignment
Fix ReadMultipleVars alignment bug
2021-06-06 22:51:03 +02:00
Michael Croes
b0a6a2375f Merge branch 'develop' into multipleVarsAlignment 2021-06-06 22:49:33 +02:00
Michael Croes
14823bca96 Merge pull request #395 from mycroes/s7-200-cr
Change S7 200 remote TSAP to 10.01
2021-06-06 22:45:53 +02:00
Serge Camille
53045c5952 Close connection on IOExceptions.
The idea behind this is that if we receive a response which does not conform to the underlying protocol specification (with all the TCP checks in place!), we are in a weird/corrupt state and it is better to just close the connection.
2021-06-06 22:40:04 +02:00
Michael Croes
677d2941e1 Apply S7 200 TSAP change to relocated code 2021-06-06 22:33:12 +02:00
Michael Croes
66b693676c Merge branch 'develop' into s7-200-cr 2021-06-06 22:32:41 +02:00
Michael Croes
4542bbedb2 Merge pull request #396 from mycroes/tsap
Refactor TSAP related code
2021-06-06 22:24:29 +02:00
Serge Camille
a4b6a360fe ParseDataIntoDataItems needs to always align the response address to a even value after each data item. 2021-06-06 22:16:59 +02:00
Serge Camille
0bef6bc9ff Add unit test for the problem. 2021-06-06 21:59:39 +02:00
Michael Croes
cbe04fbfb4 Merge branch 'develop' into tsap 2021-06-06 21:19:17 +02:00
Michael Croes
0b4c79cb08 Merge pull request #319 from scamille/githubActions2
GitHub actions
2021-06-06 21:14:26 +02:00
Serge Camille
5c24e801fd Add Actions Nuget Cache (#2)
* Try out action cache

* fix syntax error

* Now lets see what happens if it hits the cache
2021-06-05 18:50:28 +02:00
Serge Camille
bcde65120c Github Actions Net5.0 (#1)
* Try integrating dotnet setup version into build matrix.

* Another attempt

* change matrix.

* don't add dotnet-sdk as main matrix variable

* remove test framework as well.

* or maybe not

* Fix copy paste mixup
2021-06-05 18:37:35 +02:00
Serge Camille
4541a7ebb7 Try adjusting the dotnet setup version. 2021-06-05 18:11:06 +02:00
Serge Camille
fc9c33fdaf Add Net5.0 to test project as well. 2021-06-05 17:59:18 +02:00
Serge Camille
a23408d67e Add Net5.0 to test matrix 2021-06-05 17:58:05 +02:00
Serge Camille
adb55dc80f Merge branch 'develop' into githubActions2 2021-06-05 17:52:59 +02:00
Michael Croes
2fae2c01d5 Add TsapPair support to PLC
Add support for custom addressing by supplying a TsapPair to the PLC.
CPU, Rack and Slot properties are still present to preserve backwards
compatibility and to support alternate functionality based on the PLC
type.
2021-06-04 22:25:05 +02:00
Michael Croes
6465e3c8c7 Move GetDefaultTsapPair to TsapPair class 2021-06-04 22:01:40 +02:00
Michael Croes
fcd61c1236 Add CpuType.S7200Smart 2021-06-04 21:46:42 +02:00
Michael Croes
616dc1094c Refactor TSAP related code 2021-06-04 21:45:51 +02:00
Michael Croes
70bc1499ef ConnectionRequestTest: Cleanup trailing whitespace 2021-06-02 23:03:23 +02:00
Michael Croes
fd9aeb5b3b Fix unit test for S7 200 2021-06-02 23:03:06 +02:00
Michael Croes
0750ee006f Change S7 200 remote TSAP to 10.01 2021-06-02 22:06:00 +02:00
Michael Croes
5318f94dd7 Release S7NetPlus 0.12.0
Release highlights:
- Add synchronization to methods interacting with the PLC
2021-06-02 21:28:48 +02:00
Michael Croes
ea3beff481 Merge pull request #394 from mycroes/sync
Add synchronization
2021-06-02 21:25:51 +02:00
Michael Croes
f67b1e773f Add missing ConfigureAwait in OpenAsync 2021-06-01 20:59:20 +02:00
Michael Croes
e93a656312 Fix locking for OpenAsync 2021-06-01 20:28:34 +02:00
Michael Croes
8035f71a16 Apply synchronization to stream actions 2021-05-31 22:57:13 +02:00
Michael Croes
df4f258290 Move GetStreamIfAvailable to PLC.cs 2021-05-31 21:23:32 +02:00
Michael Croes
5636b93a53 PlcSynchronous: Remove unused usings 2021-05-31 21:17:42 +02:00
Michael Croes
8ed1b840bc PlcSynchronous: Clenaup trailing whitespace 2021-05-31 21:17:23 +02:00
Michael Croes
2afed88231 Consolidate sync stream calls 2021-05-31 21:17:03 +02:00
Michael Croes
1ded47971b Consolidate async stream calls 2021-05-31 21:07:16 +02:00
Serge Camille
fff6f3458f Merge branch 'develop' into githubActions2 2021-03-16 20:22:49 +01:00
Serge Camille
ae70f31af2 Remove deploy workflow. 2020-10-17 11:47:34 +02:00
Serge Camille
fb44b56c16 Skip welcome message 2020-10-17 11:47:34 +02:00
Serge Camille
ce97fcf335 Separate restore and test steps to better see execution times.
Restore could be cached, but it looks quite complicated to pull off.
2020-10-17 11:47:34 +02:00
Serge Camille
81208c0f03 Add github actions for multi-platform unit tests. 2020-10-17 11:47:34 +02:00
51 changed files with 2600 additions and 523 deletions

134
.github/workflows/dotnet.yml vendored Normal file
View File

@@ -0,0 +1,134 @@
# yaml-language-server: $schema=https://json.schemastore.org/github-workflow.json
name: .NET
on:
workflow_dispatch: # Allow running the workflow manually from the GitHub UI
push:
branches:
- 'main' # Run the workflow when pushing to the main branch
pull_request:
branches:
- '*' # Run the workflow for all pull requests
release:
types:
- published # Run the workflow when a new GitHub release is published
env:
DOTNET_SKIP_FIRST_TIME_EXPERIENCE: 1
DOTNET_NOLOGO: true
NuGetDirectory: ${{ github.workspace}}/nuget
defaults:
run:
shell: pwsh
jobs:
create_nuget:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0 # Get all history to allow automatic versioning
- name: Install GitVersion
uses: gittools/actions/gitversion/setup@v0
with:
versionSpec: '6.x'
includePrerelease: true
preferLatestVersion: true
- name: Determine Version
id: gitversion
uses: gittools/actions/gitversion/execute@v0
- name: Setup .NET
uses: actions/setup-dotnet@v3
- run: >
dotnet pack
--configuration Release
/p:AssemblyVersion=${{ steps.gitversion.outputs.assemblySemVer }}
/p:FileVersion=${{ steps.gitversion.outputs.assemblySemFileVer }}
/p:InformationalVersion=${{ steps.gitversion.outputs.informationalVersion }}
/p:PackageVersion=${{ steps.gitversion.outputs.semVer }}
--output ${{ env.NuGetDirectory }}
- uses: actions/upload-artifact@v3
with:
name: nuget
if-no-files-found: error
retention-days: 7
path: |
${{ env.NuGetDirectory }}/*.nupkg
${{ env.NuGetDirectory }}/*.snupkg
run_test:
name: test-${{ matrix.os }}
runs-on: ${{ matrix.os }}
env:
configuration: Release
artifacts: ${{ github.workspace }}/artifacts
strategy:
matrix:
os: [windows-latest, ubuntu-20.04, macos-latest]
fail-fast: false
steps:
- uses: actions/checkout@v3
- name: Install Snap7 Linux
if: ${{ matrix.os == 'ubuntu-20.04' }}
run: |
sudo add-apt-repository ppa:gijzelaar/snap7
sudo apt-get update
sudo apt-get install libsnap7-1 libsnap7-dev
- name: Install Snap7 MacOs
if: ${{ matrix.os == 'macos-latest' }}
run: |
brew install snap7
- name: Setup Dotnet
uses: actions/setup-dotnet@v3
with:
dotnet-version: |
6.x
7.x
- name: Nuget Cache
uses: actions/cache@v3
with:
path: ~/.nuget/packages
# Look to see if there is a cache hit for the corresponding requirements file
key: ${{ runner.os }}-nuget-${{ hashFiles('**/packages.lock.json') }}
restore-keys: |
${{ runner.os }}-nuget
- name: Test
run: dotnet test --nologo --verbosity normal --logger GitHubActions
deploy:
# Publish only when creating a GitHub Release
# https://docs.github.com/en/repositories/releasing-projects-on-github/managing-releases-in-a-repository
# You can update this logic if you want to manage releases differently
if: github.event_name == 'release'
runs-on: ubuntu-latest
needs: [ create_nuget, run_test ]
steps:
- uses: actions/download-artifact@v3
with:
name: nuget
path: ${{ env.NuGetDirectory }}
- name: Setup .NET Core
uses: actions/setup-dotnet@v3
# Publish all NuGet packages to NuGet.org
# Use --skip-duplicate to prevent errors if a package with the same version already exists.
# If you retry a failed workflow, already published packages will be skipped without error.
- name: Publish NuGet package
run: |
foreach($file in (Get-ChildItem "${{ env.NuGetDirectory }}" -Recurse -Include *.nupkg)) {
dotnet nuget push $file --api-key "${{ secrets.NUGET_APIKEY }}" --source https://api.nuget.org/v3/index.json --skip-duplicate
}

View File

@@ -1,21 +0,0 @@
assembly-informational-format: '{NuGetVersion}'
mode: ContinuousDeployment
branches:
master:
tag: rc
increment: Minor
feature:
regex: features?[/-]
tag: rc-{BranchName}
increment: Minor
pull-request:
regex: (pull|pull\-requests|pr)[/-]
tag: rc-pr-{BranchName}
increment: Minor
hotfix:
regex: hotfix(es)?[/-]
tag: rc
increment: Patch
develop:
regex: dev(elop)?(ment)?$
tag: b

View File

@@ -0,0 +1,259 @@
using System;
using System.Net;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using S7.Net.Protocol;
namespace S7.Net.UnitTest.CommunicationTests;
[TestClass]
public class Clock
{
[TestMethod, Timeout(1000)]
public async Task Read_Clock_Value()
{
var cs = new CommunicationSequence
{
ConnectionOpenTemplates.ConnectionRequestConfirm,
ConnectionOpenTemplates.CommunicationSetup,
{
"""
// TPKT
03 00 00 1d
// COTP
02 f0 80
// S7 read clock
// UserData header
32 07 00 00 PDU1 PDU2
// Parameter length
00 08
// Data length
00 04
// Parameter
// Head
00 01 12
// Length
04
// Method (Request/Response): Req
11
// Type request (4...) Function group timers (...7)
47
// Subfunction: read clock
01
// Sequence number
00
// Data
// Return code
0a
// Transport size
00
// Payload length
00 00
""",
"""
// TPKT
03 00 00 2b
// COTP
02 f0 80
// S7 read clock response
// UserData header
32 07 00 00 PDU1 PDU2
// Parameter length
00 0c
// Data length
00 0e
// Parameter
// Head
00 01 12
// Length
08
// Method (Request/Response): Res
12
// Type response (8...) Function group timers (...7)
87
// Subfunction: read clock
01
// Sequence number
01
// Data unit reference
00
// Last data unit? Yes
00
// Error code
00 00
// Data
// Error code
ff
// Transport size: OCTET STRING
09
// Length
00 0a
// Timestamp
// Reserved
00
// Year 1
19
// Year 2
14
// Month
08
// Day
20
// Hour
11
// Minute
59
// Seconds
43
// Milliseconds: 912..., Day of week: ...4
91 24
"""
}
};
static async Task Client(int port)
{
var conn = new Plc(IPAddress.Loopback.ToString(), port, new TsapPair(new Tsap(1, 2), new Tsap(3, 4)));
await conn.OpenAsync();
var time = await conn.ReadClockAsync();
Assert.AreEqual(new DateTime(2014, 8, 20, 11, 59, 43, 912), time);
conn.Close();
}
await Task.WhenAll(cs.Serve(out var port), Client(port));
}
[TestMethod, Timeout(1000)]
public async Task Write_Clock_Value()
{
var cs = new CommunicationSequence
{
ConnectionOpenTemplates.ConnectionRequestConfirm,
ConnectionOpenTemplates.CommunicationSetup,
{
"""
// TPKT
03 00 00 27
// COTP
02 f0 80
// S7 read clock
// UserData header
32 07 00 00 PDU1 PDU2
// Parameter length
00 08
// Data length
00 0e
// Parameter
// Head
00 01 12
// Length
04
// Method (Request/Response): Req
11
// Type request (4...) Function group timers (...7)
47
// Subfunction: write clock
02
// Sequence number
00
// Data
// Return code
ff
// Transport size
09
// Payload length
00 0a
// Payload
// Timestamp
// Reserved
00
// Year 1
19
// Year 2
14
// Month
08
// Day
20
// Hour
11
// Minute
59
// Seconds
43
// Milliseconds: 912..., Day of week: ...4
91 24
""",
"""
// TPKT
03 00 00 21
// COTP
02 f0 80
// S7 read clock response
// UserData header
32 07 00 00 PDU1 PDU2
// Parameter length
00 0c
// Data length
00 04
// Parameter
// Head
00 01 12
// Length
08
// Method (Request/Response): Res
12
// Type response (8...) Function group timers (...7)
87
// Subfunction: write clock
02
// Sequence number
01
// Data unit reference
00
// Last data unit? Yes
00
// Error code
00 00
// Data
// Error code
0a
// Transport size: NONE
00
// Length
00 00
"""
}
};
static async Task Client(int port)
{
var conn = new Plc(IPAddress.Loopback.ToString(), port, new TsapPair(new Tsap(1, 2), new Tsap(3, 4)));
await conn.OpenAsync();
await conn.WriteClockAsync(new DateTime(2014, 08, 20, 11, 59, 43, 912));
conn.Close();
}
await Task.WhenAll(cs.Serve(out var port), Client(port));
}
}

View File

@@ -0,0 +1,28 @@
using System.Net;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using S7.Net.Protocol;
namespace S7.Net.UnitTest.CommunicationTests;
[TestClass]
public class ConnectionOpen
{
[TestMethod]
public async Task Does_Not_Throw()
{
var cs = new CommunicationSequence {
ConnectionOpenTemplates.ConnectionRequestConfirm,
ConnectionOpenTemplates.CommunicationSetup
};
async Task Client(int port)
{
var conn = new Plc(IPAddress.Loopback.ToString(), port, new TsapPair(new Tsap(1, 2), new Tsap(3, 4)));
await conn.OpenAsync();
conn.Close();
}
await Task.WhenAll(cs.Serve(out var port), Client(port));
}
}

View File

@@ -0,0 +1,107 @@
namespace S7.Net.UnitTest.CommunicationTests;
internal static class ConnectionOpenTemplates
{
public static RequestResponsePair ConnectionRequestConfirm { get; } = new RequestResponsePair(
"""
// TPKT
03 // Version
00 // Reserved
00 16 // Length
// CR
11 // Number of bytes following
E0 // CR / Credit
00 00 // Destination reference, unused
__ __ // Source reference, unused
00 // Class / Option
// Source TSAP
C1 // Parameter code
02 // Parameter length
TSAP_SRC_CHAN // Channel
TSAP_SRC_POS // Position
// Destination TSAP
C2 // Parameter code
02 // Parameter length
TSAP_DEST_CHAN // Channel
TSAP_DEST_POS // Position
// PDU Size parameter
C0 // Parameter code
01 // Parameter length
0A // 1024 byte PDU (2 ^ 10)
""",
"""
// TPKT
03 // Version
00 // Reserved
00 0B // Length
// CC
06 // Length
D0 // CC / Credit
00 00 // Destination reference
00 00 // Source reference
00 // Class / Option
"""
);
public static RequestResponsePair CommunicationSetup { get; } = new RequestResponsePair(
"""
// TPKT
03 // Version
00 // Reserved
00 19 // Length
// Data header
02 // Length
F0 // Data identifier
80 // PDU number and end of transmission
// S7 header
32 // Protocol ID
01 // Message type job request
00 00 // Reserved
PDU1 PDU2 // PDU reference
00 08 // Parameter length (Communication Setup)
00 00 // Data length
// Communication Setup
F0 // Function code
00 // Reserved
00 03 // Max AMQ caller
00 03 // Max AMQ callee
03 C0 // PDU size (960)
""",
"""
// TPKT
03 // Version
00 // Reserved
00 1B // Length
// Data header
02 // Length
F0 // Data identifier
80 // PDU number and end of transmission
// S7 header
32 // Protocol ID
03 // Message type ack data
00 00 // Reserved
PDU1 PDU2 // PDU reference
00 08 // Parameter length (Communication Setup)
00 00 // Data length
00 // Error class
00 // Error code
// Communication Setup
F0 // Function code
00 // Reserved
00 03 // Max AMQ caller
00 03 // Max AMQ callee
03 C0 // PDU size (960)
"""
);
}

View File

@@ -0,0 +1,57 @@
using System.Net;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using S7.Net.Protocol;
namespace S7.Net.UnitTest.CommunicationTests;
[TestClass]
public class ReadPlcStatus
{
[TestMethod]
public async Task Read_Status_Run()
{
var cs = new CommunicationSequence {
ConnectionOpenTemplates.ConnectionRequestConfirm,
ConnectionOpenTemplates.CommunicationSetup,
{
"""
// TPKT
03 00 00 21
// COTP
02 f0 80
// S7 SZL read
32 07 00 00 PDU1 PDU2 00 08 00 08 00 01 12 04 11 44
01 00 ff 09 00 04 04 24 00 00
""",
"""
// TPKT
03 00 00 3d
// COTP
02 f0 80
// S7 SZL response
32 07 00 00 PDU1 PDU2 00 0c 00 20 00 01 12 08 12 84
01 02 00 00 00 00 ff 09 00 1c 04 24 00 00 00 14
00 01 51 44 ff 08 00 00 00 00 00 00 00 00 14 08
20 12 05 28 34 94
"""
}
};
async Task Client(int port)
{
var conn = new Plc(IPAddress.Loopback.ToString(), port, new TsapPair(new Tsap(1, 2), new Tsap(3, 4)));
await conn.OpenAsync();
var status = await conn.ReadStatusAsync();
Assert.AreEqual(0x08, status);
conn.Close();
}
await Task.WhenAll(cs.Serve(out var port), Client(port));
}
}

View File

@@ -0,0 +1,181 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
namespace S7.Net.UnitTest
{
/// <summary>
/// Test stream which only gives 1 byte per read.
/// </summary>
class TestStreamConnectionClose : Stream
{
private readonly CancellationTokenSource _cancellationTokenSource;
public TestStreamConnectionClose(CancellationTokenSource cancellationTokenSource)
{
_cancellationTokenSource = cancellationTokenSource;
}
public override bool CanRead => false;
public override bool CanSeek => throw new NotImplementedException();
public override bool CanWrite => true;
public override long Length => throw new NotImplementedException();
public override long Position { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public override void Flush()
{
throw new NotImplementedException();
}
public override int Read(byte[] buffer, int offset, int count)
{
throw new NotImplementedException();
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotImplementedException();
}
public override void SetLength(long value)
{
throw new NotImplementedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
_cancellationTokenSource.Cancel();
}
}
/// <summary>
/// These tests are intended to test <see cref="StreamExtensions"/> functions and other stream-related special cases.
/// </summary>
[TestClass]
public class ConnectionCloseTest
{
const short TestServerPort = 31122;
const string TestServerIp = "127.0.0.1";
[TestMethod]
public async Task Test_CancellationDuringTransmission()
{
var plc = new Plc(CpuType.S7300, TestServerIp, TestServerPort, 0, 2);
// Set up a shared cancellation source so we can let the stream
// initiate cancel after some data has been written to it.
var cancellationSource = new CancellationTokenSource();
var cancellationToken = cancellationSource.Token;
var stream = new TestStreamConnectionClose(cancellationSource);
var requestData = new byte[100]; // empty data, it does not matter what is in there
// Set up access to private method and field
var dynMethod = plc.GetType().GetMethod("NoLockRequestTpduAsync",
BindingFlags.NonPublic | BindingFlags.Instance);
if (dynMethod == null)
{
throw new NullReferenceException("Could not find method 'NoLockRequestTpduAsync' on Plc object.");
}
var tcpClientField = plc.GetType().GetField("tcpClient", BindingFlags.NonPublic | BindingFlags.Instance);
if (tcpClientField == null)
{
throw new NullReferenceException("Could not find field 'tcpClient' on Plc object.");
}
// Set a value to tcpClient field so we can later ensure that it has been closed.
tcpClientField.SetValue(plc, new TcpClient());
var tcpClientValue = tcpClientField.GetValue(plc);
Assert.IsNotNull(tcpClientValue);
try
{
var result = (Task<COTP.TPDU>) dynMethod.Invoke(plc, new object[] { stream, requestData, cancellationToken });
await result;
}
catch (OperationCanceledException)
{
Console.WriteLine("Task was cancelled as expected.");
// Ensure that the plc connection was closed since the task was cancelled
// after data has been sent through the network. We expect that the tcpClient
// object was set to NULL
var tcpClientValueAfter = tcpClientField.GetValue(plc);
Assert.IsNull(tcpClientValueAfter);
return;
}
catch (Exception e)
{
Assert.Fail($"Wrong exception type received. Expected {typeof(OperationCanceledException)}, received {e.GetType()}.");
}
// Ensure test fails if cancellation did not occur.
Assert.Fail("Task was not cancelled as expected.");
}
[TestMethod]
public async Task Test_CancellationBeforeTransmission()
{
var plc = new Plc(CpuType.S7300, TestServerIp, TestServerPort, 0, 2);
// Set up a cancellation source
var cancellationSource = new CancellationTokenSource();
var cancellationToken = cancellationSource.Token;
var stream = new TestStreamConnectionClose(cancellationSource);
var requestData = new byte[100]; // empty data, it does not matter what is in there
// Set up access to private method and field
var dynMethod = plc.GetType().GetMethod("NoLockRequestTpduAsync",
BindingFlags.NonPublic | BindingFlags.Instance);
if (dynMethod == null)
{
throw new NullReferenceException("Could not find method 'NoLockRequestTpduAsync' on Plc object.");
}
var tcpClientField = plc.GetType().GetField("tcpClient", BindingFlags.NonPublic | BindingFlags.Instance);
if (tcpClientField == null)
{
throw new NullReferenceException("Could not find field 'tcpClient' on Plc object.");
}
// Set a value to tcpClient field so we can later ensure that it has been closed.
tcpClientField.SetValue(plc, new TcpClient());
var tcpClientValue = tcpClientField.GetValue(plc);
Assert.IsNotNull(tcpClientValue);
try
{
// cancel the task before we start transmitting data
cancellationSource.Cancel();
var result = (Task<COTP.TPDU>)dynMethod.Invoke(plc, new object[] { stream, requestData, cancellationToken });
await result;
}
catch (OperationCanceledException)
{
Console.WriteLine("Task was cancelled as expected.");
// Ensure that the plc connection was not closed, since we cancelled the task before
// sending data through the network. We expect that the tcpClient
// object was NOT set to NULL
var tcpClientValueAfter = tcpClientField.GetValue(plc);
Assert.IsNotNull(tcpClientValueAfter);
return;
}
catch (Exception e)
{
Assert.Fail($"Wrong exception type received. Expected {typeof(OperationCanceledException)}, received {e.GetType()}.");
}
// Ensure test fails if cancellation did not occur.
Assert.Fail("Task was not cancelled as expected.");
}
}
}

View File

@@ -9,52 +9,52 @@ namespace S7.Net.UnitTest
[TestMethod]
public void Test_ConnectionRequest_S7_200()
{
CollectionAssert.AreEqual(MakeConnectionRequest(16, 0, 16, 0),
ConnectionRequest.GetCOTPConnectionRequest(CpuType.S7200, 0, 0));
CollectionAssert.AreEqual(MakeConnectionRequest(16, 0, 16, 1),
ConnectionRequest.GetCOTPConnectionRequest(TsapPair.GetDefaultTsapPair(CpuType.S7200, 0, 0)));
}
[TestMethod]
public void Test_ConnectionRequest_S7_300()
{
CollectionAssert.AreEqual(MakeConnectionRequest(1, 0, 3, 0),
ConnectionRequest.GetCOTPConnectionRequest(CpuType.S7300, 0, 0));
ConnectionRequest.GetCOTPConnectionRequest(TsapPair.GetDefaultTsapPair(CpuType.S7300, 0, 0)));
CollectionAssert.AreEqual(MakeConnectionRequest(1, 0, 3, 1),
ConnectionRequest.GetCOTPConnectionRequest(CpuType.S7300, 0, 1));
ConnectionRequest.GetCOTPConnectionRequest(TsapPair.GetDefaultTsapPair(CpuType.S7300, 0, 1)));
CollectionAssert.AreEqual(MakeConnectionRequest(1, 0, 3, 33),
ConnectionRequest.GetCOTPConnectionRequest(CpuType.S7300, 1, 1));
ConnectionRequest.GetCOTPConnectionRequest(TsapPair.GetDefaultTsapPair(CpuType.S7300, 1, 1)));
}
[TestMethod]
public void Test_ConnectionRequest_S7_400()
{
CollectionAssert.AreEqual(MakeConnectionRequest(1, 0, 3, 0),
ConnectionRequest.GetCOTPConnectionRequest(CpuType.S7400, 0, 0));
ConnectionRequest.GetCOTPConnectionRequest(TsapPair.GetDefaultTsapPair(CpuType.S7400, 0, 0)));
CollectionAssert.AreEqual(MakeConnectionRequest(1, 0, 3, 1),
ConnectionRequest.GetCOTPConnectionRequest(CpuType.S7400, 0, 1));
ConnectionRequest.GetCOTPConnectionRequest(TsapPair.GetDefaultTsapPair(CpuType.S7400, 0, 1)));
CollectionAssert.AreEqual(MakeConnectionRequest(1, 0, 3, 33),
ConnectionRequest.GetCOTPConnectionRequest(CpuType.S7400, 1, 1));
ConnectionRequest.GetCOTPConnectionRequest(TsapPair.GetDefaultTsapPair(CpuType.S7400, 1, 1)));
}
[TestMethod]
public void Test_ConnectionRequest_S7_1200()
{
CollectionAssert.AreEqual(MakeConnectionRequest(1, 0, 3, 0),
ConnectionRequest.GetCOTPConnectionRequest(CpuType.S71200, 0, 0));
ConnectionRequest.GetCOTPConnectionRequest(TsapPair.GetDefaultTsapPair(CpuType.S71200, 0, 0)));
CollectionAssert.AreEqual(MakeConnectionRequest(1, 0, 3, 1),
ConnectionRequest.GetCOTPConnectionRequest(CpuType.S71200, 0, 1));
ConnectionRequest.GetCOTPConnectionRequest(TsapPair.GetDefaultTsapPair(CpuType.S71200, 0, 1)));
CollectionAssert.AreEqual(MakeConnectionRequest(1, 0, 3, 33),
ConnectionRequest.GetCOTPConnectionRequest(CpuType.S71200, 1, 1));
ConnectionRequest.GetCOTPConnectionRequest(TsapPair.GetDefaultTsapPair(CpuType.S71200, 1, 1)));
}
[TestMethod]
public void Test_ConnectionRequest_S7_1500()
{
CollectionAssert.AreEqual(MakeConnectionRequest(0x10, 0x2, 3, 0),
ConnectionRequest.GetCOTPConnectionRequest(CpuType.S71500, 0, 0));
CollectionAssert.AreEqual(MakeConnectionRequest(0x10, 0x2, 3, 1),
ConnectionRequest.GetCOTPConnectionRequest(CpuType.S71500, 0, 1));
CollectionAssert.AreEqual(MakeConnectionRequest(0x10, 0x2, 3, 33),
ConnectionRequest.GetCOTPConnectionRequest(CpuType.S71500, 1, 1));
CollectionAssert.AreEqual(MakeConnectionRequest(1, 0, 3, 0),
ConnectionRequest.GetCOTPConnectionRequest(TsapPair.GetDefaultTsapPair(CpuType.S71500, 0, 0)));
CollectionAssert.AreEqual(MakeConnectionRequest(1, 0, 3, 1),
ConnectionRequest.GetCOTPConnectionRequest(TsapPair.GetDefaultTsapPair(CpuType.S71500, 0, 1)));
CollectionAssert.AreEqual(MakeConnectionRequest(1, 0, 3, 33),
ConnectionRequest.GetCOTPConnectionRequest(TsapPair.GetDefaultTsapPair(CpuType.S71500, 1, 1)));
}
private static byte[] MakeConnectionRequest(byte sourceTsap1, byte sourceTsap2, byte destTsap1, byte destTsap2)
@@ -63,7 +63,7 @@ namespace S7.Net.UnitTest
{
3, 0, 0, 22, //TPKT
17, //COTP Header Length
224, //Connect Request
224, //Connect Request
0, 0, //Destination Reference
0, 46, //Source Reference
0, //Flags

View File

@@ -24,5 +24,21 @@ namespace S7.Net.UnitTest
Assert.IsFalse(dummyByte.SelectBit(7));
}
[TestMethod]
public void T01_TestSetBit()
{
byte dummyByte = 0xAA; // 1010 1010
dummyByte.SetBit(0, true);
dummyByte.SetBit(1, false);
dummyByte.SetBit(2, true);
dummyByte.SetBit(3, false);
Assert.AreEqual<byte>(dummyByte, 0xA5);// 1010 0101
dummyByte.SetBit(4, true);
dummyByte.SetBit(5, true);
dummyByte.SetBit(6, true);
dummyByte.SetBit(7, true);
Assert.AreEqual<byte>(dummyByte, 0xF5);// 1111 0101
}
}
}

View File

@@ -0,0 +1,7 @@
using System.ComponentModel;
namespace System.Runtime.CompilerServices
{
[EditorBrowsable(EditorBrowsableState.Never)]
internal record IsExternalInit;
}

View File

@@ -1,4 +1,6 @@

using S7.Net.Types;
namespace S7.Net.UnitTest.Helpers
{
class TestClass
@@ -51,5 +53,16 @@ namespace S7.Net.UnitTest.Helpers
/// DB1.DBD16
/// </summary>
public ushort DWordVariable { get; set; }
/// <summary>
/// DB1.DBX20.0
/// </summary>
[S7String(S7StringType.S7WString, 10)]
public string WStringVariable { get; set; }
/// <summary>
/// DB1.DBX44.0
/// </summary>
[S7String(S7StringType.S7String, 10)]
public string StringVariable { get; set; }
}
}

View File

@@ -0,0 +1,82 @@
using System;
using System.Buffers;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
namespace S7.Net.UnitTest;
internal class CommunicationSequence : IEnumerable<RequestResponsePair>
{
private readonly List<RequestResponsePair> _requestResponsePairs = new List<RequestResponsePair>();
public void Add(RequestResponsePair requestResponsePair)
{
_requestResponsePairs.Add(requestResponsePair);
}
public void Add(string requestPattern, string responsePattern)
{
_requestResponsePairs.Add(new RequestResponsePair(requestPattern, responsePattern));
}
public IEnumerator<RequestResponsePair> GetEnumerator()
{
return _requestResponsePairs.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public Task Serve(out int port)
{
var socket = CreateBoundListenSocket(out port);
socket.Listen(0);
async Task Impl()
{
await Task.Yield();
var socketIn = socket.Accept();
var buffer = ArrayPool<byte>.Shared.Rent(1024);
try
{
foreach (var pair in _requestResponsePairs)
{
var bytesReceived = socketIn.Receive(buffer, SocketFlags.None);
var received = buffer.Take(bytesReceived).ToArray();
Console.WriteLine($"=> {BitConverter.ToString(received)}");
var response = Responder.Respond(pair, received);
Console.WriteLine($"<= {BitConverter.ToString(response)}");
socketIn.Send(response);
}
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}
socketIn.Close();
}
return Impl();
}
private static Socket CreateBoundListenSocket(out int port)
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
var endpoint = new IPEndPoint(IPAddress.Loopback, 0);
socket.Bind(endpoint);
var localEndpoint = (IPEndPoint)socket.LocalEndPoint!;
port = localEndpoint.Port;
return socket;
}
}

View File

@@ -0,0 +1,3 @@
namespace S7.Net.UnitTest;
internal record RequestResponsePair(string RequestPattern, string ResponsePattern);

View File

@@ -0,0 +1,80 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
namespace S7.Net.UnitTest;
internal static class Responder
{
private const string Comment = "//";
private static char[] Space = " ".ToCharArray();
public static byte[] Respond(RequestResponsePair pair, byte[] request)
{
var offset = 0;
var matches = new Dictionary<string, byte>();
var res = new List<byte>();
using var requestReader = new StringReader(pair.RequestPattern);
string line;
while ((line = requestReader.ReadLine()) != null)
{
var tokens = line.Split(Space, StringSplitOptions.RemoveEmptyEntries);
foreach (var token in tokens)
{
if (token.StartsWith(Comment)) break;
if (offset >= request.Length)
{
throw new Exception("Request pattern has more data than request.");
}
var received = request[offset];
if (token.Length == 2 && byte.TryParse(token, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var value))
{
// Number, exact match
if (value != received)
{
throw new Exception($"Incorrect data at offset {offset}. Expected {value:X2}, received {received:X2}.");
}
}
else
{
matches[token] = received;
}
offset++;
}
}
if (offset != request.Length) throw new Exception("Request contained more data than request pattern.");
using var responseReader = new StringReader(pair.ResponsePattern);
while ((line = responseReader.ReadLine()) != null)
{
var tokens = line.Split(Space, StringSplitOptions.RemoveEmptyEntries);
foreach (var token in tokens)
{
if (token.StartsWith(Comment)) break;
if (token.Length == 2 && byte.TryParse(token, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var value))
{
res.Add(value);
}
else
{
if (!matches.TryGetValue(token, out var match))
{
throw new Exception($"Unmatched token '{token}' in response.");
}
res.Add(match);
}
}
}
return res.ToArray();
}
}

View File

@@ -1,14 +1,10 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using S7.Net;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using S7.Net.Protocol;
using System.Collections;
namespace S7.Net.UnitTest
{
@@ -21,21 +17,17 @@ namespace S7.Net.UnitTest
public async Task TPKT_Read()
{
var m = new MemoryStream(StringToByteArray("0300002902f0803203000000010002001400000401ff0400807710000100000103000000033f8ccccd"));
var t = TPKT.Read(m);
Assert.AreEqual(0x03, t.Version);
Assert.AreEqual(0x29, t.Length);
m.Position = 0;
t = await TPKT.ReadAsync(m, TestContext.CancellationTokenSource.Token);
var t = await TPKT.ReadAsync(m, TestContext.CancellationTokenSource.Token);
Assert.AreEqual(0x03, t.Version);
Assert.AreEqual(0x29, t.Length);
}
[TestMethod]
[ExpectedException(typeof(TPKTInvalidException))]
public void TPKT_ReadShort()
public async Task TPKT_ReadShort()
{
var m = new MemoryStream(StringToByteArray("0300002902f0803203000000010002001400000401ff040080"));
var t = TPKT.Read(m);
var t = await TPKT.ReadAsync(m, CancellationToken.None);
}
@@ -48,14 +40,11 @@ namespace S7.Net.UnitTest
}
[TestMethod]
public void COTP_ReadTSDU()
public async Task COTP_ReadTSDU()
{
var expected = StringToByteArray("320700000400000800080001120411440100ff09000400000000");
var m = new MemoryStream(StringToByteArray("0300000702f0000300000702f0000300002102f080320700000400000800080001120411440100ff09000400000000"));
var t = COTP.TSDU.Read(m);
Assert.IsTrue(expected.SequenceEqual(t));
m.Position = 0;
t = COTP.TSDU.ReadAsync(m, TestContext.CancellationTokenSource.Token).Result;
var t = await COTP.TSDU.ReadAsync(m, TestContext.CancellationTokenSource.Token);
Assert.IsTrue(expected.SequenceEqual(t));
}
@@ -69,14 +58,13 @@ namespace S7.Net.UnitTest
[TestMethod]
public void TestResponseCode()
public async Task TestResponseCode()
{
var expected = StringToByteArray("320700000400000800080001120411440100ff09000400000000");
var m = new MemoryStream(StringToByteArray("0300000702f0000300000702f0000300002102f080320700000400000800080001120411440100ff09000400000000"));
var t = COTP.TSDU.Read(m);
var t = await COTP.TSDU.ReadAsync(m, CancellationToken.None);
Assert.IsTrue(expected.SequenceEqual(t));
// Test all possible byte values. Everything except 0xff should throw an exception.
var testData = Enumerable.Range(0, 256).Select(i => new { StatusCode = (ReadWriteErrorCode)i, ThrowsException = i != (byte)ReadWriteErrorCode.Success });

View File

@@ -1,8 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net452;netcoreapp3.1</TargetFrameworks>
<PropertyGroup Condition=" '$(OS)' != 'Windows_NT' ">
<TargetFrameworks>net6.0;net7.0</TargetFrameworks>
</PropertyGroup>
<PropertyGroup Condition=" '$(OS)' == 'Windows_NT' ">
<TargetFrameworks>net6.0;net7.0;net462</TargetFrameworks>
</PropertyGroup>
<PropertyGroup>
<LangVersion>latest</LangVersion>
<SignAssembly>true</SignAssembly>
<AssemblyOriginatorKeyFile>Properties\S7.Net.snk</AssemblyOriginatorKeyFile>
<IsPackable>false</IsPackable>
@@ -11,7 +17,10 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="GitHubActionsTestLogger" Version="1.1.0" />
<PackageReference Include="GitHubActionsTestLogger" Version="2.3.2">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.7.0" />
<PackageReference Include="MSTest.TestAdapter" Version="2.1.2" />
<PackageReference Include="MSTest.TestFramework" Version="2.1.2" />

View File

@@ -7,6 +7,12 @@ using S7.Net.Types;
using S7.UnitTest.Helpers;
using System.Threading.Tasks;
using System.Threading;
using System.Security.Cryptography;
#if NET5_0_OR_GREATER
using System.Buffers;
#endif
#endregion
@@ -138,6 +144,33 @@ namespace S7.Net.UnitTest
CollectionAssert.AreEqual(data, readData);
}
#if NET5_0_OR_GREATER
/// <summary>
/// Write/Read a large amount of data to test PDU max
/// </summary>
[TestMethod]
public async Task Test_Async_WriteLargeByteArrayWithMemory()
{
Assert.IsTrue(plc.IsConnected, "Before executing this test, the plc must be connected. Check constructor.");
var randomEngine = new Random();
using var dataOwner = MemoryPool<byte>.Shared.Rent(8192);
var data = dataOwner.Memory.Slice(0, 8192);
var db = 2;
randomEngine.NextBytes(data.Span);
await plc.WriteBytesAsync(DataType.DataBlock, db, 0, data);
using var readDataOwner = MemoryPool<byte>.Shared.Rent(data.Length);
var readData = readDataOwner.Memory.Slice(0, data.Length);
await plc.ReadBytesAsync(readData, DataType.DataBlock, db, 0);
CollectionAssert.AreEqual(data.ToArray(), readData.ToArray());
}
#endif
/// <summary>
/// Read/Write a class that has the same properties of a DB with the same field in the same order
/// </summary>
@@ -154,7 +187,9 @@ namespace S7.Net.UnitTest
IntVariable = -15000,
LRealVariable = -154.789,
RealVariable = -154.789f,
DWordVariable = 850
DWordVariable = 850,
WStringVariable = "ÄÜÉÊéà",
StringVariable = "Hallo"
};
await plc.WriteClassAsync(tc, DB2);
@@ -168,6 +203,8 @@ namespace S7.Net.UnitTest
Assert.AreEqual(tc.LRealVariable, tc2.LRealVariable);
Assert.AreEqual(tc.RealVariable, tc2.RealVariable);
Assert.AreEqual(tc.DWordVariable, tc2.DWordVariable);
Assert.AreEqual(tc.WStringVariable, tc2.WStringVariable);
Assert.AreEqual(tc.StringVariable, tc2.StringVariable);
}
[TestMethod]
@@ -580,7 +617,9 @@ namespace S7.Net.UnitTest
IntVariable = -15000,
LRealVariable = -154.789,
RealVariable = -154.789f,
DWordVariable = 850
DWordVariable = 850,
WStringVariable = "ÄÜÉÊéà",
StringVariable = "Hallo"
};
await plc.WriteClassAsync(tc, DB2);
@@ -628,7 +667,10 @@ namespace S7.Net.UnitTest
IntVariable = -15000,
LRealVariable = -154.789,
RealVariable = -154.789f,
DWordVariable = 850
DWordVariable = 850,
WStringVariable = "ÄÜÉÊéà",
StringVariable = "Hallo"
};
await plc.WriteClassAsync(tc, DB2);
@@ -646,6 +688,9 @@ namespace S7.Net.UnitTest
Assert.AreEqual(Math.Round(tc2.LRealVariable, 3), Math.Round(tc2Generic.LRealVariable, 3));
Assert.AreEqual(tc2.RealVariable, tc2Generic.RealVariable);
Assert.AreEqual(tc2.DWordVariable, tc2Generic.DWordVariable);
Assert.AreEqual(tc2.WStringVariable, tc2Generic.WStringVariable);
Assert.AreEqual(tc2.StringVariable, tc2Generic.StringVariable);
}
[TestMethod]
@@ -671,7 +716,9 @@ namespace S7.Net.UnitTest
IntVariable = -15000,
LRealVariable = -154.789,
RealVariable = -154.789f,
DWordVariable = 850
DWordVariable = 850,
WStringVariable = "ÄÜÉÊéà",
StringVariable = "Hallo"
};
await plc.WriteClassAsync(tc, DB2);
@@ -686,6 +733,8 @@ namespace S7.Net.UnitTest
Assert.AreEqual(Math.Round(tc2Generic.LRealVariable, 3), Math.Round(tc2GenericWithClassFactory.LRealVariable, 3));
Assert.AreEqual(tc2Generic.RealVariable, tc2GenericWithClassFactory.RealVariable);
Assert.AreEqual(tc2Generic.DWordVariable, tc2GenericWithClassFactory.DWordVariable);
Assert.AreEqual(tc2Generic.WStringVariable, tc2GenericWithClassFactory.WStringVariable);
Assert.AreEqual(tc2Generic.StringVariable, tc2GenericWithClassFactory.StringVariable);
}
[TestMethod]
@@ -792,7 +841,9 @@ namespace S7.Net.UnitTest
IntVariable = -15000,
LRealVariable = -154.789,
RealVariable = -154.789f,
DWordVariable = 850
DWordVariable = 850,
WStringVariable = "ÄÜÉÊéà",
StringVariable = "Hallo"
};
plc.WriteClass(tc, DB2);
@@ -914,6 +965,31 @@ namespace S7.Net.UnitTest
}
}
#if NET5_0_OR_GREATER
[TestMethod]
public async Task Test_Async_ReadWriteBytesManyWithMemory()
{
Assert.IsTrue(plc.IsConnected, "Before executing this test, the plc must be connected. Check constructor.");
using var data = MemoryPool<byte>.Shared.Rent(2000);
for (int i = 0; i < data.Memory.Length; i++)
data.Memory.Span[i] = (byte)(i % 256);
await plc.WriteBytesAsync(DataType.DataBlock, 2, 0, data.Memory);
using var readData = MemoryPool<byte>.Shared.Rent(data.Memory.Length);
await plc.ReadBytesAsync(readData.Memory.Slice(0, data.Memory.Length), DataType.DataBlock, 2, 0);
for (int x = 0; x < data.Memory.Length; x++)
{
Assert.AreEqual(x % 256, readData.Memory.Span[x], string.Format("Bit {0} failed", x));
}
}
#endif
/// <summary>
/// Write a large amount of data and test cancellation
/// </summary>
@@ -930,25 +1006,100 @@ namespace S7.Net.UnitTest
var db = 2;
randomEngine.NextBytes(data);
cancellationSource.CancelAfter(TimeSpan.FromMilliseconds(5));
cancellationSource.CancelAfter(System.TimeSpan.FromMilliseconds(5));
try
{
await plc.WriteBytesAsync(DataType.DataBlock, db, 0, data, cancellationToken);
}
catch(TaskCanceledException)
catch(OperationCanceledException)
{
// everything is good, that is the exception we expect
Console.WriteLine("Task was cancelled as expected.");
Console.WriteLine("Operation was cancelled as expected.");
return;
}
catch(Exception e)
{
Assert.Fail($"Wrong exception type received. Expected {typeof(TaskCanceledException)}, received {e.GetType()}.");
Assert.Fail($"Wrong exception type received. Expected {typeof(OperationCanceledException)}, received {e.GetType()}.");
}
// Depending on how tests run, this can also just succeed without getting cancelled at all. Do nothing in this case.
Console.WriteLine("Task was not cancelled as expected.");
}
#if NET5_0_OR_GREATER
/// <summary>
/// Write a large amount of data and test cancellation
/// </summary>
[TestMethod]
public async Task Test_Async_WriteLargeByteArrayWithCancellationWithMemory()
{
Assert.IsTrue(plc.IsConnected, "Before executing this test, the plc must be connected. Check constructor.");
var cancellationSource = new CancellationTokenSource();
var cancellationToken = cancellationSource.Token;
using var dataOwner = MemoryPool<byte>.Shared.Rent(8192);
var data = dataOwner.Memory.Slice(0, 8192);
var randomEngine = new Random();
var db = 2;
randomEngine.NextBytes(data.Span);
cancellationSource.CancelAfter(System.TimeSpan.FromMilliseconds(5));
try
{
await plc.WriteBytesAsync(DataType.DataBlock, db, 0, data, cancellationToken);
}
catch (OperationCanceledException)
{
// everything is good, that is the exception we expect
Console.WriteLine("Operation was cancelled as expected.");
return;
}
catch (Exception e)
{
Assert.Fail($"Wrong exception type received. Expected {typeof(OperationCanceledException)}, received {e.GetType()}.");
}
// Depending on how tests run, this can also just succeed without getting cancelled at all. Do nothing in this case.
Console.WriteLine("Task was not cancelled as expected.");
}
#endif
/// <summary>
/// Write a large amount of data and test cancellation
/// </summary>
[TestMethod]
public async Task Test_Async_ParseDataIntoDataItemsAlignment()
{
Assert.IsTrue(plc.IsConnected, "Before executing this test, the plc must be connected. Check constructor.");
var db = 2;
// First write a sensible S7 string capacity
await plc.WriteBytesAsync(DataType.DataBlock, db, 0, new byte[] {5, 0});
// Read two data items, with the first having odd number of bytes (7),
// and the second has to be aligned on a even address
var dataItems = new List<DataItem>
{
new DataItem
{
DataType = DataType.DataBlock,
DB = db,
VarType = VarType.S7String,
Count = 5
},
new DataItem
{
DataType = DataType.DataBlock,
DB = db,
VarType = VarType.Word,
}
};
await plc.ReadMultipleVarsAsync(dataItems, CancellationToken.None);
}
#endregion
}
}

View File

@@ -5,6 +5,11 @@ using Microsoft.VisualStudio.TestTools.UnitTesting;
using S7.Net.UnitTest.Helpers;
using S7.Net.Types;
using S7.UnitTest.Helpers;
using System.Security.Cryptography;
#if NET5_0_OR_GREATER
using System.Buffers;
#endif
#endregion
@@ -183,6 +188,9 @@ namespace S7.Net.UnitTest
tc.LRealVariable = -154.789;
tc.RealVariable = -154.789f;
tc.DWordVariable = 850;
tc.WStringVariable = "ÄÜÉÊéà";
tc.StringVariable = "Hallo";
plc.WriteClass(tc, DB2);
TestClass tc2 = new TestClass();
// Values that are read from a class are stored inside the class itself, that is passed by reference
@@ -194,6 +202,8 @@ namespace S7.Net.UnitTest
Assert.AreEqual(tc.LRealVariable, tc2.LRealVariable);
Assert.AreEqual(tc.RealVariable, tc2.RealVariable);
Assert.AreEqual(tc.DWordVariable, tc2.DWordVariable);
Assert.AreEqual(tc.WStringVariable, tc2.WStringVariable);
Assert.AreEqual(tc.StringVariable, tc2.StringVariable);
}
/// <summary>
@@ -577,6 +587,8 @@ namespace S7.Net.UnitTest
tc.LRealVariable = -154.789;
tc.RealVariable = -154.789f;
tc.DWordVariable = 850;
tc.WStringVariable = "ÄÜÉÊéà";
tc.StringVariable = "Hallo";
plc.WriteClass(tc, DB2);
@@ -622,6 +634,8 @@ namespace S7.Net.UnitTest
tc.LRealVariable = -154.789;
tc.RealVariable = -154.789f;
tc.DWordVariable = 850;
tc.WStringVariable = "ÄÜÉÊéà";
tc.StringVariable = "Hallo";
plc.WriteClass(tc, DB2);
@@ -637,6 +651,8 @@ namespace S7.Net.UnitTest
Assert.AreEqual(Math.Round(tc2.LRealVariable, 3), Math.Round(tc2Generic.LRealVariable, 3));
Assert.AreEqual(tc2.RealVariable, tc2Generic.RealVariable);
Assert.AreEqual(tc2.DWordVariable, tc2Generic.DWordVariable);
Assert.AreEqual(tc2.WStringVariable, tc2Generic.WStringVariable);
Assert.AreEqual(tc2.StringVariable, tc2Generic.StringVariable);
}
[TestMethod, ExpectedException(typeof(PlcException))]
@@ -665,6 +681,8 @@ namespace S7.Net.UnitTest
tc.LRealVariable = -154.789;
tc.RealVariable = -154.789f;
tc.DWordVariable = 850;
tc.WStringVariable = "ÄÜÉÊéà";
tc.StringVariable = "Hallo";
plc.WriteClass(tc, DB2);
@@ -679,6 +697,8 @@ namespace S7.Net.UnitTest
Assert.AreEqual(Math.Round(tc2Generic.LRealVariable, 3), Math.Round(tc2GenericWithClassFactory.LRealVariable, 3));
Assert.AreEqual(tc2Generic.RealVariable, tc2GenericWithClassFactory.RealVariable);
Assert.AreEqual(tc2Generic.DWordVariable, tc2GenericWithClassFactory.DWordVariable);
Assert.AreEqual(tc2Generic.WStringVariable, tc2GenericWithClassFactory.WStringVariable);
Assert.AreEqual(tc2Generic.StringVariable, tc2GenericWithClassFactory.StringVariable);
}
[TestMethod, ExpectedException(typeof(PlcException))]
@@ -762,6 +782,33 @@ namespace S7.Net.UnitTest
CollectionAssert.AreEqual(data, readData);
}
#if NET5_0_OR_GREATER
/// <summary>
/// Write/Read a large amount of data to test PDU max
/// </summary>
[TestMethod]
public void T33_WriteLargeByteArrayWithSpan()
{
Assert.IsTrue(plc.IsConnected, "Before executing this test, the plc must be connected. Check constructor.");
var randomEngine = new Random();
using var dataOwner = MemoryPool<byte>.Shared.Rent(8192);
var data = dataOwner.Memory.Span.Slice(0, 8192);
var db = 2;
randomEngine.NextBytes(data);
plc.WriteBytes(DataType.DataBlock, db, 0, data);
using var readDataOwner = MemoryPool<byte>.Shared.Rent(data.Length);
var readData = readDataOwner.Memory.Span.Slice(0, data.Length);
plc.ReadBytes(readData, DataType.DataBlock, db, 0);
CollectionAssert.AreEqual(data.ToArray(), readData.ToArray());
}
#endif
[TestMethod, ExpectedException(typeof(PlcException))]
public void T18_ReadStructThrowsIfPlcIsNotConnected()
{
@@ -837,6 +884,9 @@ namespace S7.Net.UnitTest
tc.LRealVariable = -154.789;
tc.RealVariable = -154.789f;
tc.DWordVariable = 850;
tc.WStringVariable = "ÄÜÉÊéà";
tc.StringVariable = "Hallo";
plc.WriteClass(tc, DB2);
int expectedReadBytes = (int)Types.Class.GetClassSize(tc);
@@ -987,6 +1037,32 @@ namespace S7.Net.UnitTest
}
}
#if NET5_0_OR_GREATER
[TestMethod]
public void T27_ReadWriteBytesManyWithSpan()
{
Assert.IsTrue(plc.IsConnected, "Before executing this test, the plc must be connected. Check constructor.");
using var dataOwner = MemoryPool<byte>.Shared.Rent(2000);
var data = dataOwner.Memory.Span;
for (int i = 0; i < data.Length; i++)
data[i] = (byte)(i % 256);
plc.WriteBytes(DataType.DataBlock, 2, 0, data);
using var readDataOwner = MemoryPool<byte>.Shared.Rent(data.Length);
var readData = readDataOwner.Memory.Span.Slice(0, data.Length);
plc.ReadBytes(readData, DataType.DataBlock, 2, 0);
for (int x = 0; x < data.Length; x++)
{
Assert.AreEqual(x % 256, readData[x], $"Mismatch at offset {x}, expected {x % 256}, actual {readData[x]}.");
}
}
#endif
[TestMethod]
public void T28_ReadClass_DoesntCrash_When_ReadingLessThan1Byte()
{
@@ -1041,7 +1117,7 @@ namespace S7.Net.UnitTest
Assert.AreEqual(test_value, test_value2, "Compare DateTimeLong Write/Read");
}
#endregion
#endregion
#region Private methods

View File

@@ -2,6 +2,7 @@
using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace S7.Net.UnitTest
@@ -15,6 +16,7 @@ namespace S7.Net.UnitTest
{
Data = data;
}
public override bool CanRead => _position < Data.Length;
public override bool CanSeek => throw new NotImplementedException();
@@ -26,21 +28,31 @@ namespace S7.Net.UnitTest
public override long Position { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public byte[] Data { get; }
int _position = 0;
public override void Flush()
{
throw new NotImplementedException();
}
int _position = 0;
public override int Read(byte[] buffer, int offset, int count)
{
throw new NotImplementedException();
}
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
if (_position >= Data.Length)
{
return 0;
return Task.FromResult(0);
}
buffer[offset] = Data[_position];
++_position;
return 1;
return Task.FromResult(1);
}
public override long Seek(long offset, SeekOrigin origin)
@@ -78,21 +90,21 @@ namespace S7.Net.UnitTest
}
[TestMethod]
public void TPKT_ReadRestrictedStream()
public async Task TPKT_ReadRestrictedStream()
{
var fullMessage = ProtocolUnitTest.StringToByteArray("0300002902f0803203000000010002001400000401ff0400807710000100000103000000033f8ccccd");
var m = new TestStream1BytePerRead(fullMessage);
var t = TPKT.Read(m);
var t = await TPKT.ReadAsync(m, CancellationToken.None);
Assert.AreEqual(fullMessage.Length, t.Length);
Assert.AreEqual(fullMessage.Last(), t.Data.Last());
}
[TestMethod]
public void TPKT_ReadStreamTooShort()
public async Task TPKT_ReadStreamTooShort()
{
var fullMessage = ProtocolUnitTest.StringToByteArray("0300002902f0803203000000010002001400");
var m = new TestStream1BytePerRead(fullMessage);
Assert.ThrowsException<TPKTInvalidException>(() => TPKT.Read(m));
await Assert.ThrowsExceptionAsync<TPKTInvalidException>(() => TPKT.ReadAsync(m, CancellationToken.None));
}
}
}

View File

@@ -17,6 +17,19 @@ namespace S7.Net.UnitTest.TypeTests
Assert.AreEqual(Class.GetClassSize(new TestClassUnevenSize(3, 17)), 10);
}
/// <summary>
/// Ensure Uint32 is correctly parsed through ReadClass functions. Adresses issue https://github.com/S7NetPlus/s7netplus/issues/414
/// </summary>
[TestMethod]
public void TestUint32Read()
{
var result = new TestUint32();
var data = new byte[4] { 0, 0, 0, 5 };
var bytesRead = Class.FromBytes(result, data);
Assert.AreEqual(bytesRead, data.Length);
Assert.AreEqual(5u, result.Value1);
}
private class TestClassUnevenSize
{
public bool Bool { get; set; }
@@ -29,5 +42,10 @@ namespace S7.Net.UnitTest.TypeTests
Bools = new bool[bitCount];
}
}
private class TestUint32
{
public uint Value1 { get; set; }
}
}
}

View File

@@ -0,0 +1,82 @@
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace S7.Net.UnitTest.TypeTests
{
public static class TimeSpanTests
{
private static readonly TimeSpan SampleTimeSpan = new TimeSpan(12, 0, 59, 37, 856);
private static readonly byte[] SampleByteArray = { 0x3E, 0x02, 0xE8, 0x00 };
private static readonly byte[] SpecMinByteArray = { 0x80, 0x00, 0x00, 0x00 };
private static readonly byte[] SpecMaxByteArray = { 0x7F, 0xFF, 0xFF, 0xFF };
[TestClass]
public class FromByteArray
{
[TestMethod]
public void Sample()
{
AssertFromByteArrayEquals(SampleTimeSpan, SampleByteArray);
}
[TestMethod]
public void SpecMinimum()
{
AssertFromByteArrayEquals(Types.TimeSpan.SpecMinimumTimeSpan, SpecMinByteArray);
}
[TestMethod]
public void SpecMaximum()
{
AssertFromByteArrayEquals(Types.TimeSpan.SpecMaximumTimeSpan, SpecMaxByteArray);
}
private static void AssertFromByteArrayEquals(TimeSpan expected, params byte[] bytes)
{
Assert.AreEqual(expected, Types.TimeSpan.FromByteArray(bytes));
}
}
[TestClass]
public class ToByteArray
{
[TestMethod]
public void Sample()
{
AssertToByteArrayEquals(SampleTimeSpan, SampleByteArray);
}
[TestMethod]
public void SpecMinimum()
{
AssertToByteArrayEquals(Types.TimeSpan.SpecMinimumTimeSpan, SpecMinByteArray);
}
[TestMethod]
public void SpecMaximum()
{
AssertToByteArrayEquals(Types.TimeSpan.SpecMaximumTimeSpan, SpecMaxByteArray);
}
[TestMethod, ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ThrowsOnTimeBeforeSpecMinimum()
{
Types.TimeSpan.ToByteArray(TimeSpan.FromDays(-25));
}
[TestMethod, ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ThrowsOnTimeAfterSpecMaximum()
{
Types.TimeSpan.ToByteArray(new TimeSpan(30, 15, 15, 15, 15));
}
private static void AssertToByteArrayEquals(TimeSpan value, params byte[] expected)
{
CollectionAssert.AreEqual(expected, Types.TimeSpan.ToByteArray(value));
}
}
}
}

View File

@@ -55,22 +55,7 @@ namespace S7.Net
/// See: https://tools.ietf.org/html/rfc905
/// </summary>
/// <param name="stream">The socket to read from</param>
/// <returns>COTP DPDU instance</returns>
public static TPDU Read(Stream stream)
{
var tpkt = TPKT.Read(stream);
if (tpkt.Length == 0)
{
throw new TPDUInvalidException("No protocol data received");
}
return new TPDU(tpkt);
}
/// <summary>
/// Reads COTP TPDU (Transport protocol data unit) from the network stream
/// See: https://tools.ietf.org/html/rfc905
/// </summary>
/// <param name="stream">The socket to read from</param>
/// <param name="cancellationToken">A cancellation token that can be used to cancel the asynchronous operation.</param>
/// <returns>COTP DPDU instance</returns>
public static async Task<TPDU> ReadAsync(Stream stream, CancellationToken cancellationToken)
{
@@ -105,39 +90,10 @@ namespace S7.Net
/// See: https://tools.ietf.org/html/rfc905
/// </summary>
/// <param name="stream">The stream to read from</param>
/// <returns>Data in TSDU</returns>
public static byte[] Read(Stream stream)
{
var segment = TPDU.Read(stream);
if (segment.LastDataUnit)
{
return segment.Data;
}
// More segments are expected, prepare a buffer to store all data
var buffer = new byte[segment.Data.Length];
Array.Copy(segment.Data, buffer, segment.Data.Length);
while (!segment.LastDataUnit)
{
segment = TPDU.Read(stream);
var previousLength = buffer.Length;
Array.Resize(ref buffer, buffer.Length + segment.Data.Length);
Array.Copy(segment.Data, 0, buffer, previousLength, segment.Data.Length);
}
return buffer;
}
/// <summary>
/// Reads the full COTP TSDU (Transport service data unit)
/// See: https://tools.ietf.org/html/rfc905
/// </summary>
/// <param name="stream">The stream to read from</param>
/// <param name="cancellationToken">A cancellation token that can be used to cancel the asynchronous operation.</param>
/// <returns>Data in TSDU</returns>
public static async Task<byte[]> ReadAsync(Stream stream, CancellationToken cancellationToken)
{
{
var segment = await TPDU.ReadAsync(stream, cancellationToken).ConfigureAwait(false);
if (segment.LastDataUnit)

View File

@@ -138,19 +138,59 @@ namespace S7.Net
/// <summary>
/// Helper to get a bit value given a byte and the bit index.
/// Example: DB1.DBX0.5 -> var bytes = ReadBytes(DB1.DBW0); bool bit = bytes[0].SelectBit(5);
/// <br/>
/// <example>
/// Get the bit at DB1.DBX0.5:
/// <code>
/// byte data = ReadByte("DB1.DBB0");
/// bool bit = data.SelectBit(5);
/// </code>
/// </example>
/// </summary>
/// <param name="data"></param>
/// <param name="bitPosition"></param>
/// <returns></returns>
public static bool SelectBit(this byte data, int bitPosition)
/// <param name="data">The data to get from.</param>
/// <param name="index">The zero-based index of the bit to get.</param>
/// <returns>The Boolean value will get.</returns>
public static bool SelectBit(this byte data, int index)
{
int mask = 1 << bitPosition;
int mask = 1 << index;
int result = data & mask;
return (result != 0);
}
/// <summary>
/// Helper to set a bit value to the given byte at the bit index.
/// <br/>
/// <example>
/// Set the bit at index 4:
/// <code>
/// byte data = 0;
/// data.SetBit(4, true);
/// </code>
/// </example>
/// </summary>
/// <param name="data">The data to be modified.</param>
/// <param name="index">The zero-based index of the bit to set.</param>
/// <param name="value">The Boolean value to assign to the bit.</param>
public static void SetBit(this ref byte data, int index, bool value)
{
if ((uint)index > 7)
{
return;
}
if (value)
{
byte mask = (byte)(1 << index);
data |= mask;
}
else
{
byte mask = (byte)~(1 << index);
data &= mask;
}
}
/// <summary>
/// Converts from ushort value to short value; it's used to retrieve negative values from words
/// </summary>

View File

@@ -15,6 +15,11 @@
/// </summary>
Logo0BA8 = 1,
/// <summary>
/// S7 200 Smart
/// </summary>
S7200Smart = 2,
/// <summary>
/// S7 300 cpu type
/// </summary>
@@ -197,10 +202,20 @@
/// DateTIme variable type
/// </summary>
DateTime,
/// <summary>
/// IEC date (legacy) variable type
/// </summary>
Date,
/// <summary>
/// DateTimeLong variable type
/// </summary>
DateTimeLong
DateTimeLong,
/// <summary>
/// S7 TIME variable type - serialized as S7 DInt and deserialized as C# TimeSpan
/// </summary>
Time
}
}

View File

@@ -0,0 +1,23 @@
using System;
using S7.Net.Types;
using DateTime = System.DateTime;
namespace S7.Net.Helper
{
public static class DateTimeExtensions
{
public static ushort GetDaysSinceIecDateStart(this DateTime dateTime)
{
if (dateTime < Date.IecMinDate)
{
throw new ArgumentOutOfRangeException($"DateTime must be at least {Date.IecMinDate:d}");
}
if (dateTime > Date.IecMaxDate)
{
throw new ArgumentOutOfRangeException($"DateTime must be lower than {Date.IecMaxDate:d}");
}
return (ushort)(dateTime - Date.IecMinDate).TotalDays;
}
}
}

View File

@@ -1,6 +1,10 @@

using System;
using System.Buffers;
using System.IO;
namespace S7.Net.Helper
{
#if !NET5_0_OR_GREATER
internal static class MemoryStreamExtension
{
/// <summary>
@@ -10,9 +14,25 @@ namespace S7.Net.Helper
/// </summary>
/// <param name="stream"></param>
/// <param name="value"></param>
public static void WriteByteArray(this System.IO.MemoryStream stream, byte[] value)
public static void Write(this MemoryStream stream, byte[] value)
{
stream.Write(value, 0, value.Length);
}
/// <summary>
/// Helper function to write the whole content of the given byte span to a memory stream.
/// </summary>
/// <param name="stream"></param>
/// <param name="value"></param>
public static void Write(this MemoryStream stream, ReadOnlySpan<byte> value)
{
byte[] buffer = ArrayPool<byte>.Shared.Rent(value.Length);
value.CopyTo(buffer);
stream.Write(buffer, 0, value.Length);
ArrayPool<byte>.Shared.Return(buffer);
}
}
#endif
}

View File

@@ -0,0 +1,28 @@
using System;
using System.Threading;
using System.Threading.Tasks;
namespace S7.Net.Internal
{
internal class TaskQueue
{
private static readonly object Sentinel = new object();
private Task prev = Task.FromResult(Sentinel);
public async Task<T> Enqueue<T>(Func<Task<T>> action)
{
var tcs = new TaskCompletionSource<object>();
await Interlocked.Exchange(ref prev, tcs.Task).ConfigureAwait(false);
try
{
return await action.Invoke().ConfigureAwait(false);
}
finally
{
tcs.SetResult(Sentinel);
}
}
}
}

View File

@@ -1,7 +1,9 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using S7.Net.Internal;
using S7.Net.Protocol;
using S7.Net.Types;
@@ -13,14 +15,24 @@ namespace S7.Net
/// </summary>
public partial class Plc : IDisposable
{
private const int CONNECTION_TIMED_OUT_ERROR_CODE = 10060;
/// <summary>
/// The default port for the S7 protocol.
/// </summary>
public const int DefaultPort = 102;
/// <summary>
/// The default timeout (in milliseconds) used for <see cref="P:ReadTimeout"/> and <see cref="P:WriteTimeout"/>.
/// </summary>
public const int DefaultTimeout = 10_000;
private readonly TaskQueue queue = new TaskQueue();
//TCP connection to device
private TcpClient? tcpClient;
private NetworkStream? _stream;
private int readTimeout = 0; // default no timeout
private int writeTimeout = 0; // default no timeout
private int readTimeout = DefaultTimeout; // default no timeout
private int writeTimeout = DefaultTimeout; // default no timeout
/// <summary>
/// IP address of the PLC
@@ -32,6 +44,11 @@ namespace S7.Net
/// </summary>
public int Port { get; }
/// <summary>
/// The TSAP addresses used during the connection request.
/// </summary>
public TsapPair TsapPair { get; set; }
/// <summary>
/// CPU type of the PLC
/// </summary>
@@ -104,25 +121,14 @@ namespace S7.Net
/// </summary>
/// <param name="cpu">CpuType of the PLC (select from the enum)</param>
/// <param name="ip">Ip address of the PLC</param>
/// <param name="port">Port address of the PLC, default 102</param>
/// <param name="rack">rack of the PLC, usually it's 0, but check in the hardware configuration of Step7 or TIA portal</param>
/// <param name="slot">slot of the CPU of the PLC, usually it's 2 for S7300-S7400, 0 for S7-1200 and S7-1500.
/// If you use an external ethernet card, this must be set accordingly.</param>
public Plc(CpuType cpu, string ip, int port, Int16 rack, Int16 slot)
public Plc(CpuType cpu, string ip, Int16 rack, Int16 slot)
: this(cpu, ip, DefaultPort, rack, slot)
{
if (!Enum.IsDefined(typeof(CpuType), cpu))
throw new ArgumentException($"The value of argument '{nameof(cpu)}' ({cpu}) is invalid for Enum type '{typeof(CpuType).Name}'.", nameof(cpu));
if (string.IsNullOrEmpty(ip))
throw new ArgumentException("IP address must valid.", nameof(ip));
CPU = cpu;
IP = ip;
Port = port;
Rack = rack;
Slot = slot;
MaxPDUSize = 240;
}
/// <summary>
/// Creates a PLC object with all the parameters needed for connections.
/// For S7-1200 and S7-1500, the default is rack = 0 and slot = 0.
@@ -131,23 +137,51 @@ namespace S7.Net
/// </summary>
/// <param name="cpu">CpuType of the PLC (select from the enum)</param>
/// <param name="ip">Ip address of the PLC</param>
/// <param name="port">Port number used for the connection, default 102.</param>
/// <param name="rack">rack of the PLC, usually it's 0, but check in the hardware configuration of Step7 or TIA portal</param>
/// <param name="slot">slot of the CPU of the PLC, usually it's 2 for S7300-S7400, 0 for S7-1200 and S7-1500.
/// If you use an external ethernet card, this must be set accordingly.</param>
public Plc(CpuType cpu, string ip, Int16 rack, Int16 slot)
public Plc(CpuType cpu, string ip, int port, Int16 rack, Int16 slot)
: this(ip, port, TsapPair.GetDefaultTsapPair(cpu, rack, slot))
{
if (!Enum.IsDefined(typeof(CpuType), cpu))
throw new ArgumentException($"The value of argument '{nameof(cpu)}' ({cpu}) is invalid for Enum type '{typeof(CpuType).Name}'.", nameof(cpu));
throw new ArgumentException(
$"The value of argument '{nameof(cpu)}' ({cpu}) is invalid for Enum type '{typeof(CpuType).Name}'.",
nameof(cpu));
CPU = cpu;
Rack = rack;
Slot = slot;
}
/// <summary>
/// Creates a PLC object with all the parameters needed for connections.
/// For S7-1200 and S7-1500, the default is rack = 0 and slot = 0.
/// You need slot > 0 if you are connecting to external ethernet card (CP).
/// For S7-300 and S7-400 the default is rack = 0 and slot = 2.
/// </summary>
/// <param name="ip">Ip address of the PLC</param>
/// <param name="tsapPair">The TSAP addresses used for the connection request.</param>
public Plc(string ip, TsapPair tsapPair) : this(ip, DefaultPort, tsapPair)
{
}
/// <summary>
/// Creates a PLC object with all the parameters needed for connections. Use this constructor
/// if you want to manually override the TSAP addresses used during the connection request.
/// </summary>
/// <param name="ip">Ip address of the PLC</param>
/// <param name="port">Port number used for the connection, default 102.</param>
/// <param name="tsapPair">The TSAP addresses used for the connection request.</param>
public Plc(string ip, int port, TsapPair tsapPair)
{
if (string.IsNullOrEmpty(ip))
throw new ArgumentException("IP address must valid.", nameof(ip));
CPU = cpu;
IP = ip;
Port = 102;
Rack = rack;
Slot = slot;
Port = port;
MaxPDUSize = 240;
TsapPair = tsapPair;
}
/// <summary>
@@ -158,6 +192,7 @@ namespace S7.Net
if (tcpClient != null)
{
if (tcpClient.Connected) tcpClient.Close();
tcpClient = null; // Can not reuse TcpClient once connection gets closed.
}
}
@@ -242,6 +277,16 @@ namespace S7.Net
}
}
private Stream GetStreamIfAvailable()
{
if (_stream == null)
{
throw new PlcException(ErrorCode.ConnectionError, "Plc is not connected");
}
return _stream;
}
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls

View File

@@ -6,7 +6,7 @@ using System.Runtime.Serialization;
namespace S7.Net
{
internal class WrongNumberOfBytesException : Exception
public class WrongNumberOfBytesException : Exception
{
public WrongNumberOfBytesException() : base()
{
@@ -27,7 +27,7 @@ namespace S7.Net
#endif
}
internal class InvalidAddressException : Exception
public class InvalidAddressException : Exception
{
public InvalidAddressException() : base ()
{
@@ -48,7 +48,7 @@ namespace S7.Net
#endif
}
internal class InvalidVariableTypeException : Exception
public class InvalidVariableTypeException : Exception
{
public InvalidVariableTypeException() : base()
{
@@ -69,7 +69,7 @@ namespace S7.Net
#endif
}
internal class TPKTInvalidException : Exception
public class TPKTInvalidException : Exception
{
public TPKTInvalidException() : base()
{
@@ -90,7 +90,7 @@ namespace S7.Net
#endif
}
internal class TPDUInvalidException : Exception
public class TPDUInvalidException : Exception
{
public TPDUInvalidException() : base()
{

View File

@@ -1,7 +1,6 @@
using S7.Net.Helper;
using S7.Net.Protocol.S7;
using S7.Net.Types;
using System;
using System.Collections.Generic;
using System.Linq;
using DateTime = S7.Net.Types.DateTime;
@@ -10,29 +9,104 @@ namespace S7.Net
{
public partial class Plc
{
/// <summary>
/// Creates the header to read bytes from the PLC
/// </summary>
/// <param name="amount"></param>
/// <returns></returns>
private static void BuildHeaderPackage(System.IO.MemoryStream stream, int amount = 1)
private static void WriteTpktHeader(System.IO.MemoryStream stream, int length)
{
//header size = 19 bytes
stream.WriteByteArray(new byte[] { 0x03, 0x00 });
//complete package size
stream.WriteByteArray(Types.Int.ToByteArray((short)(19 + (12 * amount))));
stream.WriteByteArray(new byte[] { 0x02, 0xf0, 0x80, 0x32, 0x01, 0x00, 0x00, 0x00, 0x00 });
//data part size
stream.WriteByteArray(Types.Word.ToByteArray((ushort)(2 + (amount * 12))));
stream.WriteByteArray(new byte[] { 0x00, 0x00, 0x04 });
stream.Write(new byte[] { 0x03, 0x00 });
stream.Write(Word.ToByteArray((ushort) length));
}
private static void WriteDataHeader(System.IO.MemoryStream stream)
{
stream.Write(new byte[] { 0x02, 0xf0, 0x80 });
}
private static void WriteS7Header(System.IO.MemoryStream stream, byte messageType, int parameterLength, int dataLength)
{
stream.WriteByte(0x32); // S7 protocol ID
stream.WriteByte(messageType); // Message type
stream.Write(new byte[] { 0x00, 0x00 }); // Reserved
stream.Write(new byte[] { 0x00, 0x00 }); // PDU ref
stream.Write(Word.ToByteArray((ushort) parameterLength));
stream.Write(Word.ToByteArray((ushort) dataLength));
}
/// <summary>
/// Creates the header to read bytes from the PLC.
/// </summary>
/// <param name="stream">The stream to write to.</param>
/// <param name="amount">The number of items to read.</param>
private static void WriteReadHeader(System.IO.MemoryStream stream, int amount = 1)
{
// Header size 19, 12 bytes per item
WriteTpktHeader(stream, 19 + 12 * amount);
WriteDataHeader(stream);
WriteS7Header(stream, 0x01, 2 + 12 * amount, 0);
// Function code: read request
stream.WriteByte(0x04);
//amount of requests
stream.WriteByte((byte)amount);
}
private static void WriteUserDataHeader(System.IO.MemoryStream stream, int parameterLength, int dataLength)
{
const byte s7MessageTypeUserData = 0x07;
WriteTpktHeader(stream, 17 + parameterLength + dataLength);
WriteDataHeader(stream);
WriteS7Header(stream, s7MessageTypeUserData, parameterLength, dataLength);
}
private static void WriteUserDataRequest(System.IO.MemoryStream stream, byte functionGroup, byte subFunction, int dataLength)
{
WriteUserDataHeader(stream, 8, dataLength);
// Parameter
const byte userDataMethodRequest = 0x11;
const byte userDataTypeRequest = 0x4;
// Parameter head
stream.Write(new byte[] { 0x00, 0x01, 0x12 });
// Parameter length
stream.WriteByte(0x04);
// Method
stream.WriteByte(userDataMethodRequest);
// Type / function group
stream.WriteByte((byte)(userDataTypeRequest << 4 | (functionGroup & 0x0f)));
// Subfunction
stream.WriteByte(subFunction);
// Sequence number
stream.WriteByte(0);
}
private static void WriteSzlReadRequest(System.IO.MemoryStream stream, ushort szlId, ushort szlIndex)
{
// Parameter
const byte szlFunctionGroupCpuFunctions = 0b100;
const byte subFunctionReadSzl = 0x01;
WriteUserDataRequest(stream, szlFunctionGroupCpuFunctions, subFunctionReadSzl, 8);
// Data
const byte success = 0xff;
const byte transportSizeOctetString = 0x09;
// Return code
stream.WriteByte(success);
// Transport size
stream.WriteByte(transportSizeOctetString);
// Length
stream.Write(Word.ToByteArray(4));
// SZL-ID
stream.Write(Word.ToByteArray(szlId));
// SZL-Index
stream.Write(Word.ToByteArray(szlIndex));
}
/// <summary>
/// Create the bytes-package to request data from the PLC. You have to specify the memory type (dataType),
/// the address of the memory, the address of the byte and the bytes count.
/// </summary>
/// <param name="stream">The stream to write the read data request to.</param>
/// <param name="dataType">MemoryType (DB, Timer, Counter, etc.)</param>
/// <param name="db">Address of the memory to be read</param>
/// <param name="startByteAdr">Start address of the byte</param>
@@ -41,7 +115,7 @@ namespace S7.Net
private static void BuildReadDataRequestPackage(System.IO.MemoryStream stream, DataType dataType, int db, int startByteAdr, int count = 1)
{
//single data req = 12
stream.WriteByteArray(new byte[] { 0x12, 0x0a, 0x10 });
stream.Write(new byte[] { 0x12, 0x0a, 0x10 });
switch (dataType)
{
case DataType.Timer:
@@ -53,8 +127,8 @@ namespace S7.Net
break;
}
stream.WriteByteArray(Word.ToByteArray((ushort)(count)));
stream.WriteByteArray(Word.ToByteArray((ushort)(db)));
stream.Write(Word.ToByteArray((ushort)(count)));
stream.Write(Word.ToByteArray((ushort)(db)));
stream.WriteByte((byte)dataType);
var overflow = (int)(startByteAdr * 8 / 0xffffU); // handles words with address bigger than 8191
stream.WriteByte((byte)overflow);
@@ -62,10 +136,10 @@ namespace S7.Net
{
case DataType.Timer:
case DataType.Counter:
stream.WriteByteArray(Types.Word.ToByteArray((ushort)(startByteAdr)));
stream.Write(Word.ToByteArray((ushort)(startByteAdr)));
break;
default:
stream.WriteByteArray(Types.Word.ToByteArray((ushort)((startByteAdr) * 8)));
stream.Write(Word.ToByteArray((ushort)((startByteAdr) * 8)));
break;
}
}
@@ -168,6 +242,24 @@ namespace S7.Net
{
return DateTimeLong.ToArray(bytes);
}
case VarType.Time:
if (varCount == 1)
{
return TimeSpan.FromByteArray(bytes);
}
else
{
return TimeSpan.ToArray(bytes);
}
case VarType.Date:
if (varCount == 1)
{
return Date.FromByteArray(bytes);
}
else
{
return Date.ToArray(bytes);
}
default:
return null;
}
@@ -197,10 +289,12 @@ namespace S7.Net
case VarType.Timer:
case VarType.Int:
case VarType.Counter:
case VarType.Date:
return varCount * 2;
case VarType.DWord:
case VarType.DInt:
case VarType.Real:
case VarType.Time:
return varCount * 4;
case VarType.LReal:
case VarType.DateTime:
@@ -242,8 +336,8 @@ namespace S7.Net
// next Item
offset += byteCnt;
// Fill byte in response when bytecount is odd
if (dataItem.Count % 2 != 0 && (dataItem.VarType == VarType.Byte || dataItem.VarType == VarType.Bit))
// Always align to even offset
if (offset % 2 != 0)
offset++;
}
}
@@ -253,7 +347,7 @@ namespace S7.Net
int packageSize = 19 + (dataItems.Count * 12);
var package = new System.IO.MemoryStream(packageSize);
BuildHeaderPackage(package, dataItems.Count);
WriteReadHeader(package, dataItems.Count);
foreach (var dataItem in dataItems)
{
@@ -262,5 +356,15 @@ namespace S7.Net
return package.ToArray();
}
private static byte[] BuildSzlReadRequestPackage(ushort szlId, ushort szlIndex)
{
var stream = new System.IO.MemoryStream();
WriteSzlReadRequest(stream, szlId, szlIndex);
stream.SetLength(stream.Position);
return stream.ToArray();
}
}
}

92
S7.Net/Plc.Clock.cs Normal file
View File

@@ -0,0 +1,92 @@
using System;
using System.IO;
using System.Linq;
using S7.Net.Helper;
using S7.Net.Types;
using DateTime = System.DateTime;
namespace S7.Net;
partial class Plc
{
private const byte SzlFunctionGroupTimers = 0x07;
private const byte SzlSubFunctionReadClock = 0x01;
private const byte SzlSubFunctionWriteClock = 0x02;
private const byte TransportSizeOctetString = 0x09;
private const int PduErrOffset = 20;
private const int UserDataResultOffset = PduErrOffset + 2;
/// <summary>
/// The length in bytes of DateTime stored in the PLC.
/// </summary>
private const int DateTimeLength = 10;
private static byte[] BuildClockReadRequest()
{
var stream = new MemoryStream();
WriteUserDataRequest(stream, SzlFunctionGroupTimers, SzlSubFunctionReadClock, 4);
stream.Write(new byte[] { 0x0a, 0x00, 0x00, 0x00 });
stream.SetLength(stream.Position);
return stream.ToArray();
}
private static DateTime ParseClockReadResponse(byte[] message)
{
const int udLenOffset = UserDataResultOffset + 2;
const int udValueOffset = udLenOffset + 2;
const int dateTimeSkip = 2;
AssertPduResult(message);
AssertUserDataResult(message, 0xff);
var len = Word.FromByteArray(message.Skip(udLenOffset).Take(2).ToArray());
if (len != DateTimeLength)
{
throw new Exception($"Unexpected response length {len}, expected {DateTimeLength}.");
}
// Skip first 2 bytes from date time value because DateTime.FromByteArray doesn't parse them.
return Types.DateTime.FromByteArray(message.Skip(udValueOffset + dateTimeSkip)
.Take(DateTimeLength - dateTimeSkip).ToArray());
}
private static byte[] BuildClockWriteRequest(DateTime value)
{
var stream = new MemoryStream();
WriteUserDataRequest(stream, SzlFunctionGroupTimers, SzlSubFunctionWriteClock, 14);
stream.Write(new byte[] { 0xff, TransportSizeOctetString, 0x00, DateTimeLength });
// Start of DateTime value, DateTime.ToByteArray only serializes the final 8 bytes
stream.Write(new byte[] { 0x00, 0x19 });
stream.Write(Types.DateTime.ToByteArray(value));
stream.SetLength(stream.Position);
return stream.ToArray();
}
private static void ParseClockWriteResponse(byte[] message)
{
AssertPduResult(message);
AssertUserDataResult(message, 0x0a);
}
private static void AssertPduResult(byte[] message)
{
var pduErr = Word.FromByteArray(message.Skip(PduErrOffset).Take(2).ToArray());
if (pduErr != 0)
{
throw new Exception($"Response from PLC indicates error 0x{pduErr:X4}.");
}
}
private static void AssertUserDataResult(byte[] message, byte expected)
{
var dtResult = message[UserDataResultOffset];
if (dtResult != expected)
{
throw new Exception($"Response from PLC was 0x{dtResult:X2}, expected 0x{expected:X2}.");
}
}
}

View File

@@ -1,11 +1,11 @@
using S7.Net.Types;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Threading.Tasks;
using S7.Net.Protocol;
using System.IO;
using System.Threading;
using S7.Net.Protocol.S7;
@@ -25,51 +25,62 @@ namespace S7.Net
/// <returns>A task that represents the asynchronous open operation.</returns>
public async Task OpenAsync(CancellationToken cancellationToken = default)
{
var stream = await ConnectAsync().ConfigureAwait(false);
var stream = await ConnectAsync(cancellationToken).ConfigureAwait(false);
try
{
cancellationToken.ThrowIfCancellationRequested();
await EstablishConnection(stream, cancellationToken).ConfigureAwait(false);
_stream = stream;
await queue.Enqueue(async () =>
{
cancellationToken.ThrowIfCancellationRequested();
await EstablishConnection(stream, cancellationToken).ConfigureAwait(false);
_stream = stream;
return default(object);
}).ConfigureAwait(false);
}
catch(Exception)
catch (Exception)
{
stream.Dispose();
throw;
}
}
private async Task<NetworkStream> ConnectAsync()
private async Task<NetworkStream> ConnectAsync(CancellationToken cancellationToken)
{
tcpClient = new TcpClient();
ConfigureConnection();
#if NET5_0_OR_GREATER
await tcpClient.ConnectAsync(IP, Port, cancellationToken).ConfigureAwait(false);
#else
await tcpClient.ConnectAsync(IP, Port).ConfigureAwait(false);
#endif
return tcpClient.GetStream();
}
private async Task EstablishConnection(NetworkStream stream, CancellationToken cancellationToken)
private async Task EstablishConnection(Stream stream, CancellationToken cancellationToken)
{
await RequestConnection(stream, cancellationToken).ConfigureAwait(false);
await SetupConnection(stream, cancellationToken).ConfigureAwait(false);
}
private async Task RequestConnection(NetworkStream stream, CancellationToken cancellationToken)
private async Task RequestConnection(Stream stream, CancellationToken cancellationToken)
{
var requestData = ConnectionRequest.GetCOTPConnectionRequest(CPU, Rack, Slot);
await stream.WriteAsync(requestData, 0, requestData.Length).ConfigureAwait(false);
var response = await COTP.TPDU.ReadAsync(stream, cancellationToken).ConfigureAwait(false);
var requestData = ConnectionRequest.GetCOTPConnectionRequest(TsapPair);
var response = await NoLockRequestTpduAsync(stream, requestData, cancellationToken).ConfigureAwait(false);
if (response.PDUType != COTP.PduType.ConnectionConfirmed)
{
throw new InvalidDataException("Connection request was denied", response.TPkt.Data, 1, 0x0d);
}
}
private async Task SetupConnection(NetworkStream stream, CancellationToken cancellationToken)
private async Task SetupConnection(Stream stream, CancellationToken cancellationToken)
{
var setupData = GetS7ConnectionSetup();
await stream.WriteAsync(setupData, 0, setupData.Length).ConfigureAwait(false);
var s7data = await COTP.TSDU.ReadAsync(stream, cancellationToken).ConfigureAwait(false);
var s7data = await NoLockRequestTsduAsync(stream, setupData, 0, setupData.Length, cancellationToken)
.ConfigureAwait(false);
if (s7data.Length < 2)
throw new WrongNumberOfBytesException("Not enough data received in response to Communication Setup");
@@ -84,7 +95,6 @@ namespace S7.Net
MaxPDUSize = s7data[18] * 256 + s7data[19];
}
/// <summary>
/// Reads a number of bytes from a DB starting from a specified index. This handles more than 200 bytes with multiple requests.
/// If the read was not successful, check LastErrorCode or LastErrorString.
@@ -99,20 +109,38 @@ namespace S7.Net
public async Task<byte[]> ReadBytesAsync(DataType dataType, int db, int startByteAdr, int count, CancellationToken cancellationToken = default)
{
var resultBytes = new byte[count];
int index = 0;
while (count > 0)
{
//This works up to MaxPDUSize-1 on SNAP7. But not MaxPDUSize-0.
var maxToRead = Math.Min(count, MaxPDUSize - 18);
await ReadBytesWithSingleRequestAsync(dataType, db, startByteAdr + index, resultBytes, index, maxToRead, cancellationToken).ConfigureAwait(false);
count -= maxToRead;
index += maxToRead;
}
await ReadBytesAsync(resultBytes, dataType, db, startByteAdr, cancellationToken).ConfigureAwait(false);
return resultBytes;
}
/// <summary>
/// Read and decode a certain number of bytes of the "VarType" provided.
/// Reads a number of bytes from a DB starting from a specified index. This handles more than 200 bytes with multiple requests.
/// If the read was not successful, check LastErrorCode or LastErrorString.
/// </summary>
/// <param name="buffer">Buffer to receive the read bytes. The <see cref="Memory{T}.Length"/> determines the number of bytes to read.</param>
/// <param name="dataType">Data type of the memory area, can be DB, Timer, Counter, Merker(Memory), Input, Output.</param>
/// <param name="db">Address of the memory area (if you want to read DB1, this is set to 1). This must be set also for other memory area types: counters, timers,etc.</param>
/// <param name="startByteAdr">Start byte address. If you want to read DB1.DBW200, this is 200.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is None.
/// Please note that cancellation is advisory/cooperative and will not lead to immediate cancellation in all cases.</param>
/// <returns>Returns the bytes in an array</returns>
public async Task ReadBytesAsync(Memory<byte> buffer, DataType dataType, int db, int startByteAdr, CancellationToken cancellationToken = default)
{
int index = 0;
while (buffer.Length > 0)
{
//This works up to MaxPDUSize-1 on SNAP7. But not MaxPDUSize-0.
var maxToRead = Math.Min(buffer.Length, MaxPDUSize - 18);
await ReadBytesWithSingleRequestAsync(dataType, db, startByteAdr + index, buffer.Slice(0, maxToRead), cancellationToken).ConfigureAwait(false);
buffer = buffer.Slice(maxToRead);
index += maxToRead;
}
}
/// <summary>
/// Read and decode a certain number of bytes of the "VarType" provided.
/// This can be used to read multiple consecutive variables of the same type (Word, DWord, Int, etc).
/// If the read was not successful, check LastErrorCode or LastErrorString.
/// </summary>
@@ -179,10 +207,10 @@ namespace S7.Net
}
/// <summary>
/// Reads all the bytes needed to fill a class in C#, starting from a certain address, and set all the properties values to the value that are read from the PLC.
/// Reads all the bytes needed to fill a class in C#, starting from a certain address, and set all the properties values to the value that are read from the PLC.
/// This reads only properties, it doesn't read private variable or public variable without {get;set;} specified.
/// </summary>
/// <param name="sourceClass">Instance of the class that will store the values</param>
/// <param name="sourceClass">Instance of the class that will store the values</param>
/// <param name="db">Index of the DB; es.: 1 is for DB1</param>
/// <param name="startByteAdr">Start byte address. If you want to read DB1.DBW200, this is 200.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is None.
@@ -205,7 +233,7 @@ namespace S7.Net
}
/// <summary>
/// Reads all the bytes needed to fill a class in C#, starting from a certain address, and set all the properties values to the value that are read from the PLC.
/// Reads all the bytes needed to fill a class in C#, starting from a certain address, and set all the properties values to the value that are read from the PLC.
/// This reads only properties, it doesn't read private variable or public variable without {get;set;} specified. To instantiate the class defined by the generic
/// type, the class needs a default constructor.
/// </summary>
@@ -221,7 +249,7 @@ namespace S7.Net
}
/// <summary>
/// Reads all the bytes needed to fill a class in C#, starting from a certain address, and set all the properties values to the value that are read from the PLC.
/// Reads all the bytes needed to fill a class in C#, starting from a certain address, and set all the properties values to the value that are read from the PLC.
/// This reads only properties, it doesn't read private variable or public variable without {get;set;} specified.
/// </summary>
/// <typeparam name="T">The class that will be instantiated</typeparam>
@@ -245,10 +273,10 @@ namespace S7.Net
}
/// <summary>
/// Reads multiple vars in a single request.
/// Reads multiple vars in a single request.
/// You have to create and pass a list of DataItems and you obtain in response the same list with the values.
/// Values are stored in the property "Value" of the dataItem and are already converted.
/// If you don't want the conversion, just create a dataItem of bytes.
/// If you don't want the conversion, just create a dataItem of bytes.
/// The number of DataItems as well as the total size of the requested data can not exceed a certain limit (protocol restriction).
/// </summary>
/// <param name="dataItems">List of dataitems that contains the list of variables that must be read.</param>
@@ -256,18 +284,15 @@ namespace S7.Net
/// Please note that cancellation is advisory/cooperative and will not lead to immediate cancellation in all cases.</param>
public async Task<List<DataItem>> ReadMultipleVarsAsync(List<DataItem> dataItems, CancellationToken cancellationToken = default)
{
//Snap7 seems to choke on PDU sizes above 256 even if snap7
//Snap7 seems to choke on PDU sizes above 256 even if snap7
//replies with bigger PDU size in connection setup.
AssertPduSizeForRead(dataItems);
var stream = GetStreamIfAvailable();
try
{
var dataToSend = BuildReadRequestPackage(dataItems.Select(d => DataItem.GetDataItemAddress(d)).ToList());
await stream.WriteAsync(dataToSend, 0, dataToSend.Length).ConfigureAwait(false);
var s7data = await RequestTsduAsync(dataToSend, cancellationToken);
var s7data = await COTP.TSDU.ReadAsync(stream, cancellationToken).ConfigureAwait(false);
ValidateResponseCode((ReadWriteErrorCode)s7data[14]);
ParseDataIntoDataItems(s7data, dataItems);
@@ -287,6 +312,48 @@ namespace S7.Net
return dataItems;
}
/// <summary>
/// Read the PLC clock value.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is None.
/// Please note that cancellation is advisory/cooperative and will not lead to immediate cancellation in all cases.</param>
/// <returns>A task that represents the asynchronous operation, with it's result set to the current PLC time on completion.</returns>
public async Task<System.DateTime> ReadClockAsync(CancellationToken cancellationToken = default)
{
var request = BuildClockReadRequest();
var response = await RequestTsduAsync(request, cancellationToken);
return ParseClockReadResponse(response);
}
/// <summary>
/// Write the PLC clock value.
/// </summary>
/// <param name="value">The date and time to set the PLC clock to</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is None.
/// Please note that cancellation is advisory/cooperative and will not lead to immediate cancellation in all cases.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public async Task WriteClockAsync(System.DateTime value, CancellationToken cancellationToken = default)
{
var request = BuildClockWriteRequest(value);
var response = await RequestTsduAsync(request, cancellationToken);
ParseClockWriteResponse(response);
}
/// <summary>
/// Read the current status from the PLC. A value of 0x08 indicates the PLC is in run status, regardless of the PLC type.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is None.
/// Please note that cancellation is advisory/cooperative and will not lead to immediate cancellation in all cases.</param>
/// <returns>A task that represents the asynchronous operation, with it's result set to the current PLC status on completion.</returns>
public async Task<byte> ReadStatusAsync(CancellationToken cancellationToken = default)
{
var dataToSend = BuildSzlReadRequestPackage(0x0424, 0);
var s7data = await RequestTsduAsync(dataToSend, cancellationToken);
return (byte) (s7data[37] & 0x0f);
}
/// <summary>
/// Write a number of bytes from a DB starting from a specified index. This handles more than 200 bytes with multiple requests.
@@ -299,15 +366,30 @@ namespace S7.Net
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is None.
/// Please note that cancellation is advisory/cooperative and will not lead to immediate cancellation in all cases.</param>
/// <returns>A task that represents the asynchronous write operation.</returns>
public async Task WriteBytesAsync(DataType dataType, int db, int startByteAdr, byte[] value, CancellationToken cancellationToken = default)
public Task WriteBytesAsync(DataType dataType, int db, int startByteAdr, byte[] value, CancellationToken cancellationToken = default)
{
return WriteBytesAsync(dataType, db, startByteAdr, value.AsMemory(), cancellationToken);
}
/// <summary>
/// Write a number of bytes from a DB starting from a specified index. This handles more than 200 bytes with multiple requests.
/// If the write was not successful, check LastErrorCode or LastErrorString.
/// </summary>
/// <param name="dataType">Data type of the memory area, can be DB, Timer, Counter, Merker(Memory), Input, Output.</param>
/// <param name="db">Address of the memory area (if you want to read DB1, this is set to 1). This must be set also for other memory area types: counters, timers,etc.</param>
/// <param name="startByteAdr">Start byte address. If you want to write DB1.DBW200, this is 200.</param>
/// <param name="value">Bytes to write. If more than 200, multiple requests will be made.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is None.
/// Please note that cancellation is advisory/cooperative and will not lead to immediate cancellation in all cases.</param>
/// <returns>A task that represents the asynchronous write operation.</returns>
public async Task WriteBytesAsync(DataType dataType, int db, int startByteAdr, ReadOnlyMemory<byte> value, CancellationToken cancellationToken = default)
{
int localIndex = 0;
int count = value.Length;
while (count > 0)
while (value.Length > 0)
{
var maxToWrite = (int)Math.Min(count, MaxPDUSize - 35);
await WriteBytesWithASingleRequestAsync(dataType, db, startByteAdr + localIndex, value, localIndex, maxToWrite, cancellationToken).ConfigureAwait(false);
count -= maxToWrite;
var maxToWrite = (int)Math.Min(value.Length, MaxPDUSize - 35);
await WriteBytesWithASingleRequestAsync(dataType, db, startByteAdr + localIndex, value.Slice(0, maxToWrite), cancellationToken).ConfigureAwait(false);
value = value.Slice(maxToWrite);
localIndex += maxToWrite;
}
}
@@ -389,7 +471,6 @@ namespace S7.Net
/// <summary>
/// Writes a single variable from the PLC, takes in input strings like "DB1.DBX0.0", "DB20.DBD200", "MB20", "T45", etc.
/// If the write was not successful, check <see cref="LastErrorCode"/> or <see cref="LastErrorString"/>.
/// </summary>
/// <param name="variable">Input strings like "DB1.DBX0.0", "DB20.DBD200", "MB20", "T45", etc.</param>
/// <param name="value">Value to be written to the PLC</param>
@@ -433,17 +514,14 @@ namespace S7.Net
await WriteBytesAsync(DataType.DataBlock, db, startByteAdr, bytes, cancellationToken).ConfigureAwait(false);
}
private async Task ReadBytesWithSingleRequestAsync(DataType dataType, int db, int startByteAdr, byte[] buffer, int offset, int count, CancellationToken cancellationToken)
private async Task ReadBytesWithSingleRequestAsync(DataType dataType, int db, int startByteAdr, Memory<byte> buffer, CancellationToken cancellationToken)
{
var stream = GetStreamIfAvailable();
var dataToSend = BuildReadRequestPackage(new[] { new DataItemAddress(dataType, db, startByteAdr, buffer.Length) });
var dataToSend = BuildReadRequestPackage(new [] { new DataItemAddress(dataType, db, startByteAdr, count)});
await stream.WriteAsync(dataToSend, 0, dataToSend.Length, cancellationToken);
var s7data = await RequestTsduAsync(dataToSend, cancellationToken);
AssertReadResponse(s7data, buffer.Length);
var s7data = await COTP.TSDU.ReadAsync(stream, cancellationToken).ConfigureAwait(false);
AssertReadResponse(s7data, count);
Array.Copy(s7data, 18, buffer, offset, count);
s7data.AsSpan(18, buffer.Length).CopyTo(buffer.Span);
}
/// <summary>
@@ -456,13 +534,11 @@ namespace S7.Net
{
AssertPduSizeForWrite(dataItems);
var stream = GetStreamIfAvailable();
var message = new ByteArray();
var length = S7WriteMultiple.CreateRequest(message, dataItems);
await stream.WriteAsync(message.Array, 0, length).ConfigureAwait(false);
var response = await COTP.TSDU.ReadAsync(stream, CancellationToken.None).ConfigureAwait(false);
var response = await RequestTsduAsync(message.Array, 0, length).ConfigureAwait(false);
S7WriteMultiple.ParseResponse(response, response.Length, dataItems);
}
@@ -473,18 +549,15 @@ namespace S7.Net
/// <param name="db">Address of the memory area (if you want to read DB1, this is set to 1). This must be set also for other memory area types: counters, timers,etc.</param>
/// <param name="startByteAdr">Start byte address. If you want to read DB1.DBW200, this is 200.</param>
/// <param name="value">Bytes to write. The lenght of this parameter can't be higher than 200. If you need more, use recursion.</param>
/// <param name="cancellationToken">A cancellation token that can be used to cancel the asynchronous operation.</param>
/// <returns>A task that represents the asynchronous write operation.</returns>
private async Task WriteBytesWithASingleRequestAsync(DataType dataType, int db, int startByteAdr, byte[] value, int dataOffset, int count, CancellationToken cancellationToken)
private async Task WriteBytesWithASingleRequestAsync(DataType dataType, int db, int startByteAdr, ReadOnlyMemory<byte> value, CancellationToken cancellationToken)
{
try
{
var stream = GetStreamIfAvailable();
var dataToSend = BuildWriteBytesPackage(dataType, db, startByteAdr, value, dataOffset, count);
var dataToSend = BuildWriteBytesPackage(dataType, db, startByteAdr, value.Span);
var s7data = await RequestTsduAsync(dataToSend, cancellationToken).ConfigureAwait(false);
await stream.WriteAsync(dataToSend, 0, dataToSend.Length, cancellationToken).ConfigureAwait(false);
var s7data = await COTP.TSDU.ReadAsync(stream, cancellationToken).ConfigureAwait(false);
ValidateResponseCode((ReadWriteErrorCode)s7data[14]);
}
catch (OperationCanceledException)
@@ -499,15 +572,11 @@ namespace S7.Net
private async Task WriteBitWithASingleRequestAsync(DataType dataType, int db, int startByteAdr, int bitAdr, bool bitValue, CancellationToken cancellationToken)
{
var stream = GetStreamIfAvailable();
try
{
var dataToSend = BuildWriteBitPackage(dataType, db, startByteAdr, bitValue, bitAdr);
var s7data = await RequestTsduAsync(dataToSend, cancellationToken).ConfigureAwait(false);
await stream.WriteAsync(dataToSend, 0, dataToSend.Length).ConfigureAwait(false);
var s7data = await COTP.TSDU.ReadAsync(stream, cancellationToken).ConfigureAwait(false);
ValidateResponseCode((ReadWriteErrorCode)s7data[14]);
}
catch (OperationCanceledException)
@@ -520,13 +589,57 @@ namespace S7.Net
}
}
private Stream GetStreamIfAvailable()
private Task<byte[]> RequestTsduAsync(byte[] requestData, CancellationToken cancellationToken = default) =>
RequestTsduAsync(requestData, 0, requestData.Length, cancellationToken);
private Task<byte[]> RequestTsduAsync(byte[] requestData, int offset, int length, CancellationToken cancellationToken = default)
{
if (_stream == null)
var stream = GetStreamIfAvailable();
return queue.Enqueue(() =>
NoLockRequestTsduAsync(stream, requestData, offset, length, cancellationToken));
}
private async Task<COTP.TPDU> NoLockRequestTpduAsync(Stream stream, byte[] requestData,
CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
try
{
throw new PlcException(ErrorCode.ConnectionError, "Plc is not connected");
using var closeOnCancellation = cancellationToken.Register(Close);
await stream.WriteAsync(requestData, 0, requestData.Length, cancellationToken).ConfigureAwait(false);
return await COTP.TPDU.ReadAsync(stream, cancellationToken).ConfigureAwait(false);
}
catch (Exception exc)
{
if (exc is TPDUInvalidException || exc is TPKTInvalidException)
{
Close();
}
throw;
}
}
private async Task<byte[]> NoLockRequestTsduAsync(Stream stream, byte[] requestData, int offset, int length,
CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
try
{
using var closeOnCancellation = cancellationToken.Register(Close);
await stream.WriteAsync(requestData, offset, length, cancellationToken).ConfigureAwait(false);
return await COTP.TSDU.ReadAsync(stream, cancellationToken).ConfigureAwait(false);
}
catch (Exception exc)
{
if (exc is TPDUInvalidException || exc is TPKTInvalidException)
{
Close();
}
throw;
}
return _stream;
}
}
}

View File

@@ -2,8 +2,6 @@
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using S7.Net.Protocol;
using S7.Net.Helper;
@@ -41,20 +39,36 @@ namespace S7.Net
public byte[] ReadBytes(DataType dataType, int db, int startByteAdr, int count)
{
var result = new byte[count];
int index = 0;
while (count > 0)
{
//This works up to MaxPDUSize-1 on SNAP7. But not MaxPDUSize-0.
var maxToRead = Math.Min(count, MaxPDUSize - 18);
ReadBytesWithSingleRequest(dataType, db, startByteAdr + index, result, index, maxToRead);
count -= maxToRead;
index += maxToRead;
}
ReadBytes(result, dataType, db, startByteAdr);
return result;
}
/// <summary>
/// Read and decode a certain number of bytes of the "VarType" provided.
/// Reads a number of bytes from a DB starting from a specified index. This handles more than 200 bytes with multiple requests.
/// If the read was not successful, check LastErrorCode or LastErrorString.
/// </summary>
/// <param name="buffer">Buffer to receive the read bytes. The <see cref="Span{T}.Length"/> determines the number of bytes to read.</param>
/// <param name="dataType">Data type of the memory area, can be DB, Timer, Counter, Merker(Memory), Input, Output.</param>
/// <param name="db">Address of the memory area (if you want to read DB1, this is set to 1). This must be set also for other memory area types: counters, timers,etc.</param>
/// <param name="startByteAdr">Start byte address. If you want to read DB1.DBW200, this is 200.</param>
/// <returns>Returns the bytes in an array</returns>
public void ReadBytes(Span<byte> buffer, DataType dataType, int db, int startByteAdr)
{
int index = 0;
while (buffer.Length > 0)
{
//This works up to MaxPDUSize-1 on SNAP7. But not MaxPDUSize-0.
var maxToRead = Math.Min(buffer.Length, MaxPDUSize - 18);
ReadBytesWithSingleRequest(dataType, db, startByteAdr + index, buffer.Slice(0, maxToRead));
buffer = buffer.Slice(maxToRead);
index += maxToRead;
}
}
/// <summary>
/// Read and decode a certain number of bytes of the "VarType" provided.
/// This can be used to read multiple consecutive variables of the same type (Word, DWord, Int, etc).
/// If the read was not successful, check LastErrorCode or LastErrorString.
/// </summary>
@@ -113,12 +127,11 @@ namespace S7.Net
return ReadStruct(typeof(T), db, startByteAdr) as T?;
}
/// <summary>
/// Reads all the bytes needed to fill a class in C#, starting from a certain address, and set all the properties values to the value that are read from the PLC.
/// Reads all the bytes needed to fill a class in C#, starting from a certain address, and set all the properties values to the value that are read from the PLC.
/// This reads only properties, it doesn't read private variable or public variable without {get;set;} specified.
/// </summary>
/// <param name="sourceClass">Instance of the class that will store the values</param>
/// <param name="sourceClass">Instance of the class that will store the values</param>
/// <param name="db">Index of the DB; es.: 1 is for DB1</param>
/// <param name="startByteAdr">Start byte address. If you want to read DB1.DBW200, this is 200.</param>
/// <returns>The number of read bytes</returns>
@@ -138,7 +151,7 @@ namespace S7.Net
}
/// <summary>
/// Reads all the bytes needed to fill a class in C#, starting from a certain address, and set all the properties values to the value that are read from the PLC.
/// Reads all the bytes needed to fill a class in C#, starting from a certain address, and set all the properties values to the value that are read from the PLC.
/// This reads only properties, it doesn't read private variable or public variable without {get;set;} specified. To instantiate the class defined by the generic
/// type, the class needs a default constructor.
/// </summary>
@@ -152,7 +165,7 @@ namespace S7.Net
}
/// <summary>
/// Reads all the bytes needed to fill a class in C#, starting from a certain address, and set all the properties values to the value that are read from the PLC.
/// Reads all the bytes needed to fill a class in C#, starting from a certain address, and set all the properties values to the value that are read from the PLC.
/// This reads only properties, it doesn't read private variable or public variable without {get;set;} specified.
/// </summary>
/// <typeparam name="T">The class that will be instantiated</typeparam>
@@ -180,17 +193,29 @@ namespace S7.Net
/// <param name="startByteAdr">Start byte address. If you want to write DB1.DBW200, this is 200.</param>
/// <param name="value">Bytes to write. If more than 200, multiple requests will be made.</param>
public void WriteBytes(DataType dataType, int db, int startByteAdr, byte[] value)
{
WriteBytes(dataType, db, startByteAdr, value.AsSpan());
}
/// <summary>
/// Write a number of bytes from a DB starting from a specified index. This handles more than 200 bytes with multiple requests.
/// If the write was not successful, check LastErrorCode or LastErrorString.
/// </summary>
/// <param name="dataType">Data type of the memory area, can be DB, Timer, Counter, Merker(Memory), Input, Output.</param>
/// <param name="db">Address of the memory area (if you want to read DB1, this is set to 1). This must be set also for other memory area types: counters, timers,etc.</param>
/// <param name="startByteAdr">Start byte address. If you want to write DB1.DBW200, this is 200.</param>
/// <param name="value">Bytes to write. If more than 200, multiple requests will be made.</param>
public void WriteBytes(DataType dataType, int db, int startByteAdr, ReadOnlySpan<byte> value)
{
int localIndex = 0;
int count = value.Length;
while (count > 0)
while (value.Length > 0)
{
//TODO: Figure out how to use MaxPDUSize here
//Snap7 seems to choke on PDU sizes above 256 even if snap7
//Snap7 seems to choke on PDU sizes above 256 even if snap7
//replies with bigger PDU size in connection setup.
var maxToWrite = Math.Min(count, MaxPDUSize - 28);//TODO tested only when the MaxPDUSize is 480
WriteBytesWithASingleRequest(dataType, db, startByteAdr + localIndex, value, localIndex, maxToWrite);
count -= maxToWrite;
var maxToWrite = Math.Min(value.Length, MaxPDUSize - 28);//TODO tested only when the MaxPDUSize is 480
WriteBytesWithASingleRequest(dataType, db, startByteAdr + localIndex, value.Slice(0, maxToWrite));
value = value.Slice(maxToWrite);
localIndex += maxToWrite;
}
}
@@ -264,7 +289,6 @@ namespace S7.Net
/// <summary>
/// Writes a single variable from the PLC, takes in input strings like "DB1.DBX0.0", "DB20.DBD200", "MB20", "T45", etc.
/// If the write was not successful, check <see cref="LastErrorCode"/> or <see cref="LastErrorString"/>.
/// </summary>
/// <param name="variable">Input strings like "DB1.DBX0.0", "DB20.DBD200", "MB20", "T45", etc.</param>
/// <param name="value">Value to be written to the PLC</param>
@@ -296,25 +320,22 @@ namespace S7.Net
WriteClassAsync(classValue, db, startByteAdr).GetAwaiter().GetResult();
}
private void ReadBytesWithSingleRequest(DataType dataType, int db, int startByteAdr, byte[] buffer, int offset, int count)
private void ReadBytesWithSingleRequest(DataType dataType, int db, int startByteAdr, Span<byte> buffer)
{
var stream = GetStreamIfAvailable();
try
{
// first create the header
int packageSize = 19 + 12; // 19 header + 12 for 1 request
var package = new System.IO.MemoryStream(packageSize);
BuildHeaderPackage(package);
const int packageSize = 19 + 12; // 19 header + 12 for 1 request
var dataToSend = new byte[packageSize];
var package = new MemoryStream(dataToSend);
WriteReadHeader(package);
// package.Add(0x02); // datenart
BuildReadDataRequestPackage(package, dataType, db, startByteAdr, count);
BuildReadDataRequestPackage(package, dataType, db, startByteAdr, buffer.Length);
var dataToSend = package.ToArray();
stream.Write(dataToSend, 0, dataToSend.Length);
var s7data = RequestTsdu(dataToSend);
AssertReadResponse(s7data, buffer.Length);
var s7data = COTP.TSDU.Read(stream);
AssertReadResponse(s7data, count);
Array.Copy(s7data, 18, buffer, offset, count);
s7data.AsSpan(18, buffer.Length).CopyTo(buffer);
}
catch (Exception exc)
{
@@ -331,26 +352,20 @@ namespace S7.Net
{
AssertPduSizeForWrite(dataItems);
var stream = GetStreamIfAvailable();
var message = new ByteArray();
var length = S7WriteMultiple.CreateRequest(message, dataItems);
stream.Write(message.Array, 0, length);
var response = RequestTsdu(message.Array, 0, length);
var response = COTP.TSDU.Read(stream);
S7WriteMultiple.ParseResponse(response, response.Length, dataItems);
}
private void WriteBytesWithASingleRequest(DataType dataType, int db, int startByteAdr, byte[] value, int dataOffset, int count)
private void WriteBytesWithASingleRequest(DataType dataType, int db, int startByteAdr, ReadOnlySpan<byte> value)
{
try
{
var stream = GetStreamIfAvailable();
var dataToSend = BuildWriteBytesPackage(dataType, db, startByteAdr, value, dataOffset, count);
var dataToSend = BuildWriteBytesPackage(dataType, db, startByteAdr, value);
var s7data = RequestTsdu(dataToSend);
stream.Write(dataToSend, 0, dataToSend.Length);
var s7data = COTP.TSDU.Read(stream);
ValidateResponseCode((ReadWriteErrorCode)s7data[14]);
}
catch (Exception exc)
@@ -359,35 +374,37 @@ namespace S7.Net
}
}
private byte[] BuildWriteBytesPackage(DataType dataType, int db, int startByteAdr, byte[] value, int dataOffset, int count)
private byte[] BuildWriteBytesPackage(DataType dataType, int db, int startByteAdr, ReadOnlySpan<byte> value)
{
int varCount = count;
int varCount = value.Length;
// first create the header
int packageSize = 35 + varCount;
var package = new MemoryStream(new byte[packageSize]);
var packageData = new byte[packageSize];
var package = new MemoryStream(packageData);
package.WriteByte(3);
package.WriteByte(0);
//complete package size
package.WriteByteArray(Int.ToByteArray((short)packageSize));
package.WriteByteArray(new byte[] { 2, 0xf0, 0x80, 0x32, 1, 0, 0 });
package.WriteByteArray(Word.ToByteArray((ushort)(varCount - 1)));
package.WriteByteArray(new byte[] { 0, 0x0e });
package.WriteByteArray(Word.ToByteArray((ushort)(varCount + 4)));
package.WriteByteArray(new byte[] { 0x05, 0x01, 0x12, 0x0a, 0x10, 0x02 });
package.WriteByteArray(Word.ToByteArray((ushort)varCount));
package.WriteByteArray(Word.ToByteArray((ushort)(db)));
package.Write(Int.ToByteArray((short)packageSize));
// This overload doesn't allocate the byte array, it refers to assembly's static data segment
package.Write(new byte[] { 2, 0xf0, 0x80, 0x32, 1, 0, 0 });
package.Write(Word.ToByteArray((ushort)(varCount - 1)));
package.Write(new byte[] { 0, 0x0e });
package.Write(Word.ToByteArray((ushort)(varCount + 4)));
package.Write(new byte[] { 0x05, 0x01, 0x12, 0x0a, 0x10, 0x02 });
package.Write(Word.ToByteArray((ushort)varCount));
package.Write(Word.ToByteArray((ushort)(db)));
package.WriteByte((byte)dataType);
var overflow = (int)(startByteAdr * 8 / 0xffffU); // handles words with address bigger than 8191
package.WriteByte((byte)overflow);
package.WriteByteArray(Word.ToByteArray((ushort)(startByteAdr * 8)));
package.WriteByteArray(new byte[] { 0, 4 });
package.WriteByteArray(Word.ToByteArray((ushort)(varCount * 8)));
package.Write(Word.ToByteArray((ushort)(startByteAdr * 8)));
package.Write(new byte[] { 0, 4 });
package.Write(Word.ToByteArray((ushort)(varCount * 8)));
// now join the header and the data
package.Write(value, dataOffset, count);
package.Write(value);
return package.ToArray();
return packageData;
}
private byte[] BuildWriteBitPackage(DataType dataType, int db, int startByteAdr, bool bitValue, int bitAdr)
@@ -396,43 +413,40 @@ namespace S7.Net
int varCount = 1;
// first create the header
int packageSize = 35 + varCount;
var package = new MemoryStream(new byte[packageSize]);
var packageData = new byte[packageSize];
var package = new MemoryStream(packageData);
package.WriteByte(3);
package.WriteByte(0);
//complete package size
package.WriteByteArray(Int.ToByteArray((short)packageSize));
package.WriteByteArray(new byte[] { 2, 0xf0, 0x80, 0x32, 1, 0, 0 });
package.WriteByteArray(Word.ToByteArray((ushort)(varCount - 1)));
package.WriteByteArray(new byte[] { 0, 0x0e });
package.WriteByteArray(Word.ToByteArray((ushort)(varCount + 4)));
package.WriteByteArray(new byte[] { 0x05, 0x01, 0x12, 0x0a, 0x10, 0x01 }); //ending 0x01 is used for writing a sinlge bit
package.WriteByteArray(Word.ToByteArray((ushort)varCount));
package.WriteByteArray(Word.ToByteArray((ushort)(db)));
package.Write(Int.ToByteArray((short)packageSize));
package.Write(new byte[] { 2, 0xf0, 0x80, 0x32, 1, 0, 0 });
package.Write(Word.ToByteArray((ushort)(varCount - 1)));
package.Write(new byte[] { 0, 0x0e });
package.Write(Word.ToByteArray((ushort)(varCount + 4)));
package.Write(new byte[] { 0x05, 0x01, 0x12, 0x0a, 0x10, 0x01 }); //ending 0x01 is used for writing a sinlge bit
package.Write(Word.ToByteArray((ushort)varCount));
package.Write(Word.ToByteArray((ushort)(db)));
package.WriteByte((byte)dataType);
var overflow = (int)(startByteAdr * 8 / 0xffffU); // handles words with address bigger than 8191
package.WriteByte((byte)overflow);
package.WriteByteArray(Word.ToByteArray((ushort)(startByteAdr * 8 + bitAdr)));
package.WriteByteArray(new byte[] { 0, 0x03 }); //ending 0x03 is used for writing a sinlge bit
package.WriteByteArray(Word.ToByteArray((ushort)(varCount)));
package.Write(Word.ToByteArray((ushort)(startByteAdr * 8 + bitAdr)));
package.Write(new byte[] { 0, 0x03 }); //ending 0x03 is used for writing a sinlge bit
package.Write(Word.ToByteArray((ushort)(varCount)));
// now join the header and the data
package.WriteByteArray(value);
package.Write(value);
return package.ToArray();
return packageData;
}
private void WriteBitWithASingleRequest(DataType dataType, int db, int startByteAdr, int bitAdr, bool bitValue)
{
var stream = GetStreamIfAvailable();
try
{
var dataToSend = BuildWriteBitPackage(dataType, db, startByteAdr, bitValue, bitAdr);
var s7data = RequestTsdu(dataToSend);
stream.Write(dataToSend, 0, dataToSend.Length);
var s7data = COTP.TSDU.Read(stream);
ValidateResponseCode((ReadWriteErrorCode)s7data[14]);
}
catch (Exception exc)
@@ -442,10 +456,10 @@ namespace S7.Net
}
/// <summary>
/// Reads multiple vars in a single request.
/// Reads multiple vars in a single request.
/// You have to create and pass a list of DataItems and you obtain in response the same list with the values.
/// Values are stored in the property "Value" of the dataItem and are already converted.
/// If you don't want the conversion, just create a dataItem of bytes.
/// If you don't want the conversion, just create a dataItem of bytes.
/// The number of DataItems as well as the total size of the requested data can not exceed a certain limit (protocol restriction).
/// </summary>
/// <param name="dataItems">List of dataitems that contains the list of variables that must be read.</param>
@@ -453,24 +467,20 @@ namespace S7.Net
{
AssertPduSizeForRead(dataItems);
var stream = GetStreamIfAvailable();
try
{
// first create the header
int packageSize = 19 + (dataItems.Count * 12);
var package = new System.IO.MemoryStream(packageSize);
BuildHeaderPackage(package, dataItems.Count);
var dataToSend = new byte[packageSize];
var package = new MemoryStream(dataToSend);
WriteReadHeader(package, dataItems.Count);
// package.Add(0x02); // datenart
foreach (var dataItem in dataItems)
{
BuildReadDataRequestPackage(package, dataItem.DataType, dataItem.DB, dataItem.StartByteAdr, VarTypeToByteLength(dataItem.VarType, dataItem.Count));
}
var dataToSend = package.ToArray();
stream.Write(dataToSend, 0, dataToSend.Length);
var s7data = COTP.TSDU.Read(stream); //TODO use Async
byte[] s7data = RequestTsdu(dataToSend);
ValidateResponseCode((ReadWriteErrorCode)s7data[14]);
@@ -481,5 +491,48 @@ namespace S7.Net
throw new PlcException(ErrorCode.ReadData, exc);
}
}
/// <summary>
/// Read the PLC clock value.
/// </summary>
/// <returns>The current PLC time.</returns>
public System.DateTime ReadClock()
{
var request = BuildClockReadRequest();
var response = RequestTsdu(request);
return ParseClockReadResponse(response);
}
/// <summary>
/// Write the PLC clock value.
/// </summary>
/// <param name="value">The date and time to set the PLC clock to.</param>
public void WriteClock(System.DateTime value)
{
var request = BuildClockWriteRequest(value);
var response = RequestTsdu(request);
ParseClockWriteResponse(response);
}
/// <summary>
/// Read the current status from the PLC. A value of 0x08 indicates the PLC is in run status, regardless of the PLC type.
/// </summary>
/// <returns>The current PLC status.</returns>
public byte ReadStatus()
{
var dataToSend = BuildSzlReadRequestPackage(0x0424, 0);
var s7data = RequestTsdu(dataToSend);
return (byte) (s7data[37] & 0x0f);
}
private byte[] RequestTsdu(byte[] requestData) => RequestTsdu(requestData, 0, requestData.Length);
private byte[] RequestTsdu(byte[] requestData, int offset, int length)
{
return RequestTsduAsync(requestData, offset, length).GetAwaiter().GetResult();
}
}
}

View File

@@ -1,68 +1,27 @@
using System;
namespace S7.Net.Protocol
namespace S7.Net.Protocol
{
internal static class ConnectionRequest
{
public static byte[] GetCOTPConnectionRequest(CpuType cpu, Int16 rack, Int16 slot)
public static byte[] GetCOTPConnectionRequest(TsapPair tsapPair)
{
byte[] bSend1 = {
3, 0, 0, 22, //TPKT
17, //COTP Header Length
224, //Connect Request
224, //Connect Request
0, 0, //Destination Reference
0, 46, //Source Reference
0, //Flags
193, //Parameter Code (src-tasp)
2, //Parameter Length
1, 0, //Source TASP
tsapPair.Local.FirstByte, tsapPair.Local.SecondByte, //Source TASP
194, //Parameter Code (dst-tasp)
2, //Parameter Length
3, 0, //Destination TASP
tsapPair.Remote.FirstByte, tsapPair.Remote.SecondByte, //Destination TASP
192, //Parameter Code (tpdu-size)
1, //Parameter Length
10 //TPDU Size (2^10 = 1024)
};
switch (cpu)
{
case CpuType.S7200:
//S7200: Chr(193) & Chr(2) & Chr(16) & Chr(0) 'Eigener Tsap
bSend1[13] = 0x10;
bSend1[14] = 0x00;
//S7200: Chr(194) & Chr(2) & Chr(16) & Chr(0) 'Fremder Tsap
bSend1[17] = 0x10;
bSend1[18] = 0x00;
break;
case CpuType.Logo0BA8:
// These values are taken from NodeS7, it's not verified if these are
// exact requirements to connect to the Logo0BA8.
bSend1[13] = 0x01;
bSend1[14] = 0x00;
bSend1[17] = 0x01;
bSend1[18] = 0x02;
break;
case CpuType.S71200:
case CpuType.S7300:
case CpuType.S7400:
//S7300: Chr(193) & Chr(2) & Chr(1) & Chr(0) 'Eigener Tsap
bSend1[13] = 0x01;
bSend1[14] = 0x00;
//S7300: Chr(194) & Chr(2) & Chr(3) & Chr(2) 'Fremder Tsap
bSend1[17] = 0x03;
bSend1[18] = (byte) ((rack << 5) | (int) slot);
break;
case CpuType.S71500:
// Eigener Tsap
bSend1[13] = 0x10;
bSend1[14] = 0x02;
// Fredmer Tsap
bSend1[17] = 0x03;
bSend1[18] = (byte) ((rack << 5) | (int) slot);
break;
default:
throw new Exception("Wrong CPU Type Secified");
}
return bSend1;
}
}

View File

@@ -26,6 +26,11 @@ namespace S7.Net.Protocol
_ => Types.String.ToByteArray(s, dataItem.Count)
};
if (dataItem.VarType == VarType.Date)
{
return Date.ToByteArray((System.DateTime)dataItem.Value);
}
return SerializeValue(dataItem.Value);
}

31
S7.Net/Protocol/Tsap.cs Normal file
View File

@@ -0,0 +1,31 @@
namespace S7.Net.Protocol
{
/// <summary>
/// Provides a representation of the Transport Service Access Point, or TSAP in short. TSAP's are used
/// to specify a client and server address. For most PLC types a default TSAP is available that allows
/// connection from any IP and can be calculated using the rack and slot numbers.
/// </summary>
public struct Tsap
{
/// <summary>
/// First byte of the TSAP.
/// </summary>
public byte FirstByte { get; set; }
/// <summary>
/// Second byte of the TSAP.
/// </summary>
public byte SecondByte { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="Tsap" /> class using the specified values.
/// </summary>
/// <param name="firstByte">The first byte of the TSAP.</param>
/// <param name="secondByte">The second byte of the TSAP.</param>
public Tsap(byte firstByte, byte secondByte)
{
FirstByte = firstByte;
SecondByte = secondByte;
}
}
}

View File

@@ -0,0 +1,96 @@
using System;
namespace S7.Net.Protocol
{
/// <summary>
/// Implements a pair of TSAP addresses used to connect to a PLC.
/// </summary>
public class TsapPair
{
/// <summary>
/// The local <see cref="Tsap" />.
/// </summary>
public Tsap Local { get; set; }
/// <summary>
/// The remote <see cref="Tsap" />
/// </summary>
public Tsap Remote { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="TsapPair" /> class using the specified local and
/// remote TSAP.
/// </summary>
/// <param name="local">The local TSAP.</param>
/// <param name="remote">The remote TSAP.</param>
public TsapPair(Tsap local, Tsap remote)
{
Local = local;
Remote = remote;
}
/// <summary>
/// Builds a <see cref="TsapPair" /> that can be used to connect to a PLC using the default connection
/// addresses.
/// </summary>
/// <remarks>
/// The remote TSAP is constructed using <code>new Tsap(0x03, (byte) ((rack &lt;&lt; 5) | slot))</code>.
/// </remarks>
/// <param name="cpuType">The CPU type of the PLC.</param>
/// <param name="rack">The rack of the PLC's network card.</param>
/// <param name="slot">The slot of the PLC's network card.</param>
/// <returns>A TSAP pair that matches the given parameters.</returns>
/// <exception cref="ArgumentOutOfRangeException">The <paramref name="cpuType"/> is invalid.
///
/// -or-
///
/// The <paramref name="rack"/> parameter is less than 0.
///
/// -or-
///
/// The <paramref name="rack"/> parameter is greater than 15.
///
/// -or-
///
/// The <paramref name="slot"/> parameter is less than 0.
///
/// -or-
///
/// The <paramref name="slot"/> parameter is greater than 15.</exception>
public static TsapPair GetDefaultTsapPair(CpuType cpuType, int rack, int slot)
{
if (rack < 0) throw InvalidRackOrSlot(rack, nameof(rack), "minimum", 0);
if (rack > 0x0F) throw InvalidRackOrSlot(rack, nameof(rack), "maximum", 0x0F);
if (slot < 0) throw InvalidRackOrSlot(slot, nameof(slot), "minimum", 0);
if (slot > 0x0F) throw InvalidRackOrSlot(slot, nameof(slot), "maximum", 0x0F);
switch (cpuType)
{
case CpuType.S7200:
return new TsapPair(new Tsap(0x10, 0x00), new Tsap(0x10, 0x01));
case CpuType.Logo0BA8:
// The actual values are probably on a per-project basis
return new TsapPair(new Tsap(0x01, 0x00), new Tsap(0x01, 0x02));
case CpuType.S7200Smart:
case CpuType.S71200:
case CpuType.S71500:
case CpuType.S7300:
case CpuType.S7400:
// Testing with S7 1500 shows only the remote TSAP needs to match. This might differ for other
// PLC types.
return new TsapPair(new Tsap(0x01, 0x00), new Tsap(0x03, (byte) ((rack << 5) | slot)));
default:
throw new ArgumentOutOfRangeException(nameof(cpuType), "Invalid CPU Type specified");
}
}
private static ArgumentOutOfRangeException InvalidRackOrSlot(int value, string name, string extrema,
int extremaValue)
{
return new ArgumentOutOfRangeException(name,
$"Invalid {name} value specified (decimal: {value}, hexadecimal: {value:X}), {extrema} value " +
$"is {extremaValue} (decimal) or {extremaValue:X} (hexadecimal).");
}
}
}

View File

@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net452;netstandard2.0;netstandard1.3</TargetFrameworks>
<TargetFrameworks>net452;net462;netstandard2.0;netstandard1.3;net5.0;net6.0;net7.0</TargetFrameworks>
<SignAssembly>true</SignAssembly>
<AssemblyOriginatorKeyFile>Properties\S7.Net.snk</AssemblyOriginatorKeyFile>
<InternalsVisibleTo>S7.Net.UnitTest</InternalsVisibleTo>
@@ -15,17 +15,22 @@
<RepositoryType>git</RepositoryType>
<PackageTags>PLC Siemens Communication S7</PackageTags>
<Copyright>Derek Heiser 2015</Copyright>
<LangVersion>8.0</LangVersion>
<LangVersion>latest</LangVersion>
<Nullable>Enable</Nullable>
<DebugType>portable</DebugType>
<IncludeSymbols>true</IncludeSymbols>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>$(NoWarn);CS1591;NETSDK1138</NoWarn>
</PropertyGroup>
<PropertyGroup Condition="'$(TargetFramework)' == 'net452' Or '$(TargetFramework)' == 'netstandard2.0' ">
<PropertyGroup Condition="'$(TargetFramework)' == 'net452' Or '$(TargetFramework)' == 'net462' Or '$(TargetFramework)' == 'netstandard2.0' ">
<DefineConstants>NET_FULL</DefineConstants>
</PropertyGroup>
<ItemGroup Condition="'$(TargetFramework)' != 'net5.0' And '$(TargetFramework)' != 'net6.0' And '$(TargetFramework)' != 'net7.0'">
<PackageReference Include="System.Memory" Version="4.5.5" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="All" />

View File

@@ -39,6 +39,7 @@ namespace S7.Net
/// <param name="buffer">the buffer to read into</param>
/// <param name="offset">the offset in the buffer to read into</param>
/// <param name="count">the amount of bytes to read into the buffer</param>
/// <param name="cancellationToken">A cancellation token that can be used to cancel the asynchronous operation.</param>
/// <returns>returns the amount of read bytes</returns>
public static async Task<int> ReadExactAsync(this Stream stream, byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{

View File

@@ -25,38 +25,11 @@ namespace S7.Net
Data = data;
}
/// <summary>
/// Reads a TPKT from the socket
/// </summary>
/// <param name="stream">The stream to read from</param>
/// <returns>TPKT Instance</returns>
public static TPKT Read(Stream stream)
{
var buf = new byte[4];
int len = stream.ReadExact(buf, 0, 4);
if (len < 4) throw new TPKTInvalidException($"TPKT header is incomplete / invalid. Received Bytes: {len} expected: {buf.Length}");
var version = buf[0];
var reserved1 = buf[1];
var length = buf[2] * 256 + buf[3]; //BigEndian
var data = new byte[length - 4];
len = stream.ReadExact(data, 0, data.Length);
if (len < data.Length)
throw new TPKTInvalidException($"TPKT payload is incomplete / invalid. Received Bytes: {len} expected: {data.Length}");
return new TPKT
(
version: version,
reserved1: reserved1,
length: length,
data: data
);
}
/// <summary>
/// Reads a TPKT from the socket Async
/// </summary>
/// <param name="stream">The stream to read from</param>
/// <param name="cancellationToken">A cancellation token that can be used to cancel the asynchronous operation.</param>
/// <returns>Task TPKT Instace</returns>
public static async Task<TPKT> ReadAsync(Stream stream, CancellationToken cancellationToken)
{

View File

@@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
namespace S7.Net.Types
{
@@ -25,7 +26,7 @@ namespace S7.Net.Types
}
private static double GetIncreasedNumberOfBytes(double numBytes, Type type)
private static double GetIncreasedNumberOfBytes(double numBytes, Type type, PropertyInfo? propertyInfo)
{
switch (type.Name)
{
@@ -38,32 +39,33 @@ namespace S7.Net.Types
break;
case "Int16":
case "UInt16":
numBytes = Math.Ceiling(numBytes);
if ((numBytes / 2 - Math.Floor(numBytes / 2.0)) > 0)
numBytes++;
IncrementToEven(ref numBytes);
numBytes += 2;
break;
case "Int32":
case "UInt32":
numBytes = Math.Ceiling(numBytes);
if ((numBytes / 2 - Math.Floor(numBytes / 2.0)) > 0)
numBytes++;
IncrementToEven(ref numBytes);
numBytes += 4;
break;
case "Single":
numBytes = Math.Ceiling(numBytes);
if ((numBytes / 2 - Math.Floor(numBytes / 2.0)) > 0)
numBytes++;
IncrementToEven(ref numBytes);
numBytes += 4;
break;
case "Double":
numBytes = Math.Ceiling(numBytes);
if ((numBytes / 2 - Math.Floor(numBytes / 2.0)) > 0)
numBytes++;
IncrementToEven(ref numBytes);
numBytes += 8;
break;
case "String":
S7StringAttribute? attribute = propertyInfo?.GetCustomAttributes<S7StringAttribute>().SingleOrDefault();
if (attribute == default(S7StringAttribute))
throw new ArgumentException("Please add S7StringAttribute to the string field");
IncrementToEven(ref numBytes);
numBytes += attribute.ReservedLengthInBytes;
break;
default:
var propertyClass = Activator.CreateInstance(type);
var propertyClass = Activator.CreateInstance(type) ??
throw new ArgumentException($"Failed to create instance of type {type}.", nameof(type));
numBytes = GetClassSize(propertyClass, numBytes, true);
break;
}
@@ -75,6 +77,8 @@ namespace S7.Net.Types
/// Gets the size of the class in bytes.
/// </summary>
/// <param name="instance">An instance of the class</param>
/// <param name="numBytes">The offset of the current field.</param>
/// <param name="isInnerProperty"><see langword="true" /> if this property belongs to a class being serialized as member of the class requested for serialization; otherwise, <see langword="false" />.</param>
/// <returns>the number of bytes</returns>
public static double GetClassSize(object instance, double numBytes = 0.0, bool isInnerProperty = false)
{
@@ -83,8 +87,10 @@ namespace S7.Net.Types
{
if (property.PropertyType.IsArray)
{
Type elementType = property.PropertyType.GetElementType();
Array array = (Array)property.GetValue(instance, null);
Type elementType = property.PropertyType.GetElementType()!;
Array array = (Array?) property.GetValue(instance, null) ??
throw new ArgumentException($"Property {property.Name} on {instance} must have a non-null value to get it's size.", nameof(instance));
if (array.Length <= 0)
{
throw new Exception("Cannot determine size of class, because an array is defined which has no fixed size greater than zero.");
@@ -93,12 +99,12 @@ namespace S7.Net.Types
IncrementToEven(ref numBytes);
for (int i = 0; i < array.Length; i++)
{
numBytes = GetIncreasedNumberOfBytes(numBytes, elementType);
numBytes = GetIncreasedNumberOfBytes(numBytes, elementType, property);
}
}
else
{
numBytes = GetIncreasedNumberOfBytes(numBytes, property.PropertyType);
numBytes = GetIncreasedNumberOfBytes(numBytes, property.PropertyType, property);
}
}
if (false == isInnerProperty)
@@ -111,7 +117,7 @@ namespace S7.Net.Types
return numBytes;
}
private static object? GetPropertyValue(Type propertyType, byte[] bytes, ref double numBytes)
private static object? GetPropertyValue(Type propertyType, PropertyInfo? propertyInfo, byte[] bytes, ref double numBytes)
{
object? value = null;
@@ -133,50 +139,35 @@ namespace S7.Net.Types
numBytes++;
break;
case "Int16":
numBytes = Math.Ceiling(numBytes);
if ((numBytes / 2 - Math.Floor(numBytes / 2.0)) > 0)
numBytes++;
IncrementToEven(ref numBytes);
// hier auswerten
ushort source = Word.FromBytes(bytes[(int)numBytes + 1], bytes[(int)numBytes]);
value = source.ConvertToShort();
numBytes += 2;
break;
case "UInt16":
numBytes = Math.Ceiling(numBytes);
if ((numBytes / 2 - Math.Floor(numBytes / 2.0)) > 0)
numBytes++;
IncrementToEven(ref numBytes);
// hier auswerten
value = Word.FromBytes(bytes[(int)numBytes + 1], bytes[(int)numBytes]);
numBytes += 2;
break;
case "Int32":
numBytes = Math.Ceiling(numBytes);
if ((numBytes / 2 - Math.Floor(numBytes / 2.0)) > 0)
numBytes++;
// hier auswerten
uint sourceUInt = DWord.FromBytes(bytes[(int)numBytes + 3],
bytes[(int)numBytes + 2],
bytes[(int)numBytes + 1],
bytes[(int)numBytes + 0]);
IncrementToEven(ref numBytes);
var wordBuffer = new byte[4];
Array.Copy(bytes, (int)numBytes, wordBuffer, 0, wordBuffer.Length);
uint sourceUInt = DWord.FromByteArray(wordBuffer);
value = sourceUInt.ConvertToInt();
numBytes += 4;
break;
case "UInt32":
numBytes = Math.Ceiling(numBytes);
if ((numBytes / 2 - Math.Floor(numBytes / 2.0)) > 0)
numBytes++;
// hier auswerten
value = DWord.FromBytes(
bytes[(int)numBytes],
bytes[(int)numBytes + 1],
bytes[(int)numBytes + 2],
bytes[(int)numBytes + 3]);
IncrementToEven(ref numBytes);
var wordBuffer2 = new byte[4];
Array.Copy(bytes, (int)numBytes, wordBuffer2, 0, wordBuffer2.Length);
value = DWord.FromByteArray(wordBuffer2);
numBytes += 4;
break;
case "Single":
numBytes = Math.Ceiling(numBytes);
if ((numBytes / 2 - Math.Floor(numBytes / 2.0)) > 0)
numBytes++;
IncrementToEven(ref numBytes);
// hier auswerten
value = Real.FromByteArray(
new byte[] {
@@ -187,17 +178,35 @@ namespace S7.Net.Types
numBytes += 4;
break;
case "Double":
numBytes = Math.Ceiling(numBytes);
if ((numBytes / 2 - Math.Floor(numBytes / 2.0)) > 0)
numBytes++;
IncrementToEven(ref numBytes);
var buffer = new byte[8];
Array.Copy(bytes, (int)numBytes, buffer, 0, 8);
// hier auswerten
value = LReal.FromByteArray(buffer);
numBytes += 8;
break;
case "String":
S7StringAttribute? attribute = propertyInfo?.GetCustomAttributes<S7StringAttribute>().SingleOrDefault();
if (attribute == default(S7StringAttribute))
throw new ArgumentException("Please add S7StringAttribute to the string field");
IncrementToEven(ref numBytes);
// get the value
var sData = new byte[attribute.ReservedLengthInBytes];
Array.Copy(bytes, (int)numBytes, sData, 0, sData.Length);
value = attribute.Type switch
{
S7StringType.S7String => S7String.FromByteArray(sData),
S7StringType.S7WString => S7WString.FromByteArray(sData),
_ => throw new ArgumentException("Please use a valid string type for the S7StringAttribute")
};
numBytes += sData.Length;
break;
default:
var propClass = Activator.CreateInstance(propertyType);
var propClass = Activator.CreateInstance(propertyType) ??
throw new ArgumentException($"Failed to create instance of type {propertyType}.", nameof(propertyType));
numBytes = FromBytes(propClass, bytes, numBytes);
value = propClass;
break;
@@ -211,6 +220,8 @@ namespace S7.Net.Types
/// </summary>
/// <param name="sourceClass">The object to fill in the given array of bytes</param>
/// <param name="bytes">The array of bytes</param>
/// <param name="numBytes">The offset for the current field.</param>
/// <param name="isInnerClass"><see langword="true" /> if this class is the type of a member of the class to be serialized; otherwise, <see langword="false" />.</param>
public static double FromBytes(object sourceClass, byte[] bytes, double numBytes = 0, bool isInnerClass = false)
{
if (bytes == null)
@@ -221,13 +232,15 @@ namespace S7.Net.Types
{
if (property.PropertyType.IsArray)
{
Array array = (Array)property.GetValue(sourceClass, null);
Array array = (Array?) property.GetValue(sourceClass, null) ??
throw new ArgumentException($"Property {property.Name} on sourceClass must be an array instance.", nameof(sourceClass));
IncrementToEven(ref numBytes);
Type elementType = property.PropertyType.GetElementType();
Type elementType = property.PropertyType.GetElementType()!;
for (int i = 0; i < array.Length && numBytes < bytes.Length; i++)
{
array.SetValue(
GetPropertyValue(elementType, bytes, ref numBytes),
GetPropertyValue(elementType, property, bytes, ref numBytes),
i);
}
}
@@ -235,7 +248,7 @@ namespace S7.Net.Types
{
property.SetValue(
sourceClass,
GetPropertyValue(property.PropertyType, bytes, ref numBytes),
GetPropertyValue(property.PropertyType, property, bytes, ref numBytes),
null);
}
}
@@ -243,7 +256,7 @@ namespace S7.Net.Types
return numBytes;
}
private static double SetBytesFromProperty(object propertyValue, byte[] bytes, double numBytes)
private static double SetBytesFromProperty(object propertyValue, PropertyInfo? propertyInfo, byte[] bytes, double numBytes)
{
int bytePos = 0;
int bitPos = 0;
@@ -285,6 +298,18 @@ namespace S7.Net.Types
case "Double":
bytes2 = LReal.ToByteArray((double)propertyValue);
break;
case "String":
S7StringAttribute? attribute = propertyInfo?.GetCustomAttributes<S7StringAttribute>().SingleOrDefault();
if (attribute == default(S7StringAttribute))
throw new ArgumentException("Please add S7StringAttribute to the string field");
bytes2 = attribute.Type switch
{
S7StringType.S7String => S7String.ToByteArray((string)propertyValue, attribute.ReservedLength),
S7StringType.S7WString => S7WString.ToByteArray((string)propertyValue, attribute.ReservedLength),
_ => throw new ArgumentException("Please use a valid string type for the S7StringAttribute")
};
break;
default:
numBytes = ToBytes(propertyValue, bytes, numBytes);
break;
@@ -306,26 +331,30 @@ namespace S7.Net.Types
/// <summary>
/// Creates a byte array depending on the struct type.
/// </summary>
/// <param name="sourceClass">The struct object</param>
/// <param name="sourceClass">The struct object.</param>
/// <param name="bytes">The target byte array.</param>
/// <param name="numBytes">The offset for the current field.</param>
/// <returns>A byte array or null if fails.</returns>
public static double ToBytes(object sourceClass, byte[] bytes, double numBytes = 0.0)
{
var properties = GetAccessableProperties(sourceClass.GetType());
foreach (var property in properties)
{
var value = property.GetValue(sourceClass, null) ??
throw new ArgumentException($"Property {property.Name} on sourceClass can't be null.", nameof(sourceClass));
if (property.PropertyType.IsArray)
{
Array array = (Array)property.GetValue(sourceClass, null);
Array array = (Array) value;
IncrementToEven(ref numBytes);
Type elementType = property.PropertyType.GetElementType();
for (int i = 0; i < array.Length && numBytes < bytes.Length; i++)
{
numBytes = SetBytesFromProperty(array.GetValue(i), bytes, numBytes);
numBytes = SetBytesFromProperty(array.GetValue(i)!, property, bytes, numBytes);
}
}
else
{
numBytes = SetBytesFromProperty(property.GetValue(sourceClass, null), bytes, numBytes);
numBytes = SetBytesFromProperty(value, property, bytes, numBytes);
}
}
return numBytes;

82
S7.Net/Types/Date.cs Normal file
View File

@@ -0,0 +1,82 @@
using System;
using S7.Net.Helper;
namespace S7.Net.Types
{
/// <summary>
/// Contains the conversion methods to convert Words from S7 plc to C#.
/// </summary>
public static class Date
{
/// <summary>
/// Minimum allowed date for the IEC date type
/// </summary>
public static System.DateTime IecMinDate { get; } = new(year: 1990, month: 01, day: 01);
/// <summary>
/// Maximum allowed date for the IEC date type
/// <remarks>
/// Although the spec allows only a max date of 31-12-2168, the PLC IEC date goes up to 06-06-2169 (which is the actual
/// WORD max value - 65535)
/// </remarks>
/// </summary>
public static System.DateTime IecMaxDate { get; } = new(year: 2169, month: 06, day: 06);
private static readonly ushort MaxNumberOfDays = (ushort)(IecMaxDate - IecMinDate).TotalDays;
/// <summary>
/// Converts a word (2 bytes) to IEC date (<see cref="System.DateTime"/>)
/// </summary>
public static System.DateTime FromByteArray(byte[] bytes)
{
if (bytes.Length != 2)
{
throw new ArgumentException("Wrong number of bytes. Bytes array must contain 2 bytes.");
}
var daysSinceDateStart = Word.FromByteArray(bytes);
if (daysSinceDateStart > MaxNumberOfDays)
{
throw new ArgumentException($"Read number exceeded the number of maximum days in the IEC date (read: {daysSinceDateStart}, max: {MaxNumberOfDays})",
nameof(bytes));
}
return IecMinDate.AddDays(daysSinceDateStart);
}
/// <summary>
/// Converts a <see cref="System.DateTime"/> to word (2 bytes)
/// </summary>
public static byte[] ToByteArray(System.DateTime dateTime) => Word.ToByteArray(dateTime.GetDaysSinceIecDateStart());
/// <summary>
/// Converts an array of <see cref="System.DateTime"/>s to an array of bytes
/// </summary>
public static byte[] ToByteArray(System.DateTime[] value)
{
var arr = new ByteArray();
foreach (var date in value)
arr.Add(ToByteArray(date));
return arr.Array;
}
/// <summary>
/// Converts an array of bytes to an array of <see cref="System.DateTime"/>s
/// </summary>
public static System.DateTime[] ToArray(byte[] bytes)
{
var values = new System.DateTime[bytes.Length / sizeof(ushort)];
for (int i = 0; i < values.Length; i++)
{
values[i] = FromByteArray(
new[]
{
bytes[i], bytes[i + 1]
});
}
return values;
}
}
}

View File

@@ -141,7 +141,7 @@ namespace S7.Net.Types
/// Converts an array of <see cref="T:System.DateTime"/> values to a byte array.
/// </summary>
/// <param name="dateTimes">The DateTime values to convert.</param>
/// <returns>A byte array containing the S7 date time representations of <paramref name="dateTime"/>.</returns>
/// <returns>A byte array containing the S7 date time representations of <paramref name="dateTimes"/>.</returns>
/// <exception cref="ArgumentOutOfRangeException">Thrown when any value of
/// <paramref name="dateTimes"/> is before <see cref="P:SpecMinimumDateTime"/>
/// or after <see cref="P:SpecMaximumDateTime"/>.</exception>

View File

@@ -9,6 +9,18 @@ namespace S7.Net.Types
/// </summary>
public static class S7String
{
private static Encoding stringEncoding = Encoding.ASCII;
/// <summary>
/// The Encoding used when serializing and deserializing S7String (Encoding.ASCII by default)
/// </summary>
/// <exception cref="ArgumentNullException">StringEncoding must not be null</exception>
public static Encoding StringEncoding
{
get => stringEncoding;
set => stringEncoding = value ?? throw new ArgumentNullException(nameof(StringEncoding));
}
/// <summary>
/// Converts S7 bytes to a string
/// </summary>
@@ -30,7 +42,7 @@ namespace S7.Net.Types
try
{
return Encoding.ASCII.GetString(bytes, 2, length);
return StringEncoding.GetString(bytes, 2, length);
}
catch (Exception e)
{
@@ -38,7 +50,6 @@ namespace S7.Net.Types
$"Failed to parse {VarType.S7String} from data. Following fields were read: size: '{size}', actual length: '{length}', total number of bytes (including header): '{bytes.Length}'.",
e);
}
}
/// <summary>
@@ -47,7 +58,7 @@ namespace S7.Net.Types
/// <param name="value">The string to convert to byte array.</param>
/// <param name="reservedLength">The length (in characters) allocated in PLC for the string.</param>
/// <returns>A <see cref="T:byte[]" /> containing the string header and string value with a maximum length of <paramref name="reservedLength"/> + 2.</returns>
public static byte[] ToByteArray(string value, int reservedLength)
public static byte[] ToByteArray(string? value, int reservedLength)
{
if (value is null)
{
@@ -56,7 +67,7 @@ namespace S7.Net.Types
if (reservedLength > 254) throw new ArgumentException($"The maximum string length supported is 254.");
var bytes = Encoding.ASCII.GetBytes(value);
var bytes = StringEncoding.GetBytes(value);
if (bytes.Length > reservedLength) throw new ArgumentException($"The provided string length ({bytes.Length} is larger than the specified reserved length ({reservedLength}).");
var buffer = new byte[2 + reservedLength];

View File

@@ -2,7 +2,7 @@
namespace S7.Net.Types
{
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
public sealed class S7StringAttribute : Attribute
{
private readonly S7StringType type;

View File

@@ -48,7 +48,7 @@ namespace S7.Net.Types
/// <param name="value">The string to convert to byte array.</param>
/// <param name="reservedLength">The length (in characters) allocated in PLC for the string.</param>
/// <returns>A <see cref="T:byte[]" /> containing the string header and string value with a maximum length of <paramref name="reservedLength"/> + 4.</returns>
public static byte[] ToByteArray(string value, int reservedLength)
public static byte[] ToByteArray(string? value, int reservedLength)
{
if (value is null)
{

View File

@@ -12,13 +12,15 @@
/// <param name="reservedLength">The amount of bytes reserved for the <paramref name="value"/> in the PLC.</param>
public static byte[] ToByteArray(string value, int reservedLength)
{
var length = value?.Length;
if (length > reservedLength) length = reservedLength;
var bytes = new byte[reservedLength];
if (value == null) return bytes;
if (length == null || length == 0) return bytes;
var length = value.Length;
if (length == 0) return bytes;
System.Text.Encoding.ASCII.GetBytes(value, 0, length.Value, bytes, 0);
if (length > reservedLength) length = reservedLength;
System.Text.Encoding.ASCII.GetBytes(value, 0, length, bytes, 0);
return bytes;
}

View File

@@ -45,6 +45,7 @@ namespace S7.Net.Types
break;
case "Int32":
case "UInt32":
case "TimeSpan":
numBytes = Math.Ceiling(numBytes);
if ((numBytes / 2 - Math.Floor(numBytes / 2.0)) > 0)
numBytes++;
@@ -98,8 +99,8 @@ namespace S7.Net.Types
int bytePos = 0;
int bitPos = 0;
double numBytes = 0.0;
object structValue = Activator.CreateInstance(structType);
object structValue = Activator.CreateInstance(structType) ??
throw new ArgumentException($"Failed to create an instance of the type {structType}.", nameof(structType));
var infos = structValue.GetType()
#if NETSTANDARD1_3
@@ -215,6 +216,21 @@ namespace S7.Net.Types
numBytes += sData.Length;
break;
case "TimeSpan":
numBytes = Math.Ceiling(numBytes);
if ((numBytes / 2 - Math.Floor(numBytes / 2.0)) > 0)
numBytes++;
// get the value
info.SetValue(structValue, TimeSpan.FromByteArray(new[]
{
bytes[(int)numBytes + 0],
bytes[(int)numBytes + 1],
bytes[(int)numBytes + 2],
bytes[(int)numBytes + 3]
}));
numBytes += 4;
break;
default:
var buffer = new byte[GetStructSize(info.FieldType)];
if (buffer.Length == 0)
@@ -254,6 +270,14 @@ namespace S7.Net.Types
foreach (var info in infos)
{
static TValue GetValueOrThrow<TValue>(FieldInfo fi, object structValue) where TValue : struct
{
var value = fi.GetValue(structValue) as TValue? ??
throw new ArgumentException($"Failed to convert value of field {fi.Name} of {structValue} to type {typeof(TValue)}");
return value;
}
bytes2 = null;
switch (info.FieldType.Name)
{
@@ -261,7 +285,7 @@ namespace S7.Net.Types
// get the value
bytePos = (int)Math.Floor(numBytes);
bitPos = (int)((numBytes - (double)bytePos) / 0.125);
if ((bool)info.GetValue(structValue))
if (GetValueOrThrow<bool>(info, structValue))
bytes[bytePos] |= (byte)Math.Pow(2, bitPos); // is true
else
bytes[bytePos] &= (byte)(~(byte)Math.Pow(2, bitPos)); // is false
@@ -270,26 +294,26 @@ namespace S7.Net.Types
case "Byte":
numBytes = (int)Math.Ceiling(numBytes);
bytePos = (int)numBytes;
bytes[bytePos] = (byte)info.GetValue(structValue);
bytes[bytePos] = GetValueOrThrow<byte>(info, structValue);
numBytes++;
break;
case "Int16":
bytes2 = Int.ToByteArray((Int16)info.GetValue(structValue));
bytes2 = Int.ToByteArray(GetValueOrThrow<short>(info, structValue));
break;
case "UInt16":
bytes2 = Word.ToByteArray((UInt16)info.GetValue(structValue));
bytes2 = Word.ToByteArray(GetValueOrThrow<ushort>(info, structValue));
break;
case "Int32":
bytes2 = DInt.ToByteArray((Int32)info.GetValue(structValue));
bytes2 = DInt.ToByteArray(GetValueOrThrow<int>(info, structValue));
break;
case "UInt32":
bytes2 = DWord.ToByteArray((UInt32)info.GetValue(structValue));
bytes2 = DWord.ToByteArray(GetValueOrThrow<uint>(info, structValue));
break;
case "Single":
bytes2 = Real.ToByteArray((float)info.GetValue(structValue));
bytes2 = Real.ToByteArray(GetValueOrThrow<float>(info, structValue));
break;
case "Double":
bytes2 = LReal.ToByteArray((double)info.GetValue(structValue));
bytes2 = LReal.ToByteArray(GetValueOrThrow<double>(info, structValue));
break;
case "String":
S7StringAttribute? attribute = info.GetCustomAttributes<S7StringAttribute>().SingleOrDefault();
@@ -298,11 +322,14 @@ namespace S7.Net.Types
bytes2 = attribute.Type switch
{
S7StringType.S7String => S7String.ToByteArray((string)info.GetValue(structValue), attribute.ReservedLength),
S7StringType.S7WString => S7WString.ToByteArray((string)info.GetValue(structValue), attribute.ReservedLength),
S7StringType.S7String => S7String.ToByteArray((string?)info.GetValue(structValue), attribute.ReservedLength),
S7StringType.S7WString => S7WString.ToByteArray((string?)info.GetValue(structValue), attribute.ReservedLength),
_ => throw new ArgumentException("Please use a valid string type for the S7StringAttribute")
};
break;
case "TimeSpan":
bytes2 = TimeSpan.ToByteArray((System.TimeSpan)info.GetValue(structValue));
break;
}
if (bytes2 != null)
{

97
S7.Net/Types/TimeSpan.cs Normal file
View File

@@ -0,0 +1,97 @@
using System;
using System.Collections.Generic;
namespace S7.Net.Types
{
/// <summary>
/// Contains the methods to convert between <see cref="T:System.TimeSpan"/> and S7 representation of TIME values.
/// </summary>
public static class TimeSpan
{
/// <summary>
/// The minimum <see cref="T:System.TimeSpan"/> value supported by the specification.
/// </summary>
public static readonly System.TimeSpan SpecMinimumTimeSpan = System.TimeSpan.FromMilliseconds(int.MinValue);
/// <summary>
/// The maximum <see cref="T:System.TimeSpan"/> value supported by the specification.
/// </summary>
public static readonly System.TimeSpan SpecMaximumTimeSpan = System.TimeSpan.FromMilliseconds(int.MaxValue);
/// <summary>
/// Parses a <see cref="T:System.TimeSpan"/> value from bytes.
/// </summary>
/// <param name="bytes">Input bytes read from PLC.</param>
/// <returns>A <see cref="T:System.TimeSpan"/> object representing the value read from PLC.</returns>
/// <exception cref="ArgumentOutOfRangeException">Thrown when the length of
/// <paramref name="bytes"/> is not 4 or any value in <paramref name="bytes"/>
/// is outside the valid range of values.</exception>
public static System.TimeSpan FromByteArray(byte[] bytes)
{
var milliseconds = DInt.FromByteArray(bytes);
return System.TimeSpan.FromMilliseconds(milliseconds);
}
/// <summary>
/// Parses an array of <see cref="T:System.TimeSpan"/> values from bytes.
/// </summary>
/// <param name="bytes">Input bytes read from PLC.</param>
/// <returns>An array of <see cref="T:System.TimeSpan"/> objects representing the values read from PLC.</returns>
/// <exception cref="ArgumentOutOfRangeException">Thrown when the length of
/// <paramref name="bytes"/> is not a multiple of 4 or any value in
/// <paramref name="bytes"/> is outside the valid range of values.</exception>
public static System.TimeSpan[] ToArray(byte[] bytes)
{
const int singleTimeSpanLength = 4;
if (bytes.Length % singleTimeSpanLength != 0)
throw new ArgumentOutOfRangeException(nameof(bytes), bytes.Length,
$"Parsing an array of {nameof(System.TimeSpan)} requires a multiple of {singleTimeSpanLength} bytes of input data, input data is '{bytes.Length}' long.");
var result = new System.TimeSpan[bytes.Length / singleTimeSpanLength];
var milliseconds = DInt.ToArray(bytes);
for (var i = 0; i < milliseconds.Length; i++)
result[i] = System.TimeSpan.FromMilliseconds(milliseconds[i]);
return result;
}
/// <summary>
/// Converts a <see cref="T:System.TimeSpan"/> value to a byte array.
/// </summary>
/// <param name="timeSpan">The TimeSpan value to convert.</param>
/// <returns>A byte array containing the S7 date time representation of <paramref name="timeSpan"/>.</returns>
/// <exception cref="ArgumentOutOfRangeException">Thrown when the value of
/// <paramref name="timeSpan"/> is before <see cref="P:SpecMinimumTimeSpan"/>
/// or after <see cref="P:SpecMaximumTimeSpan"/>.</exception>
public static byte[] ToByteArray(System.TimeSpan timeSpan)
{
if (timeSpan < SpecMinimumTimeSpan)
throw new ArgumentOutOfRangeException(nameof(timeSpan), timeSpan,
$"Time span '{timeSpan}' is before the minimum '{SpecMinimumTimeSpan}' supported in S7 time representation.");
if (timeSpan > SpecMaximumTimeSpan)
throw new ArgumentOutOfRangeException(nameof(timeSpan), timeSpan,
$"Time span '{timeSpan}' is after the maximum '{SpecMaximumTimeSpan}' supported in S7 time representation.");
return DInt.ToByteArray(Convert.ToInt32(timeSpan.TotalMilliseconds));
}
/// <summary>
/// Converts an array of <see cref="T:System.TimeSpan"/> values to a byte array.
/// </summary>
/// <param name="timeSpans">The TimeSpan values to convert.</param>
/// <returns>A byte array containing the S7 date time representations of <paramref name="timeSpans"/>.</returns>
/// <exception cref="ArgumentOutOfRangeException">Thrown when any value of
/// <paramref name="timeSpans"/> is before <see cref="P:SpecMinimumTimeSpan"/>
/// or after <see cref="P:SpecMaximumTimeSpan"/>.</exception>
public static byte[] ToByteArray(System.TimeSpan[] timeSpans)
{
var bytes = new List<byte>(timeSpans.Length * 4);
foreach (var timeSpan in timeSpans) bytes.AddRange(ToByteArray(timeSpan));
return bytes.ToArray();
}
}
}

1
S7.sln
View File

@@ -9,6 +9,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
ProjectSection(SolutionItems) = preProject
appveyor.yml = appveyor.yml
README.md = README.md
.github\workflows\test.yml = .github\workflows\test.yml
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "S7.Net.UnitTest", "S7.Net.UnitTest\S7.Net.UnitTest.csproj", "{303CCED6-9ABC-4899-A509-743341AAA804}"

View File

@@ -1,13 +0,0 @@
image: Visual Studio 2019
configuration: Release
install:
- choco install gitversion.portable -y
before_build:
- cmd: gitversion /l console /output buildserver
- dotnet restore
build_script:
msbuild /nologo /v:m /p:AssemblyVersion=%GitVersion_AssemblySemVer% /p:FileVersion=%GitVersion_MajorMinorPatch% /p:InformationalVersion=%GitVersion_InformationalVersion% /p:Configuration=%CONFIGURATION% S7.sln
after_build:
- dotnet pack S7.Net -c %CONFIGURATION% /p:Version=%GitVersion_NuGetVersion% --no-build -o artifacts
artifacts:
- path: artifacts\*.*