hybridgroup.gobot/platforms/leap/leap_motion_driver.go

105 lines
2.4 KiB
Go
Raw Permalink Normal View History

2014-04-28 08:43:15 +08:00
package leap
import (
"encoding/json"
2014-11-08 05:15:45 +08:00
"io"
2014-07-10 09:32:27 +08:00
"gobot.io/x/gobot"
"golang.org/x/net/websocket"
2014-04-28 08:43:15 +08:00
)
const (
// MessageEvent event
MessageEvent = "message"
// HandEvent event
HandEvent = "hand"
// GestureEvent event
GestureEvent = "gesture"
)
// Driver the Gobot software device to the Leap Motion
type Driver struct {
name string
connection gobot.Connection
gobot.Eventer
2014-04-28 08:43:15 +08:00
}
2014-12-19 07:13:53 +08:00
var receive = func(ws io.ReadWriteCloser, msg *[]byte) {
websocket.Message.Receive(ws.(*websocket.Conn), msg)
2014-11-08 05:15:45 +08:00
}
// NewDriver creates a new leap motion driver
//
// 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 NewDriver(a *Adaptor) *Driver {
l := &Driver{
name: "LeapMotion",
connection: a,
Eventer: gobot.NewEventer(),
2014-04-28 08:43:15 +08:00
}
2014-07-08 08:19:31 +08:00
l.AddEvent(MessageEvent)
l.AddEvent(HandEvent)
l.AddEvent(GestureEvent)
2014-07-08 08:19:31 +08:00
return l
2014-04-28 08:43:15 +08:00
}
// Name returns the Driver Name
func (l *Driver) Name() string { return l.name }
// SetName sets the Driver Name
func (l *Driver) SetName(n string) { l.name = n }
// Connection returns the Driver's Connection
func (l *Driver) Connection() gobot.Connection { return l.connection }
2014-04-28 08:43:15 +08:00
// adaptor returns leap motion adaptor
func (l *Driver) adaptor() *Adaptor {
return l.Connection().(*Adaptor)
}
// Start inits leap motion driver by enabling gestures
// and listening from incoming messages.
//
// Publishes the following events:
2014-11-08 05:15:45 +08:00
// "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 *Driver) Start() (err error) {
2014-04-28 08:43:15 +08:00
enableGestures := map[string]bool{"enableGestures": true}
b, e := json.Marshal(enableGestures)
if e != nil {
return e
2014-11-20 07:11:00 +08:00
}
_, e = l.adaptor().ws.Write(b)
if e != nil {
return e
2014-04-28 08:43:15 +08:00
}
go func() {
2014-12-19 07:13:53 +08:00
var msg []byte
var frame Frame
2014-04-28 08:43:15 +08:00
for {
2014-12-19 07:13:53 +08:00
receive(l.adaptor().ws, &msg)
frame = l.ParseFrame(msg)
l.Publish(MessageEvent, frame)
for _, hand := range frame.Hands {
l.Publish(HandEvent, hand)
}
for _, gesture := range frame.Gestures {
l.Publish(GestureEvent, gesture)
}
2014-04-28 08:43:15 +08:00
}
}()
return
2014-04-28 08:43:15 +08:00
}
// Halt returns nil if driver is halted successfully
func (l *Driver) Halt() (errs error) { return }