using System.Collections.Concurrent;
using System.Runtime.CompilerServices;
using ZB.MOM.WW.OtOpcUa.Driver.TwinCAT;
namespace ZB.MOM.WW.OtOpcUa.Driver.TwinCAT.Tests;
internal class FakeTwinCATClient : ITwinCATClient
{
/// Gets a value indicating whether the client is connected.
public bool IsConnected { get; private set; }
/// Gets the number of times Connect has been called.
public int ConnectCount { get; private set; }
/// Gets the number of times Dispose has been called.
public int DisposeCount { get; private set; }
/// Gets or sets a value indicating whether ConnectAsync should throw.
public bool ThrowOnConnect { get; set; }
/// Gets or sets a value indicating whether ReadValueAsync should throw.
public bool ThrowOnRead { get; set; }
/// Gets or sets a value indicating whether WriteValueAsync should throw.
public bool ThrowOnWrite { get; set; }
/// Gets or sets a value indicating whether ProbeAsync should throw.
public bool ThrowOnProbe { get; set; }
/// Gets or sets the exception to throw when a throw flag is set.
public Exception? Exception { get; set; }
/// Gets the simulated values by symbol path.
public Dictionary Values { get; } = new(StringComparer.OrdinalIgnoreCase);
/// Gets the read statuses by symbol path.
public Dictionary ReadStatuses { get; } = new(StringComparer.OrdinalIgnoreCase);
/// Gets the write statuses by symbol path.
public Dictionary WriteStatuses { get; } = new(StringComparer.OrdinalIgnoreCase);
/// Records the arrayCount argument of the most recent
/// call (null = scalar read) so Phase 4c array-read tests can assert the driver requested
/// the array with the authored length.
public int? LastReadArrayCount { get; private set; }
/// Gets the log of all write operations.
public List<(string symbol, TwinCATDataType type, int? bit, object? value)> WriteLog { get; } = new();
/// Gets or sets the result returned by ProbeAsync.
public bool ProbeResult { get; set; } = true;
/// Occurs when the symbol version changes.
public event EventHandler? OnSymbolVersionChanged;
/// Test hook — fire the symbol-version-changed signal as the real client would.
public void FireSymbolVersionChanged() => OnSymbolVersionChanged?.Invoke(this, EventArgs.Empty);
/// Test hook — simulate a wire-level drop that leaves the AMS port "connected" but dead:
/// flips to false without disposing, so the driver's IsConnected
/// fast-path treats the client as stale and rebuilds (exercises the STAB-2 reconnect+replay).
public void SimulateWireDrop() => IsConnected = false;
/// Simulates connecting to the TwinCAT system.
/// The AMS address to connect to.
/// The connection timeout.
/// The cancellation token.
/// A task that completes when the connection succeeds or fails.
public virtual Task ConnectAsync(TwinCATAmsAddress address, TimeSpan timeout, CancellationToken ct)
{
ConnectCount++;
if (ThrowOnConnect) throw Exception ?? new InvalidOperationException();
if (BlockConnect is { } block)
{
// Models the real client's blocking SDK Connect: ignores the token until released.
return block.Task.ContinueWith(_ => { IsConnected = true; }, TaskScheduler.Default);
}
IsConnected = true;
return Task.CompletedTask;
}
/// When set, does not complete (and ignores cancellation) until this
/// is completed — a probe wedged in the synchronous ADS Connect.
public TaskCompletionSource? BlockConnect { get; set; }
/// Gets or sets the simulated notification-queue drop count.
public long DroppedNotificationCount { get; set; }
/// Simulates reading a value from a symbol.
/// The path to the symbol to read.
/// The data type of the symbol.
/// The optional bit index for bit-level reads.
/// The optional 1-D array element count (null = scalar read).
/// The cancellation token.
/// A task that returns the simulated value and status.
public virtual Task<(object? value, uint status)> ReadValueAsync(
string symbolPath, TwinCATDataType type, int? bitIndex, int? arrayCount, CancellationToken ct)
{
if (BlockRead is { } block)
{
// A read wedged in the (uncancellable) wire call; completes with the normal answer once released.
return block.Task.ContinueWith(_ =>
{
BlockRead = null;
return ReadValueAsync(symbolPath, type, bitIndex, arrayCount, CancellationToken.None).Result;
}, TaskScheduler.Default);
}
if (ThrowOnRead) throw Exception ?? new InvalidOperationException();
Interlocked.Increment(ref _singleReadCount);
LastReadArrayCount = arrayCount;
var status = ReadStatuses.TryGetValue(symbolPath, out var s) ? s : TwinCATStatusMapper.Good;
var value = Values.TryGetValue(symbolPath, out var v) ? v : null;
return Task.FromResult((value, status));
}
/// When set, does not complete (and ignores cancellation) until this is
/// completed — a poll read wedged in the wire call.
public TaskCompletionSource? BlockRead { get; set; }
private int _singleReadCount;
/// Gets the number of individual calls served.
public int SingleReadCount { get => Volatile.Read(ref _singleReadCount); private set => Volatile.Write(ref _singleReadCount, value); }
/// Gets the size of each batch the driver issued, in order (#645).
public List SumReadBatches { get; } = new();
/// Gets or sets an exception throws instead of answering — a
/// models a target without sum commands.
public Exception? SumReadException { get; set; }
/// Gets or sets the ADS state text returns.
public string? AdsStateText { get; set; }
/// Simulates an ADS sum-read: records the batch size, then answers each item from the same
/// tables the single read uses.
/// The batch.
/// The cancellation token.
/// One outcome per item.
public virtual Task> ReadValuesAsync(
IReadOnlyList reads, CancellationToken ct)
{
if (ThrowOnRead) throw Exception ?? new InvalidOperationException();
SumReadBatches.Add(reads.Count);
if (SumReadException is { } ex) throw ex;
if (SimulateSumFallback) SumFallbackCount++;
var results = new (object? value, uint status)[reads.Count];
for (var i = 0; i < reads.Count; i++)
{
var path = reads[i].SymbolPath;
results[i] = (Values.TryGetValue(path, out var v) ? v : null,
ReadStatuses.TryGetValue(path, out var s) ? s : TwinCATStatusMapper.Good);
}
return Task.FromResult>(results);
}
/// Gets or sets whether each batch counts as a non-latching sum fallback.
public bool SimulateSumFallback { get; set; }
/// Gets the simulated count of non-latching sum fallbacks.
public long SumFallbackCount { get; private set; }
/// Gets the simulated overall code of the last fallback.
public uint LastSumFallbackCode => 1795;
/// Gets the ADS state the "probe" last read.
public string? LastAdsState => AdsStateText;
/// Simulates writing a value to a symbol.
/// The path to the symbol to write.
/// The data type of the symbol.
/// The optional bit index for bit-level writes.
/// The value to write.
/// The cancellation token.
/// A task that returns the write status.
public virtual Task WriteValueAsync(
string symbolPath, TwinCATDataType type, int? bitIndex, object? value, CancellationToken ct)
{
if (ThrowOnWrite) throw Exception ?? new InvalidOperationException();
if (type is TwinCATDataType.String or TwinCATDataType.WString
&& SymbolShapes.TryGetValue(symbolPath, out var shape))
{
// The real client's encode plan (resolve → CheckRead → codec at the PLC width).
var (planStatus, bytes) = AdsTwinCATClient.PlanStringWrite(type, shape, value, utf8: false);
if (planStatus != TwinCATStatusMapper.Good) return Task.FromResult(planStatus);
RawWrites[symbolPath] = bytes;
}
WriteLog.Add((symbolPath, type, bitIndex, value));
Values[symbolPath] = value;
var status = WriteStatuses.TryGetValue(symbolPath, out var s) ? s : TwinCATStatusMapper.Good;
return Task.FromResult(status);
}
/// Gets the log of every call.
public List<(string symbol, TwinCATDataType type, IReadOnlyList