-
Notifications
You must be signed in to change notification settings - Fork 2
/
cacheddevicestore.go
72 lines (59 loc) · 1.66 KB
/
cacheddevicestore.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
package deconz
import (
"errors"
"fmt"
)
// CachedDeviceStore is a cached typestore which provides LookupType for event passing
// it will be our default store
type CachedDeviceStore struct {
DeviceGetter
cache *Devices
}
// DeviceGetter defines how we like to ask for devices
type DeviceGetter interface {
Devices() (*Devices, error)
}
// SupportsResource returns true if this Store supports the resource type
func (c *CachedDeviceStore) SupportsResource(restype string) bool {
// TODO: determine the resource types we are interested in
return restype != "Unknown"
}
// 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 device added we dont know about
func (c *CachedDeviceStore) LookupType(id string) (string, error) {
var err error
if c.cache == nil {
err = c.populateCache()
if err != nil {
return "", fmt.Errorf("unable to populate devices: %s", err)
}
}
if s, found := (*c.cache)[id]; found {
return s.Type, nil
}
return "", errors.New("no such device")
}
// LookupDevice returns a device for an device id
func (c *CachedDeviceStore) LookupDevice(id string) (*Device, error) {
var err error
if c.cache == nil {
err = c.populateCache()
if err != nil {
return nil, fmt.Errorf("unable to populate devices: %s", err)
}
}
if s, found := (*c.cache)[id]; found {
return &s, nil
}
return nil, errors.New("no such device")
}
func (c *CachedDeviceStore) populateCache() error {
var err error
c.cache, err = c.Devices()
if err != nil {
return err
}
//log.Printf("DeviceStore updated, found %d devices", len((*c.cache)))
return nil
}