-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.go
109 lines (90 loc) · 2.28 KB
/
main.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
package main
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
"strings"
)
// This handles the LIGHT status update sent from the child process
// name on/off brightness
func set_light_status(status []string) {
name := status[0]
power := false
if strings.ToUpper(status[1]) == "ON" {
power = true
}
bri, err := strconv.Atoi(status[2])
if err != nil {
bri = 0
}
name_index := name_to_index(name)
light := get_or_create_light(name_index, name)
if light.On != power {
log.Println("Got light update for", name, "setting Power", power)
light.On = power
}
if light.Bri != bri {
log.Println("Got light update for", name, "setting Brightness", bri)
light.Bri = bri
}
Lights[name_index] = light
}
// This takes a list of lights as reported by the LIST status update
// and ensures that this list matches the Lights map. Basically we
// create any missing entries with defaults, then delete ones that are
// no longer relevant
func update_light_list(lights []string) {
// We'll make the list of lights into a map so we can quickly compare
list := make(map[string]bool)
for _, v := range lights {
name_index := name_to_index(v)
list[name_index] = true
Lights[name_index] = get_or_create_light(name_index, v)
}
for v := range Lights {
_, ok := list[v]
if !ok {
log.Println("Deleting", v)
delete(Lights, v)
}
}
}
// Input to this function will be output from the child. The line
// either needs to be
// LIST#name1#name2 ...
// or
// LIGHT#name#on/off#brightness
//
// Note that names can have spaces in them; the separator is #
func on_read(s string) {
input := strings.Split(s, "#")
cmd := strings.ToUpper(input[0])
if cmd == "LIGHT" {
set_light_status(input[1:])
} else if cmd == "LIST" {
update_light_list(input[1:])
} else {
log.Println("Ignoring", s)
}
}
func main() {
if len(os.Args) != 2 {
log.Fatal("Syntax: ", os.Args[0], " child_program")
}
// Create the new lights map
Lights = make(map[string]Light_State)
// Set the child process running to update the light status
start_child(os.Args[1])
defer child.Wait()
go read_child(on_read)
// And now start the Hue listener
log.Fatal(hue_ListenAndServe())
stdin := bufio.NewReader(os.Stdin)
for {
fmt.Print("Enter text: ")
text, _ := stdin.ReadString('\n')
send_cmd_to_child(text)
}
}