From 118dbd0086801f537c985168353cf6ff2704d28c Mon Sep 17 00:00:00 2001 From: Denis-Cosmin Nutiu Date: Sun, 24 Nov 2019 18:03:46 +0200 Subject: [PATCH] Refactor NucuCar.Sensors Bme680Sensor singleton class to use dependency injection --- NucuCar.Domain/Protos/NucuCarSensors.proto | 1 + .../EnvironmentSensor/Bme680GrpcService.cs | 8 ++--- .../EnvironmentSensor/Bme680Sensor.cs | 34 +++++++++++-------- .../EnvironmentSensor/Bme680Worker.cs | 25 +++++++------- NucuCar.Sensors/GrpcStartup.cs | 2 +- NucuCar.Sensors/Program.cs | 14 ++++++-- NucuCar.Sensors/Telemetry/TelemetryWorker.cs | 4 +-- 7 files changed, 50 insertions(+), 38 deletions(-) diff --git a/NucuCar.Domain/Protos/NucuCarSensors.proto b/NucuCar.Domain/Protos/NucuCarSensors.proto index e723e5f..fc6555a 100644 --- a/NucuCar.Domain/Protos/NucuCarSensors.proto +++ b/NucuCar.Domain/Protos/NucuCarSensors.proto @@ -8,6 +8,7 @@ enum SensorStateEnum { Error = 0; Uninitialized = 1; Initialized = 2; + Disabled = 3; } // Environment Sensor diff --git a/NucuCar.Sensors/EnvironmentSensor/Bme680GrpcService.cs b/NucuCar.Sensors/EnvironmentSensor/Bme680GrpcService.cs index 2629288..414b24f 100644 --- a/NucuCar.Sensors/EnvironmentSensor/Bme680GrpcService.cs +++ b/NucuCar.Sensors/EnvironmentSensor/Bme680GrpcService.cs @@ -10,14 +10,14 @@ namespace NucuCar.Sensors.EnvironmentSensor /// EnvironmentSensor's gRPC service. /// It allows reading the sensor's data using remote procedure calls. /// - public class GrpcService : EnvironmentSensorGrpcService.EnvironmentSensorGrpcServiceBase + public class Bme680GrpcService : EnvironmentSensorGrpcService.EnvironmentSensorGrpcServiceBase { - private readonly ILogger _logger; + private readonly ILogger _logger; private readonly Bme680Sensor _bme680Sensor; - public GrpcService(ILogger logger) + public Bme680GrpcService(ILogger logger, Bme680Sensor bme680Sensor) { - _bme680Sensor = Bme680Sensor.Instance; + _bme680Sensor = bme680Sensor; _logger = logger; } diff --git a/NucuCar.Sensors/EnvironmentSensor/Bme680Sensor.cs b/NucuCar.Sensors/EnvironmentSensor/Bme680Sensor.cs index d0722e8..a5d7991 100644 --- a/NucuCar.Sensors/EnvironmentSensor/Bme680Sensor.cs +++ b/NucuCar.Sensors/EnvironmentSensor/Bme680Sensor.cs @@ -4,6 +4,7 @@ using System.Device.I2c; using System.Threading.Tasks; using Iot.Device.Bmxx80; using Iot.Device.Bmxx80.PowerMode; +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using NucuCar.Domain.Telemetry; using NucuCarSensorsProto; @@ -16,23 +17,26 @@ namespace NucuCar.Sensors.EnvironmentSensor /// public class Bme680Sensor : IDisposable, ITelemeter { - public ILogger Logger; + private readonly ILogger _logger; private I2cConnectionSettings _i2CSettings; private I2cDevice _i2CDevice; private Bme680 _bme680; private EnvironmentSensorMeasurement _lastMeasurement; private SensorStateEnum _sensorStateEnum; - /* Singleton Instance */ - public static Bme680Sensor Instance { get; } = new Bme680Sensor(); - - static Bme680Sensor() - { - } - - private Bme680Sensor() + public Bme680Sensor(ILogger logger, IConfiguration configuration) { _sensorStateEnum = SensorStateEnum.Uninitialized; + _logger = logger; + if (configuration.GetValue("EnvironmentSensor:Enabled")) + { + InitializeSensor(); + } + else + { + _logger?.LogInformation("BME680 Sensor is disabled!"); + _sensorStateEnum = SensorStateEnum.Disabled; + } } public EnvironmentSensorMeasurement GetMeasurement() @@ -72,12 +76,12 @@ namespace NucuCar.Sensors.EnvironmentSensor _bme680.SetPressureSampling(Sampling.UltraLowPower); _sensorStateEnum = SensorStateEnum.Initialized; - Logger?.LogInformation($"{DateTimeOffset.Now}:BME680 Sensor initialization OK."); + _logger?.LogInformation($"{DateTimeOffset.Now}:BME680 Sensor initialization OK."); } catch (System.IO.IOException e) { - Logger?.LogError($"{DateTimeOffset.Now}:BME680 Sensor initialization FAIL."); - Logger?.LogTrace(e.Message); + _logger?.LogError($"{DateTimeOffset.Now}:BME680 Sensor initialization FAIL."); + _logger?.LogTrace(e.Message); _sensorStateEnum = SensorStateEnum.Error; } } @@ -86,7 +90,7 @@ namespace NucuCar.Sensors.EnvironmentSensor { if (_sensorStateEnum != SensorStateEnum.Initialized) { - Logger?.LogWarning( + _logger?.LogWarning( $"{DateTimeOffset.Now}:BME680: Attempting to take measurement while sensor is not initialized!"); return; } @@ -98,8 +102,8 @@ namespace NucuCar.Sensors.EnvironmentSensor _lastMeasurement.Pressure = await _bme680.ReadPressureAsync(); _lastMeasurement.Humidity = await _bme680.ReadHumidityAsync(); - Logger?.LogInformation($"{DateTimeOffset.Now}:BME680: reading"); - Logger?.LogInformation( + _logger?.LogInformation($"{DateTimeOffset.Now}:BME680: reading"); + _logger?.LogInformation( $"{_lastMeasurement.Temperature:N2} \u00B0C | {_lastMeasurement.Pressure:N2} hPa | {_lastMeasurement.Humidity:N2} %rH"); } diff --git a/NucuCar.Sensors/EnvironmentSensor/Bme680Worker.cs b/NucuCar.Sensors/EnvironmentSensor/Bme680Worker.cs index c2d3aba..9ff2910 100644 --- a/NucuCar.Sensors/EnvironmentSensor/Bme680Worker.cs +++ b/NucuCar.Sensors/EnvironmentSensor/Bme680Worker.cs @@ -13,23 +13,25 @@ namespace NucuCar.Sensors.EnvironmentSensor /// EnvironmentSensor's background service worker. /// It does periodic reads from the sensors and publishes telemetry data if the option is enabled. /// - public class BackgroundWorker : BackgroundService + public class Bme680Worker : BackgroundService { private readonly bool _serviceEnabled; private readonly bool _telemetryEnabled; private readonly int _measurementDelay; - private readonly ILogger _logger; + private readonly ILogger _logger; private readonly TelemetryPublisher _telemetryPublisher; + private readonly Bme680Sensor _bme680Sensor; - public BackgroundWorker(ILogger logger, IConfiguration config, - SensorTelemetry sensorTelemetry) + public Bme680Worker(ILogger logger, IConfiguration config, + SensorTelemetry sensorTelemetry, Bme680Sensor bme680Sensor) { _logger = logger; _serviceEnabled = config.GetValue("EnvironmentSensor:Enabled"); _telemetryEnabled = config.GetValue("EnvironmentSensor:Telemetry"); _measurementDelay = config.GetValue("EnvironmentSensor:MeasurementInterval"); _telemetryPublisher = sensorTelemetry.Publisher; + _bme680Sensor = bme680Sensor; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) @@ -38,33 +40,30 @@ namespace NucuCar.Sensors.EnvironmentSensor { return; } - - using var sensor = Bme680Sensor.Instance; - sensor.Logger = _logger; - sensor.InitializeSensor(); + if (_telemetryEnabled) { - _telemetryPublisher?.RegisterTelemeter(sensor); + _telemetryPublisher?.RegisterTelemeter(_bme680Sensor); } while (!stoppingToken.IsCancellationRequested) { /* If sensor is ok attempt to read. */ - if (sensor.GetState() == SensorStateEnum.Initialized) + if (_bme680Sensor.GetState() == SensorStateEnum.Initialized) { - await sensor.TakeMeasurement(); + await _bme680Sensor.TakeMeasurement(); } /* Else attempt to re-initialize. */ else { await Task.Delay(10000, stoppingToken); - sensor.InitializeSensor(); + _bme680Sensor.InitializeSensor(); } await Task.Delay(_measurementDelay, stoppingToken); } - _telemetryPublisher?.UnRegisterTelemeter(sensor); + _telemetryPublisher?.UnRegisterTelemeter(_bme680Sensor); } } } \ No newline at end of file diff --git a/NucuCar.Sensors/GrpcStartup.cs b/NucuCar.Sensors/GrpcStartup.cs index aaf5246..d1a1ff3 100644 --- a/NucuCar.Sensors/GrpcStartup.cs +++ b/NucuCar.Sensors/GrpcStartup.cs @@ -29,7 +29,7 @@ namespace NucuCar.Sensors app.UseEndpoints(endpoints => { // Add the gRPC services here. - endpoints.MapGrpcService(); + endpoints.MapGrpcService(); endpoints.MapGet("/", async context => diff --git a/NucuCar.Sensors/Program.cs b/NucuCar.Sensors/Program.cs index 9a269a3..f0df053 100644 --- a/NucuCar.Sensors/Program.cs +++ b/NucuCar.Sensors/Program.cs @@ -20,15 +20,23 @@ namespace NucuCar.Sensors // Singletons services.AddSingleton(); + services.AddSingleton(); // Workers if (config.GetValue("Telemetry:Enabled")) { - services.AddHostedService(); + services.AddHostedService(); } - services.AddHostedService(); + if (config.GetValue("EnvironmentSensor:Enabled")) + { + services.AddHostedService(); + } + }) - .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup(); }); + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.UseStartup(); + }); } } \ No newline at end of file diff --git a/NucuCar.Sensors/Telemetry/TelemetryWorker.cs b/NucuCar.Sensors/Telemetry/TelemetryWorker.cs index ad9db57..002a443 100644 --- a/NucuCar.Sensors/Telemetry/TelemetryWorker.cs +++ b/NucuCar.Sensors/Telemetry/TelemetryWorker.cs @@ -10,13 +10,13 @@ namespace NucuCar.Sensors.Telemetry /// /// Telemetry service, which pools the telemetry sources and pushes telemetry data to the cloud. /// - public class TelemetryBackgroundWorker : BackgroundService + public class TelemetryWorker : BackgroundService { private readonly int _interval; private readonly ILogger _logger; private readonly TelemetryPublisher _telemetryPublisher; - public TelemetryBackgroundWorker(ILogger logger, IConfiguration configuration, + public TelemetryWorker(ILogger logger, IConfiguration configuration, SensorTelemetry sensorTelemetry) { _logger = logger;