using System; using System.Collections.Generic; using System.Threading.Tasks; using Iot.Device.CpuTemperature; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Newtonsoft.Json; using NucuCar.Sensors.Abstractions; using NucuCarSensorsProto; namespace NucuCar.Sensors.Modules.Health { public class CpuTempSensor : GenericTelemeterSensor, ISensor { private readonly CpuTemperature _cpuTemperature; private double _lastTemperatureCelsius; public CpuTempSensor() { } public CpuTempSensor(ILogger logger, IOptions options) { Logger = logger; if (options.Value.Enabled) { CurrentState = SensorStateEnum.Uninitialized; _cpuTemperature = new CpuTemperature(); Object = this; TelemetryEnabled = options.Value.Telemetry; } else { Logger?.LogDebug("CpuTempSensor is disabled!"); CurrentState = SensorStateEnum.Disabled; } } public override void Initialize() { if (CurrentState == SensorStateEnum.Initialized || CurrentState == SensorStateEnum.Disabled) { return; } CurrentState = _cpuTemperature.IsAvailable ? SensorStateEnum.Initialized : SensorStateEnum.Error; } public override Task TakeMeasurementAsync() { if (CurrentState == SensorStateEnum.Initialized) { _lastTemperatureCelsius = _cpuTemperature.Temperature.Celsius; if (double.IsNaN(_lastTemperatureCelsius)) { CurrentState = SensorStateEnum.Error; _lastTemperatureCelsius = double.NaN; } else { _lastTemperatureCelsius = Math.Round(_lastTemperatureCelsius, 2); } } Logger?.LogDebug($"{DateTimeOffset.Now}:HealthSensor: reading"); Logger?.LogInformation($"CPU Temperature {_lastTemperatureCelsius}"); return Task.FromResult(_lastTemperatureCelsius); } public override NucuCarSensorResponse GetMeasurement() { var jsonResponse = JsonConvert.SerializeObject(new Dictionary { ["cpu_temperature"] = _lastTemperatureCelsius, }); return new NucuCarSensorResponse() { State = CurrentState, JsonData = jsonResponse }; } public override SensorStateEnum GetState() { return CurrentState; } public override string GetIdentifier() { return "CpuTemperature"; } public override Dictionary GetTelemetryData() { Dictionary returnValue = null; if (!double.IsNaN(_lastTemperatureCelsius) && TelemetryEnabled) { returnValue = new Dictionary { ["sensor_state"] = CurrentState, ["cpu_temperature"] = _lastTemperatureCelsius, }; } return returnValue; } public override bool IsTelemetryEnabled() { return TelemetryEnabled; } public CpuTempSensor Object { get; } } }