-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclient.go
More file actions
375 lines (349 loc) · 8.71 KB
/
client.go
File metadata and controls
375 lines (349 loc) · 8.71 KB
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
/*
Package golibbuttplug provides a Buttplug websocket client.
Buttplug (https://buttplug.io/) is a quasi-standard set of technologies and
protocols to allow developers to write software that controls an array of sex
toys in a semi-future-proof way.
*/
package golibbuttplug
import (
"context"
"crypto/tls"
"errors"
"fmt"
"log"
"net/url"
"sync"
"time"
"github.com/funjack/golibbuttplug/message"
"github.com/gorilla/websocket"
)
// DefaultName is used when no name is specified when creating a new client.
const DefaultName = "golibbuttplug"
var defaultTimeout = time.Second * 30
// Client is a websocket API client that performs operations against a Buttplug
// server.
type Client struct {
ctx context.Context
conn *websocket.Conn // Websocket connection with Buttplug server.
counter *message.IDCounter // Message ID counter
once sync.Once // Ensure Close() is executed only once.
stop chan struct{} // Halts pingLoop and eventLoop goroutines.
sender *message.Sender // Sending messages.
receiver *message.Receiver // Receiving messages.
m sync.RWMutex // Protects devices map.
devices map[uint32]*Device // Devices by their DeviceIndex
}
// NewClient returns a new client with a connection to a Buttplug server.
func NewClient(ctx context.Context, addr, name string, tlscfg *tls.Config) (c *Client, err error) {
c = &Client{
ctx: ctx,
counter: new(message.IDCounter),
stop: make(chan struct{}),
devices: make(map[uint32]*Device),
}
// Create websocket connection
u, err := url.ParseRequestURI(addr)
if err != nil {
return nil, err
}
dailer := &websocket.Dialer{
TLSClientConfig: tlscfg,
}
c.conn, _, err = dailer.Dial(u.String(), nil)
if err != nil {
return nil, err
}
// Start the reader and writer.
c.receiver = message.NewReceiver(c.conn, c.stop)
c.sender = message.NewSender(c.conn)
go func() {
select {
case <-ctx.Done():
case <-c.stop:
}
c.Close()
}()
// Initialize a session with the server.
if name == "" {
name = DefaultName
}
err = c.initSession(name)
if err != nil {
c.Close()
return nil, err
}
// Setup the initial device list.
err = c.initDeviceList()
if err != nil {
c.Close()
return nil, err
}
return c, nil
}
// Close the connection.
func (c *Client) Close() {
c.once.Do(func() {
log.Printf("Closing connection to Buttplug")
c.sender.Stop()
c.receiver.Stop()
<-c.stop
c.conn.Close()
c.removeAllDevices()
log.Printf("Connection to Buttplug closed")
})
}
// InitSession creates a session with server by requesting serverinfo and
// starting a ping/pong exchange.
func (c *Client) initSession(name string) error {
// Send RequestServerInfo
id := c.counter.Generate()
r := message.OutgoingMessage{
RequestServerInfo: &message.RequestServerInfo{
ID: id,
ClientName: name,
},
}
if err := c.sender.Send(r); err != nil {
return err
}
// Read reply
ctx, cancel := context.WithTimeout(c.ctx, defaultTimeout)
defer cancel()
m, err := c.receiveMessage(ctx, id)
if err != nil {
return err
}
if m.ServerInfo == nil {
return errors.New("no serverinfo received")
}
si := *m.ServerInfo
log.Printf("Connected to Buttplug %s (%d.%d.%d)", si.ServerName,
si.BuildVersion, si.MajorVersion, si.MinorVersion)
// Start ping goroutine
interval := 500 * time.Millisecond
if si.MaxPingTime != 0 && si.MaxPingTime < 1000 {
interval = time.Duration(si.MaxPingTime/2) * time.Millisecond
}
go c.pingLoop(interval)
return nil
}
// PingLoop sends out pings.
func (c *Client) pingLoop(d time.Duration) {
c.ping()
for {
select {
case <-c.ctx.Done():
return
case <-c.stop:
return
case <-time.After(d):
c.ping()
}
}
}
// Ping to server and close when an error comes back.
func (c *Client) ping() {
id := c.counter.Generate()
m := message.OutgoingMessage{
Ping: &message.Empty{
ID: id,
},
}
if err := c.sendMessage(id, m); err != nil {
log.Printf("ping error: %v", err)
c.Close()
}
}
// InitDeviceList syncs up client device list with server.
func (c *Client) initDeviceList() error {
// Send RequestDeviceList
id := c.counter.Generate()
r := message.OutgoingMessage{
RequestDeviceList: &message.Empty{
ID: id,
},
}
if err := c.sender.Send(r); err != nil {
return err
}
// Recreive response
ctx, cancel := context.WithTimeout(c.ctx, defaultTimeout)
defer cancel()
m, err := c.receiveMessage(ctx, id)
if err != nil {
return err
}
// Update DeviceList
dl := *m.DeviceList
for _, d := range dl.Devices {
c.addDevice(d)
}
// Start event watcher goroutine.
s, err := c.receiver.Subscribe()
if err != nil {
return err
}
go c.eventLoop(s)
return nil
}
// EventLoop watches for (device) events.
func (c *Client) eventLoop(in *message.Reader) {
for m := range in.Incoming() {
if m.DeviceAdded != nil {
c.addDevice(*m.DeviceAdded)
}
if m.DeviceRemoved != nil {
c.removeDevice(*m.DeviceRemoved)
}
}
}
// AddDevice to the device list.
func (c *Client) addDevice(d message.Device) {
c.m.Lock()
defer c.m.Unlock()
log.Printf("Found device: %s (%d)", d.DeviceName, d.DeviceIndex)
c.devices[d.DeviceIndex] = &Device{
client: c,
device: d,
done: make(chan struct{}),
}
}
// RemoveDevice from the device list.
func (c *Client) removeDevice(d message.Device) {
c.m.Lock()
defer c.m.Unlock()
log.Printf("Removed device: %s (%d)",
c.devices[d.DeviceIndex].device.DeviceName, d.DeviceIndex)
if dev, ok := c.devices[d.DeviceIndex]; ok {
close(dev.done)
}
delete(c.devices, d.DeviceIndex)
}
// RemoveAllDevices removes all discovered devices.
func (c *Client) removeAllDevices() {
// Get all devices.Messages
c.m.Lock()
dmsgs := make([]message.Device, 0, len(c.devices))
for _, v := range c.devices {
dmsgs = append(dmsgs, v.device)
}
c.m.Unlock()
// Remove devices
for _, m := range dmsgs {
c.removeDevice(m)
}
}
// ReceiveMessage waits for and reads a message with a given id.
func (c *Client) receiveMessage(ctx context.Context, id uint32) (message.IncomingMessage, error) {
r, err := c.receiver.Subscribe()
if err != nil {
return message.IncomingMessage{}, err
}
defer c.receiver.Unsubscribe(r)
for {
select {
case msg, ok := <-r.Incoming():
if !ok {
return msg, errors.New("reader stopped")
}
if msgid, _ := msg.Message(); msgid == id {
return msg, nil
}
case <-ctx.Done():
return message.IncomingMessage{}, ctx.Err()
}
}
}
// SendMessage is a generic send and read Ok/Error message with the default
// timeout.
func (c *Client) sendMessage(id uint32, m message.OutgoingMessage) error {
if err := c.sender.Send(m); err != nil {
return err
}
ctx, cancel := context.WithTimeout(c.ctx, defaultTimeout)
defer cancel()
r, err := c.receiveMessage(ctx, id)
if err != nil {
return err
}
if r.Error != nil {
return fmt.Errorf("server error: %s", r.Error.ErrorMessage)
}
if r.Ok == nil {
return errors.New("did not receive ok")
}
return nil
}
// StartScanning requests to have the server start scanning for devices on all
// busses that it knows about. Useful for protocols like Bluetooth, which
// require an explicit discovery phase.
func (c *Client) StartScanning() error {
id := c.counter.Generate()
m := message.OutgoingMessage{
StartScanning: &message.Empty{
ID: id,
},
}
if err := c.sendMessage(id, m); err != nil {
return err
}
return nil
}
// StopScanning requests to have the server stop scanning for devices. Useful
// for protocols like Bluetooth, which may not timeout otherwise.
func (c *Client) StopScanning() error {
id := c.counter.Generate()
m := message.OutgoingMessage{
StopScanning: &message.Empty{
ID: id,
},
}
return c.sendMessage(id, m)
}
// WaitOnScanning waits until the server has stopped scanning on all busses.
func (c *Client) WaitOnScanning(ctx context.Context) error {
r, err := c.receiver.Subscribe()
if err != nil {
return err
}
defer c.receiver.Unsubscribe(r)
for {
select {
case msg, ok := <-r.Incoming():
if !ok {
return errors.New("reader stopped")
}
if msg.ScanningFinished != nil {
return nil
}
case <-ctx.Done():
return ctx.Err()
}
}
}
// Devices returns all devices currently known by the client.
func (c *Client) Devices() []*Device {
c.m.RLock()
defer c.m.RUnlock()
d := make([]*Device, 0, len(c.devices))
for _, v := range c.devices {
d = append(d, v)
}
return d
}
// StopAllDevices tells the server to stop all devices. Can be used for
// emergency situations, on client shutdown for cleanup, etc.
func (c *Client) StopAllDevices() error {
id := c.counter.Generate()
m := message.OutgoingMessage{
StopAllDevices: &message.Empty{
ID: id,
},
}
return c.sendMessage(id, m)
}
// Disconnected returns a receiver channel that is closed when the client has
// stopped.
func (c *Client) Disconnected() <-chan struct{} {
return c.stop
}