62 lines
1.8 KiB
C#
62 lines
1.8 KiB
C#
using Microsoft.Extensions.Hosting;
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
namespace Lab505.Sim;
|
|
|
|
/// <summary>
|
|
/// Hosted service để start/stop các Modbus simulation servers
|
|
/// Port 502: ASRS
|
|
/// Port 503: Conveyor
|
|
/// </summary>
|
|
public class ModbusSimulationHostedService : IHostedService
|
|
{
|
|
private readonly ModbusSimulationServer_ASRS _asrsServer;
|
|
private readonly ConveyorModbusServer _conveyorServer;
|
|
private readonly ILogger<ModbusSimulationHostedService> _logger;
|
|
|
|
public ModbusSimulationHostedService(ILogger<ModbusSimulationHostedService> logger)
|
|
{
|
|
_logger = logger;
|
|
_asrsServer = new ModbusSimulationServer_ASRS(502);
|
|
_conveyorServer = new ConveyorModbusServer(503);
|
|
}
|
|
|
|
public Task StartAsync(CancellationToken cancellationToken)
|
|
{
|
|
_logger.LogInformation("Starting Modbus Simulation Servers...");
|
|
|
|
try
|
|
{
|
|
_asrsServer.Start();
|
|
_logger.LogInformation("✅ ASRS Modbus Simulation Server started on port 502");
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, "❌ Failed to start ASRS Modbus server on port 502");
|
|
}
|
|
|
|
try
|
|
{
|
|
_conveyorServer.Start();
|
|
_logger.LogInformation("✅ Conveyor Modbus Simulation Server started on port 503");
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, "❌ Failed to start Conveyor Modbus server on port 503");
|
|
}
|
|
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
public Task StopAsync(CancellationToken cancellationToken)
|
|
{
|
|
_logger.LogInformation("Stopping Modbus Simulation Servers...");
|
|
|
|
_asrsServer.Stop();
|
|
_conveyorServer.Stop();
|
|
|
|
_logger.LogInformation("✅ All Modbus Simulation Servers stopped");
|
|
|
|
return Task.CompletedTask;
|
|
}
|
|
} |