2026-06-10 15:54:30 +08:00
|
|
|
using Microsoft.AspNetCore.Mvc;
|
2026-06-02 10:30:05 +08:00
|
|
|
using YD_TrainingCompetition_Api.Serial;
|
|
|
|
|
|
|
|
|
|
namespace YD_TrainingCompetition_Api.Controllers;
|
|
|
|
|
|
|
|
|
|
[ApiController]
|
|
|
|
|
[Route("api/[controller]")]
|
2026-06-10 15:54:30 +08:00
|
|
|
// SerialController 给前端提供串口管理入口:
|
|
|
|
|
// 查询串口列表、查看状态、手动打开和关闭串口。
|
2026-06-02 10:30:05 +08:00
|
|
|
public sealed class SerialController : ControllerBase
|
|
|
|
|
{
|
|
|
|
|
private readonly ISerialGateway _serial;
|
|
|
|
|
|
|
|
|
|
public SerialController(ISerialGateway serial)
|
|
|
|
|
{
|
|
|
|
|
_serial = serial;
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-10 15:54:30 +08:00
|
|
|
// 返回当前机器所有可见串口,供配置页下拉框选择。
|
2026-06-02 10:30:05 +08:00
|
|
|
[HttpGet("ports")]
|
|
|
|
|
public IActionResult GetPorts() => Ok(_serial.GetAvailablePorts());
|
|
|
|
|
|
2026-06-10 15:54:30 +08:00
|
|
|
// 返回当前串口连接状态,便于前端展示“已连接/未连接”。
|
2026-06-02 10:30:05 +08:00
|
|
|
[HttpGet("status")]
|
|
|
|
|
public IActionResult GetStatus() => Ok(new { isOpen = _serial.IsOpen, port = _serial.CurrentPort });
|
|
|
|
|
|
2026-06-10 15:54:30 +08:00
|
|
|
// 手动切换到指定串口。
|
2026-06-02 10:30:05 +08:00
|
|
|
[HttpPost("open/{portName}")]
|
|
|
|
|
public async Task<IActionResult> Open(string portName, CancellationToken cancellationToken)
|
|
|
|
|
{
|
|
|
|
|
await _serial.OpenAsync(portName, cancellationToken);
|
|
|
|
|
return Ok(new { message = "opened", port = portName });
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-10 15:54:30 +08:00
|
|
|
// 主动关闭当前已打开的串口。
|
2026-06-02 10:30:05 +08:00
|
|
|
[HttpPost("close")]
|
|
|
|
|
public async Task<IActionResult> Close(CancellationToken cancellationToken)
|
|
|
|
|
{
|
|
|
|
|
await _serial.CloseAsync(cancellationToken);
|
|
|
|
|
return Ok(new { message = "closed" });
|
|
|
|
|
}
|
|
|
|
|
}
|