using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.SignalR.Client;
using RobotNet10.RobotApp.Client.Shared.Devices;
namespace RobotNet10.RobotApp.Client.Services;
///
/// SignalR client để kết nối với DeviceHub
///
public class DeviceHubClient : IAsyncDisposable
{
private readonly HubConnection _hubConnection;
private bool _disposed;
public event Action? DeviceUpdated;
public event Action? DeviceStatusChanged;
public event Action? ConnectionStateChanged;
public bool IsConnected => _hubConnection.State == HubConnectionState.Connected;
public HubConnectionState ConnectionState => _hubConnection.State;
public DeviceHubClient(NavigationManager navigationManager)
{
var hubUrl = navigationManager.ToAbsoluteUri("/hubs/devices");
_hubConnection = new HubConnectionBuilder()
.WithUrl(hubUrl)
.WithAutomaticReconnect()
.Build();
_hubConnection.On("DeviceUpdated", update => DeviceUpdated?.Invoke(update));
_hubConnection.On("DeviceStatusChanged", (deviceId, status) =>
DeviceStatusChanged?.Invoke(deviceId, status));
_hubConnection.Reconnecting += error =>
{
ConnectionStateChanged?.Invoke(_hubConnection.State);
return Task.CompletedTask;
};
_hubConnection.Reconnected += connectionId =>
{
ConnectionStateChanged?.Invoke(_hubConnection.State);
return Task.CompletedTask;
};
_hubConnection.Closed += error =>
{
ConnectionStateChanged?.Invoke(_hubConnection.State);
return Task.CompletedTask;
};
}
public async Task StartAsync()
{
if (_hubConnection.State == HubConnectionState.Disconnected)
{
await _hubConnection.StartAsync();
ConnectionStateChanged?.Invoke(_hubConnection.State);
}
}
public async Task StopAsync()
{
if (_hubConnection.State != HubConnectionState.Disconnected)
{
await _hubConnection.StopAsync();
ConnectionStateChanged?.Invoke(_hubConnection.State);
}
}
public async Task GetAllDevicesAsync()
{
return await _hubConnection.InvokeAsync("GetAllDevices");
}
public async Task GetDeviceAsync(string deviceId)
{
return await _hubConnection.InvokeAsync("GetDevice", deviceId);
}
public async Task GetDevicesByTypeAsync(DeviceType deviceType)
{
return await _hubConnection.InvokeAsync("GetDevicesByType", deviceType);
}
public async Task GetDeviceCountAsync()
{
return await _hubConnection.InvokeAsync("GetDeviceCount");
}
public async ValueTask DisposeAsync()
{
if (_disposed)
return;
_disposed = true;
await StopAsync();
await _hubConnection.DisposeAsync();
GC.SuppressFinalize(this);
}
}