-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
116 lines (99 loc) · 2.1 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
113
114
115
116
package main
import (
"context"
"flag"
"github.com/hashicorp/hcl"
"io/ioutil"
"lib.hemtjan.st/client"
"lib.hemtjan.st/transport/mqtt"
"log"
"os"
"os/signal"
"strings"
"sync"
"syscall"
)
var (
cfgFileFlag = flag.String("hl.config", "/etc/hallonlarm.conf", "Configuration file for HallonLarm")
)
func main() {
wg := sync.WaitGroup{}
mCfg := mqtt.MustFlags(flag.String, flag.Bool)
flag.Parse()
cfgFile, err := ioutil.ReadFile(*cfgFileFlag)
if err != nil {
log.Fatal("Unable to read config ("+*cfgFileFlag+"): ", err)
}
cfg := &Config{}
if err := hcl.Unmarshal(cfgFile, cfg); err != nil {
log.Fatal("Unable to parse config: ", err)
}
ctx, cancel := context.WithCancel(context.Background())
go func() {
quit := make(chan os.Signal)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
cancel()
}()
mq, err := mqtt.New(ctx, mCfg())
if err != nil {
log.Fatal(err)
}
/*
Loop through configured devices and set up
*/
for topic, dev := range cfg.Device {
devInfo := dev.DeviceInfo(topic)
md, err := client.NewDevice(devInfo, mq)
if err != nil {
log.Printf("Invalid configuration for %s: %s", topic, err)
continue
}
for name, ft := range dev.Feature {
ftr := md.Feature(name)
if ft.GpioIn != nil && ft.GpioIn.Pin > 0 {
reader := NewGpioReader(*ft.GpioIn)
wg.Add(1)
go func() {
defer wg.Done()
gpioInReporter(ftr, reader.C)
}()
wg.Add(1)
go func() {
defer wg.Done()
reader.Start(ctx)
}()
}
if ft.GpioOut != nil && ft.GpioOut.Pin > 0 {
writer := NewGpioWriter(*ft.GpioOut)
err := ftr.OnSetFunc(func(val string) {
writer.C <- val == "1" || strings.ToLower(val) == "true"
_ = ftr.Update(val)
})
if err != nil {
log.Printf("Unable to subscribe to feature %s -> %s: %s", topic, name, err)
continue
}
wg.Add(1)
go func() {
defer wg.Done()
writer.Start(ctx)
}()
}
}
}
wg.Wait()
}
func gpioInReporter(ft client.Feature, ch chan bool) {
for {
st, open := <-ch
if !open {
return
}
val := "0"
if st {
val = "1"
}
_ = ft.Update(val)
}
}