-
Notifications
You must be signed in to change notification settings - Fork 0
/
octree.go
124 lines (112 loc) · 2.57 KB
/
octree.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package main
import (
"fmt"
"log"
"strings"
"sync"
"github.com/openchirp/framework"
"github.com/openchirp/framework/rest"
)
type device struct {
rest.NodeDescriptor
data []byte
}
func (d *device) updateData(c *framework.UserClient) error {
node, err := c.FetchDeviceInfo(d.ID)
if err != nil {
return err
}
var out strings.Builder
out.WriteString(fmt.Sprintf("Name: %s\n", node.Name))
out.WriteString(fmt.Sprintf("ID: %s\n", node.ID))
out.WriteString(fmt.Sprintf("Owner: %s (%s)\n", node.Owner.Name, node.Owner.Email))
d.data = []byte(out.String())
return nil
}
type location struct {
mutex sync.Mutex
rest.LocationNode
updatedChildren bool
children map[string]*location
updatedDevices bool
devices map[string]*device
}
// pull the location info
func (l *location) pull(c *framework.UserClient) error {
loc, err := c.FetchLocation(l.ID)
if err != nil {
return err
}
l.LocationNode = loc
return nil
}
// updateChildren
func (l *location) updateChildren(c *framework.UserClient) error {
log.Println("Updating Children for", l.Name)
l.children = make(map[string]*location, len(l.Children))
for _, cID := range l.Children {
child := &location{LocationNode: rest.LocationNode{ID: cID}}
if err := child.pull(c); err != nil {
return err
}
name := child.Name
var generation = 2
for _, ok := l.children[name]; ok; _, ok = l.children[name] {
name = fmt.Sprint(child.Name, generation)
}
l.children[name] = child
}
l.updatedChildren = true
return nil
}
// updateDevices
func (l *location) updateDevices(c *framework.UserClient) error {
log.Println("Updating Devices for", l.Name)
devices, err := c.FetchLocationDevices(l.ID, false)
if err != nil {
return err
}
l.devices = make(map[string]*device, len(devices))
for _, d := range devices {
dev := &device{NodeDescriptor: d}
name := dev.Name
var generation = 2
for _, ok := l.devices[name]; ok; _, ok = l.devices[name] {
name = fmt.Sprint(dev.Name, generation)
}
l.devices[name] = dev
}
l.updatedDevices = true
return nil
}
func (l *location) ensureChildrenAndDevices(c *framework.UserClient) error {
e := make(chan error)
go func() {
var err error
if !l.updatedChildren {
err = l.updateChildren(c)
if err != nil {
log.Printf("Failed to update children %v", err)
}
}
e <- err
}()
go func() {
var err error
if !l.updatedDevices {
err = l.updateDevices(c)
if err != nil {
log.Printf("Failed to update devices %v", err)
}
}
e <- err
}()
e1, e2 := <-e, <-e
if e1 != nil {
return e1
}
if e2 != nil {
return e2
}
return nil
}