-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpoller.go
87 lines (69 loc) · 1.52 KB
/
poller.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
package main
import (
"time"
"github.com/stewart/cmus"
)
type Poller struct {
Statuses chan map[string]interface{}
Errors chan error
IncrementalUpdates bool
initialized bool
previousStatus *cmus.Status
previousError error
tick *time.Ticker
done chan int
}
// Creates a new Poller.
// `incrementalUpdates` determines whether or not Statuses will be sent
// incremental status diffs, or the full status on each change.
func NewPoller(incrementalUpdates bool) *Poller {
p := &Poller{
Statuses: make(chan map[string]interface{}),
Errors: make(chan error),
IncrementalUpdates: incrementalUpdates,
previousStatus: &cmus.Status{},
done: make(chan int),
}
return p
}
func (p *Poller) Poll() {
p.tick = time.NewTicker(200 * time.Millisecond)
for {
select {
case <-p.tick.C:
p.update()
case <-p.done:
p.tick.Stop()
return
}
}
}
func (p *Poller) update() {
state.RLock()
defer state.RUnlock()
status := state.status
err := state.err
if err == nil {
diff := diffStatus(p.previousStatus, status)
if !p.initialized {
p.Statuses <- serializeStatus(status)
p.initialized = true
} else if p.previousError != nil || len(diff) > 0 {
if p.IncrementalUpdates {
p.Statuses <- diff
} else {
p.Statuses <- serializeStatus(status)
}
}
} else {
// if a new error, send error
if p.previousError == nil || p.previousError.Error() != err.Error() {
p.Errors <- err
}
}
p.previousStatus = status
p.previousError = err
}
func (p *Poller) Close() {
close(p.done)
}