using Microsoft.AspNetCore.Mvc;
using WIDESEAWCS_S7Simulator.Core.Entities;
using WIDESEAWCS_S7Simulator.Core.Interfaces;
namespace WIDESEAWCS_S7Simulator.Server.Controllers
{
///
/// 客户端连接管理控制器
///
[ApiController]
[Route("api/[controller]")]
public class ClientsController : ControllerBase
{
private readonly ISimulatorInstanceManager _instanceManager;
private readonly ILogger _logger;
public ClientsController(
ISimulatorInstanceManager instanceManager,
ILogger logger)
{
_instanceManager = instanceManager ?? throw new ArgumentNullException(nameof(instanceManager));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
///
/// 获取连接的客户端列表
///
[HttpGet("GetConnectedClients")]
[ProducesResponseType(typeof(List), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public ActionResult> GetConnectedClients(string id)
{
try
{
if (string.IsNullOrWhiteSpace(id))
{
return BadRequest(new { error = "Instance ID is required" });
}
var instance = _instanceManager.GetInstance(id);
if (instance == null)
{
return NotFound(new { error = $"Instance with ID '{id}' not found" });
}
var state = instance.GetState();
return Ok(state.Clients);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to get clients for instance {InstanceId}", id);
return StatusCode(StatusCodes.Status500InternalServerError, new { error = "Failed to retrieve clients" });
}
}
///
/// 断开指定客户端
///
[HttpDelete("DisconnectClient")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public ActionResult DisconnectClient(string id, string clientId)
{
try
{
if (string.IsNullOrWhiteSpace(id))
{
return BadRequest(new { error = "Instance ID is required" });
}
if (string.IsNullOrWhiteSpace(clientId))
{
return BadRequest(new { error = "Client ID is required" });
}
var instance = _instanceManager.GetInstance(id);
if (instance == null)
{
return NotFound(new { error = $"Instance with ID '{id}' not found" });
}
var state = instance.GetState();
var client = state.Clients.FirstOrDefault(c => c.ClientId == clientId);
if (client == null)
{
return NotFound(new { error = $"Client with ID '{clientId}' not found" });
}
// Note: The actual disconnection logic would need to be implemented in IS7ServerInstance
// For now, we're returning a success response indicating the operation was requested
// In a real implementation, you would call instance.DisconnectClient(clientId)
_logger.LogInformation("Disconnect request for client {ClientId} on instance {InstanceId}", clientId, id);
return Ok(new
{
message = "Client disconnect requested",
clientId = clientId,
instanceId = id,
note = "Actual disconnection logic should be implemented in IS7ServerInstance"
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to disconnect client {ClientId} for instance {InstanceId}", clientId, id);
return StatusCode(StatusCodes.Status500InternalServerError, new { error = "Failed to disconnect client" });
}
}
}
}