ResetRobotCommandHandler.cs 1.8 KB
using MassTransit;
using Microsoft.Extensions.Logging;
using Rcs.Application.Common;
using Rcs.Application.MessageBus.Commands;
using Rcs.Application.Services.Protocol;
using Rcs.Domain.Extensions;
using Rcs.Domain.Repositories;

namespace Rcs.Infrastructure.MessageBus.Handlers.Commands;

/// <summary>
/// 复位机器人命令处理器
/// @author zzy
/// </summary>
public class ResetRobotCommandHandler : IConsumer<ResetRobotCommand>
{
    private readonly ILogger<ResetRobotCommandHandler> _logger;
    private readonly IRobotRepository _robotRepository;
    private readonly IProtocolServiceFactory _protocolServiceFactory;

    public ResetRobotCommandHandler(
        ILogger<ResetRobotCommandHandler> logger,
        IRobotRepository robotRepository,
        IProtocolServiceFactory protocolServiceFactory)
    {
        _logger = logger;
        _robotRepository = robotRepository;
        _protocolServiceFactory = protocolServiceFactory;
    }

    public async Task Consume(ConsumeContext<ResetRobotCommand> context)
    {
        var command = context.Message;
        try
        {
            var robot = await _robotRepository.GetByIdAsync(command.RobotId, context.CancellationToken);
            if (robot == null)
            {
                throw new BusinessException($"机器人ID {command.RobotId} 不存在");
            }

            var protocolService = _protocolServiceFactory.GetService(robot);

            // 复位机器人
            await protocolService.ResetRobotAsync(robot, context.CancellationToken);

            await context.RespondAsync(ApiResponse.Successful());
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "复位机器人失败: {RobotId}", command.RobotId);
            await context.RespondAsync(ApiResponse.Failed(ex.Message));
        }
    }
}