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 bool _serviceEnabled;
|
|
|
|
private readonly int _interval;
|
|
|
|
private readonly ILogger _logger;
|
|
|
|
|
|
|
|
public BackgroundWorker(ILogger<BackgroundWorker> logger, IConfiguration configuration)
|
|
|
|
{
|
|
|
|
_logger = logger;
|
2019-11-17 13:29:33 +00:00
|
|
|
_serviceEnabled = configuration.GetValue<bool>("Telemetry:Enabled");
|
|
|
|
_interval = configuration.GetValue<int>("Telemetry:Interval");
|
2019-11-23 18:53:04 +00:00
|
|
|
var azureIotHubConnectionString = configuration.GetValue<string>("Telemetry:AzureIotHubConnectionString");
|
2019-11-24 12:16:35 +00:00
|
|
|
if (_serviceEnabled)
|
|
|
|
{
|
|
|
|
SensorTelemetryPublisher.CreateSingleton(azureIotHubConnectionString, "NucuCar.Sensors", logger);
|
|
|
|
}
|
2019-11-14 14:45:32 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
|
|
|
{
|
|
|
|
if (!_serviceEnabled)
|
|
|
|
{
|
|
|
|
return;
|
|
|
|
}
|
2019-11-14 17:23:16 +00:00
|
|
|
|
2019-11-14 14:45:32 +00:00
|
|
|
await Task.Delay(_interval, stoppingToken);
|
|
|
|
|
2019-11-23 18:53:04 +00:00
|
|
|
var telemetryService = SensorTelemetryPublisher.Instance;
|
2019-11-14 17:23:16 +00:00
|
|
|
|
2019-11-14 14:45:32 +00:00
|
|
|
while (!stoppingToken.IsCancellationRequested)
|
|
|
|
{
|
|
|
|
_logger.LogInformation("Publishing telemetry data!");
|
2019-11-17 16:27:58 +00:00
|
|
|
await telemetryService.PublishAsync(stoppingToken);
|
2019-11-14 14:45:32 +00:00
|
|
|
await Task.Delay(_interval, stoppingToken);
|
|
|
|
}
|
|
|
|
}
|
2019-11-23 18:53:04 +00:00
|
|
|
|
|
|
|
public override void Dispose()
|
|
|
|
{
|
|
|
|
base.Dispose();
|
|
|
|
SensorTelemetryPublisher.Instance?.Dispose();
|
|
|
|
}
|
2019-11-14 14:45:32 +00:00
|
|
|
}
|
|
|
|
}
|