2019-11-24 15:47:17 +00:00
|
|
|
using System.Threading;
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
using Microsoft.Extensions.Hosting;
|
|
|
|
using Microsoft.Extensions.Logging;
|
2019-11-26 18:24:27 +00:00
|
|
|
using Microsoft.Extensions.Options;
|
2019-11-24 15:47:17 +00:00
|
|
|
using NucuCar.Domain.Telemetry;
|
|
|
|
|
2020-04-17 15:11:07 +00:00
|
|
|
namespace NucuCar.Telemetry
|
2019-11-24 15:47:17 +00:00
|
|
|
{
|
|
|
|
/// <summary>
|
|
|
|
/// Telemetry service, which pools the telemetry sources and pushes telemetry data to the cloud.
|
|
|
|
/// </summary>
|
2019-11-24 16:03:46 +00:00
|
|
|
public class TelemetryWorker : BackgroundService
|
2019-11-24 15:47:17 +00:00
|
|
|
{
|
|
|
|
private readonly int _interval;
|
2019-12-01 16:04:46 +00:00
|
|
|
private readonly bool _serviceEnabled;
|
2019-11-24 15:47:17 +00:00
|
|
|
private readonly ILogger _logger;
|
2019-11-24 15:49:46 +00:00
|
|
|
private readonly TelemetryPublisher _telemetryPublisher;
|
2019-11-24 15:47:17 +00:00
|
|
|
|
2019-11-26 18:24:27 +00:00
|
|
|
public TelemetryWorker(ILogger<TelemetryWorker> logger, IOptions<TelemetryConfig> options,
|
2019-11-24 15:47:17 +00:00
|
|
|
SensorTelemetry sensorTelemetry)
|
|
|
|
{
|
|
|
|
_logger = logger;
|
2019-11-26 18:24:27 +00:00
|
|
|
_interval = options.Value.PublishInterval;
|
2019-12-01 16:04:46 +00:00
|
|
|
_serviceEnabled = options.Value.ServiceEnabled;
|
2019-11-24 15:49:46 +00:00
|
|
|
_telemetryPublisher = sensorTelemetry.Publisher;
|
2019-11-24 15:47:17 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
|
|
|
{
|
2019-12-01 16:04:46 +00:00
|
|
|
if (!_serviceEnabled)
|
|
|
|
{
|
2020-01-24 12:28:48 +00:00
|
|
|
_logger.LogInformation("Telemetry service is disabled!");
|
2019-12-01 16:04:46 +00:00
|
|
|
return;
|
|
|
|
}
|
2019-12-06 22:31:28 +00:00
|
|
|
|
2019-12-01 16:04:46 +00:00
|
|
|
if (_telemetryPublisher == null)
|
|
|
|
{
|
|
|
|
_logger?.LogCritical("Invalid state! TelemetryPublisher is null!");
|
|
|
|
return;
|
|
|
|
}
|
2019-12-06 22:31:28 +00:00
|
|
|
|
2019-11-24 15:47:17 +00:00
|
|
|
await Task.Delay(_interval, stoppingToken);
|
|
|
|
while (!stoppingToken.IsCancellationRequested)
|
|
|
|
{
|
2019-11-24 15:49:46 +00:00
|
|
|
await _telemetryPublisher.PublishAsync(stoppingToken);
|
2019-12-01 16:04:46 +00:00
|
|
|
_logger?.LogDebug("Telemetry data published!");
|
2019-11-24 15:47:17 +00:00
|
|
|
await Task.Delay(_interval, stoppingToken);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|