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? 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("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(); } }