ReLocationCommandHandler.cs 2.49 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 ReLocationCommandHandler : IConsumer<RelocationCommand>
{
    private readonly ILogger<ReLocationCommandHandler> _logger;
    private readonly IProtocolServiceFactory _protocolServiceFactory;
    private readonly IRobotRepository _robotRepository;
    private readonly IMapRepository _mapRepository;

    public ReLocationCommandHandler(
        ILogger<ReLocationCommandHandler> logger,
        IRobotRepository robotRepository,
        IProtocolServiceFactory protocolServiceFactory,
        IMapRepository mapRepository)
    {
        _logger = logger;
        _robotRepository = robotRepository;
        _protocolServiceFactory =  protocolServiceFactory;
        _mapRepository =  mapRepository;
    }

    public async Task Consume(ConsumeContext<RelocationCommand> 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 map = await _mapRepository.GetByIdAsync(robot.CurrentMapCodeId, context.CancellationToken);
            if (map == null)
            {
                throw new BusinessException($"请先维护机器人{robot.RobotCode}所属地图");
            }
            var protocolService = _protocolServiceFactory.GetService(robot);

            var protocol = _protocolServiceFactory.GetService(robot);
            var result = await protocol.ReLocationAsync(robot, 
                map.MapCode,
                command.X, 
                command.Y, 
                command.Theta, 
                context.CancellationToken);
            
            
            await context.RespondAsync(ApiResponse.Successful());
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "取消机器人任务失败: {RobotId}", command.RobotId);
            await context.RespondAsync(ApiResponse.Failed(ex.Message));
        }
    }
}