RobotApp/RobotApp.Client/Services/RobotMonitorService.cs
Đăng Nguyễn 062a6478ce update
2025-12-20 17:37:22 +07:00

53 lines
1.3 KiB
C#

using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.SignalR.Client;
using RobotApp.Common.Shares.Dtos;
namespace RobotApp.Client.Services;
public class RobotMonitorService : IAsyncDisposable
{
private HubConnection? _hubConnection;
private readonly string _hubUrl;
public event Action<RobotMonitorDto>? OnDataReceived;
public bool IsConnected => _hubConnection?.State == HubConnectionState.Connected;
public RobotMonitorService(NavigationManager navigationManager)
{
var baseUrl = navigationManager.BaseUri.TrimEnd('/');
_hubUrl = $"{baseUrl}/hubs/robotMonitor";
}
public async Task StartAsync()
{
if (_hubConnection is not null) return;
_hubConnection = new HubConnectionBuilder()
.WithUrl(_hubUrl)
.WithAutomaticReconnect()
.Build();
_hubConnection.On<RobotMonitorDto>("ReceiveRobotMonitorData", data =>
{
OnDataReceived?.Invoke(data);
});
await _hubConnection.StartAsync();
}
public async Task StopAsync()
{
if (_hubConnection is null) return;
await _hubConnection.StopAsync();
await _hubConnection.DisposeAsync();
_hubConnection = null;
}
public async ValueTask DisposeAsync()
{
await StopAsync();
}
}