RobotApp/RobotApp/Services/Robot/RobotConnection.cs
Đăng Nguyễn b3f765d261 update
2025-12-30 16:59:08 +07:00

105 lines
3.8 KiB
C#

using RobotApp.Common.Shares;
using RobotApp.VDA5050;
using RobotApp.VDA5050.InstantAction;
using RobotApp.VDA5050.Order;
using System.Text.Json;
using System.Threading;
namespace RobotApp.Services.Robot;
public class RobotConnection(RobotConfiguration RobotConfiguration,
Logger<RobotConnection> Logger,
Logger<MQTTClient> MQTTClientLogger)
{
private MQTTClient? MqttClient;
public bool IsConnected => MqttClient is not null && MqttClient.IsConnected;
public event Action<OrderMsg>? OrderUpdated;
public event Action<InstantActionsMsg>? ActionUpdated;
private readonly SemaphoreSlim _connectionSemaphore = new(1, 1);
private CancellationTokenSource? _connectionCancel;
private void OrderChanged(string data)
{
try
{
//Logger.Debug($"Nhận Order: {data}");
var msg = JsonSerializer.Deserialize<OrderMsg>(data, JsonOptionExtends.Read);
if (msg is null || string.IsNullOrEmpty(msg.SerialNumber) || msg.SerialNumber != RobotConfiguration.SerialNumber)
{
Logger.Warning($"SerialNumber cuả order không hợp lệ: message SerialNumber {msg?.SerialNumber}");
return;
}
OrderUpdated?.Invoke(msg);
}
catch (Exception ex)
{
Logger.Warning($"Nhận Order xảy ra lỗi: {ex.Message}");
}
}
private void InstanceActionsChanged(string data)
{
try
{
//Logger.Debug($"Nhận InstanceActions: {data}");
var msg = JsonSerializer.Deserialize<InstantActionsMsg>(data, JsonOptionExtends.Read);
if (msg is null || string.IsNullOrEmpty(msg.SerialNumber) || msg.SerialNumber != RobotConfiguration.SerialNumber)
{
Logger.Warning($"SerialNumber của action không hợp lệ: message SerialNumber {msg?.SerialNumber}");
return;
}
ActionUpdated?.Invoke(msg);
}
catch (Exception ex)
{
Logger.Warning($"Nhận InstanceActions xảy ra lỗi: {ex.Message}");
}
}
public async Task<MessageResult> Publish(string topic, string data)
{
if (MqttClient is not null && MqttClient.IsConnected) return await MqttClient.PublishAsync($"{RobotConfiguration.VDA5050Setting.TopicPrefix}/{RobotConfiguration.VDA5050Setting.Manufacturer}/{RobotConfiguration.SerialNumber}/{topic}", data);
return new(false, "Chưa có kết nối tới broker");
}
public void StartConnection()
{
Task.Run(async () =>
{
await StartConnectionAsync(CancellationToken.None);
if(IsConnected)Logger.Info("Robot đã kết nối tới Fleet Manager.");
});
}
public async Task StartConnectionAsync(CancellationToken cancellationToken)
{
try
{
await StopConnection();
_connectionCancel?.Cancel();
if (_connectionSemaphore.Wait(1000, cancellationToken))
{
_connectionCancel = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
MqttClient = new MQTTClient(RobotConfiguration.SerialNumber, RobotConfiguration.VDA5050Setting, MQTTClientLogger);
MqttClient.OrderChanged += OrderChanged;
MqttClient.InstanceActionsChanged += InstanceActionsChanged;
await MqttClient.ConnectAsync(_connectionCancel.Token);
if(MqttClient is not null) await MqttClient.SubscribeAsync(_connectionCancel.Token);
}
}
finally
{
_connectionSemaphore.Release();
}
}
public async Task StopConnection()
{
if (MqttClient is not null)
{
await MqttClient.DisposeAsync();
MqttClient = null;
}
}
}