From 3825edc7b9627232b58c439ba5727075951a0669 Mon Sep 17 00:00:00 2001 From: Chris Tacke Date: Thu, 7 Mar 2024 17:48:11 -0600 Subject: [PATCH] fix temperature conversion --- .../Conversions/TempConversions.cs | 62 +++++++++++-------- 1 file changed, 35 insertions(+), 27 deletions(-) diff --git a/Source/Meadow.Units/Conversions/TempConversions.cs b/Source/Meadow.Units/Conversions/TempConversions.cs index fdd9d25..f7feabb 100644 --- a/Source/Meadow.Units/Conversions/TempConversions.cs +++ b/Source/Meadow.Units/Conversions/TempConversions.cs @@ -3,36 +3,44 @@ namespace Meadow.Units.Conversions { internal static class TempConversions { - // To Base (`C°`) - public static Func FToC = (value) => (value - 32D) * (5D / 9D); - public static Func KToC = (value) => value - 273.15D; + public static Func FToC = (value) => (value - 32d) * (5d / 9d); + public static Func KToC = (value) => value - 273.15d; + public static Func CToF = (value) => value * (9d / 5d) + 32d; + public static Func CToK = (value) => value + 273.15d; + public static Func FToK = (value) => FToC(value) + 273.15d; + public static Func KToF = (value) => CToF(value - 273.15); - // From Base - public static Func CToF = (value) => value * (9D / 5D) + 32D; - public static Func CToK = (value) => value + 273.15D; + public static double Convert(double value, Temperature.UnitType from, Temperature.UnitType to) + { + if (from == to) { return value; } - public static double Convert(double value, Temperature.UnitType from, Temperature.UnitType to) - { - if (from == to) { return value; } - - if (from == Temperature.UnitType.Celsius && to == Temperature.UnitType.Fahrenheit) { - return CToK(value); - } - if (from == Temperature.UnitType.Fahrenheit && to == Temperature.UnitType.Celsius) { - + switch (from) + { + case Temperature.UnitType.Celsius: + return to switch + { + Temperature.UnitType.Kelvin => CToK(value), + Temperature.UnitType.Fahrenheit => CToF(value), + _ => value + }; + case Temperature.UnitType.Fahrenheit: + return to switch + { + Temperature.UnitType.Kelvin => FToK(value), + Temperature.UnitType.Celsius => FToC(value), + _ => value + }; + case Temperature.UnitType.Kelvin: + return to switch + { + Temperature.UnitType.Fahrenheit => KToF(value), + Temperature.UnitType.Celsius => KToC(value), + _ => value + }; } - return value * temperatureConversions[(int)to] / temperatureConversions[(int)from]; - } - - //must align to enum - private static readonly double[] temperatureConversions = - { - 1,//Celsius, - -32*(5D/9D),//Fahrenheit, // NO WAY TO GET THIS TO WORK? - //(9D / 5D) + 32D, - 273.15D//Kelvin, - }; - } + throw new NotSupportedException(); + } + } }