-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
276 lines (244 loc) · 7.4 KB
/
server.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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
// Copyright 2017 Jacob Hesch
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/*
Server provides a basic mobile-friendly web app to control and monitor
an Integra device such as an A/V receiver. The web app uses WebSockets
to display real-time changes to the device, including changes made
elsewhere like the volume knob on the receiver or buttons on the
remote.
Server also offers a simple HTTP interface at /integra for sending
ISCP (Integra Serial Control Protocol) messages and reading the
current state of the device.
The following examples assume this server is running on localhost port
8080.
Example commands to send ISCP power on (PWR01) and volume up (MVLUP)
messages to the device by issuing POST requests to /integra:
$ curl :8080/integra -d PWR01
ok
$ curl :8080/integra -d MVLUP
ok
Up to 10 messages can be sent at once by separating them with newlines
in the request body. (Note that the $'string' form causes shells like
bash to replace occurrences of \n with newlines.) Example:
$ curl :8080/integra -d $'PWR01\nMVLUP\nSLI03'
ok
Example command to query the Integra device state by issuing a GET
request to /integra (returns JSON):
$ curl :8080/integra
{"MVL":"42","PWR":"01"}
Note that the device state reported by GET /integra is not necessarily
complete; it is made up of the messages received from the Integra
device since the server was started. If desired values are missing
from the reported device state, it can be useful to send a series of
QSTN messages to populate the state:
$ curl :8080/integra
{}
$ curl :8080/integra -d $'PWRQSTN\nMVLQSTN\nSLIQSTN'
ok
$ curl :8080/integra
{"MVL":"42","PWR":"01","SLI":"03"}
*/
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"html/template"
"io/ioutil"
"log"
"net/http"
"os"
"time"
"github.com/gorilla/websocket"
"github.com/jhesch/integra"
)
var (
httpaddr = flag.String("httpaddr", ":8080", "HTTP listen address")
integraaddr = flag.String("integraaddr", ":60128", "Integra device address")
verbose = flag.Bool("verbose", false, "Verbose logging")
)
// websocketRead blocks waiting for messages to arrive from the
// websocket connection and forwards them to the Integra device.
func websocketRead(wsConn *websocket.Conn, integraClient *integra.Client) {
for {
_, m, err := wsConn.ReadMessage()
if err != nil {
// Log errors, except for logging websocket
// going away errors (they happen every time a
// browser tab is closed).
if !websocket.IsCloseError(err, websocket.CloseGoingAway) {
log.Println("ReadMessage failed:", err)
}
return
}
var message integra.Message
err = json.Unmarshal(m, &message)
if err != nil {
log.Println("Unmarshall failed:", err)
}
err = integraClient.Send(&message)
if err != nil {
log.Println("Send failed:", err)
continue
}
}
}
// websocketWrite blocks waiting for messages to arrive from the
// Integra device and forwards them to the websocket connection.
func websocketWrite(wsConn *websocket.Conn, integraClient *integra.Client) {
for {
message, err := integraClient.Receive()
if err != nil {
if *verbose {
log.Println("Receive failed:", err)
log.Println("Closing websocket")
}
_ = wsConn.WriteMessage(websocket.CloseMessage, []byte{})
return
}
err = wsConn.WriteJSON(message)
if err != nil {
log.Println("WriteJSON failed:", err)
log.Println("Closing websocket")
_ = wsConn.WriteMessage(websocket.CloseMessage, []byte{})
return
}
}
}
func serveWs(client *integra.Client, w http.ResponseWriter, r *http.Request) {
upgrader := websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println("Upgrade failed:", err)
return
}
defer conn.Close()
go websocketWrite(conn, client)
websocketRead(conn, client)
}
func serveIntegraPost(client *integra.Client, w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
b, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Println("ReadAll failed:", err)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
messages := bytes.Split(bytes.TrimSpace(b), []byte("\n"))
if len(messages) > 10 {
http.Error(w, "Max messages (10) exceeded", http.StatusBadRequest)
return
}
for i, messageBytes := range messages {
message, err := integra.NewMessage(messageBytes)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if i > 0 {
time.Sleep(50 * time.Millisecond)
}
err = client.Send(message)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
fmt.Fprintln(w, "ok")
}
func serveIntegra(client *integra.Client, w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
state, err := json.Marshal(client.State())
if err != nil {
log.Println("Marshal failed:", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
_, err = w.Write(state)
if err != nil {
log.Println("Write failed:", err)
return
}
} else if r.Method == "POST" {
serveIntegraPost(client, w, r)
} else {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
}
type input struct {
Name string `json:"name"`
Value string `json:"value"`
}
type config struct {
Title string `json:"title"`
CSS []string `json:"css"`
Scripts []string `json:"scripts"`
Inputs []input `json:"inputs"`
}
func serveRoot() {
// Copy server/config.json.sample to server/config.json and
// modify to customize web app HTML.
var configFile string
if _, err := os.Stat("server/config.json"); os.IsNotExist(err) {
configFile = "server/config.json.sample"
} else {
configFile = "server/config.json"
}
log.Println("Using UI config file", configFile)
data, err := ioutil.ReadFile(configFile)
if err != nil {
log.Fatalln("ReadFile failed:", err)
}
var cfg config
err = json.Unmarshal(data, &cfg)
if err != nil {
log.Fatalln("Unmarshal failed:", err)
}
var templ = template.Must(template.ParseFiles("server/webapp.tmpl"))
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
err := templ.Execute(w, cfg)
if err != nil {
log.Println("Execute failed:", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})
}
func main() {
flag.Parse()
device, err := integra.Connect(*integraaddr)
if err != nil {
log.Fatalln("integra.Connect failed:", err)
}
serveRoot()
http.Handle("/vendor/", http.FileServer(http.Dir("server")))
http.HandleFunc("/webapp.js", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "server/webapp.js")
})
http.HandleFunc("/integra", func(w http.ResponseWriter, r *http.Request) {
client := device.NewSendOnlyClient()
serveIntegra(client, w, r)
})
http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
client := device.NewClient()
defer client.Close()
serveWs(client, w, r)
})
log.Fatal(http.ListenAndServe(*httpaddr, nil))
}