提交代码
This commit is contained in:
@@ -0,0 +1,106 @@
|
||||
using HardwareControl.Core;
|
||||
using HardwareControl.Core.HardwareServiceImpl.HardwareService;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace HardwareWeb.Controllers
|
||||
{
|
||||
/// <summary>位移台连接与状态查询。</summary>
|
||||
[ApiController]
|
||||
[Route("api/stage")]
|
||||
public class AxisStageController : ControllerBase
|
||||
{
|
||||
private readonly IAxisStageService _stage;
|
||||
private readonly ILogger<AxisStageController> _logger;
|
||||
|
||||
public AxisStageController(
|
||||
IAxisStageService stage,
|
||||
ILogger<AxisStageController> logger)
|
||||
{
|
||||
_stage = stage;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
[HttpPost("connect")]
|
||||
public async Task<IActionResult> Connect(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _stage.ConnectAsync(ct);
|
||||
return Ok(new
|
||||
{
|
||||
connected = _stage.IsConnected,
|
||||
port = _stage.PortName
|
||||
});
|
||||
}
|
||||
catch (HardwareException ex)
|
||||
{
|
||||
return HardwareError(ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>读取位移台当前状态(一次上传帧)。</summary>
|
||||
[HttpGet("status")]
|
||||
public async Task<IActionResult> Status(CancellationToken ct)
|
||||
{
|
||||
if (!_stage.IsConnected)
|
||||
{
|
||||
return Conflict(new
|
||||
{
|
||||
error = "NotConnected",
|
||||
message = "位移台尚未连接"
|
||||
});
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var status = await _stage.ReadStatusAsync(1000, ct);
|
||||
return Ok(new
|
||||
{
|
||||
x = status.XPosition,
|
||||
y = status.YPosition,
|
||||
z = status.ZPosition,
|
||||
moving = status.AnyMoving,
|
||||
xMoving = status.XMoving,
|
||||
yMoving = status.YMoving,
|
||||
zMoving = status.ZMoving,
|
||||
deviceError = status.DeviceError,
|
||||
updatedAt = DateTimeOffset.Now
|
||||
});
|
||||
}
|
||||
catch (HardwareException ex)
|
||||
{
|
||||
return HardwareError(ex);
|
||||
}
|
||||
}
|
||||
|
||||
private IActionResult HardwareError(HardwareException ex)
|
||||
{
|
||||
var statusCode = ex.Kind switch
|
||||
{
|
||||
HardwareErrorKind.InvalidArgument => StatusCodes.Status400BadRequest,
|
||||
HardwareErrorKind.NotConnected => StatusCodes.Status409Conflict,
|
||||
HardwareErrorKind.Timeout => StatusCodes.Status504GatewayTimeout,
|
||||
HardwareErrorKind.ConnectFailed => StatusCodes.Status503ServiceUnavailable,
|
||||
_ => StatusCodes.Status500InternalServerError,
|
||||
};
|
||||
|
||||
if (statusCode >= 500)
|
||||
{
|
||||
_logger.LogError(ex, "位移台接口失败:{Message}", ex.Message);
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogWarning("位移台接口失败:{Message}", ex.Message);
|
||||
}
|
||||
|
||||
return new ObjectResult(new
|
||||
{
|
||||
error = ex.Kind.ToString(),
|
||||
message = ex.Message
|
||||
})
|
||||
{
|
||||
StatusCode = statusCode
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user