forked from bpicode/fritzctl
/
devicelist.go
84 lines (75 loc) · 2.03 KB
/
devicelist.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
package fritz
import "strings"
// Devicelist wraps a list of devices. This corresponds to
// the outer layer of the xml that the FRITZ!Box returns.
type Devicelist struct {
Devices []Device `xml:"device"`
Groups []Group `xml:"group"`
}
// DeviceGroup is an inflated version of one Group with multiple Device members.
type DeviceGroup struct {
Group Group
Devices []Device
}
// Switches returns the devices which satisfy IsSwitch.
func (l *Devicelist) Switches() []Device {
var switches []Device
for _, d := range l.Devices {
if d.IsSwitch() {
switches = append(switches, d)
}
}
return switches
}
// Thermostats returns the devices which satisfy IsThermostat.
func (l *Devicelist) Thermostats() []Device {
var thermostats []Device
for _, d := range l.Devices {
if d.IsThermostat() {
thermostats = append(thermostats, d)
}
}
return thermostats
}
// DeviceGroups returns a slice of DeviceGroup by joining Group.Members() on Device.ID.
func (l *Devicelist) DeviceGroups() []DeviceGroup {
var gs []DeviceGroup
for _, g := range l.Groups {
ds := l.devicesWithIDs(g.Members())
gs = append(gs, DeviceGroup{Group: g, Devices: ds})
}
return gs
}
// DeviceWithID searches for a Device by its ID returns a the found/zero value and a flag true/false indicating
// whether the search was successful.
func (l *Devicelist) DeviceWithID(id string) (Device, bool) {
for _, d := range l.Devices {
if d.ID == id {
return d, true
}
}
return Device{}, false
}
// NamesAndAins returns a lookup name -> AIN.
func (l *Devicelist) NamesAndAins() map[string]string {
ds := l.Devices
gs := l.Groups
table := make(map[string]string, len(ds)+len(gs))
for _, grp := range gs {
table[grp.Name] = strings.Replace(grp.Identifier, " ", "", -1)
}
for _, dev := range ds {
table[dev.Name] = strings.Replace(dev.Identifier, " ", "", -1)
}
return table
}
func (l *Devicelist) devicesWithIDs(ids []string) []Device {
var ds []Device
for _, id := range ids {
if d, ok := l.DeviceWithID(id); ok {
ds = append(ds, d)
continue
}
}
return ds
}