save
This commit is contained in:
@@ -7,40 +7,61 @@ using System.Text.Json;
|
||||
|
||||
namespace RobotApp.Client.Services;
|
||||
|
||||
public class RobotStateClient : IAsyncDisposable
|
||||
// ================= CONNECTION STATE =================
|
||||
public enum RobotClientState
|
||||
{
|
||||
Disconnected,
|
||||
Connecting,
|
||||
Connected,
|
||||
Reconnecting
|
||||
}
|
||||
|
||||
// ================= CLIENT =================
|
||||
public sealed class RobotStateClient : IAsyncDisposable
|
||||
{
|
||||
private readonly NavigationManager _nav;
|
||||
private HubConnection? _connection;
|
||||
private bool _started;
|
||||
|
||||
private readonly object _lock = new();
|
||||
private bool _started;
|
||||
|
||||
public ConcurrentDictionary<string, StateMsg> LatestStates { get; } = new();
|
||||
|
||||
// ================= EVENTS =================
|
||||
public event Action<string, StateMsg>? OnStateReceived;
|
||||
public event Action<StateMsg>? OnStateReceivedAny;
|
||||
public event Action<RobotClientState>? OnConnectionStateChanged;
|
||||
|
||||
public RobotClientState ConnectionState { get; private set; } = RobotClientState.Disconnected;
|
||||
|
||||
// ================= CTOR =================
|
||||
public RobotStateClient(NavigationManager nav)
|
||||
{
|
||||
_nav = nav;
|
||||
}
|
||||
|
||||
// ================= STATE HELPER =================
|
||||
private void SetState(RobotClientState state)
|
||||
{
|
||||
if (ConnectionState == state) return;
|
||||
|
||||
ConnectionState = state;
|
||||
OnConnectionStateChanged?.Invoke(state);
|
||||
}
|
||||
|
||||
// ================= START =================
|
||||
public async Task StartAsync(string hubPath = "/hubs/robot")
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (_started)
|
||||
return;
|
||||
|
||||
if (_started) return;
|
||||
_started = true;
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(hubPath))
|
||||
throw new ArgumentException("Hub path is empty", nameof(hubPath));
|
||||
|
||||
var hubUri = _nav.ToAbsoluteUri(hubPath);
|
||||
Console.WriteLine($"[SIGNALR] Connecting to {hubUri}");
|
||||
SetState(RobotClientState.Connecting);
|
||||
|
||||
_connection = new HubConnectionBuilder()
|
||||
.WithUrl(hubUri)
|
||||
.WithUrl(_nav.ToAbsoluteUri(hubPath))
|
||||
.WithAutomaticReconnect(new[]
|
||||
{
|
||||
TimeSpan.Zero,
|
||||
@@ -49,11 +70,21 @@ public class RobotStateClient : IAsyncDisposable
|
||||
})
|
||||
.Build();
|
||||
|
||||
_connection.Reconnecting += _ =>
|
||||
{
|
||||
SetState(RobotClientState.Reconnecting);
|
||||
return Task.CompletedTask;
|
||||
};
|
||||
|
||||
_connection.Reconnected += _ =>
|
||||
{
|
||||
SetState(RobotClientState.Connected);
|
||||
return Task.CompletedTask;
|
||||
};
|
||||
|
||||
_connection.Closed += async error =>
|
||||
{
|
||||
Console.WriteLine($"[SIGNALR] Connection closed: {error?.Message}");
|
||||
_started = false;
|
||||
await Task.Delay(3000);
|
||||
|
||||
if (_connection != null)
|
||||
{
|
||||
@@ -65,95 +96,93 @@ public class RobotStateClient : IAsyncDisposable
|
||||
}
|
||||
};
|
||||
|
||||
_connection.Reconnecting += error =>
|
||||
{
|
||||
Console.WriteLine($"[SIGNALR] Reconnecting... {error?.Message}");
|
||||
return Task.CompletedTask;
|
||||
};
|
||||
|
||||
_connection.Reconnected += connectionId =>
|
||||
{
|
||||
Console.WriteLine($"[SIGNALR] Reconnected: {connectionId}");
|
||||
return Task.CompletedTask;
|
||||
};
|
||||
|
||||
_connection.On<string>("ReceiveState", stateJson =>
|
||||
{
|
||||
try
|
||||
{
|
||||
var state = JsonSerializer.Deserialize<StateMsg>(
|
||||
stateJson,
|
||||
JsonOptionExtends.Read
|
||||
);
|
||||
|
||||
if (state?.SerialNumber == null)
|
||||
return;
|
||||
|
||||
LatestStates[state.SerialNumber] = state;
|
||||
|
||||
OnStateReceived?.Invoke(state.SerialNumber, state);
|
||||
OnStateReceivedAny?.Invoke(state);
|
||||
|
||||
Console.WriteLine(
|
||||
$"[CLIENT] {state.SerialNumber} | " +
|
||||
$"X={state.AgvPosition?.X:F2}, " +
|
||||
$"Y={state.AgvPosition?.Y:F2}, " +
|
||||
$"Battery={state.BatteryState?.BatteryCharge:F1}%"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"[CLIENT] Deserialize error: {ex.Message}");
|
||||
}
|
||||
});
|
||||
_connection.On<string>("ReceiveState", HandleState);
|
||||
|
||||
try
|
||||
{
|
||||
await _connection.StartAsync();
|
||||
Console.WriteLine("[SIGNALR] Connected successfully!");
|
||||
SetState(RobotClientState.Connected);
|
||||
}
|
||||
catch (Exception ex)
|
||||
catch
|
||||
{
|
||||
_started = false;
|
||||
Console.WriteLine($"❌ [SIGNALR] Connection failed: {ex.Message}");
|
||||
SetState(RobotClientState.Disconnected);
|
||||
}
|
||||
}
|
||||
|
||||
// ================= HANDLE STATE =================
|
||||
private void HandleState(string stateJson)
|
||||
{
|
||||
StateMsg? state;
|
||||
|
||||
try
|
||||
{
|
||||
state = JsonSerializer.Deserialize<StateMsg>(
|
||||
stateJson,
|
||||
JsonOptionExtends.Read
|
||||
);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (state?.SerialNumber == null)
|
||||
return;
|
||||
|
||||
LatestStates[state.SerialNumber] = state;
|
||||
|
||||
OnStateReceived?.Invoke(state.SerialNumber, state);
|
||||
OnStateReceivedAny?.Invoke(state);
|
||||
}
|
||||
|
||||
// ================= SUBSCRIBE =================
|
||||
public async Task SubscribeRobotAsync(string serialNumber)
|
||||
{
|
||||
if (_connection?.State != HubConnectionState.Connected)
|
||||
throw new InvalidOperationException("SignalR is not connected");
|
||||
return;
|
||||
|
||||
await _connection.InvokeAsync("JoinRobot", serialNumber);
|
||||
Console.WriteLine($"[SIGNALR] Subscribed to {serialNumber}");
|
||||
try
|
||||
{
|
||||
await _connection.InvokeAsync("JoinRobot", serialNumber);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// ignore – reconnect sẽ tự join lại
|
||||
}
|
||||
}
|
||||
|
||||
public async Task UnsubscribeRobotAsync(string serialNumber)
|
||||
{
|
||||
if (_connection?.State == HubConnectionState.Connected)
|
||||
{
|
||||
await _connection.InvokeAsync("LeaveRobot", serialNumber);
|
||||
try
|
||||
{
|
||||
await _connection.InvokeAsync("LeaveRobot", serialNumber);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
LatestStates.TryRemove(serialNumber, out _);
|
||||
Console.WriteLine($"[SIGNALR] Unsubscribed from {serialNumber}");
|
||||
}
|
||||
|
||||
// ================= GET CACHE =================
|
||||
public StateMsg? GetLatestState(string serialNumber)
|
||||
{
|
||||
LatestStates.TryGetValue(serialNumber, out var state);
|
||||
return state;
|
||||
}
|
||||
|
||||
// ================= DISPOSE =================
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
_started = false;
|
||||
SetState(RobotClientState.Disconnected);
|
||||
|
||||
if (_connection != null)
|
||||
{
|
||||
await _connection.DisposeAsync();
|
||||
_connection = null;
|
||||
Console.WriteLine("[SIGNALR] Disposed");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user