NucuCar/NucuCar.Sensors/EnvironmentSensor/BackgroundWorker.cs

54 lines
1.8 KiB
C#
Raw Normal View History

2019-11-09 13:34:49 +00:00
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
2019-11-09 13:34:49 +00:00
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NucuCarSensorsProto;
2019-11-09 13:34:49 +00:00
namespace NucuCar.Sensors.EnvironmentSensor
2019-11-09 13:34:49 +00:00
{
public class BackgroundWorker : BackgroundService
2019-11-09 13:34:49 +00:00
{
2019-11-11 15:58:46 +00:00
private readonly bool _serviceEnabled;
private readonly bool _telemetryEnabled;
private readonly int _measurementDelay;
private readonly ILogger<BackgroundWorker> _logger;
2019-11-09 13:34:49 +00:00
2019-11-09 14:54:06 +00:00
public BackgroundWorker(ILogger<BackgroundWorker> logger, IConfiguration config)
2019-11-09 13:34:49 +00:00
{
_logger = logger;
2019-11-11 15:58:46 +00:00
var configSection = config.GetSection("EnvironmentSensor");
_serviceEnabled = configSection.GetValue<bool>("Enabled");
_telemetryEnabled = configSection.GetValue<bool>("Telemetry");
_measurementDelay = configSection.GetValue<int>("MeasurementDelay");
2019-11-09 13:34:49 +00:00
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
2019-11-11 15:58:46 +00:00
if (!_serviceEnabled)
{
return;
}
using var sensor = Sensor.Instance;
sensor.SetLogger(_logger);
sensor.InitializeSensor();
2019-11-09 13:34:49 +00:00
while (!stoppingToken.IsCancellationRequested)
{
if (sensor.GetState() == SensorStateEnum.Initialized)
2019-11-09 14:54:06 +00:00
{
await sensor.TakeMeasurement();
}
else
{
await Task.Delay(10000, stoppingToken);
2019-11-09 14:54:06 +00:00
/* Attempt to reinitialize the sensor. */
sensor.InitializeSensor();
}
2019-11-11 15:58:46 +00:00
await Task.Delay(_measurementDelay, stoppingToken);
2019-11-09 13:34:49 +00:00
}
}
}
}