using FinlyticAssets.Util;
using FinlyticCore.Models;
namespace FinlyticAssets.Services;
///
/// A hosted service responsible for managing the lifecycle of the MQTT client connection
/// when the application starts up and shuts down.
///
public class MqttConnectionService : IHostedService
{
private readonly AssetsMqttClient _mqttClient;
private readonly IConfiguration _configuration;
///
/// Initializes a new instance of the class.
///
/// The MQTT client wrapper instance.
/// The application configuration provider.
public MqttConnectionService(AssetsMqttClient mqttClient, IConfiguration configuration)
{
_mqttClient = mqttClient;
_configuration = configuration;
}
///
/// Starts the MQTT client connection using settings resolved from configuration.
///
/// A token to monitor for cancellation requests.
/// A task representing the asynchronous start operation.
public async Task StartAsync(CancellationToken cancellationToken)
{
var config = new MqttConfiguration()
{
Host = _configuration["MQTT__Host"]!,
Port = Convert.ToInt32(_configuration["MQTT__Port"]!),
ClientId = $"{_configuration["MQTT__ClientId"]!}_{Guid.NewGuid()}"
};
await _mqttClient.ConnectAsync(config);
}
///
/// Stops and disconnects the MQTT client connection.
///
/// A token to monitor for cancellation requests.
/// A task representing the asynchronous stop operation.
public async Task StopAsync(CancellationToken cancellationToken)
{
await _mqttClient.DisconnectAsync();
}
}