mirror of
https://github.com/evopro-ag/Sharp7Reactive.git
synced 2025-12-15 11:22:52 +00:00
Compare commits
5 Commits
master
...
75a893f51f
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
75a893f51f | ||
|
|
61e04c7f63 | ||
|
|
af2df01617 | ||
|
|
a2b6d84862 | ||
|
|
79031d6f1c |
@@ -10,7 +10,7 @@ using Sharp7.Rx.Settings;
|
||||
|
||||
namespace Sharp7.Rx;
|
||||
|
||||
internal class Sharp7Connector: IDisposable
|
||||
internal class Sharp7Connector : IDisposable
|
||||
{
|
||||
private readonly BehaviorSubject<ConnectionState> connectionStateSubject = new(Enums.ConnectionState.Initial);
|
||||
private readonly int cpuSlotNr;
|
||||
@@ -35,16 +35,21 @@ internal class Sharp7Connector: IDisposable
|
||||
rackNr = settings.RackNumber;
|
||||
|
||||
ReconnectDelay = TimeSpan.FromSeconds(5);
|
||||
|
||||
ConnectionIdentifier = $"{ipAddress}:{port} Cpu {cpuSlotNr} Rack {rackNr}";
|
||||
}
|
||||
|
||||
public IObservable<ConnectionState> ConnectionState => connectionStateSubject.DistinctUntilChanged().AsObservable();
|
||||
public ConnectionState CurrentConnectionState => connectionStateSubject.Value;
|
||||
|
||||
public ILogger Logger { get; set; }
|
||||
|
||||
public TimeSpan ReconnectDelay { get; set; }
|
||||
private string ConnectionIdentifier { get; }
|
||||
|
||||
private bool IsConnected => connectionStateSubject.Value == Enums.ConnectionState.Connected;
|
||||
|
||||
private TimeSpan ReconnectDelay { get; }
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(true);
|
||||
@@ -67,13 +72,13 @@ internal class Sharp7Connector: IDisposable
|
||||
else
|
||||
{
|
||||
var errorText = EvaluateErrorCode(errorCode);
|
||||
Logger.LogError("Failed to establish initial connection: {Error}", errorText);
|
||||
Logger.LogError("Failed to establish initial connection to {Connection}: {Error}", ConnectionIdentifier, errorText);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
connectionStateSubject.OnNext(Enums.ConnectionState.ConnectionLost);
|
||||
Logger.LogError(ex, "Failed to establish initial connection.");
|
||||
Logger.LogError(ex, "Failed to establish initial connection ro {Connection}.", ConnectionIdentifier);
|
||||
}
|
||||
|
||||
return false;
|
||||
@@ -112,12 +117,11 @@ internal class Sharp7Connector: IDisposable
|
||||
return buffers.ToDictionary(arg => arg.VariableName, arg => arg.Buffer);
|
||||
}
|
||||
|
||||
public Task InitializeAsync()
|
||||
public void InitializeAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
sharp7 = new S7Client();
|
||||
sharp7.PLCPort = port;
|
||||
sharp7 = new S7Client {PLCPort = port};
|
||||
|
||||
var subscription =
|
||||
ConnectionState
|
||||
@@ -125,17 +129,15 @@ internal class Sharp7Connector: IDisposable
|
||||
.Take(1)
|
||||
.SelectMany(_ => Reconnect())
|
||||
.RepeatAfterDelay(ReconnectDelay)
|
||||
.LogAndRetry(Logger, "Error while reconnecting to S7.")
|
||||
.LogAndRetry(Logger, $"Error while reconnecting to {ConnectionIdentifier}.")
|
||||
.Subscribe();
|
||||
|
||||
disposables.Add(subscription);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger?.LogError(ex, "S7 driver could not be initialized");
|
||||
Logger?.LogError(ex, "S7 driver for {Connection} could not be initialized", ConnectionIdentifier);
|
||||
}
|
||||
|
||||
return Task.FromResult(true);
|
||||
}
|
||||
|
||||
public async Task<byte[]> ReadBytes(Operand operand, ushort startByteAddress, ushort bytesToRead, ushort dbNo, CancellationToken token)
|
||||
@@ -149,11 +151,13 @@ internal class Sharp7Connector: IDisposable
|
||||
await Task.Factory.StartNew(() => sharp7.ReadArea(operand.ToArea(), dbNo, startByteAddress, bytesToRead, S7WordLength.Byte, buffer), token, TaskCreationOptions.None, scheduler);
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
EnsureSuccessOrThrow(result, $"Error reading {operand}{dbNo}:{startByteAddress}->{bytesToRead}");
|
||||
EnsureSuccessOrThrow(result, $"Error reading {operand}{dbNo}:{startByteAddress} ({bytesToRead} bytes)");
|
||||
|
||||
return buffer;
|
||||
}
|
||||
|
||||
public override string ToString() => ConnectionIdentifier;
|
||||
|
||||
public async Task WriteBit(Operand operand, ushort startByteAddress, byte bitAdress, bool value, ushort dbNo, CancellationToken token)
|
||||
{
|
||||
EnsureConnectionValid();
|
||||
@@ -175,7 +179,7 @@ internal class Sharp7Connector: IDisposable
|
||||
var result = await Task.Factory.StartNew(() => sharp7.WriteArea(operand.ToArea(), dbNo, startByteAddress, bytesToWrite, S7WordLength.Byte, data), token, TaskCreationOptions.None, scheduler);
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
EnsureSuccessOrThrow(result, $"Error writing {operand}{dbNo}:{startByteAddress}.{data.Length}");
|
||||
EnsureSuccessOrThrow(result, $"Error writing {operand}{dbNo}:{startByteAddress} ({data.Length} bytes)");
|
||||
}
|
||||
|
||||
|
||||
@@ -222,18 +226,18 @@ internal class Sharp7Connector: IDisposable
|
||||
throw new InvalidOperationException("Plc is not connected");
|
||||
}
|
||||
|
||||
private void EnsureSuccessOrThrow(int result, string message)
|
||||
private void EnsureSuccessOrThrow(int errorCode, string message)
|
||||
{
|
||||
if (result == 0) return;
|
||||
if (errorCode == 0) return;
|
||||
|
||||
var errorText = EvaluateErrorCode(result);
|
||||
var errorText = EvaluateErrorCode(errorCode);
|
||||
var completeMessage = $"{message}: {errorText}";
|
||||
|
||||
var additionalErrorText = S7ErrorCodes.GetAdditionalErrorText(result);
|
||||
var additionalErrorText = S7ErrorCodes.GetAdditionalErrorText(errorCode);
|
||||
if (additionalErrorText != null)
|
||||
completeMessage += Environment.NewLine + additionalErrorText;
|
||||
|
||||
throw new S7CommunicationException(completeMessage, result, errorText);
|
||||
throw new S7CommunicationException(completeMessage, errorCode, errorText);
|
||||
}
|
||||
|
||||
private string EvaluateErrorCode(int errorCode)
|
||||
@@ -245,7 +249,6 @@ internal class Sharp7Connector: IDisposable
|
||||
throw new InvalidOperationException("S7 driver is not initialized.");
|
||||
|
||||
var errorText = $"0x{errorCode:X}, {sharp7.ErrorText(errorCode)}";
|
||||
Logger?.LogError($"S7 Error {errorText}");
|
||||
|
||||
if (S7ErrorCodes.AssumeConnectionLost(errorCode))
|
||||
SetConnectionLostState();
|
||||
|
||||
@@ -28,7 +28,7 @@ public class Sharp7Plc : IPlc
|
||||
private readonly ConcurrentSubjectDictionary<string, byte[]> multiVariableSubscriptions = new(StringComparer.InvariantCultureIgnoreCase);
|
||||
private readonly List<long> performanceCounter = new(1000);
|
||||
private readonly PlcConnectionSettings plcConnectionSettings;
|
||||
private readonly CacheVariableNameParser variableNameParser = new CacheVariableNameParser(new VariableNameParser());
|
||||
private readonly CacheVariableNameParser variableNameParser = new(new VariableNameParser());
|
||||
private bool disposed;
|
||||
private int initialized;
|
||||
|
||||
@@ -37,10 +37,10 @@ public class Sharp7Plc : IPlc
|
||||
|
||||
/// <summary>
|
||||
/// </summary>
|
||||
/// <param name="ipAddress"></param>
|
||||
/// <param name="rackNumber"></param>
|
||||
/// <param name="cpuMpiAddress"></param>
|
||||
/// <param name="port"></param>
|
||||
/// <param name="ipAddress">IP address of S7.</param>
|
||||
/// <param name="rackNumber">See <see href="https://github.com/fbarresi/Sharp7/wiki/Connection#rack-and-slot">Sharp7 wiki</see></param>
|
||||
/// <param name="cpuMpiAddress">See <see href="https://github.com/fbarresi/Sharp7/wiki/Connection#rack-and-slot">Sharp7 wiki</see></param>
|
||||
/// <param name="port">TCP port for communication</param>
|
||||
/// <param name="multiVarRequestCycleTime">
|
||||
/// <para>
|
||||
/// Polling interval for multi variable read from PLC.
|
||||
@@ -90,10 +90,6 @@ public class Sharp7Plc : IPlc
|
||||
/// Create an Observable for a given variable. Multiple notifications are automatically combined into a multi-variable subscription to
|
||||
/// reduce network trafic and PLC workload.
|
||||
/// </summary>
|
||||
/// <typeparam name="TValue"></typeparam>
|
||||
/// <param name="variableName"></param>
|
||||
/// <param name="transmissionMode"></param>
|
||||
/// <returns></returns>
|
||||
public IObservable<TValue> CreateNotification<TValue>(string variableName, TransmissionMode transmissionMode)
|
||||
{
|
||||
return Observable.Create<TValue>(observer =>
|
||||
@@ -105,9 +101,13 @@ public class Sharp7Plc : IPlc
|
||||
disposableContainer.AddDisposableTo(disp);
|
||||
|
||||
var observable =
|
||||
// Read variable with GetValue first.
|
||||
// This will propagate any errors due to reading from invalid addresses.
|
||||
Observable.FromAsync(() => GetValue<TValue>(variableName))
|
||||
ConnectionState
|
||||
// Wait for connection to be established
|
||||
.FirstAsync(c => c == Enums.ConnectionState.Connected)
|
||||
// Read variable with GetValue first.
|
||||
// This will propagate any errors due to reading from invalid addresses.
|
||||
.SelectMany(_ => GetValue<TValue>(variableName))
|
||||
// Output results from read loop
|
||||
.Concat(
|
||||
disposableContainer.Observable
|
||||
.Select(bytes => ValueConverter.ReadFromBuffer<TValue>(bytes, address))
|
||||
@@ -124,12 +124,28 @@ public class Sharp7Plc : IPlc
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Read PLC variable as generic variable.
|
||||
/// Creates an observable of object for a variable.
|
||||
/// The return type is automatically infered from the variable name.
|
||||
/// </summary>
|
||||
/// <returns>The return type is infered from the variable name.</returns>
|
||||
public IObservable<object> CreateNotification(string variableName, TransmissionMode transmissionMode)
|
||||
{
|
||||
var address = variableNameParser.Parse(variableName);
|
||||
var clrType = address.GetClrType();
|
||||
|
||||
var genericCreateNotification = createNotificationMethod!.MakeGenericMethod(clrType);
|
||||
|
||||
var genericNotification = genericCreateNotification.Invoke(this, [variableName, transmissionMode]);
|
||||
|
||||
return SignatureConverter.ConvertToObjectObservable(genericNotification, clrType);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Read PLC variable as generic variable.
|
||||
/// <para>
|
||||
/// The method will fail with a <see cref="InvalidOperationException" />, if <see cref="ConnectionState" /> is not <see cref="ConnectionState.Connected" />.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
/// <typeparam name="TValue"></typeparam>
|
||||
/// <param name="variableName"></param>
|
||||
/// <param name="token"></param>
|
||||
/// <returns></returns>
|
||||
public async Task<TValue> GetValue<TValue>(string variableName, CancellationToken token = default)
|
||||
{
|
||||
var address = ParseAndVerify(variableName, typeof(TValue));
|
||||
@@ -141,9 +157,10 @@ public class Sharp7Plc : IPlc
|
||||
/// <summary>
|
||||
/// Read PLC variable as object.
|
||||
/// The return type is automatically infered from the variable name.
|
||||
/// <para>
|
||||
/// The method will fail with a <see cref="InvalidOperationException" />, if <see cref="ConnectionState" /> is not <see cref="ConnectionState.Connected" />.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
/// <param name="variableName"></param>
|
||||
/// <param name="token"></param>
|
||||
/// <returns>The actual return type is infered from the variable name.</returns>
|
||||
public async Task<object> GetValue(string variableName, CancellationToken token = default)
|
||||
{
|
||||
@@ -164,12 +181,10 @@ public class Sharp7Plc : IPlc
|
||||
|
||||
/// <summary>
|
||||
/// Write value to the PLC.
|
||||
/// <para>
|
||||
/// The method will fail with a <see cref="InvalidOperationException" />, if <see cref="ConnectionState" /> is not <see cref="ConnectionState.Connected" />.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
/// <typeparam name="TValue"></typeparam>
|
||||
/// <param name="variableName"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="token"></param>
|
||||
/// <returns></returns>
|
||||
public async Task SetValue<TValue>(string variableName, TValue value, CancellationToken token = default)
|
||||
{
|
||||
var address = ParseAndVerify(variableName, typeof(TValue));
|
||||
@@ -197,25 +212,6 @@ public class Sharp7Plc : IPlc
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an observable of object for a variable.
|
||||
/// The return type is automatically infered from the variable name.
|
||||
/// </summary>
|
||||
/// <param name="variableName"></param>
|
||||
/// <param name="transmissionMode"></param>
|
||||
/// <returns>The return type is infered from the variable name.</returns>
|
||||
public IObservable<object> CreateNotification(string variableName, TransmissionMode transmissionMode)
|
||||
{
|
||||
var address = variableNameParser.Parse(variableName);
|
||||
var clrType = address.GetClrType();
|
||||
|
||||
var genericCreateNotification = createNotificationMethod!.MakeGenericMethod(clrType);
|
||||
|
||||
var genericNotification = genericCreateNotification.Invoke(this, [variableName, transmissionMode]);
|
||||
|
||||
return SignatureConverter.ConvertToObjectObservable(genericNotification, clrType);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Trigger PLC connection and start notification loop.
|
||||
/// <para>
|
||||
@@ -224,26 +220,37 @@ public class Sharp7Plc : IPlc
|
||||
/// </summary>
|
||||
/// <returns>Always true</returns>
|
||||
[Obsolete($"Use {nameof(InitializeConnection)} or {nameof(TriggerConnection)}.")]
|
||||
public async Task<bool> InitializeAsync()
|
||||
public Task<bool> InitializeAsync()
|
||||
{
|
||||
await TriggerConnection();
|
||||
return true;
|
||||
TriggerConnection();
|
||||
return Task.FromResult(true);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Initialize PLC connection and wait for connection to be established.
|
||||
/// Initialize PLC connection and wait for connection to be established (<see cref="ConnectionState" /> is <see cref="ConnectionState.Connected" />).
|
||||
/// </summary>
|
||||
/// <param name="token"></param>
|
||||
/// <returns></returns>
|
||||
public async Task InitializeConnection(CancellationToken token = default) => await DoInitializeConnection(true, token);
|
||||
public async Task InitializeConnection(CancellationToken token = default)
|
||||
{
|
||||
DoInitializeConnection();
|
||||
await s7Connector.ConnectionState
|
||||
.FirstAsync(c => c == Enums.ConnectionState.Connected)
|
||||
.ToTask(token);
|
||||
}
|
||||
|
||||
public override string ToString() => $"S7 {s7Connector} ({s7Connector.CurrentConnectionState})";
|
||||
|
||||
/// <summary>
|
||||
/// Initialize PLC and trigger connection. This method will not wait for the connection to be established.
|
||||
/// <para>
|
||||
/// Without an established connection, it is safe to call <see cref="CreateNotification" />, but <see cref="GetValue{TValue}" />
|
||||
/// and <see cref="SetValue{TValue}" /> will fail.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
/// <param name="token"></param>
|
||||
/// <returns></returns>
|
||||
public async Task TriggerConnection(CancellationToken token = default) => await DoInitializeConnection(false, token);
|
||||
public void TriggerConnection() => DoInitializeConnection();
|
||||
|
||||
protected virtual void Dispose(bool disposing)
|
||||
{
|
||||
@@ -266,11 +273,12 @@ public class Sharp7Plc : IPlc
|
||||
}
|
||||
}
|
||||
|
||||
private async Task DoInitializeConnection(bool waitForConnection, CancellationToken token)
|
||||
private void DoInitializeConnection()
|
||||
{
|
||||
if (Interlocked.Exchange(ref initialized, 1) == 1) return;
|
||||
if (Interlocked.Exchange(ref initialized, 1) == 1)
|
||||
return;
|
||||
|
||||
await s7Connector.InitializeAsync();
|
||||
s7Connector.InitializeAsync();
|
||||
|
||||
// Triger connection.
|
||||
// The initial connection might fail. In this case a reconnect is initiated.
|
||||
@@ -281,16 +289,11 @@ public class Sharp7Plc : IPlc
|
||||
{
|
||||
await s7Connector.Connect();
|
||||
}
|
||||
catch (Exception e)
|
||||
catch (Exception)
|
||||
{
|
||||
Logger?.LogError(e, "Intiial PLC connection failed.");
|
||||
// Ignore. Exception is logged in the connector
|
||||
}
|
||||
}, token);
|
||||
|
||||
if (waitForConnection)
|
||||
await s7Connector.ConnectionState
|
||||
.FirstAsync(c => c == Enums.ConnectionState.Connected)
|
||||
.ToTask(token);
|
||||
});
|
||||
|
||||
StartNotificationLoop();
|
||||
}
|
||||
@@ -329,9 +332,12 @@ public class Sharp7Plc : IPlc
|
||||
|
||||
private void PrintAndResetPerformanceStatistik()
|
||||
{
|
||||
if (performanceCounter.Count == performanceCounter.Capacity)
|
||||
if (performanceCounter.Count != performanceCounter.Capacity) return;
|
||||
|
||||
if (Logger.IsEnabled(LogLevel.Trace))
|
||||
{
|
||||
var average = performanceCounter.Average();
|
||||
|
||||
var min = performanceCounter.Min();
|
||||
var max = performanceCounter.Max();
|
||||
|
||||
@@ -340,8 +346,9 @@ public class Sharp7Plc : IPlc
|
||||
performanceCounter.Capacity, min, max, average,
|
||||
multiVariableSubscriptions.ExistingKeys.Count(),
|
||||
MultiVarRequestMaxItems);
|
||||
performanceCounter.Clear();
|
||||
}
|
||||
|
||||
performanceCounter.Clear();
|
||||
}
|
||||
|
||||
private void StartNotificationLoop()
|
||||
@@ -355,16 +362,11 @@ public class Sharp7Plc : IPlc
|
||||
.FirstAsync(states => states == Enums.ConnectionState.Connected)
|
||||
.SelectMany(_ => GetAllValues(s7Connector))
|
||||
.RepeatAfterDelay(MultiVarRequestCycleTime)
|
||||
.LogAndRetryAfterDelay(Logger, MultiVarRequestCycleTime, "Error while getting batch notifications from plc")
|
||||
.LogAndRetryAfterDelay(Logger, MultiVarRequestCycleTime, $"Error while getting batch notifications from {s7Connector}")
|
||||
.Subscribe();
|
||||
|
||||
if (Interlocked.CompareExchange(ref notificationSubscription, subscription, null) != null)
|
||||
// Subscription has already been created (race condition). Dispose new subscription.
|
||||
subscription.Dispose();
|
||||
}
|
||||
|
||||
~Sharp7Plc()
|
||||
{
|
||||
Dispose(false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ await plc.InitializeConnection();
|
||||
// create an IObservable
|
||||
var observable = plc.CreateNotification<short>($"DB{db}.Int6", Sharp7.Rx.Enums.TransmissionMode.OnChange);
|
||||
|
||||
observable.Dump();
|
||||
_ = observable.Dump();
|
||||
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
|
||||
@@ -20,10 +20,12 @@ using var plc = new Sharp7Plc(ip, rackNumber, cpuMpiAddress);
|
||||
// Initialize connection
|
||||
await plc.InitializeConnection();
|
||||
|
||||
// wait for connection to be established
|
||||
await plc.ConnectionState
|
||||
.FirstAsync(c => c == Sharp7.Rx.Enums.ConnectionState.Connected)
|
||||
.ToTask();
|
||||
// // Alternative: Trigger connection and wait for ConnectionState == Connected
|
||||
// plc.TriggerConnection();
|
||||
// // wait for connection to be established
|
||||
//await plc.ConnectionState
|
||||
// .FirstAsync(c => c == Sharp7.Rx.Enums.ConnectionState.Connected)
|
||||
// .ToTask();
|
||||
|
||||
"Connection established".Dump();
|
||||
|
||||
|
||||
@@ -16,13 +16,13 @@ var cpuMpiAddress = 0;
|
||||
|
||||
using var plc = new Sharp7Plc(ip, rackNumber, cpuMpiAddress);
|
||||
|
||||
plc.ConnectionState.Dump();
|
||||
_ = plc.ConnectionState.Dump();
|
||||
|
||||
await plc.InitializeConnection();
|
||||
|
||||
// create an IObservable
|
||||
plc.CreateNotification<short>($"DB{db}.Int6", Sharp7.Rx.Enums.TransmissionMode.OnChange).Dump("Int 6");
|
||||
plc.CreateNotification<float>($"DB{db}.Real10", Sharp7.Rx.Enums.TransmissionMode.OnChange).Dump("Real 10");
|
||||
_ = plc.CreateNotification<short>($"DB{db}.Int6", Sharp7.Rx.Enums.TransmissionMode.OnChange).Dump("Int 6");
|
||||
_ = plc.CreateNotification<float>($"DB{db}.Real10", Sharp7.Rx.Enums.TransmissionMode.OnChange).Dump("Real 10");
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user