UnPauseRobotCommandHandler.cs 1.69 KB
using MassTransit;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Rcs.Application.Common;
using Rcs.Application.MessageBus.Commands;
using Rcs.Application.Services.Protocol;
using Rcs.Cyaninetech.Services;
using Rcs.Domain.Extensions;
using Rcs.Domain.Repositories;

namespace Rcs.Infrastructure.MessageBus.Handlers.Commands;

/// <summary>
/// 复位机器人命令处理器
/// @author zzy
/// </summary>
public class UnPauseRobotCommandHandler : IConsumer<UnPauseRobotCommand>
{
    private readonly ILogger<UnPauseRobotCommandHandler> _logger;
    private readonly IRobotRepository _robotRepository;
    private readonly IServiceProvider _serviceProvider;

    public UnPauseRobotCommandHandler(
        ILogger<UnPauseRobotCommandHandler> logger,
        IRobotRepository robotRepository,
        IServiceProvider serviceProvider)
    {
        _logger = logger;
        _robotRepository = robotRepository;
        _serviceProvider = serviceProvider;
    }

    public async Task Consume(ConsumeContext<UnPauseRobotCommand> context)
    {
        var command = context.Message;
        try
        {
            var robot = await _robotRepository.GetByIdAsync(command.RobotId, context.CancellationToken);
            if (robot == null)
            {
                throw new BusinessException($"机器人ID {command.RobotId} 不存在");
            }
            robot.UnPause();
            await context.RespondAsync(ApiResponse.Successful());
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "取消暂停机器人失败: {RobotId}", command.RobotId);
            await context.RespondAsync(ApiResponse.Failed(ex.Message));
        }
    }
}