Initial commit
This commit is contained in:
@@ -0,0 +1,92 @@
|
||||
using Microsoft.AspNetCore.Components;
|
||||
using Microsoft.AspNetCore.SignalR.Client;
|
||||
using RobotNet10.RobotApp.Client.Shared.Plc;
|
||||
|
||||
namespace RobotNet10.RobotApp.Client.Clients;
|
||||
|
||||
/// <summary>
|
||||
/// SignalR client để kết nối với PlcControllerHub (read-only)
|
||||
/// </summary>
|
||||
public class PlcControllerHubClient : IAsyncDisposable
|
||||
{
|
||||
private readonly HubConnection _hubConnection;
|
||||
private bool _disposed;
|
||||
|
||||
public bool IsConnected => _hubConnection.State == HubConnectionState.Connected;
|
||||
public HubConnectionState ConnectionState => _hubConnection.State;
|
||||
|
||||
/// <summary>
|
||||
/// Event fired when connection state changes
|
||||
/// </summary>
|
||||
public event Action<HubConnectionState>? ConnectionStateChanged;
|
||||
|
||||
public PlcControllerHubClient(NavigationManager navigationManager)
|
||||
{
|
||||
var hubUrl = navigationManager.ToAbsoluteUri("/hubs/plc/controller");
|
||||
|
||||
_hubConnection = new HubConnectionBuilder()
|
||||
.WithUrl(hubUrl)
|
||||
.WithAutomaticReconnect()
|
||||
.Build();
|
||||
|
||||
_hubConnection.Reconnecting += async (ex) =>
|
||||
{
|
||||
ConnectionStateChanged?.Invoke(_hubConnection.State);
|
||||
await Task.CompletedTask;
|
||||
};
|
||||
|
||||
_hubConnection.Reconnected += async (id) =>
|
||||
{
|
||||
ConnectionStateChanged?.Invoke(_hubConnection.State);
|
||||
await Task.CompletedTask;
|
||||
};
|
||||
|
||||
_hubConnection.Closed += async (ex) =>
|
||||
{
|
||||
ConnectionStateChanged?.Invoke(_hubConnection.State);
|
||||
await Task.CompletedTask;
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Connect to hub
|
||||
/// </summary>
|
||||
public async Task StartAsync()
|
||||
{
|
||||
if (_hubConnection.State == HubConnectionState.Disconnected)
|
||||
{
|
||||
await _hubConnection.StartAsync();
|
||||
ConnectionStateChanged?.Invoke(_hubConnection.State);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disconnect from hub
|
||||
/// </summary>
|
||||
public async Task StopAsync()
|
||||
{
|
||||
if (_hubConnection.State != HubConnectionState.Disconnected)
|
||||
{
|
||||
await _hubConnection.StopAsync();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get current status
|
||||
/// </summary>
|
||||
public async Task<PlcControllerStatusDto> GetStatusAsync()
|
||||
{
|
||||
return await _hubConnection.InvokeAsync<PlcControllerStatusDto>("GetStatus");
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (_disposed)
|
||||
return;
|
||||
|
||||
_disposed = true;
|
||||
|
||||
await StopAsync();
|
||||
await _hubConnection.DisposeAsync();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user