-
Notifications
You must be signed in to change notification settings - Fork 29
/
cgmhistory.go
56 lines (53 loc) · 1.37 KB
/
cgmhistory.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
package medtronic
import (
"log"
"time"
)
// CGMHistory returns the CGM records since the specified time.
func (pump *Pump) CGMHistory(since time.Time) CGMHistory {
n := pump.CGMCurrentGlucosePage()
m := n - MaxGlucosePages + 1
if m < 0 {
m = 0
}
if pump.Error() != nil {
return nil
}
var results CGMHistory
var last time.Time
wroteTimestamp := false
for page := n; page >= m && pump.Error() == nil; page-- {
data := pump.GlucosePage(page)
records, t, err := DecodeCGMHistory(data, last)
if err != nil {
if err == ErrorNeedsTimestamp && page == n && !wroteTimestamp {
// This is only tried once, for the first page.
log.Printf("writing CGM timestamp for page %d and rescanning", page)
pump.CGMWriteTimestamp()
wroteTimestamp = true
page = n + 1
continue
}
pump.SetError(err)
}
i := findCGMSince(records, since)
results = append(results, records[:i]...)
if i < len(records) {
break
}
last = t
}
return results
}
// findCGMSince finds the first record that did not occur after the cutoff and returns its index,
// or len(records) if all the records occur more recently.
func findCGMSince(records CGMHistory, cutoff time.Time) int {
for i, r := range records {
t := r.Time
if !t.IsZero() && !t.After(cutoff) {
log.Printf("stopping CGM history scan at %s", t.Format(UserTimeLayout))
return i
}
}
return len(records)
}