This repository has been archived by the owner on Feb 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
227 lines (192 loc) · 5.83 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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
package main
import (
"fmt"
"log"
"net/http"
"os"
"strings"
"sync"
"time"
"github.com/gorilla/websocket"
"goji.io"
"goji.io/pat"
)
type DeviceID string
type Command struct {
Scene string `json:"scene"`
Fade time.Duration `json:"fade"`
}
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool { return true },
}
type CommandAndControl struct {
M sync.Mutex
LastCommand map[DeviceID]Command
Connections map[DeviceID]map[*websocket.Conn]bool
}
func (cnc *CommandAndControl) sendCommand(conn *websocket.Conn, cmd Command) error {
return conn.WriteJSON(cmd)
}
func (cnc *CommandAndControl) blastCommand(device DeviceID, cmd Command) error {
cnc.M.Lock()
defer cnc.M.Unlock()
log.Printf("cnc: blasting command: device=%s command=%s devices=%d", device, cmd, len(cnc.Connections[device]))
var firstErr error
for conn := range cnc.Connections[device] {
err := cnc.sendCommand(conn, cmd)
if err != nil {
log.Printf("cnc: error sending command: device=%s addr=%s command=%s err=%q",
device, conn.RemoteAddr().String(), cmd, err)
}
if firstErr == nil {
firstErr = err
}
}
cnc.LastCommand[device] = cmd
return firstErr
}
// HandleWebsocket accepts incoming connections. To subscribe to
// commands, a device just needs to connect. The only data sent from
// the device to the CNC server is a device identifier, which is
// provided as part of the URL.
//
// Otherwise, the only non-control message sent over the websocket are
// commands, which are sent as websocket text messages. (Note that the
// fade time is encoded in nanoseconds.)
//
// If a command has previously been sent to the named device through
// this server, that command is automatically sent to the device when
// it first connects.
func (cnc *CommandAndControl) HandleWebsocket(w http.ResponseWriter, r *http.Request) {
device := DeviceID(pat.Param(r, "device"))
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Printf("cnc: error upgrading websocket: device=%s addr=%s err=%q",
device, r.RemoteAddr, err)
http.Error(w, err.Error(), 500)
return
}
log.Printf("cnc: accepted new connection: device=%s addr=%s",
device, r.RemoteAddr)
// we never need to read messages, so spin off a goroutine to
// handle connection maintenance and close
go func() {
if _, _, err := conn.NextReader(); err != nil {
log.Printf("cnc: connection closed: device=%s addr=%s",
device, r.RemoteAddr)
conn.Close()
cnc.M.Lock()
defer cnc.M.Unlock()
delete(cnc.Connections[device], conn)
return
}
}()
cnc.M.Lock()
defer cnc.M.Unlock()
if cmd, ok := cnc.LastCommand[device]; ok {
log.Printf("cnc: sending initial command to device: device=%s addr=%s command=%s",
device, r.RemoteAddr, cmd)
err := cnc.sendCommand(conn, cmd)
if err != nil {
log.Printf("cnc: error sending initial command to device: device=%s addr=%s err=%q",
device, r.RemoteAddr, err)
return
}
}
if _, ok := cnc.Connections[device]; !ok {
cnc.Connections[device] = make(map[*websocket.Conn]bool)
}
cnc.Connections[device][conn] = true
}
type sequenceElem struct {
deviceID DeviceID
command Command
}
// HandleSequence handles control requests to send a sequence of
// changes to the devices
//
// It accepts a "sequence" form argument as either a query string or
// POST parameter. The sequence is a series of commands, which are
// each a tuple of (device ID, scene, fade time) joined with ".". The
// separate commands are joined with ","
//
// (These aren't the greatest separators, but it keeps the protocol
// simple and concise.)
//
// Ex (GET): curl -i http://127.0.0.1:8080/sequence?sequence=a.SolidRed.2s,b.SolidGreen.1s500ms
// EX (POST): curl -i -X POST http://127.0.0.1:8080/sequence -d "sequence=a.SolidRed.2s,b.SolidGreen.1s500ms"
//
// It returns a 200 if all commands were successfully sent to all
// connected devices, and a 500 otherwise.
func (cnc *CommandAndControl) HandleSequence(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
http.Error(w, err.Error(), 400)
}
sequence := r.Form.Get("sequence")
if sequence == "" {
http.Error(w, "no sequence provided", 400)
return
}
commandStrings := strings.Split(sequence, ",")
commands := make([]sequenceElem, 0, len(commandStrings))
for _, str := range commandStrings {
split := strings.Split(str, ".")
if len(split) != 3 {
http.Error(w, fmt.Sprintf("malformed sequence: %s", str), 400)
return
}
deviceID := DeviceID(split[0])
scene := split[1]
fade, err := time.ParseDuration(split[2])
if err != nil {
http.Error(w, fmt.Sprintf("malformed sequence fade duration: %s", str), 400)
return
}
commands = append(commands, sequenceElem{deviceID, Command{scene, fade}})
}
var firstErr error
for _, elem := range commands {
err := cnc.blastCommand(elem.deviceID, elem.command)
if firstErr == nil {
firstErr = err
}
}
if err != nil {
w.WriteHeader(500)
w.Write([]byte("error\n"))
return
}
w.Write([]byte("ok\n"))
}
func main() {
cnc := CommandAndControl{
LastCommand: make(map[DeviceID]Command),
Connections: make(map[DeviceID]map[*websocket.Conn]bool),
}
mux := goji.NewMux()
mux.Use(func(h http.Handler) http.Handler {
if os.Getenv("HUNT_REDIRECT_HTTP") == "" {
return h
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/healthz" {
h.ServeHTTP(w, r)
return
}
if r.Header.Get("X-Forwarded-Proto") == "https" {
h.ServeHTTP(w, r)
return
}
url := r.URL
url.Scheme = "https"
http.Redirect(w, r, url.String(), http.StatusPermanentRedirect)
})
})
mux.HandleFunc(pat.Get("/ws/:device"), cnc.HandleWebsocket)
mux.HandleFunc(pat.New("/sequence"), cnc.HandleSequence)
mux.HandleFunc(pat.Get("/healthz"), func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("ok\n"))
})
http.ListenAndServe(":8080", mux)
}