Skip to content

Commit

Permalink
Apply analyzer suggestions (#383)
Browse files Browse the repository at this point in the history
* Apply analyzer suggestions

* Apply more suggestions

* Apply suggestion
  • Loading branch information
luiscantero authored Aug 1, 2024
1 parent ef2454e commit 87a000a
Show file tree
Hide file tree
Showing 27 changed files with 69 additions and 70 deletions.
4 changes: 2 additions & 2 deletions src/Configuration/OpcApplicationConfiguration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,12 @@ public string Hostname
/// <summary>
/// Enables unsecure endpoint access to the application.
/// </summary>
public bool EnableUnsecureTransport { get; set; } = false;
public bool EnableUnsecureTransport { get; set; }

/// <summary>
/// Sets the LDS registration interval in milliseconds.
/// </summary>
public int LdsRegistrationInterval { get; set; } = 0;
public int LdsRegistrationInterval { get; set; }

/// <summary>
/// Set the max string length the OPC stack supports.
Expand Down
11 changes: 6 additions & 5 deletions src/DeterministicAlarms/DeterministicAlarmsNodeManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,13 @@ namespace OpcPlc.DeterministicAlarms;
using System;
using System.Collections.Generic;
using System.IO;

using System.Linq;

public class DeterministicAlarmsNodeManager : CustomNodeManager2
{
private readonly SimBackendService _system;
private readonly List<SimFolderState> _folders = new();
private uint _nodeIdCounter = 0;
private uint _nodeIdCounter;
private List<NodeState> _rootNotifiers;
private readonly IServerInternal _server;
private readonly ServerSystemContext _defaultSystemContext;
Expand Down Expand Up @@ -119,11 +120,11 @@ private void ReplayScriptStart(Configuration.Configuration scriptConfiguration)
{
VerifyScriptConfiguration(scriptConfiguration);
_logger.LogInformation("Script starts executing");
var scriptEngine = new ScriptEngine(scriptConfiguration.Script, OnScriptStepAvailable, _timeService);
_ = new ScriptEngine(scriptConfiguration.Script, OnScriptStepAvailable, _timeService);
}
catch (ScriptException ex)
{
_logger.LogError($"Script Engine Exception '{ex.Message}'\nSCRIPT WILL NOT START");
_logger.LogError(ex, $"Script Engine Exception '{ex.Message}'\nSCRIPT WILL NOT START");
throw;
}
}
Expand Down Expand Up @@ -512,7 +513,7 @@ public override ServiceResult ConditionRefresh(
OperationContext context,
IList<IEventMonitoredItem> monitoredItems)
{
foreach (MonitoredItem monitoredItem in monitoredItems)
foreach (var monitoredItem in monitoredItems.Cast<MonitoredItem>())
{
if (monitoredItem == null)
{
Expand Down
2 changes: 1 addition & 1 deletion src/Helpers/MetricsHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ public static void AddMonitoredItemCount(int delta = 1)
/// <summary>
/// Add a published count.
/// </summary>
public static void AddPublishedCount(string sessionId, string subscriptionId, int dataChanges, int events)
public static void AddPublishedCount(int dataChanges, int events)
{
if (!IsEnabled)
{
Expand Down
2 changes: 1 addition & 1 deletion src/Helpers/PnJsonHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public static async Task PrintPublisherConfigJsonAsync(string pnJsonFileName, st
sb.AppendLine("]");

string pnJson = sb.ToString();
logger.LogInformation("OPC Publisher configuration file: {pnJsonFile}", $"{pnJsonFileName}{pnJson}");
logger.LogInformation("OPC Publisher configuration file: {PnJsonFile}", $"{pnJsonFileName}{pnJson}");

await File.WriteAllTextAsync(pnJsonFileName, pnJson.Trim()).ConfigureAwait(false);
}
Expand Down
28 changes: 14 additions & 14 deletions src/OpcPlcServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ public async Task StartAsync(string[] args, CancellationToken cancellationToken
// Validate and parse extra arguments.
if (extraArgs.Count > 0)
{
Logger.LogWarning($"Found one or more invalid command line arguments: {string.Join(" ", extraArgs)}");
Logger.LogWarning("Found one or more invalid command line arguments: {InvalidArgs}", string.Join(" ", extraArgs));
Logger.LogInformation(CliOptions.GetUsageHelp(Config.ProgramName));
}

Expand Down Expand Up @@ -196,20 +196,20 @@ private void StartWebServer(IHost host)

if (Config.ShowPublisherConfigJsonIp)
{
Logger.LogInformation("Web server started: {pnJsonUri}", $"http://{GetIpAddress()}:{Config.WebServerPort}/{Config.PnJson}");
Logger.LogInformation("Web server started: {PnJsonUri}", $"http://{GetIpAddress()}:{Config.WebServerPort}/{Config.PnJson}");
}
else if (Config.ShowPublisherConfigJsonPh)
{
Logger.LogInformation("Web server started: {pnJsonUri}", $"http://{Config.OpcUa.Hostname}:{Config.WebServerPort}/{Config.PnJson}");
Logger.LogInformation("Web server started: {PnJsonUri}", $"http://{Config.OpcUa.Hostname}:{Config.WebServerPort}/{Config.PnJson}");
}
else
{
Logger.LogInformation("Web server started on port {webServerPort}", Config.WebServerPort);
Logger.LogInformation("Web server started on port {WebServerPort}", Config.WebServerPort);
}
}
catch (Exception e)
{
Logger.LogError("Could not start web server on port {webServerPort}: {message}",
Logger.LogError(e, "Could not start web server on port {WebServerPort}: {Message}",
Config.WebServerPort,
e.Message);
}
Expand Down Expand Up @@ -289,22 +289,22 @@ private async Task StartPlcServerAndSimulationAsync()
ApplicationConfiguration plcApplicationConfiguration = await opcUaAppConfigFactory.ConfigureAsync().ConfigureAwait(false);

// start the server.
Logger.LogInformation("Starting server on endpoint {endpoint} ...", plcApplicationConfiguration.ServerConfiguration.BaseAddresses[0]);
Logger.LogInformation("Starting server on endpoint {Endpoint} ...", plcApplicationConfiguration.ServerConfiguration.BaseAddresses[0]);
Logger.LogInformation("Simulation settings are:");
Logger.LogInformation("One simulation phase consists of {SimulationCycleCount} cycles", PlcSimulationInstance.SimulationCycleCount);
Logger.LogInformation("One cycle takes {SimulationCycleLength} ms", PlcSimulationInstance.SimulationCycleLength);
Logger.LogInformation("Reference test simulation: {addReferenceTestSimulation}",
Logger.LogInformation("Reference test simulation: {AddReferenceTestSimulation}",
PlcSimulationInstance.AddReferenceTestSimulation ? "Enabled" : "Disabled");
Logger.LogInformation("Simple events: {addSimpleEventsSimulation}",
Logger.LogInformation("Simple events: {AddSimpleEventsSimulation}",
PlcSimulationInstance.AddSimpleEventsSimulation ? "Enabled" : "Disabled");
Logger.LogInformation("Alarms: {addAlarmSimulation}", PlcSimulationInstance.AddAlarmSimulation ? "Enabled" : "Disabled");
Logger.LogInformation("Deterministic alarms: {deterministicAlarmSimulation}",
Logger.LogInformation("Alarms: {AddAlarmSimulation}", PlcSimulationInstance.AddAlarmSimulation ? "Enabled" : "Disabled");
Logger.LogInformation("Deterministic alarms: {DeterministicAlarmSimulation}",
PlcSimulationInstance.DeterministicAlarmSimulationFile != null ? "Enabled" : "Disabled");

Logger.LogInformation("Anonymous authentication: {anonymousAuth}", Config.DisableAnonymousAuth ? "Disabled" : "Enabled");
Logger.LogInformation("Reject chain validation with CA certs with unknown revocation status: {rejectValidationUnknownRevocStatus}", Config.OpcUa.DontRejectUnknownRevocationStatus ? "Disabled" : "Enabled");
Logger.LogInformation("Username/Password authentication: {usernamePasswordAuth}", Config.DisableUsernamePasswordAuth ? "Disabled" : "Enabled");
Logger.LogInformation("Certificate authentication: {certAuth}", Config.DisableCertAuth ? "Disabled" : "Enabled");
Logger.LogInformation("Anonymous authentication: {AnonymousAuth}", Config.DisableAnonymousAuth ? "Disabled" : "Enabled");
Logger.LogInformation("Reject chain validation with CA certs with unknown revocation status: {RejectValidationUnknownRevocStatus}", Config.OpcUa.DontRejectUnknownRevocationStatus ? "Disabled" : "Enabled");
Logger.LogInformation("Username/Password authentication: {UsernamePasswordAuth}", Config.DisableUsernamePasswordAuth ? "Disabled" : "Enabled");
Logger.LogInformation("Certificate authentication: {CertAuth}", Config.DisableCertAuth ? "Disabled" : "Enabled");

// Add simple events, alarms, reference test simulation and deterministic alarms.
PlcServer = new PlcServer(Config, PlcSimulationInstance, TimeService, _pluginNodes, Logger);
Expand Down
4 changes: 2 additions & 2 deletions src/PlcNodeManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ private BaseDataVariableState CreateBaseVariable(BaseDataVariableState baseDataV
{
ushort namespaceIndex = NamespaceIndexes[(int)namespaceType];

if (path is uint || path is long)
if (path is uint or long)
{
baseDataVariableState.NodeId = new NodeId((uint)path, namespaceIndex);
baseDataVariableState.BrowseName = new QualifiedName(((uint)path).ToString(), namespaceIndex);
Expand All @@ -195,7 +195,7 @@ private BaseDataVariableState CreateBaseVariable(BaseDataVariableState baseDataV
}
else
{
_logger.LogDebug("NodeId type is {nodeIdType}", (string)path.GetType().ToString());
_logger.LogDebug("NodeId type is {NodeIdType}", (string)path.GetType().ToString());
baseDataVariableState.NodeId = new NodeId(path, namespaceIndex);
baseDataVariableState.BrowseName = new QualifiedName(name, namespaceIndex);
}
Expand Down
10 changes: 5 additions & 5 deletions src/PlcServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ public override ResponseHeader Publish(

if (PublishMetricsEnabled)
{
AddPublishMetrics(notificationMessage, context.SessionId.ToString(), subscriptionId.ToString());
AddPublishMetrics(notificationMessage);
}

LogSuccessWithSessionIdAndSubscriptionId(
Expand Down Expand Up @@ -431,13 +431,13 @@ protected override MasterNodeManager CreateMasterNodeManager(IServerInternal ser
{
string errorMessage = "The script file for deterministic testing is not set (deterministicalarms)";
LogErrorMessage(errorMessage);
throw new Exception(errorMessage);
throw new ArgumentNullException(errorMessage);
}
if (!File.Exists(scriptFileName))
{
string errorMessage = $"The script file ({scriptFileName}) for deterministic testing does not exist";
LogErrorMessage(errorMessage);
throw new Exception(errorMessage);
throw new InvalidOperationException(errorMessage);
}

DeterministicAlarmsNodeManager = new DeterministicAlarmsNodeManager(server, configuration, TimeService, scriptFileName, _logger);
Expand Down Expand Up @@ -574,7 +574,7 @@ protected override void OnServerStopping()
base.OnServerStopping();
}

private void AddPublishMetrics(NotificationMessage notificationMessage, string sessionId, string subscriptionId)
private void AddPublishMetrics(NotificationMessage notificationMessage)
{
int events = 0;
int dataChanges = 0;
Expand All @@ -596,7 +596,7 @@ private void AddPublishMetrics(NotificationMessage notificationMessage, string s
}
});

MetricsHelper.AddPublishedCount(sessionId, subscriptionId, dataChanges, events);
MetricsHelper.AddPublishedCount(dataChanges, events);
}

[LoggerMessage(
Expand Down
4 changes: 2 additions & 2 deletions src/PlcSimulation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public PlcSimulation(ImmutableList<IPluginNodes> pluginNodes)
public bool AddReferenceTestSimulation { get; set; } = true;
public string DeterministicAlarmSimulationFile { get; set; }

public uint EventInstanceCount { get; set; } = 0;
public uint EventInstanceCount { get; set; }
public uint EventInstanceRate { get; set; } = 1000; // ms.

/// <summary>
Expand Down Expand Up @@ -128,5 +128,5 @@ private void Disable(ITimer timer)
private PlcServer _plcServer;

private ITimer _eventInstanceGenerator;
private uint _eventInstanceCycle = 0;
private uint _eventInstanceCycle;
}
2 changes: 1 addition & 1 deletion src/PluginNodes/Boiler2PluginNodes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public class Boiler2PluginNodes(TimeService timeService, ILogger logger) : Plugi
private TimeSpan _maintenanceInterval = TimeSpan.FromSeconds(300); // 5 min.
private TimeSpan _overheatInterval = TimeSpan.FromSeconds(120); // 2 min.

private bool _isOverheated = false;
private bool _isOverheated;
private readonly SemaphoreSlim _lock = new(1, 1);

public void AddOptions(Mono.Options.OptionSet optionSet)
Expand Down
6 changes: 3 additions & 3 deletions src/PluginNodes/FastPluginNodes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,14 @@ public class FastPluginNodes(TimeService timeService, ILogger logger) : PluginNo
private NodeType NodeType { get; set; } = NodeType.UInt;
private string NodeMinValue { get; set; }
private string NodeMaxValue { get; set; }
private bool NodeRandomization { get; set; } = false;
private bool NodeRandomization { get; set; }
private string NodeStepSize { get; set; } = "1";
private uint NodeSamplingInterval { get; set; } // ms.

private PlcNodeManager _plcNodeManager;
private SlowFastCommon _slowFastCommon;
protected BaseDataVariableState[] _nodes = null;
protected BaseDataVariableState[] _badNodes = null;
protected BaseDataVariableState[] _nodes;
protected BaseDataVariableState[] _badNodes;
private ITimer _nodeGenerator;
private bool _updateNodes = true;

Expand Down
8 changes: 4 additions & 4 deletions src/PluginNodes/SlowFastCommon.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public class SlowFastCommon

private readonly Random _random = new();
private BaseDataVariableState _numberOfUpdates;
private uint _badNodesCycle = 0;
private uint _badNodesCycle;
private const string NumberOfUpdates = "NumberOfUpdates";

public SlowFastCommon(PlcNodeManager plcNodeManager, TimeService timeService, ILogger logger)
Expand Down Expand Up @@ -43,8 +43,8 @@ private BaseDataVariableState[] CreateBaseLoadNodes(FolderState folder, string n

if (count > 0)
{
_logger.LogInformation($"Creating {count} {name} nodes of type: {type}");
_logger.LogInformation($"Node values will change every {nodeRate} ms");
_logger.LogInformation("Creating {Count} {Name} nodes of type: {Type}", count, name, type);
_logger.LogInformation("Node values will change every {NodeRate} ms", nodeRate);
}

for (int i = 0; i < count; i++)
Expand Down Expand Up @@ -140,7 +140,7 @@ private void UpdateNodes(BaseDataVariableState[] nodes, NodeType type, StatusCod
{
if (nodes == null || nodes.Length == 0)
{
_logger.LogWarning("Invalid argument {argument} provided.", nodes);
_logger.LogWarning("Invalid argument {Argument} provided.", nodes);
return;
}

Expand Down
6 changes: 3 additions & 3 deletions src/PluginNodes/SlowPluginNodes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,14 @@ public class SlowPluginNodes(TimeService timeService, ILogger logger) : PluginNo
private NodeType NodeType { get; set; } = NodeType.UInt;
private string NodeMinValue { get; set; }
private string NodeMaxValue { get; set; }
private bool NodeRandomization { get; set; } = false;
private bool NodeRandomization { get; set; }
private string NodeStepSize { get; set; } = "1";
private uint NodeSamplingInterval { get; set; } // ms.

private PlcNodeManager _plcNodeManager;
private SlowFastCommon _slowFastCommon;
protected BaseDataVariableState[] _nodes = null;
protected BaseDataVariableState[] _badNodes = null;
protected BaseDataVariableState[] _nodes;
protected BaseDataVariableState[] _badNodes;
private ITimer _nodeGenerator;
private bool _updateNodes = true;

Expand Down
12 changes: 5 additions & 7 deletions src/TimeService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -99,9 +99,7 @@ public interface ITimer : IDisposable
void Close();
}

public class FastTimerElapsedEventArgs : EventArgs
{
}
public class FastTimerElapsedEventArgs : EventArgs;

public delegate void FastTimerElapsedEventHandler(object sender, FastTimerElapsedEventArgs e);

Expand Down Expand Up @@ -151,8 +149,8 @@ public bool Enabled
/// <summary>
/// The current interval between triggering of this timer
/// </summary>
public double Interval { get; set; } = 0.0;

public double Interval { get; set; }

/// <summary>
/// The event handler we call when the timer is triggered
/// </summary>
Expand Down Expand Up @@ -268,6 +266,6 @@ public void Dispose()

private static readonly float _tickFrequency = 1000f / Stopwatch.Frequency;

private bool _isEnabled = false;
private int _isRunning = 0;
private bool _isEnabled;
private int _isRunning;
}
2 changes: 1 addition & 1 deletion tests/AlarmTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ public class AlarmTests : SubscriptionTestsBase
{
private NodeId _eventType;

public AlarmTests() : base(new[] { "--alm" })
public AlarmTests() : base(["--alm"])
{
}

Expand Down
4 changes: 2 additions & 2 deletions tests/Boiler2DeviceHealthEventsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,13 @@ public class Boiler2DeviceHealthEventsTests : SubscriptionTestsBase
{
private NodeId _eventType;

public Boiler2DeviceHealthEventsTests() : base(new[] {
public Boiler2DeviceHealthEventsTests() : base([
"--b2ts=5", // Temperature change speed.
"--b2bt=1", // Base temperature.
"--b2tt=123", // Target temperature.
"--b2mi=567", // Maintenance interval.
"--b2oi=678", // Overheat interval.
})
])
{
}

Expand Down
4 changes: 2 additions & 2 deletions tests/Boiler2Tests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,13 @@ namespace OpcPlc.Tests;
[TestFixture]
public class Boiler2Tests : SimulatorTestsBase
{
public Boiler2Tests() : base(new[] {
public Boiler2Tests() : base([
"--b2ts=5", // Temperature change speed.
"--b2bt=1", // Base temperature.
"--b2tt=123", // Target temperature.
"--b2mi=567", // Maintenance interval.
"--b2oi=678", // Overheat interval.
})
])
{
}

Expand Down
2 changes: 1 addition & 1 deletion tests/BoilerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ namespace OpcPlc.Tests;
public class BoilerTests : SimulatorTestsBase
{
private ComplexTypeSystem _complexTypeSystem;
public BoilerTests() : base(new[] { "--ctb" })
public BoilerTests() : base(["--ctb"])
{
}

Expand Down
2 changes: 1 addition & 1 deletion tests/DataRandomizationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
public class DataRandomizationTests : SubscriptionTestsBase
{
// Set any cmd params needed for the plc server explicitly
public DataRandomizationTests() : base(new[] { "--str=true" })
public DataRandomizationTests() : base(["--str=true"])
{
}

Expand Down
6 changes: 3 additions & 3 deletions tests/DeterministicAlarmsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,10 @@ public class DeterministicAlarmsTests : SubscriptionTestsBase
private static readonly LocalizedText Disabled = English("Disabled");
private static readonly LocalizedText Enabled = English("Enabled");

public DeterministicAlarmsTests() : base(new[]
{
public DeterministicAlarmsTests() : base(
[
"--dalm=DeterministicAlarmsTests/dalm001.json",
})
])
{
}

Expand Down
Loading

0 comments on commit 87a000a

Please sign in to comment.