-
Notifications
You must be signed in to change notification settings - Fork 2
/
refresher.go
59 lines (49 loc) · 1.41 KB
/
refresher.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
package plc
import (
"reflect"
"sync"
"time"
)
// A Refresher can be used to periodically reissue the read for every seen value, so that values are readily available in a cache.
type Refresher struct {
plc Reader
period time.Duration
seen map[string]struct{}
mutex sync.Mutex
// ErrorCallback is called if an error is encountered while refreshing.
// If no callback is set, the error is silently discarded (and you're a bad
// person for not handling your errors 😜).
ErrorCallback func(error)
}
var _ = Reader(&Refresher{}) // Compiler makes sure this type is a Reader
// NewRefresher returns a refresher that will update every read value.
func NewRefresher(plc Reader, period time.Duration) *Refresher {
return &Refresher{
plc: plc,
period: period,
seen: map[string]struct{}{},
}
}
func (r *Refresher) launchIfNecessary(name string, value interface{}, f func(v interface{})) {
r.mutex.Lock()
defer r.mutex.Unlock()
if _, ok := r.seen[name]; ok {
return
}
r.seen[name] = struct{}{}
value = reflect.New(reflect.TypeOf(value).Elem()).Interface()
go func() {
for _ = range time.NewTicker(r.period).C {
f(value)
}
}()
}
func (r *Refresher) ReadTag(name string, value interface{}) error {
r.launchIfNecessary(name, value, func(v interface{}) {
err := r.plc.ReadTag(name, v)
if err != nil && r.ErrorCallback != nil {
r.ErrorCallback(err)
}
})
return r.plc.ReadTag(name, value)
}