aboutsummaryrefslogtreecommitdiffstats
path: root/temperature.go
diff options
context:
space:
mode:
authorsam-anthony <samanthony6@protonmail.com>2022-03-26 15:56:22 -0230
committersam-anthony <samanthony6@protonmail.com>2022-03-26 15:56:22 -0230
commit0c5d33fc817047ab2c2c9dd3ed6784c032755819 (patch)
tree2bbd7896ddff8c623a7a631307b5fc51689ada34 /temperature.go
parent713b65d414e327db7b530ce0be8403bc0ff4ff3b (diff)
downloadvolute-0c5d33fc817047ab2c2c9dd3ed6784c032755819.zip
intake air temperature
Diffstat (limited to 'temperature.go')
-rw-r--r--temperature.go71
1 files changed, 71 insertions, 0 deletions
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))
+ }
+}