forked from bpicode/fritzctl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
list_groups.go
103 lines (88 loc) · 2.46 KB
/
list_groups.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
package cmd
import (
"os"
"sort"
"strings"
"github.com/bpicode/fritzctl/console"
"github.com/bpicode/fritzctl/fritz"
"github.com/bpicode/fritzctl/stringutils"
"github.com/spf13/cobra"
)
var listGroupsCmd = &cobra.Command{
Use: "groups",
Short: "List the device groups",
Long: "List the device groups configured at the FRITZ!Box.",
Example: "fritzctl list groups",
RunE: listGroups,
}
func init() {
listCmd.AddCommand(listGroupsCmd)
}
func listGroups(_ *cobra.Command, _ []string) error {
c := homeAutoClient()
list, err := c.List()
assertNoErr(err, "cannot obtain data for smart home groups")
printGroups(list)
return nil
}
type byGroupName []fritz.DeviceGroup
// Len returns the length of the slice.
func (p byGroupName) Len() int {
return len(p)
}
// Swap exchanges elements in the slice.
func (p byGroupName) Swap(i, j int) {
p[i], p[j] = p[j], p[i]
}
// Less compares group names.
func (p byGroupName) Less(i, j int) bool {
return p[i].Group.Name < p[j].Group.Name
}
func printGroups(list *fritz.Devicelist) {
groups := list.DeviceGroups()
sort.Sort(byGroupName(groups))
table := console.NewTable(console.Headers("NAME", "MEMBERS", "MASTER", "PRESENT", "STATE", "TEMP (MEAS/WANT/SAV/COMF) [°C]"))
for _, g := range groups {
table.Append(groupColumns(g, list))
}
table.Print(os.Stdout)
}
func groupColumns(group fritz.DeviceGroup, list *fritz.Devicelist) []string {
return []string{
group.Group.Name,
strings.Join(memberNames(group, list), ", "),
masterName(group, list),
console.IntToCheckmark(group.Group.Present),
console.StringToCheckmark(group.Group.Switch.State),
joinTemperatures(group.Group.Thermostat),
}
}
func memberNames(group fritz.DeviceGroup, list *fritz.Devicelist) []string {
var names []string
for _, id := range group.Group.Members() {
if d, ok := list.DeviceWithID(id); ok {
names = append(names, d.Name)
}
}
sort.Strings(names)
return names
}
func masterName(group fritz.DeviceGroup, list *fritz.Devicelist) string {
master, ok := list.DeviceWithID(group.Group.GroupInfo.MasterDeviceID)
if !ok {
return "(none)"
}
return master.Name
}
func joinTemperatures(th fritz.Thermostat) string {
return strings.Join([]string{
valueOrQm(th.FmtMeasuredTemperature),
valueOrQm(th.FmtGoalTemperature),
valueOrQm(th.FmtSavingTemperature),
valueOrQm(th.FmtComfortTemperature)},
"/")
}
func valueOrQm(f func() string) string {
yellowQm := console.Yellow("?")
return stringutils.DefaultIfEmpty(f(), yellowQm)
}