-
Notifications
You must be signed in to change notification settings - Fork 6
/
config.go
66 lines (56 loc) · 1.24 KB
/
config.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package main
import (
"fmt"
"log"
"github.com/currantlabs/ble/linux"
"gopkg.in/ini.v1"
)
// Config represents a configuration
type Config struct {
MQTT MQTT
Devices []Device
Host *linux.Device
}
// NewConfig returns a new Config
func NewConfig(file string) (*Config, error) {
log.Printf("[Config] Loading Configuration (%s)", file)
cfg, err := ini.Load(file)
if err != nil {
return &Config{}, err
}
sec, err := cfg.GetSection("MQTT")
if err != nil {
return &Config{}, err
}
if !sec.HasKey("host") {
return &Config{}, fmt.Errorf("Configuration requires MQTT host")
}
if !sec.HasKey("port") {
log.Print("MQTT port not defined; defaulting to 1883")
sec.NewKey("port", "1883")
}
mqtt := MQTT{
Host: sec.Key("host").String(),
Port: sec.Key("port").String(),
User: sec.Key("user").String(),
Pass: sec.Key("pass").String(),
}
sec, err = cfg.GetSection("Devices")
if err != nil {
return &Config{}, err
}
names := sec.KeyStrings()
devices := []Device{}
for i, name := range names {
addr := sec.Key(name).String()
log.Printf("[Config] Device %02d: %s (%s)", i, name, addr)
devices = append(devices, Device{
Name: name,
Addr: addr,
})
}
return &Config{
MQTT: mqtt,
Devices: devices,
}, nil
}