From 0c5d33fc817047ab2c2c9dd3ed6784c032755819 Mon Sep 17 00:00:00 2001 From: sam-anthony Date: Sat, 26 Mar 2022 15:56:22 -0230 Subject: intake air temperature --- temperature.go | 71 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 temperature.go (limited to 'temperature.go') diff --git a/temperature.go b/temperature.go new file mode 100644 index 0000000..89cb1ba --- /dev/null +++ b/temperature.go @@ -0,0 +1,71 @@ +package main + +import ( + "errors" + "fmt" +) + +type temperatureUnit int + +const ( + celcius temperatureUnit = iota + kelvin + fahrenheit +) + +// temperatureUnitStrings returns a slice of strings, each representing a +// temperatureUnit. +// This is necessary because giu.Combo only works with strings. +func temperatureUnitStrings() []string { + return []string{"°C", "°K", "°F"} +} + +const ( + defaultTemperatureUnit temperatureUnit = celcius + // Used to index temperatureUnitStrings + defaultTemperatureUnitIndex int32 = 0 // celcius +) + +func temperatureUnitFromString(s string) (temperatureUnit, error) { + // Each case corresponds to a value in volumeUnitStrings. + switch s { + case "°C": + return celcius, nil + case "°K": + return kelvin, nil + case "°F": + return fahrenheit, nil + default: + return *new(temperatureUnit), errors.New(fmt.Sprintf("invalid temperatureUnit: '%s'", s)) + } +} + +type temperature struct { + val float32 + unit temperatureUnit +} + +func (t temperature) asUnit(u temperatureUnit) (float32, error) { + // Convert to celcius + var c float32 + switch t.unit { + case celcius: + c = t.val + case kelvin: + c = t.val - 272.15 + case fahrenheit: + c = (t.val - 32.0) * (5.0 / 9.0) + } + + // Convert to desired unit + switch u { + case celcius: + return c, nil + case kelvin: + return c + 272.15, nil + case fahrenheit: + return c * (9.0 / 5.0) + 32.0, nil + default: + return 0, errors.New(fmt.Sprintf("invalid temperatureUnit: '%v'", u)) + } +} -- cgit v1.2.3