feat(plc4net/s7): add advanced S7 tags and native subscriptions (#2910) * feat(plc4net/s7): support bit and string arrays across PDUs Read packed BOOL arrays, preserve adjacent bits on writes, and handle fixed-length STRING and WSTRING arrays. Split oversized array transfers at the negotiated PDU boundary and aggregate item response codes. * feat(plc4net/s7): support 64-bit scalar values Address types without S7-ANY transport codes as byte spans, encode signed and unsigned 64-bit values and LREAL, and reject scalar values that cross the addressable byte range. * feat(plc4net/s7): support temporal tags Use the generated S7 data-item codecs for durations, dates and time-of-day values, including aliases and DTL. Reject values that cannot be represented without truncation or overflow. * feat(plc4net/s7): support direct peripheral addresses * feat(plc4net/s7): accept raw byte array tag alias * feat(plc4net/s7): support variable and large strings * feat(plc4net/s7): support numbered counters * feat(plc4net/s7): list program blocks through user data * feat(plc4net/s7): expose PLC-driven cyclic subscriptions Add S7 user-data subscribe, push, and unsubscribe exchange with bounded value delivery. Cover initial values and unsolicited pushes with synthetic wire frames. Assisted-by: OpenAI Codex * feat(plc4net/s7): query buffered PLC alarms Expose the S7 alarm-query user-data exchange for ALARM_S and ALARM_8 and validate raw response bytes and refusal handling. Assisted-by: OpenAI Codex * feat(plc4net/s7): receive native alarm indications Expose ALARM_S and ALARM_8 user-data subscriptions with explicit abort, bounded event delivery, and synthetic indication coverage. Assisted-by: OpenAI Codex * fix(plc4net/s7): address follow-up review findings Preserve numeric and temporal values, split large string arrays, and make native subscriptions safe across early pushes, disconnects, repeated close, and alarm resubscription. Add regression coverage for each boundary. * fix(plc4net/s7): close native subscription lifecycle races Serialize native subscription registration with connection shutdown, preserve tracking when PLC aborts fail, reject subscriptions after disconnect, and keep alarm streams bounded by dropping oldest events. * fix(plc4net/modbus): isolate tls test certificate subjects * fix(plc4net/s7): make native subscription cleanup retryable Generated-by: OpenAI Codex GPT-6
diff --git a/plc4net/drivers/s7/S7AlarmSubscription.cs b/plc4net/drivers/s7/S7AlarmSubscription.cs new file mode 100644 index 0000000..a24de39 --- /dev/null +++ b/plc4net/drivers/s7/S7AlarmSubscription.cs
@@ -0,0 +1,68 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Channels; +using System.Threading.Tasks; +using org.apache.plc4net.drivers.s7.readwrite.model; + +namespace org.apache.plc4net.drivers.s7 +{ + /// <summary>PLC-driven alarm indications. Each item retains its generated S7 payload type.</summary> + public sealed class S7AlarmSubscription : IAsyncDisposable + { + private readonly S7Connection _connection; + private readonly Channel<S7PayloadUserDataItem> _items = Channel.CreateBounded<S7PayloadUserDataItem>( + new BoundedChannelOptions(1024) { SingleReader = false, SingleWriter = true, + FullMode = BoundedChannelFullMode.DropOldest }); + private readonly SemaphoreSlim _disposeGate = new(1, 1); + private bool _disposed; + + internal S7AlarmSubscription(S7Connection connection, bool alarm8) + { + _connection = connection; + Alarm8 = alarm8; + } + + internal bool Alarm8 { get; } + + public IAsyncEnumerable<S7PayloadUserDataItem> ReadAllAsync(CancellationToken cancellationToken = default) + => _items.Reader.ReadAllAsync(cancellationToken); + + internal void Publish(S7PayloadUserDataItem item) => _items.Writer.TryWrite(item); + + internal void Complete() => _items.Writer.TryComplete(); + + public async ValueTask DisposeAsync() + { + await _disposeGate.WaitAsync().ConfigureAwait(false); + try + { + if (_disposed) + return; + await _connection.UnsubscribeAlarmsAsync(this).ConfigureAwait(false); + _disposed = true; + Complete(); + } + finally { _disposeGate.Release(); } + } + } +}
diff --git a/plc4net/drivers/s7/S7Connection.cs b/plc4net/drivers/s7/S7Connection.cs index 4376aa9..1d81227 100644 --- a/plc4net/drivers/s7/S7Connection.cs +++ b/plc4net/drivers/s7/S7Connection.cs
@@ -19,6 +19,7 @@ using System; using System.Collections; +using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; using System.Linq; @@ -49,8 +50,8 @@ /// </summary> /// <remarks> /// <para> - /// Every message, and every value, is encoded and decoded by a type generated from - /// <c>s7.mspec</c>; nothing here handles bytes itself. A read or write of several tags is cut + /// Messages are encoded and decoded by types generated from <c>s7.mspec</c>. + /// A read or write of several tags is cut /// into jobs that each fit the PDU length the CPU granted, and the jobs go out one after the /// other: the connection keeps one request outstanding. /// </para> @@ -115,11 +116,24 @@ private readonly SemaphoreSlim _exchangeGate = new SemaphoreSlim(1, 1); private readonly S7MessageCodec _codec; private readonly PollingSubscriptionManager _subscriptions; + private readonly ConcurrentDictionary<byte, S7CyclicSubscription> _nativeSubscriptions = new(); + private readonly Dictionary<byte, S7PayloadUserDataItemCyclicServicesPush> _earlyCyclicPushes = new(); + private readonly object _earlyCyclicLock = new(); + private readonly object _nativeLifecycleLock = new(); + private readonly SemaphoreSlim _alarmLifecycleGate = new SemaphoreSlim(1, 1); + private readonly CancellationTokenSource _nativeStop = new(); + private Task? _nativePump; + private S7AlarmSubscription? _alarmSubscription; + private int _pendingCyclicSubscriptions; + private int _closed; + private int _disposed; + private int _nativePumpStopped; // Set by an async transport's read thread. The exchange loop owns clearing it. private TaskCompletionSource<bool>? _dataArrival; private int _tpduReference; private ushort _expectedTpduReference; + private bool _expectedUserData; private S7Response? _response; public S7Connection(ConnectionString connectionString, ITransportInstance transport) @@ -346,8 +360,387 @@ throw new S7DriverException($"S7 ping failed: {response.GetResponseCode("ping")}."); } + /// <summary>Lists block numbers using the S7 UserData block-functions service.</summary> + public async Task<IReadOnlyList<int>> ListBlocksOfTypeAsync( + string blockType, CancellationToken cancellationToken = default) + { + var code = blockType?.ToUpperInvariant() switch + { + "OB" => 0x3038, + "DB" => 0x3041, + "SDB" => 0x3042, + "FC" => 0x3043, + "SFC" => 0x3044, + "FB" => 0x3045, + "SFB" => 0x3046, + _ => throw new ArgumentException("Unknown S7 block type.", nameof(blockType)) + }; + var reference = NextTpduReference(); + var parameter = new S7ParameterUserData(new List<S7ParameterUserDataItem> + { + new S7ParameterUserDataItemCPUFunctions(0x11, 0x04, 0x03, 0x02, 0, + null, null, null) + }); + var payload = new S7PayloadUserData(new List<S7PayloadUserDataItem> + { + new S7PayloadUserDataItemCpuFunctionListBlocksOfTypeRequest( + DataTransportErrorCode.OK, DataTransportSize.OCTET_STRING, 2, (ushort)code) + }); + var request = new S7MessageUserData(reference, parameter, payload); + if (request.GetLengthInBytes() > PduLength) + throw new S7DriverException("The S7 block-list request exceeds the negotiated PDU."); + var response = await ExchangeAsync(request, reference, cancellationToken).ConfigureAwait(false); + if (response.HasError) + throw new S7DriverException("The S7 block-list request was refused."); + if (response.UserData?.Parameter is not S7ParameterUserData responseParameter || + response.UserData.Payload is not S7PayloadUserData responsePayload || + responseParameter.Items.Count != 1 || responsePayload.Items.Count != 1 || + responseParameter.Items[0] is not S7ParameterUserDataItemCPUFunctions function || + function.CpuFunctionType != 0x08 || function.CpuFunctionGroup != 0x03 || + function.CpuSubfunction != 0x02 || function.ErrorCode.GetValueOrDefault() != 0 || + responsePayload.Items[0] is not S7PayloadUserDataItemCpuFunctionListBlocksOfTypeResponse blocks || + blocks.ReturnCode != DataTransportErrorCode.OK || + blocks.TransportSize != DataTransportSize.OCTET_STRING || + blocks.DataLength != blocks.Items.Length || blocks.Items.Length % 4 != 0) + throw new S7DriverException("The S7 block-list response is malformed or reports an error."); + var numbers = new List<int>(blocks.Items.Length / 4); + for (var i = 0; i < blocks.Items.Length; i += 4) + numbers.Add((blocks.Items[i] << 8) | blocks.Items[i + 1]); + return numbers; + } + + public Task<IReadOnlyList<int>> ListDataBlocksAsync(CancellationToken cancellationToken = default) + => ListBlocksOfTypeAsync("DB", cancellationToken); + + /// <summary>Queries the PLC's buffered ALARM_S or ALARM_8 messages.</summary> + public async Task<byte[]> QueryBufferedAlarmsAsync( + QueryType queryType, CancellationToken cancellationToken = default) + { + if (queryType != QueryType.ALARM_S && queryType != QueryType.ALARM_8) + throw new ArgumentOutOfRangeException(nameof(queryType)); + var reference = NextTpduReference(); + var request = new S7MessageUserData(reference, + new S7ParameterUserData(new List<S7ParameterUserDataItem> + { + new S7ParameterUserDataItemCPUFunctions(0x11, 0x04, 0x04, 0x13, 0, + null, null, null) + }), + new S7PayloadUserData(new List<S7PayloadUserDataItem> + { + new S7PayloadUserDataItemCpuFunctionAlarmQueryRequest( + DataTransportErrorCode.OK, DataTransportSize.OCTET_STRING, 12, + SyntaxIdType.ALARM_QUERYREQSET, queryType, + queryType == QueryType.ALARM_8 ? AlarmType.ALARM_8 : AlarmType.ALARM_S) + })); + var response = await ExchangeAsync(request, reference, cancellationToken).ConfigureAwait(false); + if (response.HasError || response.UserData?.Parameter is not S7ParameterUserData parameter || + response.UserData.Payload is not S7PayloadUserData payload || + parameter.Items.Count != 1 || payload.Items.Count != 1 || + parameter.Items[0] is not S7ParameterUserDataItemCPUFunctions function || + function.CpuFunctionType != 8 || function.CpuFunctionGroup != 4 || + function.CpuSubfunction != 0x13 || function.ErrorCode.GetValueOrDefault() != 0 || + payload.Items[0] is not S7PayloadUserDataItemCpuFunctionAlarmQueryResponse alarms || + alarms.ReturnCode != DataTransportErrorCode.OK || + alarms.TransportSize != DataTransportSize.OCTET_STRING || + alarms.DataLength != alarms.Items.Length) + throw new S7DriverException("The S7 alarm-query response was refused or malformed."); + return alarms.Items; + } + + /// <summary> + /// Subscribes to the PLC's ALARM_S/SQ or ALARM_8 indication stream. Cancellation prevents + /// the request from being sent; after it is sent, the acknowledgement is drained so the + /// client does not lose track of a subscription the PLC may have created. + /// </summary> + public async Task<S7AlarmSubscription> SubscribeAlarmsAsync( + bool alarm8 = false, CancellationToken cancellationToken = default) + { + await _alarmLifecycleGate.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + if (Volatile.Read(ref _closed) != 0) + throw new S7DriverException("The S7 connection is closed."); + if (Volatile.Read(ref _alarmSubscription) != null) + throw new InvalidOperationException("This S7 connection already has an alarm subscription."); + // Register before the exchange: the acknowledgement and first indication may + // arrive in the same transport read and be decoded in one pass. + var subscription = new S7AlarmSubscription(this, alarm8); + Volatile.Write(ref _alarmSubscription, subscription); + var plcAccepted = false; + try + { + var response = await SendAlarmSubscriptionAsync(alarm8, false, cancellationToken, + drainAfterSendOnCancellation: true) + .ConfigureAwait(false); + ValidateAlarmSubscriptionResponse(response); + plcAccepted = true; + if (Volatile.Read(ref _closed) != 0) + throw new S7DriverException("The S7 connection is closed."); + lock (_nativeLifecycleLock) + { + if (_closed != 0 || _nativePumpStopped != 0 || !TransportInstance.IsOpen) + throw new S7DriverException("The S7 connection closed during alarm subscription."); + _nativePump ??= Task.Run(RunNativePumpAsync); + } + return subscription; + } + catch + { + Interlocked.CompareExchange(ref _alarmSubscription, null, subscription); + subscription.Complete(); + if (plcAccepted && TransportInstance.IsOpen && Volatile.Read(ref _closed) == 0) + { + try + { + var abort = await SendAlarmSubscriptionAsync(alarm8, true, CancellationToken.None) + .ConfigureAwait(false); + ValidateAlarmSubscriptionResponse(abort); + } + catch (Exception cleanupException) + { + Logger.LogWarning(cleanupException, + "S7 alarm subscription cleanup failed after setup failed"); + } + } + throw; + } + } + finally { _alarmLifecycleGate.Release(); } + } + + internal async Task UnsubscribeAlarmsAsync(S7AlarmSubscription subscription) + { + await _alarmLifecycleGate.WaitAsync().ConfigureAwait(false); + try + { + if (!ReferenceEquals(Volatile.Read(ref _alarmSubscription), subscription)) + return; + try + { + if (TransportInstance.IsOpen) + { + var response = await SendAlarmSubscriptionAsync(subscription.Alarm8, true, + CancellationToken.None).ConfigureAwait(false); + ValidateAlarmSubscriptionResponse(response); + } + Interlocked.CompareExchange(ref _alarmSubscription, null, subscription); + } + catch + { + if (!TransportInstance.IsOpen || Volatile.Read(ref _closed) != 0) + Interlocked.CompareExchange(ref _alarmSubscription, null, subscription); + throw; + } + } + finally { _alarmLifecycleGate.Release(); } + } + + private async Task<S7Response> SendAlarmSubscriptionAsync( + bool alarm8, bool abort, CancellationToken cancellationToken, + bool drainAfterSendOnCancellation = false) + { + var reference = NextTpduReference(); + var state = alarm8 + ? abort ? AlarmStateType.ALARM_ABORT : AlarmStateType.ALARM_INITIATE + : abort ? AlarmStateType.ALARM_S_ABORT : AlarmStateType.ALARM_S_INITIATE; + var request = new S7MessageUserData(reference, + new S7ParameterUserData(new List<S7ParameterUserDataItem> + { + new S7ParameterUserDataItemCPUFunctions(0x11, 0x04, 0x04, 0x02, 0, + null, null, null) + }), + new S7PayloadUserData(new List<S7PayloadUserDataItem> + { + new S7PayloadUserDataItemCpuFunctionMsgSubscriptionRequest( + DataTransportErrorCode.OK, DataTransportSize.OCTET_STRING, 12, + 0x80, "HmiRtm ", state, 0) + })); + return await ExchangeAsync(request, reference, cancellationToken, + drainAfterSendOnCancellation).ConfigureAwait(false); + } + + private static void ValidateAlarmSubscriptionResponse(S7Response response) + { + if (response.HasError || response.UserData?.Parameter is not S7ParameterUserData parameter || + response.UserData.Payload is not S7PayloadUserData payload || + parameter.Items.Count != 1 || payload.Items.Count != 1 || + parameter.Items[0] is not S7ParameterUserDataItemCPUFunctions function || + function.CpuFunctionType != 8 || function.CpuFunctionGroup != 4 || + function.CpuSubfunction != 2 || function.ErrorCode.GetValueOrDefault() != 0 || + payload.Items[0].ReturnCode != DataTransportErrorCode.OK || + payload.Items[0] is not S7PayloadUserDataItemCpuFunctionMsgSubscriptionResponse && + payload.Items[0] is not S7PayloadUserDataItemCpuFunctionMsgSubscriptionAlarmResponse + { Result: 0 or 2 }) + throw new S7DriverException("The S7 alarm-subscription response was refused or malformed."); + } + + /// <summary> + /// Requests PLC-driven cyclic pushes for one fixed-size S7 tag. Cancellation prevents the + /// request from being sent; after it is sent, the acknowledgement is drained so a created + /// PLC subscription can be tracked and disposed by the caller. + /// </summary> + public async Task<S7CyclicSubscription> SubscribeCyclicAsync( + string address, TimeSpan interval, CancellationToken cancellationToken = default) + { + var tag = S7Tag.Parse(address); + if (tag.IsVariableString || tag.SizeInBytes > PduLength - AckSize - DataItemHeaderSize) + throw new ArgumentException("A cyclic tag must have a fixed size that fits one PDU.", nameof(address)); + var (timeBase, factor) = CyclicInterval(interval); + var itemAddress = ToAddress(tag); + var item = new CycServiceItemAnyType(0x0A, 0x10, itemAddress.TransportSize, + itemAddress.NumberOfElements, itemAddress.DbNumber, itemAddress.Area, + (uint)((itemAddress.ByteAddress << 3) | itemAddress.BitAddress)); + var reference = NextTpduReference(); + var request = new S7MessageUserData(reference, + new S7ParameterUserData(new List<S7ParameterUserDataItem> + { + new S7ParameterUserDataItemCPUFunctions(0x11, 0x04, 0x02, 0x01, 0, + null, null, null) + }), + new S7PayloadUserData(new List<S7PayloadUserDataItem> + { + new S7PayloadUserDataItemCyclicServicesSubscribeRequest( + DataTransportErrorCode.OK, DataTransportSize.OCTET_STRING, 16, + 1, timeBase, factor, new List<CycServiceItemType> { item }) + })); + if (request.GetLengthInBytes() > PduLength) + throw new S7DriverException("The S7 cyclic-subscribe request exceeds the negotiated PDU."); + lock (_nativeLifecycleLock) + { + if (_closed != 0 || !TransportInstance.IsOpen) + throw new S7DriverException("The S7 connection is closed."); + Interlocked.Increment(ref _pendingCyclicSubscriptions); + } + try + { + var response = await ExchangeAsync(request, reference, cancellationToken, + drainAfterSendOnCancellation: true).ConfigureAwait(false); + if (response.HasError || response.UserData?.Parameter is not S7ParameterUserData parameter || + response.UserData.Payload is not S7PayloadUserData payload || + parameter.Items.Count != 1 || payload.Items.Count != 1 || + parameter.Items[0] is not S7ParameterUserDataItemCPUFunctions function || + function.CpuFunctionType != 8 || function.CpuFunctionGroup != 2 || + function.CpuSubfunction != 1 || function.ErrorCode.GetValueOrDefault() != 0 || + payload.Items[0].ReturnCode != DataTransportErrorCode.OK || + payload.Items[0] is not (S7PayloadUserDataItemCyclicServicesSubscribeResponse or + S7PayloadUserDataItemCyclicServicesSubscribeEmptyResponse)) + throw new S7DriverException("The S7 cyclic-subscribe response was refused or malformed."); + IPlcValue? initialValue = null; + if (payload.Items[0] is S7PayloadUserDataItemCyclicServicesSubscribeResponse initial) + { + if (initial.Items.Count != 1 || initial.Items[0].ReturnCode != DataTransportErrorCode.OK) + throw new S7DriverException("The S7 cyclic-subscribe initial value is missing or invalid."); + initialValue = ParseValue(tag, initial.Items[0].Data.ToArray()); + } + var subscription = new S7CyclicSubscription(this, function.SequenceNumber, tag); + lock (_earlyCyclicLock) + { + if (Volatile.Read(ref _closed) != 0) + throw new S7DriverException("The S7 connection is closed."); + if (!TransportInstance.IsOpen) + throw new S7DriverException("The S7 transport disconnected during cyclic subscription."); + if (!_nativeSubscriptions.TryAdd(subscription.JobId, subscription)) + throw new S7DriverException("The PLC reused an active S7 cyclic job ID."); + if (initialValue != null) + subscription.Publish(initialValue); + if (_earlyCyclicPushes.Remove(subscription.JobId, out var early)) + PublishCyclicValue(subscription, early); + } + lock (_nativeLifecycleLock) + { + if (_closed != 0 || _nativePumpStopped != 0 || !TransportInstance.IsOpen) + { + _nativeSubscriptions.TryRemove(subscription.JobId, out _); + subscription.Complete(); + throw new S7DriverException("The S7 connection closed during cyclic subscription."); + } + _nativePump ??= Task.Run(RunNativePumpAsync); + } + return subscription; + } + finally + { + lock (_earlyCyclicLock) + { + if (Interlocked.Decrement(ref _pendingCyclicSubscriptions) == 0) + _earlyCyclicPushes.Clear(); + } + } + } + + private static (TimeBase Base, byte Factor) CyclicInterval(TimeSpan interval) + { + var ticks = interval.Ticks; + if (ticks < TimeSpan.TicksPerMillisecond * 100 || + ticks > TimeSpan.TicksPerSecond * 2550 || + ticks % (TimeSpan.TicksPerMillisecond * 100) != 0) + throw new ArgumentOutOfRangeException(nameof(interval), + "An S7 cyclic interval must be an exact multiple of 100 ms between 100 ms and 2550 s."); + if (ticks % (TimeSpan.TicksPerSecond * 10) == 0) + return (TimeBase.B10SEC, checked((byte)(ticks / (TimeSpan.TicksPerSecond * 10)))); + if (ticks % TimeSpan.TicksPerSecond == 0 && ticks <= TimeSpan.TicksPerSecond * 255) + return (TimeBase.B1SEC, checked((byte)(ticks / TimeSpan.TicksPerSecond))); + if (ticks <= TimeSpan.TicksPerMillisecond * 25500) + return (TimeBase.B01SEC, checked((byte)(ticks / (TimeSpan.TicksPerMillisecond * 100)))); + throw new ArgumentOutOfRangeException(nameof(interval), "The S7 interval cannot be encoded exactly."); + } + + internal async Task UnsubscribeNativeAsync(S7CyclicSubscription subscription) + { + if (!_nativeSubscriptions.TryGetValue(subscription.JobId, out var active) || + !ReferenceEquals(active, subscription)) + return; + if (!TransportInstance.IsOpen) + { + RemoveNativeSubscription(subscription); + return; + } + var reference = NextTpduReference(); + var request = new S7MessageUserData(reference, + new S7ParameterUserData(new List<S7ParameterUserDataItem> + { + new S7ParameterUserDataItemCPUFunctions(0x11, 0x04, 0x02, 0x04, 0, + null, null, null) + }), + new S7PayloadUserData(new List<S7PayloadUserDataItem> + { + new S7PayloadUserDataItemCyclicServicesUnsubscribeRequest( + DataTransportErrorCode.OK, DataTransportSize.OCTET_STRING, 2, 5, + subscription.JobId) + })); + var response = await ExchangeAsync(request, reference, CancellationToken.None).ConfigureAwait(false); + if (response.HasError || response.UserData?.Parameter is not S7ParameterUserData parameter || + response.UserData.Payload is not S7PayloadUserData payload || + parameter.Items.Count != 1 || payload.Items.Count != 1 || + parameter.Items[0] is not S7ParameterUserDataItemCPUFunctions function || + function.CpuFunctionType != 8 || function.CpuFunctionGroup != 2 || + function.CpuSubfunction != 4 || function.ErrorCode.GetValueOrDefault() != 0 || + payload.Items[0] is not S7PayloadUserDataItemCyclicServicesUnsubscribeResponse result || + result.ReturnCode != DataTransportErrorCode.OK) + throw new S7DriverException("The S7 cyclic-unsubscribe response was refused or malformed."); + RemoveNativeSubscription(subscription); + } + + private void RemoveNativeSubscription(S7CyclicSubscription subscription) + => ((ICollection<KeyValuePair<byte, S7CyclicSubscription>>)_nativeSubscriptions) + .Remove(new KeyValuePair<byte, S7CyclicSubscription>(subscription.JobId, subscription)); + public override void Close() { + lock (_nativeLifecycleLock) + { + if (Interlocked.Exchange(ref _closed, 1) != 0) + return; + _nativeStop.Cancel(); + } + Interlocked.Exchange(ref _alarmSubscription, null)?.Complete(); + lock (_earlyCyclicLock) + { + foreach (var subscription in _nativeSubscriptions.Values) + subscription.Complete(); + _nativeSubscriptions.Clear(); + _earlyCyclicPushes.Clear(); + } _subscriptions.DisposeAsync().AsTask().GetAwaiter().GetResult(); base.Close(); } @@ -357,18 +750,21 @@ /// <summary>The parts of an acknowledgement that the driver acts on.</summary> private sealed class S7Response { - public S7Response(byte errorClass, byte errorCode, S7Parameter? parameter, S7Payload? payload) + public S7Response(byte errorClass, byte errorCode, S7Parameter? parameter, S7Payload? payload, + S7MessageUserData? userData = null) { ErrorClass = errorClass; ErrorCode = errorCode; Parameter = parameter; Payload = payload; + UserData = userData; } public byte ErrorClass { get; } public byte ErrorCode { get; } public S7Parameter? Parameter { get; } public S7Payload? Payload { get; } + public S7MessageUserData? UserData { get; } /// <summary>The CPU refused the whole job: the error class and code of the header.</summary> public bool HasError => ErrorClass != 0x00 || ErrorCode != 0x00; @@ -380,6 +776,10 @@ private void OnMessage(S7Message message) { + if (message is S7MessageUserData pushMessage && TryPublishNativePush(pushMessage)) + return; + if (message is S7MessageUserData alarmMessage && TryPublishNativeAlarm(alarmMessage)) + return; ushort reference; S7Response response; switch (message) @@ -395,6 +795,10 @@ reference = ack.TpduReference; response = new S7Response(ack.ErrorClass, ack.ErrorCode, ack.Parameter, ack.Payload); break; + case S7MessageUserData userData: + reference = userData.TpduReference; + response = new S7Response(0, 0, userData.Parameter, userData.Payload, userData); + break; default: Logger.LogDebug("S7: ignored a {Type}, which no job of ours is waiting for", message.GetType().Name); return; @@ -408,20 +812,138 @@ reference, _expectedTpduReference); return; } + if (_expectedUserData + ? message is not S7MessageUserData && !response.HasError + : message is S7MessageUserData) + { + Logger.LogDebug("S7: ignored an unexpected response type for TPDU reference {Reference}", reference); + return; + } _response = response; } + private bool TryPublishNativePush(S7MessageUserData message) + { + if (message.Parameter is not S7ParameterUserData parameter || + parameter.Items.Count != 1 || + parameter.Items[0] is not S7ParameterUserDataItemCPUFunctions function || + function.CpuFunctionType != 0 || function.CpuFunctionGroup != 2 || + function.CpuSubfunction != 1 || + message.Payload is not S7PayloadUserData payload || + payload.Items.Count != 1 || + payload.Items[0] is not S7PayloadUserDataItemCyclicServicesPush push) + return false; + if (push.ReturnCode == DataTransportErrorCode.OK && push.Items.Count == 1 && + push.Items[0].ReturnCode == DataTransportErrorCode.OK) + { + lock (_earlyCyclicLock) + { + if (_nativeSubscriptions.TryGetValue(function.SequenceNumber, out var subscription)) + PublishCyclicValue(subscription, push); + else if (Volatile.Read(ref _pendingCyclicSubscriptions) > 0) + _earlyCyclicPushes[function.SequenceNumber] = push; + } + } + return true; + } + + private void PublishCyclicValue(S7CyclicSubscription subscription, + S7PayloadUserDataItemCyclicServicesPush push) + { + try + { + subscription.Publish(ParseValue(subscription.Tag, push.Items[0].Data.ToArray())); + } + catch (Exception ex) when (ex is S7DriverException || ex is ParseException) + { + Logger.LogWarning(ex, "S7 cyclic push for job {JobId} is malformed", subscription.JobId); + } + } + + private bool TryPublishNativeAlarm(S7MessageUserData message) + { + if (message.Parameter is not S7ParameterUserData parameter || + parameter.Items.Count != 1 || + parameter.Items[0] is not S7ParameterUserDataItemCPUFunctions function || + function.CpuFunctionType != 0 || function.CpuFunctionGroup != 4 || + message.Payload is not S7PayloadUserData payload || payload.Items.Count != 1) + return false; + var item = payload.Items[0]; + if (item is not (S7PayloadAlarmS or S7PayloadAlarmSQ or S7PayloadAlarmSC or + S7PayloadAlarm8 or S7PayloadNotify or S7PayloadNotify8 or S7PayloadAlarmAckInd)) + return false; + if (item.ReturnCode == DataTransportErrorCode.OK) + Volatile.Read(ref _alarmSubscription)?.Publish(item); + return true; + } + + private async Task RunNativePumpAsync() + { + var disconnected = false; + try + { + while (!_nativeStop.IsCancellationRequested) + { + if (!TransportInstance.IsOpen) + { + disconnected = true; + break; + } + await _exchangeGate.WaitAsync(_nativeStop.Token).ConfigureAwait(false); + try + { + _codec.ProcessIncomingData(); + } + catch (MessageCodecException ex) when (!TransportInstance.IsOpen || + ex.InnerException is TransportException) + { + disconnected = true; + break; + } + catch (MessageCodecException ex) + { + Logger.LogWarning(ex, "S7 cyclic push could not be parsed"); + DiscardBufferedBytes(); + } + finally { _exchangeGate.Release(); } + await Task.Delay(20, _nativeStop.Token).ConfigureAwait(false); + } + } + catch (OperationCanceledException) when (_nativeStop.IsCancellationRequested) { } + finally + { + if (disconnected) + { + lock (_nativeLifecycleLock) + { + _nativePumpStopped = 1; + Interlocked.Exchange(ref _alarmSubscription, null)?.Complete(); + lock (_earlyCyclicLock) + { + foreach (var subscription in _nativeSubscriptions.Values) + subscription.Complete(); + _nativeSubscriptions.Clear(); + _earlyCyclicPushes.Clear(); + } + } + } + } + } + /// <summary> /// Sends a job and returns the acknowledgement that carries its TPDU reference. Throws /// <see cref="TimeoutException"/> when none arrives within the read timeout. /// </summary> private async Task<S7Response> ExchangeAsync( - S7Message request, ushort reference, CancellationToken cancellationToken) + S7Message request, ushort reference, CancellationToken cancellationToken, + bool drainAfterSendOnCancellation = false) { await _exchangeGate.WaitAsync(cancellationToken).ConfigureAwait(false); try { + cancellationToken.ThrowIfCancellationRequested(); _expectedTpduReference = reference; + _expectedUserData = request is S7MessageUserData; _response = null; _codec.Send(request); @@ -463,15 +985,18 @@ try { + var waitCancellation = drainAfterSendOnCancellation + ? CancellationToken.None : cancellationToken; if (dataArrival == null) { - await Task.Delay(delayMs, cancellationToken).ConfigureAwait(false); + await Task.Delay(delayMs, waitCancellation).ConfigureAwait(false); } else { - await Task.WhenAny(dataArrival.Task, Task.Delay(delayMs, cancellationToken)) + await Task.WhenAny(dataArrival.Task, Task.Delay(delayMs, waitCancellation)) .ConfigureAwait(false); - cancellationToken.ThrowIfCancellationRequested(); + if (!drainAfterSendOnCancellation) + cancellationToken.ThrowIfCancellationRequested(); } } finally @@ -521,16 +1046,18 @@ protected override void Dispose(bool disposing) { - if (disposing) + if (!disposing || Interlocked.Exchange(ref _disposed, 1) != 0) + return; + _nativeStop.Cancel(); + _nativePump?.GetAwaiter().GetResult(); + if (TransportInstance is IAsyncTransportInstance asyncTransport) { - if (TransportInstance is IAsyncTransportInstance asyncTransport) - { - asyncTransport.RemoveDataListener(); - asyncTransport.RemoveDisconnectListener(); - } - _exchangeGate.Dispose(); + asyncTransport.RemoveDataListener(); + asyncTransport.RemoveDisconnectListener(); } base.Dispose(disposing); + _exchangeGate.Dispose(); + _nativeStop.Dispose(); } // ── Jobs ─────────────────────────────────────────────── @@ -596,16 +1123,21 @@ /// <summary>The S7-ANY address of one tag.</summary> internal static S7AddressAny ToAddress(S7Tag tag) { + if (tag.IsCounter) + return new S7AddressAny(TransportSize.COUNTER, tag.Quantity, + (ushort)tag.DbNumber, tag.Area, (ushort)tag.ByteOffset, tag.BitOffset); // Fixed strings are addressed by their complete byte representation, including // the length header, using CHAR transport elements. var isString = tag.DataType == TransportSize.STRING || tag.DataType == TransportSize.WSTRING; + var isBoolArray = tag.DataType == TransportSize.BOOL && tag.ExplicitRange; + var rawBytes = !isString && !isBoolArray && tag.DataType.GetCode() == 0; return new S7AddressAny( - isString ? TransportSize.CHAR : tag.DataType, - isString ? checked((ushort)tag.SizeInBytes) : tag.Quantity, + isString ? TransportSize.CHAR : isBoolArray || rawBytes ? TransportSize.BYTE : tag.DataType, + isString || isBoolArray || rawBytes ? checked((ushort)tag.SizeInBytes) : tag.Quantity, (ushort)tag.DbNumber, tag.Area, (ushort)tag.ByteOffset, - tag.BitOffset); + isBoolArray ? (byte)0 : tag.BitOffset); } // ── PlcReader ────────────────────────────────────────── @@ -615,12 +1147,21 @@ { var results = new Dictionary<string, PlcResponseItem<IPlcValue>>(); var work = new List<(string Name, S7Tag Tag)>(); + var split = new List<(string Name, S7Tag Tag)>(); + var strings = new List<(string Name, S7Tag Tag)>(); foreach (var name in request.TagNames) { if (request.GetTagByName(name) is S7Tag tag) { - work.Add((name, tag)); + if (tag.IsVariableString || + (tag.StringLength.HasValue && !tag.ExplicitRange && + tag.SizeInBytes > PduLength - AckSize - DataItemHeaderSize)) + strings.Add((name, tag)); + else if (tag.ExplicitRange && tag.SizeInBytes > PduLength - AckSize - DataItemHeaderSize) + split.Add((name, tag)); + else + work.Add((name, tag)); } else { @@ -652,9 +1193,163 @@ } } + foreach (var (name, tag) in split) + { + try + { + results[name] = await ReadArrayChunksAsync(tag, cancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException) { throw; } + catch (Exception ex) + { + Logger.LogWarning(ex, "S7 array read of {TagName} failed", name); + results[name] = new DefaultPlcTagErrorItem<IPlcValue>(MapException(ex)); + } + } + + foreach (var (name, tag) in strings) + { + try + { + var resolved = tag; + if (tag.IsVariableString) + { + var (fixedTag, code) = await ResolveVariableStringAsync(tag, cancellationToken) + .ConfigureAwait(false); + if (fixedTag == null) + { + results[name] = new DefaultPlcTagErrorItem<IPlcValue>(code); + continue; + } + resolved = fixedTag; + } + results[name] = await ReadStringAsync(resolved, cancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException) { throw; } + catch (Exception ex) + { + Logger.LogWarning(ex, "S7 string read of {TagName} failed", name); + results[name] = new DefaultPlcTagErrorItem<IPlcValue>(MapException(ex)); + } + } + return new DefaultPlcReadResponse(request, results); } + private async Task<DefaultPlcReadResponse> ReadSingleAsync(S7Tag tag, CancellationToken cancellationToken) + { + var fields = new Dictionary<string, PlcTagItem<IPlcTag>> + { + ["value"] = new DefaultPlcTagItem<IPlcTag>("value", tag) + }; + return (DefaultPlcReadResponse)await Read( + new DefaultPlcReadRequest(this, fields), cancellationToken).ConfigureAwait(false); + } + + private async Task<(S7Tag? Tag, PlcResponseCode Code)> ResolveVariableStringAsync( + S7Tag tag, CancellationToken cancellationToken) + { + var headerLength = tag.SizeInBytes; + var headerTag = new S7Tag(tag.Area, tag.DbNumber, tag.ByteOffset, 0, + TransportSize.BYTE, null, (ushort)headerLength, true); + var response = await ReadSingleAsync(headerTag, cancellationToken).ConfigureAwait(false); + var code = response.GetResponseCode("value"); + if (code != PlcResponseCode.Ok) + return (null, code); + var bytes = response.GetValue("value")!.GetList().Select(item => item.GetByte()).ToArray(); + var maximum = tag.DataType == TransportSize.WSTRING + ? (bytes[0] << 8) | bytes[1] : bytes[0]; + var current = tag.DataType == TransportSize.WSTRING + ? (bytes[2] << 8) | bytes[3] : bytes[1]; + var limit = tag.DataType == TransportSize.WSTRING ? 16382 : 254; + if (maximum < 1 || maximum > limit || current > maximum || + (long)tag.ByteOffset + (maximum + 2) * (headerLength / 2) > S7Tag.MaxByteOffset + 1L) + return (null, PlcResponseCode.InternalError); + return (new S7Tag(tag.Area, tag.DbNumber, tag.ByteOffset, 0, + tag.DataType, maximum), PlcResponseCode.Ok); + } + + private async Task<PlcResponseItem<IPlcValue>> ReadStringAsync( + S7Tag tag, CancellationToken cancellationToken) + { + if (tag.SizeInBytes <= PduLength - AckSize - DataItemHeaderSize) + { + var response = await ReadSingleAsync(tag, cancellationToken).ConfigureAwait(false); + var code = response.GetResponseCode("value"); + return code == PlcResponseCode.Ok + ? new DefaultPlcResponseItem<IPlcValue>(code, response.GetValue("value")!) + : new DefaultPlcTagErrorItem<IPlcValue>(code); + } + var bytesTag = new S7Tag(tag.Area, tag.DbNumber, tag.ByteOffset, 0, + TransportSize.BYTE, null, checked((ushort)tag.SizeInBytes), true); + var bytesResponse = await ReadSingleAsync(bytesTag, cancellationToken).ConfigureAwait(false); + var result = bytesResponse.GetResponseCode("value"); + if (result != PlcResponseCode.Ok) + return new DefaultPlcTagErrorItem<IPlcValue>(result); + var bytes = bytesResponse.GetValue("value")!.GetList().Select(item => item.GetByte()).ToArray(); + return new DefaultPlcResponseItem<IPlcValue>(PlcResponseCode.Ok, ParseValue(tag, bytes)); + } + + private async Task<PlcResponseItem<IPlcValue>> ReadArrayChunksAsync( + S7Tag tag, CancellationToken cancellationToken) + { + var capacity = PduLength - AckSize - DataItemHeaderSize; + var values = new List<IPlcValue>(tag.Quantity); + if (tag.StringLength.HasValue && tag.SizeInBytes / tag.Quantity > capacity) + { + var elementSize = tag.SizeInBytes / tag.Quantity; + for (var i = 0; i < tag.Quantity; i++) + { + var element = new S7Tag(tag.Area, tag.DbNumber, + tag.ByteOffset + i * elementSize, 0, tag.DataType, tag.StringLength); + var result = await ReadStringAsync(element, cancellationToken).ConfigureAwait(false); + if (result.Code != PlcResponseCode.Ok) + return result; + values.Add(result.Value!); + } + return new DefaultPlcResponseItem<IPlcValue>(PlcResponseCode.Ok, new PlcList(values)); + } + for (var offset = 0; offset < tag.Quantity;) + { + var count = ChunkCount(tag, offset, capacity); + var chunk = ChunkTag(tag, offset, count); + var fields = new Dictionary<string, PlcTagItem<IPlcTag>> + { + ["chunk"] = new DefaultPlcTagItem<IPlcTag>("chunk", chunk) + }; + var response = (DefaultPlcReadResponse)await Read( + new DefaultPlcReadRequest(this, fields), cancellationToken).ConfigureAwait(false); + var code = response.GetResponseCode("chunk"); + if (code != PlcResponseCode.Ok) + return new DefaultPlcTagErrorItem<IPlcValue>(code); + values.AddRange(response.GetValue("chunk")!.GetList()); + offset += count; + } + return new DefaultPlcResponseItem<IPlcValue>(PlcResponseCode.Ok, new PlcList(values)); + } + + private static int ChunkCount(S7Tag tag, int offset, int capacity) + { + var available = tag.DataType == TransportSize.BOOL + ? capacity * 8 - (tag.BitOffset + offset) % 8 + : capacity / (tag.SizeInBytes / tag.Quantity); + if (available < 1) + throw new S7DriverException($"An S7 {tag.DataType} item cannot fit in the negotiated PDU."); + return Math.Min(tag.Quantity - offset, available); + } + + private static S7Tag ChunkTag(S7Tag tag, int offset, int count) + { + if (tag.IsCounter) + return tag.CounterSlice(offset, count); + var bit = tag.BitOffset + offset; + return new S7Tag(tag.Area, tag.DbNumber, + tag.ByteOffset + (tag.DataType == TransportSize.BOOL + ? bit / 8 : offset * (tag.SizeInBytes / tag.Quantity)), + tag.DataType == TransportSize.BOOL ? (byte)(bit % 8) : (byte)0, + tag.DataType, tag.StringLength, checked((ushort)count), true); + } + private async Task ReadJobAsync( List<(string Name, S7Tag Tag)> items, Dictionary<string, PlcResponseItem<IPlcValue>> results, @@ -726,11 +1421,27 @@ throw new S7DriverException( $"The S7 answer carries {data.Length} byte(s) for {tag}; a {tag.DataType} takes {tag.SizeInBytes}."); } + if (tag.IsCounter) + { + var counterValues = new List<IPlcValue>(tag.Quantity); + for (var i = 0; i < tag.Quantity; i++) + counterValues.Add(new PlcWORD((ushort)((data[i * 2] << 8) | data[i * 2 + 1]))); + return tag.ExplicitRange ? new PlcList(counterValues) : counterValues[0]; + } if (!tag.ExplicitRange) return ParseElement(tag, new ReadBuffer(data)); var values = new List<IPlcValue>(tag.Quantity); - var elementSize = tag.DataType.GetSizeInBytes(); + if (tag.DataType == TransportSize.BOOL) + { + for (var i = 0; i < tag.Quantity; i++) + { + var bit = tag.BitOffset + i; + values.Add(new PlcBOOL((data[bit / 8] & (1 << (bit % 8))) != 0)); + } + return new PlcList(values); + } + var elementSize = tag.SizeInBytes / tag.Quantity; for (var i = 0; i < tag.Quantity; i++) values.Add(ParseElement(tag, new ReadBuffer(data, i * elementSize, elementSize))); return new PlcList(values); @@ -773,7 +1484,85 @@ // reaches the CPU. try { - work.Add((name, tag, EncodeValue(tag, value))); + if (tag.IsVariableString) + { + var (fixedTag, code) = await ResolveVariableStringAsync(tag, cancellationToken) + .ConfigureAwait(false); + if (fixedTag == null) + { + codes[name] = code; + continue; + } + tag = fixedTag; + } + if (tag.DataType == TransportSize.BOOL && tag.ExplicitRange) + { + // Write each selected bit with BIT transport so adjacent bits survive. + // Prepare every item before adding any of them to the outgoing work. + var values = ArrayItems(value, tag.Quantity); + var pieces = new List<(string Name, S7Tag Tag, byte[] Data)>(values.Length); + for (var i = 0; i < values.Length; i++) + { + var bit = tag.BitOffset + i; + var scalar = new S7Tag(tag.Area, tag.DbNumber, + tag.ByteOffset + bit / 8, (byte)(bit % 8), TransportSize.BOOL); + pieces.Add((name, scalar, EncodeValue(scalar, values[i]))); + } + work.AddRange(pieces); + } + else + { + var data = EncodeValue(tag, value); + var capacity = PduLength - JobSize - AddressItemSize - DataItemHeaderSize; + if (capacity < 1) + throw new S7DriverException("The negotiated S7 PDU cannot hold a write item."); + if (tag.StringLength.HasValue && !tag.ExplicitRange && data.Length > capacity) + { + // The string layout is a contiguous byte range. Preserve the + // complete header and padding while splitting the wire writes. + var bytesTag = new S7Tag(tag.Area, tag.DbNumber, tag.ByteOffset, 0, + TransportSize.BYTE, null, checked((ushort)data.Length), true); + for (var offset = 0; offset < data.Length;) + { + var count = ChunkCount(bytesTag, offset, capacity); + var part = new byte[count]; + Array.Copy(data, offset, part, 0, count); + work.Add((name, ChunkTag(bytesTag, offset, count), part)); + offset += count; + } + continue; + } + if (tag.ExplicitRange && data.Length > capacity) + { + var elementSize = tag.SizeInBytes / tag.Quantity; + if (tag.StringLength.HasValue && elementSize > capacity) + { + for (var offset = 0; offset < data.Length;) + { + var count = Math.Min(capacity, data.Length - offset); + var part = new byte[count]; + Array.Copy(data, offset, part, 0, count); + var chunk = new S7Tag(tag.Area, tag.DbNumber, + tag.ByteOffset + offset, 0, TransportSize.BYTE, + null, checked((ushort)count), true); + work.Add((name, chunk, part)); + offset += count; + } + continue; + } + for (var offset = 0; offset < tag.Quantity;) + { + var count = ChunkCount(tag, offset, capacity); + var size = count * elementSize; + var part = new byte[size]; + Array.Copy(data, offset * elementSize, part, 0, size); + work.Add((name, ChunkTag(tag, offset, count), part)); + offset += count; + } + } + else + work.Add((name, tag, data)); + } } catch (Exception ex) when (ex is FormatException || ex is InvalidCastException || ex is OverflowException) { @@ -801,7 +1590,7 @@ var code = MapException(ex); foreach (var (name, _, _) in items) { - codes[name] = code; + RecordCode(codes, name, code); } } } @@ -833,7 +1622,7 @@ var refused = MapHeaderError(response.ErrorClass, response.ErrorCode); foreach (var (name, _, _) in items) { - codes[name] = refused; + RecordCode(codes, name, refused); } return; } @@ -846,14 +1635,21 @@ for (var i = 0; i < items.Count; i++) { - codes[items[i].Name] = i >= payload.Items.Count + var code = i >= payload.Items.Count ? PlcResponseCode.InternalError : payload.Items[i].ReturnCode == DataTransportErrorCode.OK ? PlcResponseCode.Ok : MapReturnCode(payload.Items[i].ReturnCode); + RecordCode(codes, items[i].Name, code); } } + private static void RecordCode(Dictionary<string, PlcResponseCode> codes, string name, PlcResponseCode code) + { + if (!codes.TryGetValue(name, out var previous) || previous == PlcResponseCode.Ok) + codes[name] = code; + } + /// <summary> /// Encodes a value for a tag with the generated <c>DataItem</c>, so the value has to fit /// the tag's data type: an <c>INT</c> tag takes -32768..32767, a <c>BYTE</c> tag 0..255. @@ -863,15 +1659,21 @@ /// <exception cref="InvalidCastException">The value is not of a kind the data type takes.</exception> internal static byte[] EncodeValue(S7Tag tag, object value) { + if (tag.IsCounter) + { + var values = tag.ExplicitRange ? ArrayItems(value, tag.Quantity) : new[] { value }; + var data = new byte[values.Length * 2]; + for (var i = 0; i < values.Length; i++) + { + var word = checked((ushort)ToInteger(values[i])); + data[i * 2] = (byte)(word >> 8); + data[i * 2 + 1] = (byte)word; + } + return data; + } if (tag.ExplicitRange) { - var values = value is IPlcValue plc && plc.IsList() - ? plc.GetList().Cast<object>().ToArray() - : value is IEnumerable sequence && value is not string - ? sequence.Cast<object>().ToArray() - : new[] { value }; - if (values.Length != tag.Quantity) - throw new InvalidCastException($"The S7 array needs {tag.Quantity} values, but got {values.Length}."); + var values = ArrayItems(value, tag.Quantity); var scalar = new S7Tag(tag.Area, tag.DbNumber, tag.ByteOffset, tag.BitOffset, tag.DataType, tag.StringLength); var bytes = new List<byte>(tag.SizeInBytes); @@ -888,6 +1690,9 @@ case TransportSize.REAL: plcValue = new PlcREAL(ToSingle(value)); break; + case TransportSize.LREAL: + plcValue = new PlcLREAL(ToDouble(value)); + break; case TransportSize.BYTE: plcValue = new PlcBYTE(checked((byte)ToInteger(value))); break; @@ -909,18 +1714,41 @@ case TransportSize.DWORD: plcValue = new PlcDWORD(checked((uint)ToInteger(value))); break; + case TransportSize.LWORD: + plcValue = new PlcLWORD(ToUnsigned(value)); + break; case TransportSize.DINT: plcValue = new PlcDINT(checked((int)ToInteger(value))); break; case TransportSize.UDINT: plcValue = new PlcUDINT(checked((uint)ToInteger(value))); break; + case TransportSize.LINT: + plcValue = new PlcLINT(ToInteger(value)); + break; + case TransportSize.ULINT: + plcValue = new PlcULINT(ToUnsigned(value)); + break; case TransportSize.STRING: plcValue = new PlcSTRING(ToStringValue(value)); break; case TransportSize.WSTRING: plcValue = new PlcWSTRING(ToStringValue(value)); break; + case TransportSize.S5TIME: + case TransportSize.TIME: + case TransportSize.LTIME: + case TransportSize.DATE: + case TransportSize.TIME_OF_DAY: + case TransportSize.TOD: + case TransportSize.LTIME_OF_DAY: + case TransportSize.LTOD: + case TransportSize.DT: + case TransportSize.DATE_AND_LTIME: + case TransportSize.LDT: + case TransportSize.DTL: + plcValue = ToTemporalValue(tag.DataType, value); + break; case TransportSize.CHAR: case TransportSize.WCHAR: var character = value is char ch ? ch.ToString() : ToStringValue(value); @@ -946,6 +1774,106 @@ return buffer.GetBytes(); } + private static object[] ArrayItems(object value, ushort quantity) + { + var values = value is IPlcValue plc && plc.IsList() + ? plc.GetList().Cast<object>().ToArray() + : value is IEnumerable sequence && value is not string + ? sequence.Cast<object>().ToArray() + : new[] { value }; + if (values.Length != quantity) + throw new InvalidCastException($"The S7 array needs {quantity} values, but got {values.Length}."); + return values; + } + + private static IPlcValue ToTemporalValue(TransportSize type, object value) + { + switch (type) + { + case TransportSize.S5TIME: + case TransportSize.TIME: + var time = value as PlcTIME ?? (value is TimeSpan duration ? new PlcTIME(duration) : null); + if (time != null) + { + var span = time.GetDuration(); + var milliseconds = span.TotalMilliseconds; + if (span.Ticks % TimeSpan.TicksPerMillisecond != 0 || milliseconds < 0 || + milliseconds > (type == TransportSize.S5TIME ? 9_990_000 : uint.MaxValue)) + throw new InvalidCastException($"An S7 {type} duration is outside its millisecond range."); + if (type == TransportSize.S5TIME) + { + var resolution = milliseconds <= 9_990 ? 10 : + milliseconds <= 99_900 ? 100 : milliseconds <= 999_000 ? 1_000 : 10_000; + if (milliseconds % resolution != 0) + throw new InvalidCastException("An S7 S5TIME duration is not representable exactly."); + } + return time; + } + break; + case TransportSize.LTIME: + if (value is PlcLTIME longTime) return longTime; + if (value is ulong nanoseconds) return new PlcLTIME(nanoseconds); + break; + case TransportSize.DATE: + var date = value as PlcDATE ?? (value is DateOnly day ? new PlcDATE(day) : null); + if (date != null) + { + var days = date.GetDate().DayNumber - new DateOnly(1990, 1, 1).DayNumber; + if (days < 0 || days > ushort.MaxValue) + throw new InvalidCastException("An S7 DATE must fit the Siemens 16-bit day range."); + return date; + } + break; + case TransportSize.TIME_OF_DAY: + case TransportSize.TOD: + if (value is PlcTIME_OF_DAY timeOfDay) return timeOfDay; + if (value is TimeOnly clock) return new PlcTIME_OF_DAY(clock); + break; + case TransportSize.LTIME_OF_DAY: + case TransportSize.LTOD: + if (value is PlcLTIME_OF_DAY longTimeOfDay) return longTimeOfDay; + if (value is ulong nanosecondsSinceMidnight) + { + if (nanosecondsSinceMidnight >= 86_400_000_000_000UL) + throw new InvalidCastException("An S7 LTIME_OF_DAY must be within one day."); + return new PlcLTIME_OF_DAY(nanosecondsSinceMidnight); + } + break; + case TransportSize.DT: + var dateTime = value as PlcDATE_AND_TIME ?? + (value is DateTime dateAndTime ? new PlcDATE_AND_TIME(dateAndTime) : null); + if (dateTime != null) + { + var instant = dateTime.GetDateTime(); + if (instant.Year < 1990 || instant.Year > 2089 || + instant.Ticks % TimeSpan.TicksPerMillisecond != 0) + throw new InvalidCastException("An S7 DATE_AND_TIME needs a representable year and millisecond."); + return dateTime; + } + break; + case TransportSize.DATE_AND_LTIME: + case TransportSize.LDT: + case TransportSize.DTL: + var longDateTime = value as PlcDATE_AND_LTIME ?? + (value is DateTime longDateAndTime ? new PlcDATE_AND_LTIME(longDateAndTime, 0) : null); + if (longDateTime != null) + { + if (type != TransportSize.DTL) + { + var seconds = (longDateTime.GetDateTime().Ticks - DateTime.UnixEpoch.Ticks) / + TimeSpan.TicksPerSecond; + if (longDateTime.GetDateTime().Ticks < DateTime.UnixEpoch.Ticks || + (decimal)seconds * 1_000_000_000 + + longDateTime.GetNanosecondsOfSecond() > ulong.MaxValue) + throw new InvalidCastException("An S7 DATE_AND_LTIME must fit the 64-bit Unix nanosecond range."); + } + return longDateTime; + } + break; + } + throw new InvalidCastException($"An S7 {type} requires a matching temporal value."); + } + private static string ToStringValue(object value) { switch (value) @@ -984,8 +1912,10 @@ return WholeNumber(f); case double d: return WholeNumber(d); - case decimal m: - return WholeNumber((double)m); + case decimal m when m == decimal.Truncate(m): + return checked((long)m); + case decimal _: + throw new FormatException("An integer must be whole."); case ulong u: return checked((long)u); case string s: @@ -1004,6 +1934,44 @@ return checked((long)value); } + private static ulong ToUnsigned(object value) + { + switch (value) + { + case bool _: + throw new InvalidCastException("A boolean cannot be written to an unsigned number."); + case IPlcValue plc: + return plc.GetUlong(); + case float f: + return checked((ulong)WholeNumber(f)); + case double d: + return checked((ulong)WholeNumber(d)); + case decimal m when m == decimal.Truncate(m): + return checked((ulong)m); + case decimal _: + throw new FormatException("An unsigned number must be whole."); + case string s: + return ulong.Parse(s, NumberStyles.Integer, CultureInfo.InvariantCulture); + default: + return Convert.ToUInt64(value, CultureInfo.InvariantCulture); + } + } + + private static double ToDouble(object value) + { + switch (value) + { + case bool _: + throw new InvalidCastException("A boolean cannot be written to an LREAL."); + case IPlcValue plc: + return plc.GetDouble(); + case string s: + return double.Parse(s, NumberStyles.Float, CultureInfo.InvariantCulture); + default: + return Convert.ToDouble(value, CultureInfo.InvariantCulture); + } + } + private static float ToSingle(object value) { switch (value)
diff --git a/plc4net/drivers/s7/S7CyclicSubscription.cs b/plc4net/drivers/s7/S7CyclicSubscription.cs new file mode 100644 index 0000000..ad82aa9 --- /dev/null +++ b/plc4net/drivers/s7/S7CyclicSubscription.cs
@@ -0,0 +1,70 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Channels; +using System.Threading.Tasks; +using org.apache.plc4net.api.value; + +namespace org.apache.plc4net.drivers.s7 +{ + /// <summary>A PLC-driven S7 cyclic subscription to one tag.</summary> + public sealed class S7CyclicSubscription : IAsyncDisposable + { + private readonly S7Connection _connection; + private readonly Channel<IPlcValue> _values = Channel.CreateBounded<IPlcValue>( + new BoundedChannelOptions(1) { SingleReader = false, SingleWriter = true, + FullMode = BoundedChannelFullMode.DropOldest }); + private readonly SemaphoreSlim _disposeGate = new(1, 1); + private bool _disposed; + + internal S7CyclicSubscription(S7Connection connection, byte jobId, S7Tag tag) + { + _connection = connection; + JobId = jobId; + Tag = tag; + } + + public byte JobId { get; } + public S7Tag Tag { get; } + + /// <summary>Reads the most recent PLC push; slow consumers skip older values.</summary> + public IAsyncEnumerable<IPlcValue> ReadAllAsync(CancellationToken cancellationToken = default) + => _values.Reader.ReadAllAsync(cancellationToken); + + internal void Publish(IPlcValue value) => _values.Writer.TryWrite(value); + internal void Complete() => _values.Writer.TryComplete(); + + public async ValueTask DisposeAsync() + { + await _disposeGate.WaitAsync().ConfigureAwait(false); + try + { + if (_disposed) + return; + await _connection.UnsubscribeNativeAsync(this).ConfigureAwait(false); + _disposed = true; + Complete(); + } + finally { _disposeGate.Release(); } + } + } +}
diff --git a/plc4net/drivers/s7/S7Tag.cs b/plc4net/drivers/s7/S7Tag.cs index a2c3d1d..362fe3b 100644 --- a/plc4net/drivers/s7/S7Tag.cs +++ b/plc4net/drivers/s7/S7Tag.cs
@@ -52,9 +52,8 @@ /// a <c>REAL</c>. /// </para> /// <para> - /// BOOL and string array selections, the 64-bit types, the date and time types, counters, - /// timers and the other memory areas are not supported here yet; they are rejected rather - /// than read as something else. Fixed-length STRING and WSTRING are supported only in data blocks. + /// Timers and local data are not supported here yet; they are rejected rather + /// than read as something else. STRING and WSTRING are supported only in data blocks. /// </para> /// </remarks> public sealed class S7Tag : IPlcTag @@ -72,9 +71,25 @@ TransportSize.DWORD, TransportSize.DINT, TransportSize.UDINT, + TransportSize.LWORD, + TransportSize.LINT, + TransportSize.ULINT, TransportSize.REAL, + TransportSize.LREAL, TransportSize.CHAR, TransportSize.WCHAR, + TransportSize.S5TIME, + TransportSize.TIME, + TransportSize.LTIME, + TransportSize.DATE, + TransportSize.TIME_OF_DAY, + TransportSize.TOD, + TransportSize.LTIME_OF_DAY, + TransportSize.LTOD, + TransportSize.DT, + TransportSize.DATE_AND_LTIME, + TransportSize.LDT, + TransportSize.DTL, }; /// <summary>The highest data block number: it travels in 16 bits.</summary> @@ -86,7 +101,7 @@ // [0-9], not \d: in .NET \d matches every Unicode decimal digit, so a non-ASCII number would // pass the pattern and then blow up int.Parse instead of failing here as an invalid tag. private const string Tail = - @"(?<byte>[0-9]{1,7})(\.(?<bit>[0-7]))?(?<array>\[[^\]]*\])?:(?<type>(S5)?[A-Za-z_]+)(\((?<stringLength>[0-9]{1,3})\))?$"; + @"(?<byte>[0-9]{1,7})(\.(?<bit>[0-7]))?(?<array>\[[^\]]*\])?:(?<type>(S5)?[A-Za-z_]+)(\((?<stringLength>[0-9]{1,5})\))?$"; private static readonly Regex DataBlockPattern = new Regex( @"^%DB(?<db>[0-9]{1,5})\.DB(?<size>[XBWD]?)" + Tail, @@ -119,19 +134,35 @@ public S7Tag( MemoryArea area, int dbNumber, int byteOffset, byte bitOffset, TransportSize dataType, int? stringLength, ushort quantity, bool explicitRange) + : this(area, dbNumber, byteOffset, bitOffset, dataType, stringLength, quantity, explicitRange, false) + { + } + + /// <summary>Creates a numbered S7 counter tag in the counter area or a data block.</summary> + public static S7Tag ForCounter(MemoryArea area, int dbNumber, int counterNumber, + ushort quantity = 1) + { + if (area != MemoryArea.COUNTERS && area != MemoryArea.DATA_BLOCKS) + throw new PlcInvalidFieldException("An S7 counter belongs to the counter area or a data block."); + return new S7Tag(area, dbNumber, counterNumber, 0, + TransportSize.COUNTER, null, quantity, quantity > 1, true); + } + + private S7Tag( + MemoryArea area, int dbNumber, int byteOffset, byte bitOffset, + TransportSize dataType, int? stringLength, ushort quantity, bool explicitRange, bool isCounter) { if (quantity == 0) throw new PlcInvalidFieldException("An S7 array must contain at least one element."); - if ((quantity != 1 || explicitRange) && - (dataType == TransportSize.BOOL || dataType == TransportSize.STRING || dataType == TransportSize.WSTRING)) - throw new PlcInvalidFieldException("S7 BOOL and string array selections are not supported yet."); if (area != MemoryArea.DATA_BLOCKS && area != MemoryArea.INPUTS - && area != MemoryArea.OUTPUTS && area != MemoryArea.FLAGS_MARKERS) + && area != MemoryArea.OUTPUTS && area != MemoryArea.FLAGS_MARKERS + && area != MemoryArea.DIRECT_PERIPHERAL_ACCESS + && !(isCounter && area == MemoryArea.COUNTERS)) { throw new PlcInvalidFieldException( - $"The memory area {area} is not supported yet; supported: data blocks, inputs, outputs and flags."); + $"The memory area {area} is not supported yet; supported: data blocks, inputs, outputs, flags, direct peripheral access and counters (for COUNTER tags)."); } - if (!SupportedTypes.Contains(dataType) && dataType != TransportSize.STRING + if (!isCounter && !SupportedTypes.Contains(dataType) && dataType != TransportSize.STRING && dataType != TransportSize.WSTRING) { throw new PlcInvalidFieldException(UnsupportedType(dataType.ToString())); @@ -142,15 +173,20 @@ { throw new PlcInvalidFieldException("S7 STRING and WSTRING tags are supported only in data blocks."); } - if (!stringLength.HasValue || stringLength.Value < 1 || stringLength.Value > 254) + var maximumLength = dataType == TransportSize.WSTRING ? 16382 : 254; + if (stringLength.HasValue && (stringLength.Value < 1 || stringLength.Value > maximumLength)) { - throw new PlcInvalidFieldException("An S7 STRING or WSTRING length must be between 1 and 254 characters."); + throw new PlcInvalidFieldException( + $"An S7 {dataType} length must be between 1 and {maximumLength} characters."); } + if (!stringLength.HasValue && (quantity != 1 || explicitRange)) + throw new PlcInvalidFieldException("A variable-length S7 string cannot have an array selection."); if (bitOffset != 0) { throw new PlcInvalidFieldException("An S7 STRING or WSTRING cannot have a bit offset."); } - var sizeInBytes = (stringLength.Value + 2) * (dataType == TransportSize.WSTRING ? 2 : 1); + var sizeInBytes = (stringLength.GetValueOrDefault() + 2) * + (dataType == TransportSize.WSTRING ? 2 : 1) * quantity; if (byteOffset > MaxByteOffset - (sizeInBytes - 1)) { throw new PlcInvalidFieldException( @@ -171,15 +207,26 @@ throw new PlcInvalidFieldException( $"The S7 memory area {area} must use data block number 0, but was {dbNumber}."); } - if (byteOffset < 0 || byteOffset > MaxByteOffset) + var highestOffset = isCounter ? MaxByteOffset * 8L + 7 : MaxByteOffset; + if (byteOffset < 0 || byteOffset > highestOffset) { throw new PlcInvalidFieldException( - $"The S7 byte offset must be between 0 and {MaxByteOffset}, but was {byteOffset}."); + $"The S7 address offset must be between 0 and {highestOffset}, but was {byteOffset}."); } - if ((quantity != 1 || explicitRange) && - (long)byteOffset + (long)quantity * dataType.GetSizeInBytes() > MaxByteOffset + 1L) + if (isCounter && (dataType != TransportSize.COUNTER || stringLength.HasValue || bitOffset != 0)) + throw new PlcInvalidFieldException("An S7 COUNTER uses a numbered address without a bit or string length."); + if (isCounter && (long)byteOffset + quantity - 1 > highestOffset) + throw new PlcInvalidFieldException("The S7 counter array extends past the addressable range."); + if (!isCounter && (quantity != 1 || explicitRange) && + (long)byteOffset + (dataType == TransportSize.BOOL + ? ((long)bitOffset + quantity + 7) / 8 + : (long)quantity * dataType.GetSizeInBytes()) > MaxByteOffset + 1L) throw new PlcInvalidFieldException("The S7 array extends past the addressable byte range."); - if (bitOffset > 7 || (dataType != TransportSize.BOOL && bitOffset != 0)) + if (!isCounter && quantity == 1 && !explicitRange && !stringLength.HasValue && + dataType != TransportSize.STRING && dataType != TransportSize.WSTRING && + (long)byteOffset + dataType.GetSizeInBytes() > MaxByteOffset + 1L) + throw new PlcInvalidFieldException("The S7 value extends past the addressable byte range."); + if (bitOffset > 7 || (!isCounter && dataType != TransportSize.BOOL && bitOffset != 0)) { throw new PlcInvalidFieldException( "The S7 bit offset must be 0 to 7, and only a BOOL has one that is not 0."); @@ -187,9 +234,10 @@ Area = area; DbNumber = dbNumber; - ByteOffset = byteOffset; - BitOffset = bitOffset; + ByteOffset = isCounter ? byteOffset / 8 : byteOffset; + BitOffset = isCounter ? (byte)(byteOffset % 8) : bitOffset; DataType = dataType; + IsCounter = isCounter; StringLength = stringLength; Quantity = quantity; ExplicitRange = explicitRange || quantity > 1; @@ -207,17 +255,34 @@ public TransportSize DataType { get; } + public bool IsCounter { get; } + + internal S7Tag CounterSlice(int offset, int count) + { + if (!IsCounter) + throw new InvalidOperationException("Only a counter tag can be sliced as counters."); + return new S7Tag(Area, DbNumber, (ByteOffset << 3) + BitOffset + offset, + 0, TransportSize.COUNTER, null, checked((ushort)count), true, true); + } + /// <summary>The declared maximum character count for a fixed-length STRING; null otherwise.</summary> public int? StringLength { get; } + public bool IsVariableString => + !StringLength.HasValue && (DataType == TransportSize.STRING || DataType == TransportSize.WSTRING); + public ushort Quantity { get; } public bool ExplicitRange { get; } /// <summary>The bytes the value takes on the wire, including a string's length header.</summary> public int SizeInBytes => StringLength.HasValue - ? (StringLength.Value + 2) * (DataType == TransportSize.WSTRING ? 2 : 1) - : DataType.GetSizeInBytes() * Quantity; + ? (StringLength.Value + 2) * (DataType == TransportSize.WSTRING ? 2 : 1) * Quantity + : IsCounter ? 2 * Quantity + : IsVariableString ? (DataType == TransportSize.WSTRING ? 4 : 2) + : DataType == TransportSize.BOOL && ExplicitRange + ? (BitOffset + Quantity + 7) / 8 + : DataType.GetSizeInBytes() * Quantity; /// <summary> /// Parses a tag address such as <c>%DB1.DBW10:INT</c> or <c>%M0.0:BOOL</c>. @@ -255,8 +320,8 @@ throw new PlcInvalidFieldException( $"'{tagAddress}' is not a supported S7 tag address. Expected " + "%DB{block}.DB{X|B|W|D}{byte}[.{bit}]:{TYPE}, %DB{block}:{byte}[.{bit}]:{TYPE} or " + - "%{I|Q|M}[X|B|W|D]{byte}[.{bit}]:{TYPE}, for example %DB1.DBW10:INT or %M0.0:BOOL; " + - "a data-block string uses %DB{block}:{byte}:STRING({length}) or :WSTRING({length}). The other memory areas " + + "%{I|Q|M|D}[X|B|W|D]{byte}[.{bit}]:{TYPE}, for example %DB1.DBW10:INT or %M0.0:BOOL; " + + "a data-block string uses %DB{block}:{byte}:STRING[(length)] or :WSTRING[(length)]. The other memory areas " + "are not supported yet."); } @@ -264,10 +329,28 @@ { var dataType = TypeOf(match.Groups["type"].Value); var byteOffset = int.Parse(match.Groups["byte"].Value, CultureInfo.InvariantCulture); + int? stringLength = null; + if (match.Groups["stringLength"].Success) + { + if (dataType != TransportSize.STRING && dataType != TransportSize.WSTRING) + throw new PlcInvalidFieldException($"'{match.Value}': a length is supported only for STRING or WSTRING."); + stringLength = int.Parse(match.Groups["stringLength"].Value, CultureInfo.InvariantCulture); + } + byte bitOffset = 0; + if (dataType == TransportSize.COUNTER && + string.Equals(match.Groups["type"].Value, "COUNTER", StringComparison.OrdinalIgnoreCase) && + match.Groups["bit"].Success) + throw new PlcInvalidFieldException($"'{match.Value}': a counter number cannot have a bit offset."); + if (match.Groups["bit"].Success) + bitOffset = byte.Parse(match.Groups["bit"].Value, CultureInfo.InvariantCulture); + else if (dataType == TransportSize.BOOL) + throw new PlcInvalidFieldException($"'{match.Value}': a BOOL needs a bit offset, as in %M0.0:BOOL."); ushort quantity = 1; var explicitRange = false; if (match.Groups["array"].Success) { + if ((dataType == TransportSize.STRING || dataType == TransportSize.WSTRING) && !stringLength.HasValue) + throw new PlcInvalidFieldException($"'{match.Value}': a variable-length string cannot have an array selection."); var selection = Regex.Match(match.Groups["array"].Value, @"^\[(?<start>[0-9]+)(\.\.(?<end>[0-9]+))?\]$", RegexOptions.CultureInvariant); if (!selection.Success || @@ -280,40 +363,24 @@ !int.TryParse(selection.Groups["end"].Value, NumberStyles.None, CultureInfo.InvariantCulture, out end)) throw new PlcInvalidFieldException($"'{match.Value}': invalid array selection."); - if (end < start || (long)end - start + 1 > ushort.MaxValue || - dataType == TransportSize.BOOL || dataType == TransportSize.STRING || - dataType == TransportSize.WSTRING) + if (end < start || (long)end - start + 1 > ushort.MaxValue) throw new PlcInvalidFieldException($"'{match.Value}': array selection is not supported for this type or range."); quantity = checked((ushort)((long)end - start + 1)); - var resolved = (long)byteOffset + (long)start * dataType.GetSizeInBytes(); - if (resolved > MaxByteOffset) + var firstBit = (long)bitOffset + start; + var elementSize = stringLength.HasValue + ? (stringLength.Value + 2) * (dataType == TransportSize.WSTRING ? 2 : 1) + : dataType.GetSizeInBytes(); + var isCounter = dataType == TransportSize.COUNTER && + string.Equals(match.Groups["type"].Value, "COUNTER", StringComparison.OrdinalIgnoreCase); + var resolved = (long)byteOffset + (isCounter ? start : dataType == TransportSize.BOOL + ? firstBit / 8 + : (long)start * elementSize); + if (resolved > (isCounter ? MaxByteOffset * 8L + 7 : MaxByteOffset)) throw new PlcInvalidFieldException($"'{match.Value}': array selection exceeds the addressable byte range."); byteOffset = (int)resolved; + if (dataType == TransportSize.BOOL) + bitOffset = (byte)(firstBit % 8); } - int? stringLength = null; - if (match.Groups["stringLength"].Success) - { - if (dataType != TransportSize.STRING && dataType != TransportSize.WSTRING) - { - throw new PlcInvalidFieldException($"'{match.Value}': a length is supported only for STRING or WSTRING."); - } - stringLength = int.Parse(match.Groups["stringLength"].Value, CultureInfo.InvariantCulture); - } - else if (dataType == TransportSize.STRING || dataType == TransportSize.WSTRING) - { - throw new PlcInvalidFieldException($"'{match.Value}': STRING and WSTRING need a declared length, as in :STRING(10)."); - } - - byte bitOffset = 0; - if (match.Groups["bit"].Success) - { - bitOffset = byte.Parse(match.Groups["bit"].Value, CultureInfo.InvariantCulture); - } - else if (dataType == TransportSize.BOOL) - { - throw new PlcInvalidFieldException($"'{match.Value}': a BOOL needs a bit offset, as in %M0.0:BOOL."); - } - var size = match.Groups["size"]; if (size.Success && size.Length > 0 && char.ToUpperInvariant(size.Value[0]) != (char)dataType.GetShortName()) @@ -323,8 +390,9 @@ $"which is '{(char)dataType.GetShortName()}'."); } + var counter = string.Equals(match.Groups["type"].Value, "COUNTER", StringComparison.OrdinalIgnoreCase); return new S7Tag(area, dbNumber, byteOffset, bitOffset, dataType, - stringLength, quantity, explicitRange); + stringLength, quantity, explicitRange, counter); } private static MemoryArea AreaOf(string letter) @@ -337,14 +405,27 @@ return MemoryArea.OUTPUTS; case "M": return MemoryArea.FLAGS_MARKERS; + case "D": + return MemoryArea.DIRECT_PERIPHERAL_ACCESS; + case "C": + return MemoryArea.COUNTERS; default: throw new PlcInvalidFieldException( - $"The memory area '{letter}' is not supported yet; supported: DB, I, Q and M."); + $"The memory area '{letter}' is not supported yet; supported: DB, I, Q, M, D and C (counters)."); } } private static TransportSize TypeOf(string name) { + // PLC4J accepts this legacy name for a BYTE array; the wire type is BYTE. + if (string.Equals(name, "RAW_BYTE_ARRAY", StringComparison.OrdinalIgnoreCase)) + return TransportSize.BYTE; + // The generated C# enum assigns COUNTER and DATE_AND_TIME the same + // numeric value. DT has the DATE_AND_TIME wire layout without that collision. + if (string.Equals(name, "DATE_AND_TIME", StringComparison.OrdinalIgnoreCase)) + return TransportSize.DT; + if (string.Equals(name, "COUNTER", StringComparison.OrdinalIgnoreCase)) + return TransportSize.COUNTER; // Enum.TryParse would also accept a number; only the names are data types. foreach (var candidate in Enum.GetNames(typeof(TransportSize))) { @@ -370,16 +451,22 @@ public override string ToString() { var bit = DataType == TransportSize.BOOL ? $".{BitOffset}" : string.Empty; - var type = StringLength.HasValue ? $"{DataType}({StringLength})" : DataType.ToString(); + var typeName = IsCounter ? "COUNTER" : DataType.ToString(); + var type = StringLength.HasValue ? $"{typeName}({StringLength})" : typeName; var selection = ExplicitRange ? $"[0..{Quantity - 1}]" : string.Empty; + var offset = IsCounter ? (ByteOffset << 3) | BitOffset : ByteOffset; switch (Area) { case MemoryArea.DATA_BLOCKS: - return $"%DB{DbNumber}.DB{ByteOffset}{bit}{selection}:{type}"; + return $"%DB{DbNumber}.DB{offset}{bit}{selection}:{type}"; + case MemoryArea.COUNTERS: + return $"%C{offset}{selection}:{type}"; case MemoryArea.INPUTS: return $"%I{ByteOffset}{bit}{selection}:{type}"; case MemoryArea.OUTPUTS: return $"%Q{ByteOffset}{bit}{selection}:{type}"; + case MemoryArea.DIRECT_PERIPHERAL_ACCESS: + return $"%D{ByteOffset}{bit}{selection}:{type}"; default: return $"%M{ByteOffset}{bit}{selection}:{type}"; }
diff --git a/plc4net/test/modbus-test/TlsCertificateTests.cs b/plc4net/test/modbus-test/TlsCertificateTests.cs index 747b514..e3ec01d 100644 --- a/plc4net/test/modbus-test/TlsCertificateTests.cs +++ b/plc4net/test/modbus-test/TlsCertificateTests.cs
@@ -173,9 +173,10 @@ [InlineData(false, false)] public async Task Mutual_tls_sends_intermediate_chain_to_a_server_trusting_only_root(bool includeIntermediate, bool programmatic) { - using var root = Certificate("root-" + Guid.NewGuid().ToString("N"), "1.3.6.1.5.5.7.3.2"); - using var intermediate = SignedCertificate("intermediate", root, true); - using var identity = SignedCertificate("client", intermediate, false); + var certificateId = Guid.NewGuid().ToString("N"); + using var root = Certificate("root-" + certificateId, "1.3.6.1.5.5.7.3.2"); + using var intermediate = SignedCertificate("intermediate-" + certificateId, root, true); + using var identity = SignedCertificate("client-" + certificateId, intermediate, false); using var rootPublic = new X509Certificate2(root.Export(X509ContentType.Cert)); using var intermediatePublic = new X509Certificate2(intermediate.Export(X509ContentType.Cert)); using var serverCertificate = Certificate("localhost", "1.3.6.1.5.5.7.3.1");
diff --git a/plc4net/test/s7-test/S7ConnectionTests.cs b/plc4net/test/s7-test/S7ConnectionTests.cs index a4f8973..348c9e5 100644 --- a/plc4net/test/s7-test/S7ConnectionTests.cs +++ b/plc4net/test/s7-test/S7ConnectionTests.cs
@@ -23,6 +23,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using org.apache.plc4net.api.value; using org.apache.plc4net.drivers.s7.readwrite.model; using org.apache.plc4net.exceptions; using org.apache.plc4net.messages; @@ -42,6 +43,7 @@ /// </summary> public class S7ConnectionTests { + private const byte DirectPeripheralAccess = 0x80; private const byte Inputs = 0x81; private const byte Outputs = 0x82; private const byte Flags = 0x83; @@ -225,6 +227,7 @@ [InlineData("%MW30:WORD", 0x04, 0, Flags, 30, 0, 2, 0x04)] [InlineData("%QD4:DWORD", 0x06, 0, Outputs, 4, 0, 4, 0x04)] [InlineData("%IB2:BYTE", 0x02, 0, Inputs, 2, 0, 1, 0x04)] + [InlineData("%DW10:WORD", 0x04, 0, DirectPeripheralAccess, 10, 0, 2, 0x04)] public async Task A_read_asks_for_the_address_with_the_transport_size_of_the_type( string address, byte transportSize, ushort block, byte area, int byteOffset, int bitOffset, int dataBytes, byte answerSize) @@ -672,6 +675,7 @@ [InlineData("%DB1.DBB1:SINT", -2, 0x02, 0x04, "FE")] [InlineData("%DB1.DBB1:USINT", 254, 0x02, 0x04, "FE")] [InlineData("%QW4:WORD", 48879, 0x04, 0x04, "BEEF")] + [InlineData("%DW10:WORD", 48879, 0x04, 0x04, "BEEF")] [InlineData("%DB1.DBD4:DWORD", 3735928559L, 0x06, 0x04, "DEADBEEF")] [InlineData("%DB1.DBD4:DINT", -200, 0x07, 0x05, "FFFFFF38")] [InlineData("%DB1.DBD4:UDINT", 4294967096L, 0x07, 0x05, "FFFFFF38")] @@ -683,7 +687,8 @@ var connection = ConnectQuietly(transport); transport.InjectTestData(S7Frames.WriteAck(2, 0xFF)); var tag = S7Tag.Parse(address); - var area = tag.Area == MemoryArea.DATA_BLOCKS ? DataBlocks + var area = tag.Area == MemoryArea.DIRECT_PERIPHERAL_ACCESS ? DirectPeripheralAccess + : tag.Area == MemoryArea.DATA_BLOCKS ? DataBlocks : tag.Area == MemoryArea.OUTPUTS ? Outputs : tag.Area == MemoryArea.INPUTS ? Inputs : Flags; @@ -730,6 +735,453 @@ Written(transport)); } + [Theory] + [InlineData("%DB1:10:STRING", "0402", "040248690000", "Hi")] + [InlineData("%DB1:10:WSTRING", "00040002", "000400020048006900000000", "Hi")] + public async Task A_variable_string_reads_its_header_before_its_value( + string address, string headerHex, string valueHex, string expected) + { + var transport = Ready(); + var connection = ConnectQuietly(transport); + var cpu = new FakeCpu(transport, + S7Frames.ReadAck(2, (0xFF, 0x04, Hex(headerHex))), + S7Frames.ReadAck(3, (0xFF, 0x09, Hex(valueHex)))); + + var response = await ReadAsync(connection, address); + await cpu.Running; + + Assert.Equal(expected, ValueOf(response).GetString()); + var header = S7Frames.AddressItem(0x02, 1, DataBlocks, 10, 0); + header[5] = (byte)(headerHex.Length / 2); + Assert.Equal(S7Frames.ReadRequest(2, header), cpu.Requests[0]); + var value = S7Frames.AddressItem(0x03, 1, DataBlocks, 10, 0); + value[5] = (byte)(valueHex.Length / 2); + Assert.Equal(S7Frames.ReadRequest(3, value), cpu.Requests[1]); + } + + [Fact] + public async Task A_variable_string_write_uses_the_declared_capacity() + { + var transport = Ready(); + var connection = ConnectQuietly(transport); + var cpu = new FakeCpu(transport, + S7Frames.ReadAck(2, (0xFF, 0x04, Hex("0402"))), + S7Frames.WriteAck(3, 0xFF)); + + var response = await WriteAsync(connection, "%DB1:10:STRING", "Hi"); + await cpu.Running; + + Assert.Equal(PlcResponseCode.Ok, response.GetResponseCode("v")); + var item = S7Frames.AddressItem(0x03, 1, DataBlocks, 10, 0); + item[5] = 6; + Assert.Equal(S7Frames.WriteRequest(3, new[] { item }, (0x09, Hex("040248690000"))), + cpu.Requests[1]); + } + + [Fact] + public async Task A_variable_string_rejects_an_invalid_length_header() + { + var transport = Ready(); + var connection = ConnectQuietly(transport); + transport.InjectTestData(S7Frames.ReadAck(2, (0xFF, 0x04, Hex("0405")))); + + var response = await ReadAsync(connection, "%DB1:10:STRING"); + + Assert.Equal(PlcResponseCode.InternalError, response.GetResponseCode("v")); + } + + [Fact] + public async Task A_large_string_is_read_and_written_across_pdus() + { + var transport = Ready(240); + var connection = ConnectQuietly(transport); + var bytes = new byte[232]; + bytes[0] = 230; + bytes[1] = 2; + bytes[2] = (byte)'H'; + bytes[3] = (byte)'i'; + var cpu = new FakeCpu(transport, + S7Frames.ReadAck(2, (0xFF, 0x04, bytes[..222])), + S7Frames.ReadAck(3, (0xFF, 0x04, bytes[222..])), + S7Frames.WriteAck(4, 0xFF), + S7Frames.WriteAck(5, 0xFF)); + + var read = await ReadAsync(connection, "%DB1:10:STRING(230)"); + var write = await WriteAsync(connection, "%DB1:10:STRING(230)", "Hi"); + await cpu.Running; + + Assert.Equal("Hi", ValueOf(read).GetString()); + Assert.Equal(PlcResponseCode.Ok, write.GetResponseCode("v")); + var firstRead = S7Frames.AddressItem(0x02, 1, DataBlocks, 10, 0); + firstRead[5] = 222; + var secondRead = S7Frames.AddressItem(0x02, 1, DataBlocks, 232, 0); + secondRead[5] = 10; + Assert.Equal(S7Frames.ReadRequest(2, firstRead), cpu.Requests[0]); + Assert.Equal(S7Frames.ReadRequest(3, secondRead), cpu.Requests[1]); + var firstWrite = S7Frames.AddressItem(0x02, 1, DataBlocks, 10, 0); + firstWrite[5] = 212; + var secondWrite = S7Frames.AddressItem(0x02, 1, DataBlocks, 222, 0); + secondWrite[5] = 20; + Assert.Equal(S7Frames.WriteRequest(4, new[] { firstWrite }, (0x04, bytes[..212])), cpu.Requests[2]); + Assert.Equal(S7Frames.WriteRequest(5, new[] { secondWrite }, (0x04, bytes[212..])), cpu.Requests[3]); + } + + [Fact] + public async Task A_counter_uses_its_numbered_address_and_octet_value() + { + var transport = Ready(); + var connection = ConnectQuietly(transport); + var cpu = new FakeCpu(transport, + S7Frames.ReadAck(2, (0xFF, 0x09, Hex("1234"))), + S7Frames.WriteAck(3, 0xFF)); + + var read = await ReadAsync(connection, "%C9:COUNTER"); + var write = await WriteAsync(connection, "%C9:COUNTER", 0x5678); + await cpu.Running; + + Assert.Equal((ushort)0x1234, ValueOf(read).GetUshort()); + Assert.Equal(PlcResponseCode.Ok, write.GetResponseCode("v")); + var address = S7Frames.AddressItem(0x1C, 0, 0x1C, 1, 1); + Assert.Equal(S7Frames.ReadRequest(2, address), cpu.Requests[0]); + Assert.Equal(S7Frames.WriteRequest(3, new[] { address }, (0x09, Hex("5678"))), cpu.Requests[1]); + } + + [Fact] + public async Task Block_browse_uses_the_userdata_service_and_parses_block_numbers() + { + var transport = Ready(); + var connection = ConnectQuietly(transport); + var parameter = Hex("000112081283020000000000"); + var payload = Hex("FF0900080001000000070000"); + var cpu = new FakeCpu(transport, + S7Frames.Dt(S7Frames.UserData(2, parameter, payload))); + + var numbers = await connection.ListDataBlocksAsync(); + await cpu.Running; + + Assert.Equal(new[] { 1, 7 }, numbers); + Assert.Equal(S7Frames.Dt(S7Frames.UserData(2, + Hex("0001120411430200"), Hex("FF0900023041"))), cpu.Requests[0]); + } + + [Theory] + [InlineData("000112081283020000000000", "FF0900050001000000")] + [InlineData("000112081283020000000001", "FF09000400010000")] + public async Task Block_browse_rejects_a_malformed_response(string parameterHex, string payloadHex) + { + var transport = Ready(); + var connection = ConnectQuietly(transport); + var cpu = new FakeCpu(transport, + S7Frames.Dt(S7Frames.UserData(2, Hex(parameterHex), Hex(payloadHex)))); + + await Assert.ThrowsAsync<S7DriverException>(() => connection.ListDataBlocksAsync()); + await cpu.Running; + } + + [Fact] + public async Task Alarm_query_returns_the_buffered_wire_data() + { + var transport = Ready(); + var connection = ConnectQuietly(transport); + var cpu = new FakeCpu(transport, + S7Frames.Dt(S7Frames.UserData(2, + Hex("000112081284130000000000"), Hex("FF09000412345678")))); + + var alarms = await connection.QueryBufferedAlarmsAsync(QueryType.ALARM_S); + await cpu.Running; + + Assert.Equal(Hex("12345678"), alarms); + Assert.Equal(S7Frames.Dt(S7Frames.UserData(2, + Hex("0001120411441300"), Hex("FF09000C000112081A00043404"))), cpu.Requests[0]); + } + + [Fact] + public async Task Alarm_query_rejects_a_refused_item() + { + var transport = Ready(); + var connection = ConnectQuietly(transport); + var cpu = new FakeCpu(transport, + S7Frames.Dt(S7Frames.UserData(2, + Hex("000112081284130000000000"), Hex("05090000")))); + + await Assert.ThrowsAsync<S7DriverException>(() => + connection.QueryBufferedAlarmsAsync(QueryType.ALARM_8)); + await cpu.Running; + } + + [Fact] + public async Task Alarm_subscription_receives_an_indication_and_aborts() + { + var transport = Ready(); + var connection = ConnectQuietly(transport); + var cpu = new FakeCpu(transport, + S7Frames.Dt(S7Frames.UserData(2, + Hex("000112081284020000000000"), Hex("FF0900050000090000"))), + S7Frames.Dt(S7Frames.UserData(3, + Hex("000112081284020000000000"), Hex("FF0900050000080000")))); + var subscription = await connection.SubscribeAlarmsAsync(); + var push = S7Frames.UserData(0, + Hex("0001120412041207"), Hex("FF09000A24120210203000010100")); + Assert.IsType<S7MessageUserData>(S7Message.StaticParse( + new org.apache.plc4net.spi.generation.ReadBuffer(push))); + transport.InjectTestData(S7Frames.Dt(push)); + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(3)); + S7PayloadUserDataItem? received = null; + await foreach (var item in subscription.ReadAllAsync(timeout.Token)) + { + received = item; + break; + } + await subscription.DisposeAsync(); + await cpu.Running; + + Assert.Equal((byte)1, Assert.IsType<S7PayloadAlarmS>(received).AlarmMessage.FunctionId); + Assert.Equal(S7Frames.Dt(S7Frames.UserData(2, + Hex("0001120411440200"), Hex("FF09000C8000486D6952746D20200900"))), cpu.Requests[0]); + Assert.Equal(S7Frames.Dt(S7Frames.UserData(3, + Hex("0001120411440200"), Hex("FF09000C8000486D6952746D20200800"))), cpu.Requests[1]); + } + + [Fact] + public async Task Alarm_subscription_rejects_a_PLC_refusal() + { + var transport = Ready(); + var connection = ConnectQuietly(transport); + var cpu = new FakeCpu(transport, + S7Frames.Dt(S7Frames.UserData(2, + Hex("000112081284020000000000"), Hex("FF0900050300090000")))); + + await Assert.ThrowsAsync<S7DriverException>(() => connection.SubscribeAlarmsAsync()); + await cpu.Running; + } + + [Fact] + public async Task Alarm_subscription_can_be_retried_after_a_PLC_refusal() + { + var transport = Ready(); + using var connection = ConnectQuietly(transport); + var refusingCpu = new FakeCpu(transport, + S7Frames.Dt(S7Frames.UserData(2, + Hex("000112081284020000000000"), Hex("FF0900050300090000")))); + + await Assert.ThrowsAsync<S7DriverException>(() => connection.SubscribeAlarmsAsync()); + await refusingCpu.Running; + + var cpu = new FakeCpu(transport, + S7Frames.Dt(S7Frames.UserData(3, + Hex("000112081284020000000000"), Hex("FF0900050000090000"))), + S7Frames.Dt(S7Frames.UserData(4, + Hex("000112081284020000000000"), Hex("FF0900050000080000")))); + var subscription = await connection.SubscribeAlarmsAsync(); + await subscription.DisposeAsync(); + await cpu.Running; + } + + [Fact] + public async Task Alarm_subscription_cancellation_after_send_returns_a_disposable_subscription() + { + var transport = Ready(); + using var connection = ConnectQuietly(transport); + using var cancellation = new CancellationTokenSource(); + var cpu = new FakeCpu(transport, 50, + S7Frames.Dt(S7Frames.UserData(2, + Hex("000112081284020000000000"), Hex("FF0900050000090000"))), + S7Frames.Dt(S7Frames.UserData(3, + Hex("000112081284020000000000"), Hex("FF0900050000080000")))); + + var subscribing = connection.SubscribeAlarmsAsync(cancellationToken: cancellation.Token); + cancellation.Cancel(); + var subscription = await subscribing; + await subscription.DisposeAsync(); + await cpu.Running; + } + + [Fact] + public async Task Alarm_indication_in_the_same_batch_as_subscribe_ack_is_delivered() + { + var transport = Ready(); + using var connection = ConnectQuietly(transport); + var acknowledgement = S7Frames.Dt(S7Frames.UserData(2, + Hex("000112081284020000000000"), Hex("FF0900050000090000"))); + var indication = S7Frames.Dt(S7Frames.UserData(0, + Hex("0001120412041207"), Hex("FF09000A24120210203000010100"))); + var cpu = new FakeCpu(transport, acknowledgement.Concat(indication).ToArray()); + + var subscription = await connection.SubscribeAlarmsAsync(); + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(3)); + await using var reader = subscription.ReadAllAsync(timeout.Token).GetAsyncEnumerator(); + Assert.True(await reader.MoveNextAsync()); + Assert.IsType<S7PayloadAlarmS>(reader.Current); + await cpu.Running; + } + + [Fact] + public async Task Alarm_resubscribe_waits_for_the_previous_abort_ack() + { + var transport = Ready(); + using var connection = ConnectQuietly(transport); + var firstCpu = new FakeCpu(transport, + S7Frames.Dt(S7Frames.UserData(2, + Hex("000112081284020000000000"), Hex("FF0900050000090000"))), + null); + var first = await connection.SubscribeAlarmsAsync(); + var abort = first.DisposeAsync().AsTask(); + await firstCpu.Running; + + var next = connection.SubscribeAlarmsAsync(); + var secondCpu = new FakeCpu(transport, + S7Frames.Dt(S7Frames.UserData(4, + Hex("000112081284020000000000"), Hex("FF0900050000090000")))); + transport.InjectTestData(S7Frames.Dt(S7Frames.UserData(3, + Hex("000112081284020000000000"), Hex("FF0900050000080000")))); + + await abort; + var second = await next; + await secondCpu.Running; + Assert.Equal(S7Frames.Dt(S7Frames.UserData(3, + Hex("0001120411440200"), Hex("FF09000C8000486D6952746D20200800"))), firstCpu.Requests[1]); + Assert.Equal(S7Frames.Dt(S7Frames.UserData(4, + Hex("0001120411440200"), Hex("FF09000C8000486D6952746D20200900"))), secondCpu.Requests[0]); + Assert.NotSame(first, second); + } + + [Fact] + public async Task Native_cyclic_subscription_receives_a_push_and_unsubscribes() + { + var transport = Ready(); + var connection = ConnectQuietly(transport); + var cpu = new FakeCpu(transport, + S7Frames.Dt(S7Frames.UserData(2, + Hex("000112081282010700000000"), Hex("FF090000"))), + S7Frames.Dt(S7Frames.UserData(3, + Hex("000112081282040000000000"), Hex("FF090000")))); + var subscription = await connection.SubscribeCyclicAsync( + "%DB1.DBW10:INT", TimeSpan.FromSeconds(1)); + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(3)); + var push = S7Frames.UserData(0, + Hex("000112081202010700000000"), Hex("FF0900080001FF0500101234")); + var parsedPush = S7Message.StaticParse(new org.apache.plc4net.spi.generation.ReadBuffer(push)); + Assert.IsType<S7MessageUserData>(parsedPush); + transport.InjectTestData(S7Frames.Dt(push)); + + IPlcValue? received = null; + await foreach (var value in subscription.ReadAllAsync(timeout.Token)) + { + received = value; + break; + } + await subscription.DisposeAsync(); + await cpu.Running; + + Assert.Equal(0x1234, received!.GetInt()); + Assert.Equal(S7Frames.Dt(S7Frames.UserData(2, + Hex("0001120411420100"), + Hex("FF09001000010101120A10050001000184000050"))), cpu.Requests[0]); + Assert.Equal(S7Frames.Dt(S7Frames.UserData(3, + Hex("0001120411420400"), Hex("FF0900020507"))), cpu.Requests[1]); + } + + [Fact] + public async Task Native_cyclic_subscription_exposes_the_initial_value() + { + var transport = Ready(); + var connection = ConnectQuietly(transport); + var cpu = new FakeCpu(transport, + S7Frames.Dt(S7Frames.UserData(2, + Hex("000112081282010700000000"), Hex("FF0900080001FF0500101234"))), + S7Frames.Dt(S7Frames.UserData(3, + Hex("000112081282040000000000"), Hex("FF090000")))); + var subscription = await connection.SubscribeCyclicAsync( + "%DB1.DBW10:INT", TimeSpan.FromSeconds(1)); + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(3)); + await foreach (var value in subscription.ReadAllAsync(timeout.Token)) + { + Assert.Equal(0x1234, value.GetInt()); + break; + } + await subscription.DisposeAsync(); + await cpu.Running; + } + + [Fact] + public async Task Native_cyclic_subscription_cancellation_after_send_returns_a_disposable_subscription() + { + var transport = Ready(); + using var connection = ConnectQuietly(transport); + using var cancellation = new CancellationTokenSource(); + var cpu = new FakeCpu(transport, 50, + S7Frames.Dt(S7Frames.UserData(2, + Hex("000112081282010700000000"), Hex("FF090000"))), + S7Frames.Dt(S7Frames.UserData(3, + Hex("000112081282040000000000"), Hex("FF090000")))); + + var subscribing = connection.SubscribeCyclicAsync( + "%DB1.DBW10:INT", TimeSpan.FromSeconds(1), cancellation.Token); + cancellation.Cancel(); + var subscription = await subscribing; + await subscription.DisposeAsync(); + await cpu.Running; + } + + [Fact] + public async Task Native_cyclic_unsubscribe_can_be_retried_after_a_PLC_refusal() + { + var transport = Ready(); + using var connection = ConnectQuietly(transport); + var cpu = new FakeCpu(transport, + S7Frames.Dt(S7Frames.UserData(2, + Hex("000112081282010700000000"), Hex("FF090000"))), + S7Frames.Dt(S7Frames.UserData(3, + Hex("000112081282040000000000"), Hex("05090000"))), + S7Frames.Dt(S7Frames.UserData(4, + Hex("000112081282040000000000"), Hex("FF090000")))); + var subscription = await connection.SubscribeCyclicAsync( + "%DB1.DBW10:INT", TimeSpan.FromSeconds(1)); + + await Assert.ThrowsAsync<S7DriverException>(() => subscription.DisposeAsync().AsTask()); + await subscription.DisposeAsync(); + await cpu.Running; + } + + [Fact] + public async Task Alarm_unsubscribe_can_be_retried_after_a_PLC_refusal() + { + var transport = Ready(); + using var connection = ConnectQuietly(transport); + var cpu = new FakeCpu(transport, + S7Frames.Dt(S7Frames.UserData(2, + Hex("000112081284020000000000"), Hex("FF0900050000090000"))), + S7Frames.Dt(S7Frames.UserData(3, + Hex("000112081284020000000000"), Hex("FF0900050300080000"))), + S7Frames.Dt(S7Frames.UserData(4, + Hex("000112081284020000000000"), Hex("FF0900050000080000")))); + var subscription = await connection.SubscribeAlarmsAsync(); + + await Assert.ThrowsAsync<S7DriverException>(() => subscription.DisposeAsync().AsTask()); + await subscription.DisposeAsync(); + await cpu.Running; + } + + [Fact] + public async Task Cyclic_push_in_the_same_batch_as_subscribe_ack_is_delivered() + { + var transport = Ready(); + using var connection = ConnectQuietly(transport); + var acknowledgement = S7Frames.Dt(S7Frames.UserData(2, + Hex("000112081282010700000000"), Hex("FF090000"))); + var push = S7Frames.Dt(S7Frames.UserData(0, + Hex("000112081202010700000000"), Hex("FF0900080001FF0500101234"))); + var cpu = new FakeCpu(transport, acknowledgement.Concat(push).ToArray()); + + var subscription = await connection.SubscribeCyclicAsync( + "%DB1.DBW10:INT", TimeSpan.FromSeconds(1)); + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(3)); + await using var reader = subscription.ReadAllAsync(timeout.Token).GetAsyncEnumerator(); + Assert.True(await reader.MoveNextAsync()); + Assert.Equal(0x1234, reader.Current.GetInt()); + await cpu.Running; + } + [Fact] public async Task A_write_to_a_flag_word_puts_the_value_big_endian_on_the_wire() { @@ -895,6 +1347,35 @@ } [Fact] + public void Closing_and_disposing_twice_is_safe() + { + var connection = ConnectQuietly(Ready()); + + connection.Close(); + connection.Close(); + connection.Dispose(); + connection.Dispose(); + connection.Close(); + } + + [Fact] + public async Task Native_subscription_completes_when_the_transport_disconnects() + { + var transport = Ready(); + using var connection = ConnectQuietly(transport); + var cpu = new FakeCpu(transport, S7Frames.Dt(S7Frames.UserData(2, + Hex("000112081282010700000000"), Hex("FF090000")))); + var subscription = await connection.SubscribeCyclicAsync( + "%DB1.DBW10:INT", TimeSpan.FromSeconds(1)); + await cpu.Running; + + transport.Close(); + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(3)); + await using var reader = subscription.ReadAllAsync(timeout.Token).GetAsyncEnumerator(); + Assert.False(await reader.MoveNextAsync()); + } + + [Fact] public async Task A_numeric_array_range_reads_and_writes_every_element() { var transport = Ready(); @@ -917,6 +1398,314 @@ (0x05, Hex("000400050006"))), cpu.Requests[1]); } + [Fact] + public async Task A_bool_array_reads_packed_bits_and_writes_only_selected_bits() + { + var transport = Ready(); + using var connection = ConnectQuietly(transport); + var cpu = new FakeCpu(transport, + S7Frames.ReadAck(2, (0xFF, 0x04, Hex("4005"))), + S7Frames.WriteAck(3, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF)); + const string address = "%DB1.DBX16.6[0..4]:BOOL"; + + var read = ValueOf(await ReadAsync(connection, address)); + Assert.Equal(new[] { true, false, true, false, true }, + read.GetList().Select(value => value.GetBool()).ToArray()); + var write = await WriteAsync(connection, address, + new[] { true, false, true, false, true }); + Assert.Equal(PlcResponseCode.Ok, write.GetResponseCode("v")); + await cpu.Running; + + var readItem = S7Frames.AddressItem(0x02, 1, DataBlocks, 16, 0); + readItem[5] = 2; + Assert.Equal(S7Frames.ReadRequest(2, readItem), cpu.Requests[0]); + var bits = new[] { (16, 6), (16, 7), (17, 0), (17, 1), (17, 2) } + .Select(bit => S7Frames.AddressItem(0x01, 1, DataBlocks, bit.Item1, bit.Item2)).ToArray(); + Assert.Equal(S7Frames.WriteRequest(3, bits, + (0x03, Hex("01")), (0x03, Hex("00")), (0x03, Hex("01")), + (0x03, Hex("00")), (0x03, Hex("01"))), cpu.Requests[1]); + } + + [Fact] + public async Task A_failed_bool_array_item_is_not_hidden_by_later_successes() + { + var transport = Ready(); + using var connection = ConnectQuietly(transport); + transport.InjectTestData(S7Frames.WriteAck(2, 0x03, 0xFF, 0xFF)); + + var response = await WriteAsync(connection, "%M0.5[0..2]:BOOL", + new[] { true, false, true }); + + Assert.Equal(PlcResponseCode.AccessDenied, response.GetResponseCode("v")); + } + + [Fact] + public async Task A_large_array_is_split_for_read_and_write_at_the_PDU_boundary() + { + var transport = Ready(240); + using var connection = ConnectQuietly(transport); + var bytes = Enumerable.Range(0, 230).Select(i => (byte)i).ToArray(); + var cpu = new FakeCpu(transport, + S7Frames.ReadAck(2, (0xFF, 0x04, bytes[..222])), + S7Frames.ReadAck(3, (0xFF, 0x04, bytes[222..])), + S7Frames.WriteAck(4, 0xFF), + S7Frames.WriteAck(5, 0xFF)); + const string address = "%DB1.DBB0[0..229]:BYTE"; + + var read = ValueOf(await ReadAsync(connection, address)); + Assert.Equal(bytes, read.GetList().Select(value => value.GetByte()).ToArray()); + var write = await WriteAsync(connection, address, bytes); + Assert.Equal(PlcResponseCode.Ok, write.GetResponseCode("v")); + await cpu.Running; + + var firstRead = S7Frames.AddressItem(0x02, 1, DataBlocks, 0, 0); + firstRead[5] = 222; + var secondRead = S7Frames.AddressItem(0x02, 1, DataBlocks, 222, 0); + secondRead[5] = 8; + Assert.Equal(S7Frames.ReadRequest(2, firstRead), cpu.Requests[0]); + Assert.Equal(S7Frames.ReadRequest(3, secondRead), cpu.Requests[1]); + var firstWrite = S7Frames.AddressItem(0x02, 1, DataBlocks, 0, 0); + firstWrite[5] = 212; + var secondWrite = S7Frames.AddressItem(0x02, 1, DataBlocks, 212, 0); + secondWrite[5] = 18; + Assert.Equal(S7Frames.WriteRequest(4, new[] { firstWrite }, (0x04, bytes[..212])), cpu.Requests[2]); + Assert.Equal(S7Frames.WriteRequest(5, new[] { secondWrite }, (0x04, bytes[212..])), cpu.Requests[3]); + } + + [Fact] + public async Task A_fixed_string_array_reads_and_writes_each_header_and_value() + { + var transport = Ready(); + using var connection = ConnectQuietly(transport); + var data = Hex("0402486900000402596F0000"); + var cpu = new FakeCpu(transport, + S7Frames.ReadAck(2, (0xFF, 0x09, data)), + S7Frames.WriteAck(3, 0xFF)); + const string address = "%DB1:10[1..2]:STRING(4)"; + + var read = ValueOf(await ReadAsync(connection, address)); + Assert.Equal(new[] { "Hi", "Yo" }, + read.GetList().Select(value => value.GetString()).ToArray()); + var write = await WriteAsync(connection, address, new[] { "Hi", "Yo" }); + Assert.Equal(PlcResponseCode.Ok, write.GetResponseCode("v")); + await cpu.Running; + + var item = S7Frames.AddressItem(0x03, 1, DataBlocks, 16, 0); + item[5] = 12; + Assert.Equal(S7Frames.ReadRequest(2, item), cpu.Requests[0]); + Assert.Equal(S7Frames.WriteRequest(3, new[] { item }, (0x09, data)), cpu.Requests[1]); + } + + [Fact] + public async Task Large_wstring_array_elements_split_across_multiple_PDUs() + { + var transport = Ready(128); + using var connection = ConnectQuietly(transport); + var first = new byte[204]; + var second = new byte[204]; + first[1] = second[1] = 100; + first[3] = second[3] = 1; + first[5] = (byte)'A'; + second[5] = (byte)'B'; + var data = first.Concat(second).ToArray(); + var replies = new List<byte[]?>(); + for (var i = 0; i < 4; i++) + { + var offset = i < 2 ? 0 : 204; + offset += i % 2 == 0 ? 0 : 110; + var length = i % 2 == 0 ? 110 : 94; + replies.Add(S7Frames.ReadAck((ushort)(i + 2), + (0xFF, 0x04, data[offset..(offset + length)]))); + } + for (var i = 0; i < 5; i++) + replies.Add(S7Frames.WriteAck((ushort)(i + 6), 0xFF)); + var cpu = new FakeCpu(transport, replies.ToArray()); + const string address = "%DB1:0[0..1]:WSTRING(100)"; + + var read = ValueOf(await ReadAsync(connection, address)); + Assert.Equal(new[] { "A", "B" }, + read.GetList().Select(value => value.GetString()).ToArray()); + var write = await WriteAsync(connection, address, new[] { "A", "B" }); + Assert.Equal(PlcResponseCode.Ok, write.GetResponseCode("v")); + await cpu.Running; + + Assert.Equal(9, cpu.Requests.Count); + for (var i = 0; i < 5; i++) + { + var offset = i * 100; + var count = Math.Min(100, data.Length - offset); + var item = S7Frames.AddressItem(0x02, 1, DataBlocks, offset, 0); + item[5] = (byte)count; + Assert.Equal(S7Frames.WriteRequest((ushort)(i + 6), new[] { item }, + (0x04, data[offset..(offset + count)])), cpu.Requests[i + 4]); + } + } + + [Theory] + [InlineData("LINT", "FFFFFFFFFFFFFFFE", -2L)] + [InlineData("ULINT", "FFFFFFFFFFFFFFFF", ulong.MaxValue)] + [InlineData("LWORD", "0123456789ABCDEF", 0x0123456789ABCDEFUL)] + [InlineData("LREAL", "3FF0000000000000", 1.0)] + public async Task Eight_byte_types_use_byte_addresses_and_round_trip_values( + string type, string wireHex, object value) + { + var transport = Ready(); + using var connection = ConnectQuietly(transport); + var cpu = new FakeCpu(transport, + S7Frames.ReadAck(2, (0xFF, 0x04, Hex(wireHex))), + S7Frames.WriteAck(3, 0xFF)); + var address = "%DB1:0:" + type; + + var read = ValueOf(await ReadAsync(connection, address)); + switch (type) + { + case "LINT": Assert.Equal(-2L, Assert.IsType<PlcLINT>(read).GetLong()); break; + case "ULINT": Assert.Equal(ulong.MaxValue, Assert.IsType<PlcULINT>(read).GetUlong()); break; + case "LWORD": Assert.Equal(0x0123456789ABCDEFUL, Assert.IsType<PlcLWORD>(read).GetUlong()); break; + default: Assert.Equal(1.0, Assert.IsType<PlcLREAL>(read).GetDouble()); break; + } + var write = await WriteAsync(connection, address, value); + Assert.Equal(PlcResponseCode.Ok, write.GetResponseCode("v")); + await cpu.Running; + + var item = S7Frames.AddressItem(0x02, 1, DataBlocks, 0, 0); + item[5] = 8; + Assert.Equal(S7Frames.ReadRequest(2, item), cpu.Requests[0]); + Assert.Equal(S7Frames.WriteRequest(3, new[] { item }, (0x04, Hex(wireHex))), cpu.Requests[1]); + } + + [Fact] + public void Decimal_LINT_values_keep_every_integer_bit() + { + var tag = S7Tag.Parse("%DB1:0:LINT"); + + Assert.Equal(Hex("0020000000000001"), + S7Connection.EncodeValue(tag, 9007199254740993m)); + Assert.Throws<FormatException>(() => S7Connection.EncodeValue(tag, 1.5m)); + } + + [Theory] + [InlineData("TIME", "000003E8")] + [InlineData("DATE", "0001")] + [InlineData("TIME_OF_DAY", "000003E8")] + [InlineData("S5TIME", "0100")] + [InlineData("DATE_AND_TIME", "2408191435071232")] + [InlineData("DTL", "07E801020303040500000000")] + public async Task Temporal_types_round_trip_their_documented_wire_layout(string type, string wireHex) + { + var transport = Ready(); + using var connection = ConnectQuietly(transport); + var cpu = new FakeCpu(transport, + S7Frames.ReadAck(2, (0xFF, 0x04, Hex(wireHex))), + S7Frames.WriteAck(3, 0xFF)); + object value = type switch + { + "TIME" or "S5TIME" => TimeSpan.FromSeconds(1), + "DATE" => new DateOnly(1990, 1, 2), + "TIME_OF_DAY" => new TimeOnly(0, 0, 1), + "DATE_AND_TIME" => new DateTime(2024, 8, 19, 14, 35, 7, 123), + _ => new DateTime(2024, 1, 2, 3, 4, 5) + }; + var address = "%DB1:0:" + type; + + var read = ValueOf(await ReadAsync(connection, address)); + Assert.Equal(value switch + { + TimeSpan duration => duration, + DateOnly date => date, + TimeOnly time => time, + DateTime dateTime => dateTime, + _ => throw new InvalidOperationException() + }, read switch + { + PlcTIME duration => (object)duration.GetDuration(), + PlcDATE date => date.GetDate(), + PlcTIME_OF_DAY time => time.GetTime(), + PlcDATE_AND_TIME dateTime => dateTime.GetDateTime(), + PlcDATE_AND_LTIME longDateTime => longDateTime.GetDateTime(), + _ => throw new InvalidOperationException() + }); + var write = await WriteAsync(connection, address, value); + Assert.Equal(PlcResponseCode.Ok, write.GetResponseCode("v")); + await cpu.Running; + + var item = S7Frames.AddressItem(0x02, 1, DataBlocks, 0, 0); + item[5] = (byte)Hex(wireHex).Length; + Assert.Equal(S7Frames.ReadRequest(2, item), cpu.Requests[0]); + Assert.Equal(S7Frames.WriteRequest(3, new[] { item }, (0x04, Hex(wireHex))), cpu.Requests[1]); + } + + [Theory] + [InlineData("LTIME")] + [InlineData("LTIME_OF_DAY")] + [InlineData("DATE_AND_LTIME")] + public async Task Nanosecond_types_preserve_their_64_bit_wire_value(string type) + { + var transport = Ready(); + using var connection = ConnectQuietly(transport); + var cpu = new FakeCpu(transport, + S7Frames.ReadAck(2, (0xFF, 0x04, Hex("000000003B9ACA00"))), + S7Frames.WriteAck(3, 0xFF)); + var address = "%DB1:0:" + type; + object value = type == "DATE_AND_LTIME" + ? DateTime.UnixEpoch.AddSeconds(1) : 1_000_000_000UL; + + var read = ValueOf(await ReadAsync(connection, address)); + Assert.Equal(1_000_000_000UL, type switch + { + "LTIME" => Assert.IsType<PlcLTIME>(read).GetNanoseconds(), + "LTIME_OF_DAY" => Assert.IsType<PlcLTIME_OF_DAY>(read).GetNanosecondsSinceMidnight(), + _ => Assert.IsType<PlcDATE_AND_LTIME>(read).GetNanosecondsSinceEpoch() + }); + var write = await WriteAsync(connection, address, value); + Assert.Equal(PlcResponseCode.Ok, write.GetResponseCode("v")); + await cpu.Running; + + var item = S7Frames.AddressItem(0x02, 1, DataBlocks, 0, 0); + item[5] = 8; + Assert.Equal(S7Frames.ReadRequest(2, item), cpu.Requests[0]); + Assert.Equal(S7Frames.WriteRequest(3, new[] { item }, + (0x04, Hex("000000003B9ACA00"))), cpu.Requests[1]); + } + + [Theory] + [InlineData("TIME")] + [InlineData("S5TIME")] + [InlineData("DATE")] + [InlineData("DATE_AND_TIME")] + public async Task Unrepresentable_temporal_values_are_rejected_before_send(string type) + { + var transport = Ready(); + using var connection = ConnectQuietly(transport); + object value = type switch + { + "TIME" => TimeSpan.FromMilliseconds(-1), + "S5TIME" => TimeSpan.FromMilliseconds(11), + "DATE" => new DateOnly(1989, 12, 31), + _ => new DateTime(2090, 1, 1) + }; + + var response = await WriteAsync(connection, "%DB1:0:" + type, value); + + Assert.Equal(PlcResponseCode.InvalidDatatype, response.GetResponseCode("v")); + Assert.Empty(transport.GetAllWrittenData()); + } + + [Theory] + [InlineData("LDT")] + [InlineData("DATE_AND_LTIME")] + public async Task Pre_epoch_fractional_long_dates_are_rejected_before_send(string type) + { + var transport = Ready(); + using var connection = ConnectQuietly(transport); + + var response = await WriteAsync(connection, "%DB1:0:" + type, + new DateTime(1969, 12, 31, 23, 59, 59, 500)); + + Assert.Equal(PlcResponseCode.InvalidDatatype, response.GetResponseCode("v")); + Assert.Empty(transport.GetAllWrittenData()); + } + [Theory] [InlineData("CHAR", 0x03, "41")] [InlineData("WCHAR", 0x13, "0041")]
diff --git a/plc4net/test/s7-test/S7Frames.cs b/plc4net/test/s7-test/S7Frames.cs index 9e4fa6b..3424e81 100644 --- a/plc4net/test/s7-test/S7Frames.cs +++ b/plc4net/test/s7-test/S7Frames.cs
@@ -50,6 +50,9 @@ /// <summary>The S7 message of a job: ten header bytes, the parameter, the data.</summary> public static byte[] Job(ushort reference, byte[] parameter, byte[] data) => Message(0x01, reference, parameter, data, false); + public static byte[] UserData(ushort reference, byte[] parameter, byte[] data) + => Message(0x07, reference, parameter, data, false); + /// <summary>An acknowledgement with data (message type 3): twelve header bytes, the parameter, the data.</summary> public static byte[] AckData(ushort reference, byte[] parameter, byte[] data, byte errorClass = 0, byte errorCode = 0) => Message(0x03, reference, parameter, data, true, errorClass, errorCode);
diff --git a/plc4net/test/s7-test/S7TagTests.cs b/plc4net/test/s7-test/S7TagTests.cs index b526f1a..2df7608 100644 --- a/plc4net/test/s7-test/S7TagTests.cs +++ b/plc4net/test/s7-test/S7TagTests.cs
@@ -34,6 +34,7 @@ [InlineData("%DB1.DBX0.0:BOOL", MemoryArea.DATA_BLOCKS, 1, 0, 0, TransportSize.BOOL)] [InlineData("%DB100.DBX5.7:BOOL", MemoryArea.DATA_BLOCKS, 100, 5, 7, TransportSize.BOOL)] [InlineData("%DB1.DBB3:BYTE", MemoryArea.DATA_BLOCKS, 1, 3, 0, TransportSize.BYTE)] + [InlineData("%DB1.DBB3:RAW_BYTE_ARRAY", MemoryArea.DATA_BLOCKS, 1, 3, 0, TransportSize.BYTE)] [InlineData("%DB1.DBB3:SINT", MemoryArea.DATA_BLOCKS, 1, 3, 0, TransportSize.SINT)] [InlineData("%DB1.DBB3:USINT", MemoryArea.DATA_BLOCKS, 1, 3, 0, TransportSize.USINT)] [InlineData("%DB1.DBW2:WORD", MemoryArea.DATA_BLOCKS, 1, 2, 0, TransportSize.WORD)] @@ -51,7 +52,14 @@ [InlineData("%M10.3:BOOL", MemoryArea.FLAGS_MARKERS, 0, 10, 3, TransportSize.BOOL)] [InlineData("%MD12:REAL", MemoryArea.FLAGS_MARKERS, 0, 12, 0, TransportSize.REAL)] [InlineData("%M20:INT", MemoryArea.FLAGS_MARKERS, 0, 20, 0, TransportSize.INT)] - [InlineData("%DB65535.DBW65535:INT", MemoryArea.DATA_BLOCKS, 65535, 65535, 0, TransportSize.INT)] + [InlineData("%DW10:WORD", MemoryArea.DIRECT_PERIPHERAL_ACCESS, 0, 10, 0, TransportSize.WORD)] + [InlineData("%DB65535.DBW65534:INT", MemoryArea.DATA_BLOCKS, 65535, 65534, 0, TransportSize.INT)] + [InlineData("%DB1:0:LINT", MemoryArea.DATA_BLOCKS, 1, 0, 0, TransportSize.LINT)] + [InlineData("%DB1:8:ULINT", MemoryArea.DATA_BLOCKS, 1, 8, 0, TransportSize.ULINT)] + [InlineData("%DB1:16:LWORD", MemoryArea.DATA_BLOCKS, 1, 16, 0, TransportSize.LWORD)] + [InlineData("%DB1:24:LREAL", MemoryArea.DATA_BLOCKS, 1, 24, 0, TransportSize.LREAL)] + [InlineData("%C9:COUNTER", MemoryArea.COUNTERS, 0, 1, 1, TransportSize.COUNTER)] + [InlineData("%DB1.DB100:COUNTER", MemoryArea.DATA_BLOCKS, 1, 12, 4, TransportSize.COUNTER)] public void A_address_names_its_area_block_offset_and_type( string address, MemoryArea area, int block, int byteOffset, int bitOffset, TransportSize type) { @@ -130,9 +138,31 @@ } [Theory] - [InlineData("%DB1:10:WSTRING")] + [InlineData("%DB1:10:STRING", TransportSize.STRING, 2)] + [InlineData("%DB1:10:WSTRING", TransportSize.WSTRING, 4)] + public void A_variable_string_uses_its_length_header_first(string address, TransportSize type, int headerSize) + { + var tag = S7Tag.Parse(address); + + Assert.True(tag.IsVariableString); + Assert.Equal(type, tag.DataType); + Assert.Equal(headerSize, tag.SizeInBytes); + Assert.Equal(tag.ToString(), S7Tag.Parse(tag.ToString()).ToString()); + } + + [Fact] + public void A_wide_string_can_use_its_16_bit_length_header() + { + var tag = S7Tag.Parse("%DB1:10:WSTRING(16382)"); + + Assert.Equal(32768, tag.SizeInBytes); + Assert.Equal(16382, tag.StringLength); + } + + [Theory] + [InlineData("%DB1:10[0..2]:WSTRING")] [InlineData("%DB1:10:WSTRING(0)")] - [InlineData("%DB1:10:WSTRING(255)")] + [InlineData("%DB1:10:WSTRING(16383)")] [InlineData("%M10:WSTRING(4)")] [InlineData("%DB1:65525:WSTRING(4)")] public void An_invalid_fixed_wstring_is_rejected(string address) @@ -240,24 +270,54 @@ [InlineData("%DB1.DBW10[65536]:INT")] [InlineData("%DB1.DBW65534[0..1]:INT")] [InlineData("%DB1.DBW10[1,2]:INT")] - [InlineData("%DB1.DBX0.0[0..1]:BOOL")] + [InlineData("%DB1.DBX65535.7[0..1]:BOOL")] public void Invalid_or_unsupported_array_selection_is_rejected(string address) { Assert.Throws<PlcInvalidFieldException>(() => S7Tag.Parse(address)); } - [Theory] - [InlineData("%DB1.DBD0:LREAL")] - [InlineData("%DB1.DBD0:LWORD")] - [InlineData("%DB1.DBD0:LINT")] - [InlineData("%DB1.DBD0:TIME")] - [InlineData("%DB1.DBW0:DATE")] - [InlineData("%DB1.DBW0:S5TIME")] - [InlineData("%DB1.DBX0.0:COUNTER")] - public void The_types_that_are_not_supported_yet_are_refused_with_an_explanation(string address) + [Fact] + public void Bool_array_selection_counts_bits_across_byte_boundaries() { - var exception = Assert.Throws<PlcInvalidFieldException>(() => S7Tag.Parse(address)); - Assert.Contains("not supported yet", exception.Message); + var tag = S7Tag.Parse("%DB1.DBX16.6[1..5]:BOOL"); + Assert.Equal(16, tag.ByteOffset); + Assert.Equal((byte)7, tag.BitOffset); + Assert.Equal((ushort)5, tag.Quantity); + Assert.Equal(2, tag.SizeInBytes); + Assert.True(tag.ExplicitRange); + Assert.Equal(tag.ToString(), S7Tag.Parse(tag.ToString()).ToString()); + + var single = S7Tag.Parse("%DB1.DBX16.6[3]:BOOL"); + Assert.Equal(17, single.ByteOffset); + Assert.Equal((byte)1, single.BitOffset); + Assert.False(single.ExplicitRange); + } + + [Theory] + [InlineData("STRING", 6)] + [InlineData("WSTRING", 12)] + public void Fixed_string_arrays_use_the_complete_element_stride(string type, int stride) + { + var tag = S7Tag.Parse($"%DB1:10[1..2]:{type}(4)"); + Assert.Equal(10 + stride, tag.ByteOffset); + Assert.Equal((ushort)2, tag.Quantity); + Assert.Equal(2 * stride, tag.SizeInBytes); + Assert.Equal(tag.ToString(), S7Tag.Parse(tag.ToString()).ToString()); + } + + [Fact] + public void A_counter_number_cannot_have_a_bit_offset() + { + var exception = Assert.Throws<PlcInvalidFieldException>( + () => S7Tag.Parse("%DB1.DBX0.0:COUNTER")); + Assert.Contains("bit offset", exception.Message); + } + + [Fact] + public void A_scalar_must_fit_within_the_addressable_byte_range() + { + Assert.Throws<PlcInvalidFieldException>(() => S7Tag.Parse("%DB1.DBW65535:INT")); + Assert.Throws<PlcInvalidFieldException>(() => S7Tag.Parse("%DB1:65529:LINT")); } [Fact] @@ -267,16 +327,58 @@ Assert.Contains("Unknown S7 data type", exception.Message); } + [Fact] + public void A_raw_byte_array_uses_the_byte_wire_type() + { + var tag = S7Tag.Parse("%DB1.DBB0[0..15]:RAW_BYTE_ARRAY"); + + Assert.Equal(TransportSize.BYTE, tag.DataType); + Assert.Equal((ushort)16, tag.Quantity); + Assert.Equal("%DB1.DB0[0..15]:BYTE", tag.ToString()); + Assert.Equal(16, S7Connection.ToAddress(tag).NumberOfElements); + } + + [Fact] + public void A_counter_preserves_its_number_and_wire_transport() + { + var tag = S7Tag.Parse("%C9[0..2]:COUNTER"); + + Assert.True(tag.IsCounter); + Assert.Equal((ushort)3, tag.Quantity); + Assert.Equal(6, tag.SizeInBytes); + Assert.Equal("%C9[0..2]:COUNTER", tag.ToString()); + Assert.Equal((byte)0x1C, S7Connection.ToAddress(tag).TransportSize.GetCode()); + Assert.Equal((ushort)1, S7Connection.ToAddress(tag).ByteAddress); + Assert.Equal((byte)1, S7Connection.ToAddress(tag).BitAddress); + } + + [Fact] + public void A_counter_can_be_constructed_without_parsing_an_address() + { + var parsed = S7Tag.Parse("%C9[0..2]:COUNTER"); + var constructed = S7Tag.ForCounter(MemoryArea.COUNTERS, 0, 9, 3); + + Assert.Equal(parsed.ToString(), constructed.ToString()); + Assert.Equal(parsed.SizeInBytes, constructed.SizeInBytes); + Assert.Equal(S7Connection.ToAddress(parsed).ByteAddress, + S7Connection.ToAddress(constructed).ByteAddress); + Assert.Throws<PlcInvalidFieldException>(() => + S7Tag.ForCounter(MemoryArea.COUNTERS, 0, -1)); + Assert.Throws<PlcInvalidFieldException>(() => + S7Tag.ForCounter(MemoryArea.FLAGS_MARKERS, 0, 9)); + } + [Theory] [InlineData("%C5:WORD")] [InlineData("%T0:WORD")] [InlineData("%PIW0:WORD")] [InlineData("%L0.0:BOOL")] - [InlineData("%D10:INT")] public void The_other_memory_areas_are_refused_with_an_explanation(string address) { var exception = Assert.Throws<PlcInvalidFieldException>(() => S7Tag.Parse(address)); Assert.Contains("not supported yet", exception.Message); + if (address == "%C5:WORD") + Assert.Contains("counters", exception.Message); } [Fact] @@ -285,7 +387,7 @@ Assert.Throws<PlcInvalidFieldException>( () => new S7Tag(MemoryArea.COUNTERS, 0, 0, 0, TransportSize.WORD)); Assert.Throws<PlcInvalidFieldException>( - () => new S7Tag(MemoryArea.DATA_BLOCKS, 1, 0, 0, TransportSize.LREAL)); + () => new S7Tag(MemoryArea.DATA_BLOCKS, 1, 0, 0, (TransportSize)0xFF)); Assert.Throws<PlcInvalidFieldException>( () => new S7Tag(MemoryArea.FLAGS_MARKERS, 5, 0, 0, TransportSize.BYTE)); // a block number outside a data block Assert.Throws<PlcInvalidFieldException>(