forked from fasmide/deflux
/
cachedsensorstore.go
77 lines (64 loc) · 1.7 KB
/
cachedsensorstore.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
package deconz
import (
"errors"
"fmt"
"log"
)
// CachedSensorStore is a cached typestore which provides LookupType for event passing
// it will be our default store
type CachedSensorStore struct {
SensorGetter
cache *Sensors
}
// SensorGetter defines how we like to ask for sensors
type SensorGetter interface {
Sensors() (*Sensors, error)
}
// LookupType lookups deCONZ event types though a cache
// TODO: if we where unable to lookup an ID we should try to refetch the cache
// - there could have been an sensor added we dont know about
func (c *CachedSensorStore) LookupType(i int) (string, error) {
var err error
if c.cache == nil {
err = c.populateCache()
if err != nil {
return "", fmt.Errorf("unable to populate sensors: %s", err)
}
}
if s, found := (*c.cache)[i]; found {
return s.Type, nil
}
return "", errors.New("no such sensor")
}
// LookupSensor returns a sensor for an sensor id
func (c *CachedSensorStore) LookupSensor(i int) (*Sensor, error) {
var err error
if c.cache == nil {
err = c.populateCache()
if err != nil {
return nil, fmt.Errorf("unable to populate sensors: %s", err)
}
}
if s, found := (*c.cache)[i]; found {
return &s, nil
}
// try repopulating cache once to see if any new sensors have arrived
// could be better logic here...
err = c.populateCache()
if err != nil {
return nil, fmt.Errorf("unable to populate sensors: %s", err)
}
if s, found := (*c.cache)[i]; found {
return &s, nil
}
return nil, errors.New("no such sensor")
}
func (c *CachedSensorStore) populateCache() error {
var err error
c.cache, err = c.Sensors()
if err != nil {
return err
}
log.Printf("SensorStore updated, found %d sensors", len((*c.cache)))
return nil
}