Init
This commit is contained in:
@@ -0,0 +1,52 @@
|
||||
using FinlyticAssets.Util;
|
||||
using FinlyticCore.Models;
|
||||
|
||||
namespace FinlyticAssets.Services;
|
||||
|
||||
/// <summary>
|
||||
/// A hosted service responsible for managing the lifecycle of the MQTT client connection
|
||||
/// when the application starts up and shuts down.
|
||||
/// </summary>
|
||||
public class MqttConnectionService : IHostedService
|
||||
{
|
||||
private readonly AssetsMqttClient _mqttClient;
|
||||
private readonly IConfiguration _configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MqttConnectionService"/> class.
|
||||
/// </summary>
|
||||
/// <param name="mqttClient">The MQTT client wrapper instance.</param>
|
||||
/// <param name="configuration">The application configuration provider.</param>
|
||||
public MqttConnectionService(AssetsMqttClient mqttClient, IConfiguration configuration)
|
||||
{
|
||||
_mqttClient = mqttClient;
|
||||
_configuration = configuration;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Starts the MQTT client connection using settings resolved from configuration.
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">A token to monitor for cancellation requests.</param>
|
||||
/// <returns>A task representing the asynchronous start operation.</returns>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stops and disconnects the MQTT client connection.
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">A token to monitor for cancellation requests.</param>
|
||||
/// <returns>A task representing the asynchronous stop operation.</returns>
|
||||
public async Task StopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
await _mqttClient.DisconnectAsync();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user