update
This commit is contained in:
52
RobotApp.Client/Services/RobotMonitorService.cs
Normal file
52
RobotApp.Client/Services/RobotMonitorService.cs
Normal file
@@ -0,0 +1,52 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user