forked from gonium/gosdm630
-
Notifications
You must be signed in to change notification settings - Fork 0
/
measurementcache.go
53 lines (47 loc) · 1.12 KB
/
measurementcache.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
package sdm630
import (
"github.com/zfjagann/golang-ring"
"log"
)
type MeasurementCache struct {
datastream ReadingChannel
secsBetweenReadings int
lastminutebuffer *ring.Ring
lastreading Readings
verbose bool
}
func NewMeasurementCache(ds ReadingChannel, interval int, isVerbose bool) *MeasurementCache {
r := &ring.Ring{}
r.SetCapacity(60 / interval)
return &MeasurementCache{
datastream: ds,
secsBetweenReadings: interval,
lastminutebuffer: r,
verbose: isVerbose,
}
}
func (mc *MeasurementCache) ConsumeData() {
for {
reading := <-mc.datastream
mc.lastreading = reading
mc.lastminutebuffer.Enqueue(reading)
if mc.verbose {
log.Printf("%s\r\n", &mc.lastreading)
}
}
}
func (mc *MeasurementCache) GetLast() Readings {
return mc.lastreading
}
func (mc *MeasurementCache) GetMinuteAvg() Readings {
measurements := mc.lastminutebuffer.Values()
var avg Readings
for _, m := range measurements {
r, _ := m.(Readings)
avg = r.add(&avg)
}
if mc.verbose {
log.Printf("%s\r\n", avg.String())
}
return avg.divide(float32(len(measurements)))
}