NucuCar/NucuCar.Sensors/Telemetry/BackgroundWorker.cs

55 lines
1.8 KiB
C#
Raw Normal View History

2019-11-14 14:45:32 +00:00
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace NucuCar.Sensors.Telemetry
{
2019-11-24 13:12:12 +00:00
/// <summary>
/// Telemetry service, which pools the telemetry sources and pushes telemetry data to the cloud.
/// </summary>
2019-11-14 14:45:32 +00:00
public class BackgroundWorker : BackgroundService
{
private readonly bool _serviceEnabled;
private readonly int _interval;
private readonly ILogger _logger;
public BackgroundWorker(ILogger<BackgroundWorker> logger, IConfiguration configuration)
{
_logger = logger;
_serviceEnabled = configuration.GetValue<bool>("Telemetry:Enabled");
_interval = configuration.GetValue<int>("Telemetry:Interval");
var connectionString = configuration.GetValue<string>("Telemetry:ConnectionString");
if (_serviceEnabled)
{
SensorTelemetryPublisher.CreateSingleton(connectionString, "NucuCar.Sensors", logger);
}
2019-11-14 14:45:32 +00:00
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
if (!_serviceEnabled)
{
return;
}
2019-11-14 14:45:32 +00:00
await Task.Delay(_interval, stoppingToken);
var telemetryService = SensorTelemetryPublisher.Instance;
2019-11-14 14:45:32 +00:00
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation("Publishing telemetry data!");
await telemetryService.PublishAsync(stoppingToken);
2019-11-14 14:45:32 +00:00
await Task.Delay(_interval, stoppingToken);
}
}
public override void Dispose()
{
base.Dispose();
SensorTelemetryPublisher.Instance?.Dispose();
}
2019-11-14 14:45:32 +00:00
}
}