forked from hybridgroup/gobot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
leap_motion_driver.go
89 lines (75 loc) · 2.27 KB
/
leap_motion_driver.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
package leap
import (
"encoding/json"
"io"
"github.com/hybridgroup/gobot"
"golang.org/x/net/websocket"
)
var _ gobot.Driver = (*LeapMotionDriver)(nil)
type LeapMotionDriver struct {
name string
connection gobot.Connection
gobot.Eventer
}
var receive = func(ws io.ReadWriteCloser, msg *[]byte) {
websocket.Message.Receive(ws.(*websocket.Conn), msg)
}
// NewLeapMotionDriver creates a new leap motion driver with specified name
//
// Adds the following events:
// "message" - Gets triggered when receiving a message from leap motion
// "hand" - Gets triggered per-message when leap motion detects a hand
// "gesture" - Gets triggered per-message when leap motion detects a hand
func NewLeapMotionDriver(a *LeapMotionAdaptor, name string) *LeapMotionDriver {
l := &LeapMotionDriver{
name: name,
connection: a,
Eventer: gobot.NewEventer(),
}
l.AddEvent("message")
l.AddEvent("hand")
l.AddEvent("gesture")
return l
}
func (l *LeapMotionDriver) Name() string { return l.name }
func (l *LeapMotionDriver) Connection() gobot.Connection { return l.connection }
// adaptor returns leap motion adaptor
func (l *LeapMotionDriver) adaptor() *LeapMotionAdaptor {
return l.Connection().(*LeapMotionAdaptor)
}
// Start inits leap motion driver by enabling gestures
// and listening from incoming messages.
//
// Publishes the following events:
// "message" - Emits Frame on new message received from Leap.
// "hand" - Emits Hand when detected in message from Leap.
// "gesture" - Emits Gesture when detected in message from Leap.
func (l *LeapMotionDriver) Start() (errs []error) {
enableGestures := map[string]bool{"enableGestures": true}
b, err := json.Marshal(enableGestures)
if err != nil {
return []error{err}
}
_, err = l.adaptor().ws.Write(b)
if err != nil {
return []error{err}
}
go func() {
var msg []byte
var frame Frame
for {
receive(l.adaptor().ws, &msg)
frame = l.ParseFrame(msg)
gobot.Publish(l.Event("message"), frame)
for _, hand := range frame.Hands {
gobot.Publish(l.Event("hand"), hand)
}
for _, gesture := range frame.Gestures {
gobot.Publish(l.Event("gesture"), gesture)
}
}
}()
return
}
// Halt returns true if driver is halted succesfully
func (l *LeapMotionDriver) Halt() (errs []error) { return }