th7/config/config.go

123 lines
2.6 KiB
Go

package config
import (
"errors"
"fmt"
"th7/data/config"
"th7/data/temperature"
"th7/data/thermocouple"
"github.com/spf13/viper"
)
var (
ErrConfigBadThermocoupleType = errors.New("unrecognised thermocouple type")
ErrConfigBadTemperatureUnit = errors.New("unrecognised temperature unit")
)
var (
thermocoupleTypes = map[string]thermocouple.Type{
"B": thermocouple.B,
"E": thermocouple.E,
"J": thermocouple.J,
"K": thermocouple.K,
"N": thermocouple.N,
"R": thermocouple.R,
"S": thermocouple.S,
"T": thermocouple.T,
}
temperatureUnits = map[string]temperature.Unit{
"C": temperature.C,
"F": temperature.F,
"K": temperature.K,
}
)
func getThermocoupleType(t string) (thermocouple.Type, error) {
if val, ok := thermocoupleTypes[t]; ok {
return val, nil
} else {
return thermocouple.None, ErrConfigBadThermocoupleType
}
}
func getTemperatureUnit(u string) (temperature.Unit, error) {
if val, ok := temperatureUnits[u]; ok {
return val, nil
} else {
return temperature.None, ErrConfigBadTemperatureUnit
}
}
func Load() (config.Config, error) {
var cfg config.Config
var err error
v := viper.New()
v.AddConfigPath(".")
v.SetConfigFile("config.toml")
err = v.ReadInConfig()
if err != nil {
return cfg, err
}
v.SetDefault("TH7.port", 8080)
v.SetDefault("TH7.cache", true)
v.SetDefault("TH7.LED", true)
v.SetDefault("TH7.logfreq", 60)
v.SetDefault("TH7.debug", false)
cfg.Board.Port = v.GetInt("TH7.port")
cfg.Board.Cache = v.GetBool("TH7.cache")
cfg.Board.Led = v.GetBool("TH7.LED")
cfg.Board.Logfreq = v.GetInt("TH7.logfreq")
cfg.Board.Debug = v.GetBool("TH7.debug")
cfg.Channels = make([]config.Channel, 0)
var c config.Channel
// set defaults for channels
for i := 1; i < 8; i++ {
var head = fmt.Sprintf("Channel_%d", i)
v.SetDefault(head+".gain", 106.8)
v.SetDefault(head+".offset", 0.0)
v.SetDefault(head+".unit", "C")
}
for i := 1; i < 8; i++ {
var head = fmt.Sprintf("Channel_%d", i)
tc := v.GetString(head + ".type")
// thermocouple type is non-optional, so if it doesnt exist
// then the entry does not exist.
if tc == "" {
continue
}
c.Id = i
c.Gain = v.GetFloat64(head + ".gain")
c.Offset = v.GetFloat64(head + ".offset")
tctype, err := getThermocoupleType(tc)
if err != nil {
return cfg, err
}
c.Thermo = tctype
unit, err := getTemperatureUnit(v.GetString(head + ".unit"))
if err != nil {
fmt.Printf("%s.unit=%c\n", head, v.GetInt(head+".unit"))
return cfg, err
}
c.Unit = unit
cfg.Channels = append(cfg.Channels, c)
}
cfg.DB = v.GetStringMap("DB")
return cfg, nil
}