NucuCar/NucuCar.Sensors/Modules/Environment/Bme680Sensor.cs

182 lines
6.3 KiB
C#
Raw Normal View History

2019-11-09 14:54:06 +00:00
using System;
2019-11-14 14:45:32 +00:00
using System.Collections.Generic;
2019-11-09 14:54:06 +00:00
using System.Device.I2c;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
2020-08-01 15:07:13 +00:00
using NucuCar.Sensors.Abstractions;
using NucuCar.Sensors.Modules.Environment.Bmxx80;
using NucuCarSensorsProto;
using Bme680 = NucuCar.Sensors.Modules.Environment.Bmxx80.Bme680;
using Bme680PowerMode = NucuCar.Sensors.Modules.Environment.Bmxx80.PowerMode.Bme680PowerMode;
using Sampling = NucuCar.Sensors.Modules.Environment.Bmxx80.Sampling;
2019-11-09 14:54:06 +00:00
namespace NucuCar.Sensors.Modules.Environment
2019-11-09 14:54:06 +00:00
{
internal class Bme680MeasurementData
{
public double Temperature { get; set; }
public double Humidity { get; set; }
public double Pressure { get; set; }
public double VolatileOrganicCompounds { get; set; }
}
2019-11-24 13:12:12 +00:00
/// <summary>
/// Abstraction for the BME680 sensor.
/// See: https://www.bosch-sensortec.com/bst/products/all_products/bme680
/// </summary>
public class Bme680Sensor : GenericTelemeterSensor, IDisposable, ISensor<Bme680Sensor>
2019-11-09 14:54:06 +00:00
{
private I2cConnectionSettings _i2CSettings;
private I2cDevice _i2CDevice;
private Bme680 _bme680;
private Bme680MeasurementData _lastMeasurement;
2019-11-09 14:54:06 +00:00
public Bme680Sensor()
{
}
public Bme680Sensor(ILogger<Bme680Sensor> logger, IOptions<Bme680Config> options)
{
2019-12-29 11:58:32 +00:00
CurrentState = SensorStateEnum.Uninitialized;
2019-12-17 19:40:20 +00:00
Logger = logger;
if (!options.Value.Enabled)
{
Logger?.LogDebug("BME680 Sensor is disabled!");
2019-12-29 11:58:32 +00:00
CurrentState = SensorStateEnum.Disabled;
}
2019-11-30 16:55:55 +00:00
2019-12-17 19:40:20 +00:00
TelemetryEnabled = options.Value.Telemetry;
2019-11-30 16:55:55 +00:00
Object = this;
}
public override NucuCarSensorResponse GetMeasurement()
{
var jsonResponse = JsonConvert.SerializeObject(_lastMeasurement);
return new NucuCarSensorResponse
{
State = GetState(),
JsonData = jsonResponse
};
}
2019-12-17 19:40:20 +00:00
public override SensorStateEnum GetState()
{
2019-12-29 11:58:32 +00:00
return CurrentState;
}
public void Dispose()
{
_bme680?.Dispose();
}
public override void Initialize()
2019-11-09 14:54:06 +00:00
{
2019-12-29 11:58:32 +00:00
if (CurrentState == SensorStateEnum.Initialized || CurrentState == SensorStateEnum.Disabled)
{
return;
}
_lastMeasurement = new Bme680MeasurementData();
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 */
_bme680.Reset();
_bme680.TemperatureSampling = Sampling.HighResolution;
_bme680.HumiditySampling = Sampling.HighResolution;
_bme680.PressureSampling = Sampling.HighResolution;
_bme680.HeaterProfile = Bme680HeaterProfile.Profile2;
2019-12-29 11:58:32 +00:00
CurrentState = SensorStateEnum.Initialized;
2019-12-17 19:40:20 +00:00
Logger?.LogInformation($"{DateTimeOffset.Now}:BME680 Sensor initialization OK.");
2019-11-09 14:54:06 +00:00
}
catch (System.IO.IOException e)
{
HandleInitializationException(e);
}
catch (ArgumentException e)
{
HandleInitializationException(e);
2019-11-09 14:54:06 +00:00
}
}
2019-12-17 19:40:20 +00:00
public override async Task TakeMeasurementAsync()
2019-11-09 14:54:06 +00:00
{
2019-12-29 11:58:32 +00:00
if (CurrentState != SensorStateEnum.Initialized)
2019-11-09 14:54:06 +00:00
{
throw new InvalidOperationException("Can't take measurement on uninitialized sensor!");
2019-11-09 14:54:06 +00:00
}
_bme680.ConfigureHeatingProfile(Bme680HeaterProfile.Profile2,
280, 80, _lastMeasurement.Temperature);
var measurementDuration = _bme680.GetMeasurementDuration(_bme680.HeaterProfile);
2019-11-09 14:54:06 +00:00
/* Force the sensor to take a measurement. */
_bme680.SetPowerMode(Bme680PowerMode.Forced);
await Task.Delay(measurementDuration);
_bme680.TryReadTemperature(out var temp);
_bme680.TryReadHumidity(out var humidity);
_bme680.TryReadPressure(out var pressure);
_bme680.TryReadGasResistance(out var gasResistance);
_lastMeasurement.Temperature = Math.Round(temp.Celsius, 2);
_lastMeasurement.Pressure = Math.Round(pressure.Hectopascal, 2);
_lastMeasurement.Humidity = Math.Round(humidity, 2);
2020-02-09 14:37:45 +00:00
_lastMeasurement.VolatileOrganicCompounds = Math.Round(gasResistance / 1000, 2);
2019-12-17 19:40:20 +00:00
Logger?.LogDebug($"{DateTimeOffset.Now}:BME680: reading");
Logger?.LogInformation(
$"temperature:{_lastMeasurement.Temperature:N2} \u00B0C|" +
$"pressure:{_lastMeasurement.Pressure:N2} hPa|" +
$"humidity:{_lastMeasurement.Humidity:N2} %rH|" +
$"voc:{_lastMeasurement.VolatileOrganicCompounds}");
2019-11-09 14:54:06 +00:00
}
2019-11-14 14:45:32 +00:00
public override string GetIdentifier()
{
return "Environment";
}
public override Dictionary<string, object> GetTelemetryData()
2019-11-14 14:45:32 +00:00
{
Dictionary<string, object> returnValue = null;
2019-12-17 19:40:20 +00:00
if (_lastMeasurement != null && TelemetryEnabled)
2019-11-14 14:45:32 +00:00
{
returnValue = new Dictionary<string, object>
{
2019-12-29 11:58:32 +00:00
["sensor_state"] = CurrentState,
["temperature"] = _lastMeasurement.Temperature,
["humidity"] = _lastMeasurement.Humidity,
["pressure"] = _lastMeasurement.Pressure,
["voc"] = _lastMeasurement.VolatileOrganicCompounds
};
}
2019-11-24 13:12:12 +00:00
return returnValue;
2019-11-14 14:45:32 +00:00
}
2019-11-30 16:55:55 +00:00
public override bool IsTelemetryEnabled()
{
return TelemetryEnabled;
}
2019-11-30 16:55:55 +00:00
public Bme680Sensor Object { get; }
private void HandleInitializationException(Exception e)
{
Logger?.LogError($"{DateTimeOffset.Now}:BME680 Sensor initialization FAIL.");
Logger?.LogDebug(e.Message);
CurrentState = SensorStateEnum.Error;
}
2019-11-09 14:54:06 +00:00
}
}