forked from evcc-io/evcc
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcache.go
93 lines (75 loc) · 1.59 KB
/
cache.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
package util
import (
"sync"
)
// Cache is a data store
type Cache struct {
sync.Mutex
val map[string]Param
}
// NewCache creates cache
func NewCache() *Cache {
return &Cache{
val: make(map[string]Param),
}
}
// Run adds input channel's values to cache
func (c *Cache) Run(in <-chan Param) {
log := NewLogger("cache")
for p := range in {
log.DEBUG.Printf("%s: %v", p.Key, p.Val)
c.Add(p.UniqueID(), p)
}
}
// State provides a structured copy of the cached values
// Loadpoints are aggregated as loadpoints array
func (c *Cache) State() map[string]interface{} {
c.Lock()
defer c.Unlock()
res := map[string]interface{}{}
lps := make(map[int]map[string]interface{})
for _, param := range c.val {
if param.LoadPoint == nil {
res[param.Key] = param.Val
} else {
lp, ok := lps[*param.LoadPoint]
if !ok {
lp = make(map[string]interface{})
lps[*param.LoadPoint] = lp
}
lp[param.Key] = param.Val
}
}
// convert map to array
loadpoints := make([]map[string]interface{}, len(lps))
for id, lp := range lps {
loadpoints[id] = lp
}
res["loadpoints"] = loadpoints
return res
}
// All provides a copy of the cached values
func (c *Cache) All() []Param {
c.Lock()
defer c.Unlock()
copy := make([]Param, 0, len(c.val))
for _, val := range c.val {
copy = append(copy, val)
}
return copy
}
// Add entry to cache
func (c *Cache) Add(key string, param Param) {
c.Lock()
defer c.Unlock()
c.val[key] = param
}
// Get entry from cache
func (c *Cache) Get(key string) Param {
c.Lock()
defer c.Unlock()
if val, ok := c.val[key]; ok {
return val
}
return Param{}
}