initial commit
This commit is contained in:
104
Lab505.Sim/OpcUaSimulationServer.cs
Normal file
104
Lab505.Sim/OpcUaSimulationServer.cs
Normal file
@@ -0,0 +1,104 @@
|
||||
using Opc.Ua;
|
||||
using Opc.Ua.Configuration;
|
||||
using Opc.Ua.Server;
|
||||
|
||||
namespace Lab505.Sim;
|
||||
|
||||
public class OpcUaSimulationServer : IDisposable
|
||||
{
|
||||
private ApplicationInstance? _app;
|
||||
private bool _isRunning;
|
||||
private readonly object _lock = new();
|
||||
|
||||
public bool IsRunning
|
||||
{
|
||||
get { lock (_lock) return _isRunning; }
|
||||
}
|
||||
|
||||
public async Task StartAsync()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (_isRunning)
|
||||
{
|
||||
Console.WriteLine("[OpcUaSim:4840] Already running");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
#pragma warning disable CS0618
|
||||
_app = new ApplicationInstance
|
||||
{
|
||||
ApplicationName = "Lab505OpcUaSim",
|
||||
ApplicationType = ApplicationType.Server,
|
||||
ConfigSectionName = "OpcUaClient"
|
||||
};
|
||||
#pragma warning restore CS0618
|
||||
|
||||
// Load XML
|
||||
await _app.LoadApplicationConfigurationAsync("Quickstarts.ReferenceServer.Config.xml", false);
|
||||
|
||||
// Không cần certificate khi security = None
|
||||
await _app.CheckApplicationInstanceCertificatesAsync(silent: true);
|
||||
|
||||
// Start server custom
|
||||
await _app.StartAsync(new SimulationServer());
|
||||
|
||||
lock (_lock) _isRunning = true;
|
||||
Console.WriteLine("[OpcUaSim:4840] Server started");
|
||||
}
|
||||
|
||||
public async Task StopAsync()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (!_isRunning)
|
||||
{
|
||||
Console.WriteLine("[OpcUaSim:4840] Not running");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (_app != null)
|
||||
{
|
||||
await _app.StopAsync();
|
||||
|
||||
// Give the server time to fully release the port
|
||||
await Task.Delay(500);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"[OpcUaSim:4840] Error stopping: {ex.Message}");
|
||||
}
|
||||
|
||||
_app = null;
|
||||
lock (_lock) _isRunning = false;
|
||||
Console.WriteLine("[OpcUaSim:4840] Server stopped");
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
StopAsync().GetAwaiter().GetResult();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
|
||||
public class SimulationServer : StandardServer
|
||||
{
|
||||
protected override MasterNodeManager CreateMasterNodeManager(
|
||||
IServerInternal server,
|
||||
ApplicationConfiguration config)
|
||||
{
|
||||
return new MasterNodeManager(
|
||||
server,
|
||||
config,
|
||||
null,
|
||||
[
|
||||
new RcsNodeManager(server, config)
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user