|
| 1 | +package config |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "io" |
| 6 | + |
| 7 | + "github.com/lazy-electron-consulting/ve-direct-exporter/internal/util" |
| 8 | + "gopkg.in/yaml.v2" |
| 9 | +) |
| 10 | + |
| 11 | +const ( |
| 12 | + DefaultAddress = ":8000" |
| 13 | + DefaultBaudRate = 19200 |
| 14 | + DefaultDataBits = 8 |
| 15 | + DefaultStopBits = 1 |
| 16 | + DefaultParity = "N" |
| 17 | +) |
| 18 | + |
| 19 | +type Serial struct { |
| 20 | + Path string `json:"path,omitempty" yaml:"path,omitempty"` |
| 21 | + BaudRate int `json:"baudRate,omitempty" yaml:"baudRate,omitempty"` |
| 22 | + DataBits int `json:"dataBits,omitempty" yaml:"dataBits,omitempty"` |
| 23 | + StopBits int `json:"stopBits,omitempty" yaml:"stopBits,omitempty"` |
| 24 | + Parity string `json:"parity,omitempty" yaml:"parity,omitempty"` |
| 25 | +} |
| 26 | + |
| 27 | +func (m *Serial) defaults() { |
| 28 | + m.BaudRate = util.Default(m.BaudRate, DefaultBaudRate) |
| 29 | + m.DataBits = util.Default(m.DataBits, DefaultDataBits) |
| 30 | + m.StopBits = util.Default(m.StopBits, DefaultStopBits) |
| 31 | + m.Parity = util.Default(m.Parity, DefaultParity) |
| 32 | +} |
| 33 | + |
| 34 | +type Gauge struct { |
| 35 | + Name string `json:"name,omitempty" yaml:"name,omitempty"` |
| 36 | + Label string `json:"label,omitempty" yaml:"label,omitempty"` |
| 37 | + Help string `json:"help,omitempty" yaml:"help,omitempty"` |
| 38 | + Multiplier float32 `json:"multiplier,omitempty" yaml:"multiplier,omitempty"` |
| 39 | +} |
| 40 | + |
| 41 | +type Config struct { |
| 42 | + Address string `json:"address,omitempty" yaml:"address,omitempty"` |
| 43 | + Serial Serial `json:"serial,omitempty" yaml:"serial,omitempty"` |
| 44 | + Gauges []Gauge `json:"gauges,omitempty" yaml:"gauges,omitempty"` |
| 45 | +} |
| 46 | + |
| 47 | +func (c *Config) defaults() { |
| 48 | + c.Address = util.Default(c.Address, DefaultAddress) |
| 49 | + c.Serial.defaults() |
| 50 | + |
| 51 | +} |
| 52 | + |
| 53 | +func ParseYaml(r io.Reader) (*Config, error) { |
| 54 | + decoder := yaml.NewDecoder(r) |
| 55 | + decoder.SetStrict(true) |
| 56 | + |
| 57 | + var config Config |
| 58 | + if err := decoder.Decode(&config); err != nil { |
| 59 | + return nil, fmt.Errorf("failed to parse: %w", err) |
| 60 | + } |
| 61 | + config.defaults() |
| 62 | + return &config, nil |
| 63 | +} |
0 commit comments