-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathruuvibeacon.go
201 lines (181 loc) · 4.25 KB
/
ruuvibeacon.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
package ruuvibeacon
import (
"context"
"encoding/json"
"flag"
"fmt"
"log"
"net/http"
"os"
"strings"
"sync"
"time"
"github.com/peknur/ruuvitag"
)
// Publisher type
type Publisher = func(ctx context.Context, e *Envelope)
// Publishers hold functions to publish envelope
var Publishers = make(map[string]Publisher)
// Reading represents Readinged data
type Reading struct {
DeviceID string
Version string
Humidity float32
Temperature float32
Pressure uint32
AccelerationX float32
AccelerationY float32
AccelerationZ float32
BatteryVoltage float32
TXPower int8
MovementCounter uint8
Timestamp time.Time
}
// Envelope represent Beacon data in some point in time
type Envelope struct {
Host string
Tick int
Time time.Time
Started time.Time
Data []Reading
}
// Beacon object
type Beacon struct {
hostname string
scanner ruuvitag.Scanner
data map[string]Reading
mu sync.RWMutex
started time.Time
tick int
publishers []Publisher
}
// WebViewHandler is http handler
func (b *Beacon) WebViewHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
js, err := json.MarshalIndent(b, "", " ")
if err != nil {
log.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Write(js)
}
// Readings returns latest device readings as array
func (b *Beacon) Readings() []Reading {
b.mu.RLock()
defer b.mu.RUnlock()
d := make([]Reading, len(b.data))
i := 0
for _, v := range b.data {
d[i] = v
i++
}
return d
}
// EncodeEnvelope creates envelope for publisher
func (b *Beacon) EncodeEnvelope() *Envelope {
return &Envelope{
Host: b.hostname,
Tick: b.tick,
Time: time.Now(),
Started: b.started,
Data: b.Readings(),
}
}
// MarshalJSON is encodes an envelope
func (b *Beacon) MarshalJSON() ([]byte, error) {
return json.Marshal(b.EncodeEnvelope())
}
// Publisher publishes envelopes in intervals set by tick
func (b *Beacon) Publisher() {
ticker := time.NewTicker(time.Duration(b.tick) * time.Second)
for {
select {
case <-ticker.C:
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(b.tick)*time.Second)
defer cancel()
for _, p := range b.publishers {
go p(ctx, b.EncodeEnvelope())
}
}
}
}
// Scan starts scanner and updates beacon readings
func (b *Beacon) Scan() {
output := b.scanner.Start()
for {
data, ok := <-output
if ok == false {
log.Println("scanner closed channel")
return
}
b.setData(data.DeviceID(), newReading(data))
}
}
func (b *Beacon) setData(key string, value Reading) {
b.mu.Lock()
defer b.mu.Unlock()
b.data[key] = value
}
// newReading from Measurement
func newReading(m ruuvitag.Measurement) Reading {
return Reading{
m.DeviceID(),
fmt.Sprintf("%d", m.Format()),
m.Humidity(),
m.Temperature(),
m.Pressure(),
m.AccelerationX(),
m.AccelerationY(),
m.AccelerationZ(),
m.BatteryVoltage(),
m.TXPower(),
m.MovementCounter(),
m.Timestamp()}
}
func loadOuputs(outputs string) []Publisher {
if outputs == "" {
log.Panicln("invalid -output flag value")
}
selected := strings.Split(outputs, ",")
p := make([]Publisher, 0)
for _, s := range selected {
f, ok := Publishers[s]
if ok {
log.Printf("load '%s' publisher", s)
p = append(p, f)
}
}
return p
}
// Run ruuvibeacon
func Run() {
var tick int
var scannerBufferSize int
var httpPort string
var outputs string
flag.IntVar(&tick, "tick", 60, "Data sending interval (seconds)")
flag.IntVar(&scannerBufferSize, "buffer", 10, "Scanner buffer size. How many measurements are buffered.")
flag.StringVar(&httpPort, "port", "8080", "httpd server port")
flag.StringVar(&outputs, "output", "log", "comma separated list of outputs")
flag.Parse()
scanner, err := ruuvitag.OpenScanner(scannerBufferSize)
if err != nil {
log.Fatal(err)
}
defer scanner.Stop()
hostname, _ := os.Hostname()
beacon := Beacon{
scanner: scanner,
data: make(map[string]Reading),
started: time.Now(),
tick: tick,
hostname: hostname,
publishers: loadOuputs(outputs),
}
go beacon.Scan()
go beacon.Publisher()
http.HandleFunc("/", beacon.WebViewHandler)
<-httpListenAndServer(":" + httpPort)
log.Println("shutting down ..")
}