hybridgroup.gobot/platforms/leap/leap_motion_driver.go

72 lines
1.6 KiB
Go
Raw 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
"code.google.com/p/go.net/websocket"
2014-04-28 08:43:15 +08:00
"github.com/hybridgroup/gobot"
)
var _ gobot.DriverInterface = (*LeapMotionDriver)(nil)
2014-04-28 08:43:15 +08:00
type LeapMotionDriver struct {
gobot.Driver
}
2014-11-08 05:15:45 +08:00
var receive = func(ws io.ReadWriteCloser) []byte {
var msg []byte
websocket.Message.Receive(ws.(*websocket.Conn), &msg)
return 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
2014-05-23 11:35:45 +08:00
func NewLeapMotionDriver(a *LeapMotionAdaptor, name string) *LeapMotionDriver {
2014-07-08 08:19:31 +08:00
l := &LeapMotionDriver{
Driver: *gobot.NewDriver(
name,
"LeapMotionDriver",
a,
),
2014-04-28 08:43:15 +08:00
}
2014-07-08 08:19:31 +08:00
l.AddEvent("message")
2014-07-08 08:19:31 +08:00
return l
2014-04-28 08:43:15 +08:00
}
// adaptor returns leap motion adaptor
func (l *LeapMotionDriver) adaptor() *LeapMotionAdaptor {
2014-07-10 09:32:27 +08:00
return l.Adaptor().(*LeapMotionAdaptor)
}
// 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.
func (l *LeapMotionDriver) Start() (errs []error) {
2014-04-28 08:43:15 +08:00
enableGestures := map[string]bool{"enableGestures": true}
2014-11-20 07:11:00 +08:00
b, err := json.Marshal(enableGestures)
2014-04-28 08:43:15 +08:00
if err != nil {
return []error{err}
2014-11-20 07:11:00 +08:00
}
_, err = l.adaptor().ws.Write(b)
if err != nil {
return []error{err}
2014-04-28 08:43:15 +08:00
}
go func() {
for {
2014-11-08 05:15:45 +08:00
gobot.Publish(l.Event("message"), l.ParseFrame(receive(l.adaptor().ws)))
2014-04-28 08:43:15 +08:00
}
}()
return
2014-04-28 08:43:15 +08:00
}
// Halt returns true if driver is halted succesfully
func (l *LeapMotionDriver) Halt() (errs []error) { return }