forked from llun/soundtouch-golang
-
Notifications
You must be signed in to change notification settings - Fork 0
/
soundtouch.go
257 lines (222 loc) · 5.7 KB
/
soundtouch.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
package soundtouch
import (
"bytes"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/url"
log "github.com/sirupsen/logrus"
"github.com/gorilla/websocket"
"github.com/hashicorp/mdns"
)
const websocketPort int = 8080
const messageBufferSize int = 256
// Speaker defines a soundtouch speaker
type Speaker struct {
IP net.IP
Port int
BaseHTTPURL url.URL
WebSocketURL url.URL
DeviceInfo Info
conn *websocket.Conn
WebSocketCh chan *Update
Plugins []Plugin
}
// LookupSpeakers listens via mdns for soundtouch speakers and returns Speaker channel
func LookupSpeakers(iface *net.Interface) <-chan *Speaker {
speakerCh := make(chan *Speaker)
entriesCh := make(chan *mdns.ServiceEntry, 7)
defer close(entriesCh)
go func() {
defer close(speakerCh)
for entry := range entriesCh {
fSpeaker := NewMdnsSpeaker(entry)
// filter non-soundtouch speakers
if fSpeaker.DeviceInfo.String() != "" {
speakerCh <- fSpeaker
}
}
}()
params := mdns.DefaultParams("_soundtouch._tcp")
params.Entries = entriesCh
if iface != nil {
params.Interface = iface
}
mdns.Query(params)
return speakerCh
}
// LookupSpeakers listens via mdns for soundtouch speakers and returns Speaker channel
func LookupStaticSpeakers(speakerIPs []string) <-chan *Speaker {
speakerCh := make(chan *Speaker)
go func() {
defer close(speakerCh)
for _, ip := range speakerIPs {
fSpeaker := NewIPSpeaker(ip)
// filter non-soundtouch speakers
if fSpeaker.DeviceInfo.String() != "" {
speakerCh <- fSpeaker
}
}
}()
return speakerCh
}
// NewMdnsSpeaker returns a new Speaker entity based on a mdns service entry
func NewMdnsSpeaker(entry *mdns.ServiceEntry) *Speaker {
if entry == nil {
return &Speaker{}
}
fSpeaker := &Speaker{
entry.AddrV4,
entry.Port,
url.URL{
Scheme: "http",
Host: fmt.Sprintf("%v:%v", entry.AddrV4.String(), entry.Port),
},
url.URL{
Scheme: "ws",
Host: fmt.Sprintf("%v:%v", entry.AddrV4.String(), websocketPort),
},
Info{},
nil,
nil,
nil,
}
// Ask ones for Info() to fill the speaker
_, err := fSpeaker.Info()
if err != nil {
log.Warnf("Error %v while retrieving info for speaker %v", err, fSpeaker.DeviceInfo.Name)
}
return fSpeaker
}
// NewIPSpeaker creates a new speaker for the given ipAdress
func NewIPSpeaker(ipAddress string) *Speaker {
if ipAddress == "" {
return &Speaker{}
}
AddrV4 := net.ParseIP(ipAddress)
return &Speaker{
AddrV4,
8090,
url.URL{
Scheme: "http",
Host: fmt.Sprintf("%v:%v", AddrV4.String(), 8090),
},
url.URL{
Scheme: "ws",
Host: fmt.Sprintf("%v:%v", AddrV4.String(), websocketPort),
},
Info{},
nil,
nil,
nil,
}
}
// Listen creates a listenes that distributes Update messages via channel
func (s *Speaker) Listen() (chan *Update, error) {
spkLogger := log.WithFields(log.Fields{
"Speaker": s.DeviceInfo.Name,
"ID": s.DeviceInfo.DeviceID,
})
spkLogger.Tracef("Dialing %v", s.WebSocketURL.String())
conn, _, err := websocket.DefaultDialer.Dial(
s.WebSocketURL.String(),
http.Header{
"Sec-WebSocket-Protocol": []string{"gabbo"},
})
if err != nil {
return nil, err
}
s.conn = conn
messageCh := make(chan *Update, messageBufferSize)
go func() {
for {
mLogger := log.WithFields(log.Fields{
"Speaker": s.DeviceInfo.Name,
"ID": s.DeviceInfo.DeviceID,
})
_, body, err := conn.ReadMessage()
if err != nil {
spkLogger.Warn(err)
spkLogger.Warn("Trying to reconnect")
spkLogger.Tracef("Re-Dialing %v", s.WebSocketURL.String())
conn, _, err = websocket.DefaultDialer.Dial(
s.WebSocketURL.String(),
http.Header{
"Sec-WebSocket-Protocol": []string{"gabbo"},
})
if err != nil {
spkLogger.Warn("Re-Dialing failed")
spkLogger.Fatal(err)
}
s.conn = conn
}
mLogger.Tracef("Raw Message: %v", string(body))
update, err := NewUpdate(body)
if err != nil {
mLogger.Tracef("Message: unkown")
mLogger.Tracef(err.Error())
} else {
mLogger.Tracef("Message: %v", update)
}
if update != nil {
messageCh <- update
}
}
}()
return messageCh, nil
}
// Close closes the socket to the soundtouch speaker
func (s *Speaker) Close() error {
log.Debugf("Closing socket")
return s.conn.Close()
}
// GetData returns received raw data retrieved a GET for a given soundtouch action
func (s *Speaker) GetData(action string) ([]byte, error) {
actionURL := s.BaseHTTPURL
actionURL.Path = action
mLogger := log.WithFields(log.Fields{
"Speaker": s.DeviceInfo.Name,
"ID": s.DeviceInfo.DeviceID,
})
mLogger.Tracef("GET: %s\n", actionURL.String())
resp, err := http.Get(actionURL.String())
if err != nil {
return nil, err
}
body, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
return nil, err
}
return body, nil
}
// SetData sets raw data via POST for a given soundtouch action
func (s *Speaker) SetData(action string, input []byte) ([]byte, error) {
actionURL := s.BaseHTTPURL
actionURL.Path = action
buffer := bytes.NewBuffer(input)
mLogger := log.WithFields(log.Fields{
"Speaker": s.DeviceInfo.Name,
"ID": s.DeviceInfo.DeviceID,
})
mLogger.Tracef("POST: %s, %v\n", actionURL.String(), buffer)
resp, err := http.Post(actionURL.String(), "application/xml", buffer)
if err != nil {
return nil, err
}
body, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
return nil, err
}
return body, nil
}
// Name returns the speakers name as indicated in the info message, or "" if name unknwon
func (s *Speaker) Name() (name string) {
return s.DeviceInfo.Name
}
// DeviceID returns the speakers DeviceID as indicated in the info message, or "" if name unknwon
func (s *Speaker) DeviceID() (name string) {
return s.DeviceInfo.DeviceID
}