-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
250 lines (220 loc) · 5.53 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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
package main
import (
"context"
"fmt"
"math"
"net/http"
"strings"
"sync"
"syscall"
"time"
"github.com/prometheus/client_golang/prometheus/promhttp"
log "github.com/sirupsen/logrus"
"github.com/go-ble/ble"
"github.com/go-ble/ble/examples/lib/dev"
"github.com/pkg/errors"
"github.com/spf13/viper"
"github.com/vrecan/death/v3"
)
type Sensor struct {
sync.RWMutex
Name string
Addr string
Parser AdvParser
Updates <-chan ble.Advertisement
currReading *Reading
updtTime time.Time
// TODO: expire the reading if it has been too long since an update
}
func (s *Sensor) Run(ctx context.Context) {
log.Infof("starting sensor %s", s.Name)
go func() {
defer log.Infof("halting sensor %s", s.Name)
for {
select {
case <-ctx.Done():
return
case adv := <-s.Updates:
if adv == nil {
// update channel closed, we're done
return
}
r, err := s.Parser.Parse(adv)
if err != nil {
log.Printf("parsing advertisement for %s: %s", s.Name, err)
continue
}
s.Lock()
s.currReading = r
s.updtTime = time.Now()
s.Unlock()
log.Info(s.String())
}
}
}()
}
func (s *Sensor) String() string {
s.RLock()
defer s.RUnlock()
if s.currReading == nil {
return fmt.Sprintf("[%s] - no reading", s.Name)
}
return fmt.Sprintf("[%s] %s (as of %s)", s.Name, s.currReading, s.updtTime.Format(time.RFC3339))
}
func (s *Sensor) IsStale() bool {
if s.currReading == nil {
return true
}
// TODO: add threshold config for updtTime too old
return false
}
func (s *Sensor) Temperature() float64 {
s.RLock()
defer s.RUnlock()
if s.currReading == nil {
return math.NaN()
}
return float64(s.currReading.Temp)
}
func (s *Sensor) Humidity() float64 {
s.RLock()
defer s.RUnlock()
if s.currReading == nil {
return math.NaN()
}
return float64(s.currReading.Humidity)
}
func (s *Sensor) Battery() float64 {
s.RLock()
defer s.RUnlock()
if s.currReading == nil {
return math.NaN()
}
return float64(s.currReading.Battery)
}
type Reading struct {
Temp float32
Humidity float32
Battery int8
}
func (r Reading) String() string {
return fmt.Sprintf("%.2f ℃ | %.2f%% humidity | %d%% battery", r.Temp, r.Humidity, r.Battery)
}
type ScannerOptions struct {
Duration time.Duration
Interval time.Duration
}
func startScanner(ctx context.Context, advRouter map[string]chan<- ble.Advertisement, options ScannerOptions) {
log.Infof("Scanner options: %#v", options)
go func() {
fmt.Printf("Scanning for %s...\n", options.Duration)
blectx := ble.WithSigHandler(context.WithTimeout(context.Background(), options.Duration))
chkErr(ble.Scan(blectx, true, handler(advRouter), supportedDeviceFilter))
interval := time.NewTicker(options.Interval)
for {
select {
case <-ctx.Done():
case <-interval.C:
// Scan for specified durantion, or until interrupted by user.
log.Infof("Scanning for %s...\n", options.Duration)
blectx := ble.WithSigHandler(context.WithTimeout(context.Background(), options.Duration))
chkErr(ble.Scan(blectx, true, handler(advRouter), supportedDeviceFilter))
}
}
}()
}
func handler(advRouter map[string]chan<- ble.Advertisement) func(a ble.Advertisement) {
return func(a ble.Advertisement) {
upC, ok := advRouter[a.Addr().String()]
if !ok {
// not a sensor we're tracking
log.Infof("ignoring advertisement for %s", a.Addr())
return
}
upC <- a
}
}
func chkErr(err error) {
switch errors.Cause(err) {
case nil:
case context.DeadlineExceeded:
log.Infof("scanning done\n")
case context.Canceled:
log.Infof("scanning canceled\n")
default:
// the scanner should keep running so just log the unexpected error
log.Errorf("scanning: %s", err.Error())
}
}
func init() {
viper.AutomaticEnv()
viper.SetDefault("Scanner.Duration", 15*time.Second)
viper.SetDefault("Scanner.Interval", 5*time.Minute)
viper.SetDefault("prometheus.port", 2112)
viper.AddConfigPath("/etc/sensor-bridge")
viper.AddConfigPath("$HOME/.sensorbridge")
viper.AddConfigPath(".")
viper.SetConfigName("config")
// viper.SetConfigType("toml")
}
func main() {
err := viper.ReadInConfig()
if err != nil {
log.Fatal(err)
}
d, err := dev.NewDevice("default")
if err != nil {
log.Fatalf("can't create ble device: %s", err)
}
ble.SetDefaultDevice(d)
var sensors []*Sensor
err = viper.UnmarshalKey("sensors", &sensors)
if err != nil {
log.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
startScanner(ctx, initSensors(ctx, sensors), ScannerOptions{
Duration: viper.GetDuration("Scanner.Duration"),
Interval: viper.GetDuration("Scanner.Interval"),
})
for _, s := range sensors {
CreateGauges(s)
}
http.Handle("/metrics", promhttp.Handler())
go http.ListenAndServe(fmt.Sprintf(":%d", viper.GetInt("prometheus.port")), nil)
go func() {
for {
tick := time.NewTicker(10 * time.Second)
select {
case <-tick.C:
for _, s := range sensors {
log.Println(s.String())
}
case <-ctx.Done():
return
}
}
}()
// block until done
death := death.NewDeath(syscall.SIGINT, syscall.SIGTERM)
death.WaitForDeath()
}
func supportedDeviceFilter(a ble.Advertisement) bool {
supported := strings.HasPrefix(a.LocalName(), "GVH510")
if supported {
log.Infof("allow %s: %t", a.LocalName(), supported)
}
return supported
}
func initSensors(ctx context.Context, s []*Sensor) map[string]chan<- ble.Advertisement {
m := map[string]chan<- ble.Advertisement{}
for _, i := range s {
c := make(chan ble.Advertisement)
i.Updates = c
m[i.Addr] = c
i.Run(ctx)
i.Parser = H5102Parser{}
}
return m
}