NucuCar/NucuCar.Sensors/Telemetry/BackgroundWorker.cs

51 lines
1.8 KiB
C#
Raw Normal View History

using System.Collections.Generic;
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
{
public class BackgroundWorker : BackgroundService
{
private readonly string _azureIotHubConnectionString;
2019-11-14 14:45:32 +00:00
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");
_azureIotHubConnectionString = configuration.GetValue<string>("Telemetry:AzureIotHubConnectionString");
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);
using var telemetryService = TelemetryPublisher.Instance;
telemetryService.SetLogger(_logger);
telemetryService.Configure(new Dictionary<string, object>()
{
["AzureIotHubConnectionString"] = _azureIotHubConnectionString
});
telemetryService.Start();
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);
}
}
}
}