NucuCar/NucuCar.Sensors/EnvironmentSensor/Sensor.cs

105 lines
3.2 KiB
C#
Raw Normal View History

2019-11-09 14:54:06 +00:00
using System;
using System.Device.I2c;
using System.Threading.Tasks;
using Iot.Device.Bmxx80;
using Iot.Device.Bmxx80.PowerMode;
using Microsoft.Extensions.Logging;
namespace NucuCar.Sensors.EnvironmentSensor
2019-11-09 14:54:06 +00:00
{
public class Sensor : IDisposable
2019-11-09 14:54:06 +00:00
{
private ILogger _logger;
2019-11-09 14:54:06 +00:00
private I2cConnectionSettings _i2CSettings;
private I2cDevice _i2CDevice;
private Bme680 _bme680;
private Measurement _measurement;
private SensorState _sensorState;
2019-11-09 14:54:06 +00:00
/* Singleton Instance */
public static Sensor Instance { get; } = new Sensor();
static Sensor()
{
}
private Sensor()
{
_sensorState = SensorState.Uninitialized;
}
public Measurement GetMeasurement()
{
return _measurement;
}
public SensorState GetState()
{
return _sensorState;
}
public void Dispose()
{
_bme680?.Dispose();
}
internal void SetLogger(ILogger logger)
2019-11-09 14:54:06 +00:00
{
_logger = logger;
}
2019-11-09 14:54:06 +00:00
internal void InitializeSensor()
{
if (_sensorState == SensorState.Initialized)
{
return;
}
2019-11-09 14:54:06 +00:00
try
{
/* Connect to default i2c address 0x76 */
_i2CSettings = new I2cConnectionSettings(1, Bme680.DefaultI2cAddress);
_i2CDevice = I2cDevice.Create(_i2CSettings);
_bme680 = new Bme680(_i2CDevice);
2019-11-09 14:54:06 +00:00
/* Initialize measurement */
_measurement = new Measurement();
_bme680.Reset();
_bme680.SetHumiditySampling(Sampling.UltraLowPower);
_bme680.SetTemperatureSampling(Sampling.UltraHighResolution);
_bme680.SetPressureSampling(Sampling.UltraLowPower);
_sensorState = SensorState.Initialized;
2019-11-09 14:54:06 +00:00
_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);
_sensorState = SensorState.Error;
2019-11-09 14:54:06 +00:00
}
}
internal async Task TakeMeasurement()
{
if (_sensorState != SensorState.Initialized)
2019-11-09 14:54:06 +00:00
{
_logger.LogWarning(
$"{DateTimeOffset.Now}:BME680: Attempting to take measurement while sensor is not initialized!");
2019-11-09 14:54:06 +00:00
return;
}
2019-11-09 14:54:06 +00:00
/* Force the sensor to take a measurement. */
_bme680.SetPowerMode(Bme680PowerMode.Forced);
2019-11-09 14:54:06 +00:00
var temperature = await _bme680.ReadTemperatureAsync();
var pressure = await _bme680.ReadPressureAsync();
var humidity = await _bme680.ReadHumidityAsync();
_measurement.SetMeasurement(temperature, pressure, humidity);
2019-11-09 14:54:06 +00:00
_logger.LogInformation($"{DateTimeOffset.Now}:BME680: reading");
_logger.LogInformation(
$"{temperature.Celsius:N2} \u00B0C | {pressure} hPa | {humidity:N2} %rH");
}
}
}