85 lines
2.6 KiB
C#
85 lines
2.6 KiB
C#
using Microsoft.AspNetCore.SignalR;
|
|
using RobotApp.Common.Shares.Dtos;
|
|
using RobotApp.Hubs;
|
|
using RobotApp.Interfaces;
|
|
using RobotApp.VDA5050.State;
|
|
|
|
namespace RobotApp.Services;
|
|
|
|
public class RobotMonitorService(IHubContext<RobotMonitorHub> HubContext,
|
|
IOrder OrderManager,
|
|
ILocalization Localization,
|
|
Logger<RobotMonitorService> Logger) : BackgroundService
|
|
{
|
|
private WatchTimerAsync<RobotMonitorService>? UpdateTimer;
|
|
private const int UpdateInterval = 200; // 200ms
|
|
|
|
private async Task UpdateHandler()
|
|
{
|
|
try
|
|
{
|
|
// Lấy vị trí robot từ ILocalization (giống như RobotVisualization)
|
|
var robotPosition = new RobotPositionDto
|
|
{
|
|
X = Localization.X,
|
|
Y = Localization.Y,
|
|
Theta = Localization.Theta
|
|
};
|
|
|
|
// Kiểm tra có order không
|
|
bool hasOrder = OrderManager.NodeStates.Length > 0 || OrderManager.EdgeStates.Length > 0;
|
|
|
|
// Lấy CurrentPath từ IOrder
|
|
(NodeState[] nodeStates, EdgeStateDto[] edgeStates) = OrderManager.CurrentPath;
|
|
// Tạo DTO
|
|
var monitorDto = new RobotMonitorDto
|
|
{
|
|
RobotPosition = robotPosition,
|
|
NodeStates = nodeStates,
|
|
EdgeStates = [.. edgeStates],
|
|
HasOrder = hasOrder,
|
|
Timestamp = DateTime.UtcNow
|
|
};
|
|
|
|
// Broadcast qua SignalR Hub
|
|
await HubContext.Clients.All.SendAsync("ReceiveRobotMonitorData", monitorDto);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Logger.Warning($"Lỗi khi broadcast robot monitor data: {ex.Message}");
|
|
}
|
|
}
|
|
|
|
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
|
{
|
|
await Task.Yield();
|
|
|
|
// Đợi robot sẵn sàng
|
|
while (!stoppingToken.IsCancellationRequested)
|
|
{
|
|
try
|
|
{
|
|
// Kiểm tra xem Localization có sẵn sàng không
|
|
if (Localization.IsReady) break;
|
|
}
|
|
catch { }
|
|
|
|
await Task.Delay(1000, stoppingToken);
|
|
}
|
|
|
|
if (!stoppingToken.IsCancellationRequested)
|
|
{
|
|
UpdateTimer = new(UpdateInterval, UpdateHandler, Logger);
|
|
UpdateTimer.Start();
|
|
}
|
|
}
|
|
|
|
public override Task StopAsync(CancellationToken cancellationToken)
|
|
{
|
|
UpdateTimer?.Dispose();
|
|
UpdateTimer = null;
|
|
return base.StopAsync(cancellationToken);
|
|
}
|
|
}
|
|
|