-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
112 lines (98 loc) · 2.42 KB
/
main.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package main
import (
"encoding/json"
"fmt"
"gopkg.in/yaml.v2"
"log"
"os"
"os/signal"
"syscall"
)
type Config struct {
Debug bool `yaml:"debug"`
BobcatAddress string `yaml:"bobcatAddress"`
IntervalSeconds int `yaml:"intervalSeconds"`
Mqtt struct {
Enabled bool `yaml:"enabled"`
Server string `yaml:"server"`
Port int `yaml:"port,omitempty"`
Username string `yaml:"username"`
Password string `yaml:"password"`
ClientId string `yaml:"clientId,omitempty"`
TopicRoot string `yaml:"topicRoot"`
} `yaml:"mqtt"`
}
func readConfig() (*Config, error) {
config := &Config{}
file, err := os.Open("config.yml")
if err != nil {
return nil, err
}
defer file.Close()
decoder := yaml.NewDecoder(file)
if err := decoder.Decode(config); err != nil {
return nil, err
}
return config, nil
}
func main() {
osChannel := make(chan os.Signal, 1)
signal.Notify(osChannel, os.Interrupt, syscall.SIGTERM)
// LOAD CONFIG
config, err := readConfig()
if err != nil {
log.Fatalln("Failed to read config. Exiting!")
return
}
mqttBus := MqttBus{}
if config.Mqtt.Enabled {
if config.Debug {
fmt.Println("MQTT ENABLED, CONNECTING...")
}
if config.Mqtt.TopicRoot == "" {
config.Mqtt.TopicRoot = "bobcat-monitor"
}
mqttBus.Debug = config.Debug
mqttBus.Server = config.Mqtt.Server
mqttBus.Port = config.Mqtt.Port
mqttBus.Username = config.Mqtt.Username
mqttBus.Password = config.Mqtt.Password
mqttBus.ClientId = config.Mqtt.ClientId
mqttBus.TopicRoot = config.Mqtt.TopicRoot
mqttBus.Initialize()
if config.Debug {
fmt.Println("MQTT BUS INITIALIZED")
}
}
bobcatChannel := make(chan BobcatStatus, 5)
bobcat := Bobcat{
Debug: config.Debug,
periodSeconds: config.IntervalSeconds,
address: config.BobcatAddress,
eventChannel: bobcatChannel,
}
go bobcat.Begin()
println("BOBCAT INIT DONE!")
go func() {
for {
bobcatStatus := <-bobcatChannel
if config.Mqtt.Enabled {
if config.Debug {
log.Println("POSTING STATUS TO MQTT...")
}
payload, err := json.Marshal(bobcatStatus)
if err != nil {
log.Printf("Error while unmarshalling JSON: %s", err)
} else {
var topic = config.Mqtt.TopicRoot + "/bobcat"
mqttBus.SendMessage(topic, payload)
if config.Debug {
log.Printf("SENT MQTT MESSAGE: %s TO TOPIC %s \n", payload, topic)
}
}
}
}
}()
// WAIT FOR SIGTERM FOREVER
<-osChannel
}