From 46d46a8ad0e073bcb1e5f6c2a38c7b624a4b3d33 Mon Sep 17 00:00:00 2001 From: Nathan Youngman Date: Tue, 9 Sep 2014 21:45:38 -0600 Subject: [PATCH] sphero: return collision data as a struct --- examples/sphero.go | 2 +- platforms/sphero/sphero_driver.go | 24 +++++++++++++++++++++++- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/examples/sphero.go b/examples/sphero.go index 65b35b42..556e915f 100644 --- a/examples/sphero.go +++ b/examples/sphero.go @@ -16,7 +16,7 @@ func main() { work := func() { gobot.On(spheroDriver.Event("collision"), func(data interface{}) { - fmt.Println("Collision Detected!") + fmt.Printf("Collision Detected! %+v\n", data) }) gobot.Every(3*time.Second, func() { diff --git a/platforms/sphero/sphero_driver.go b/platforms/sphero/sphero_driver.go index d528dceb..f2cc5c3a 100644 --- a/platforms/sphero/sphero_driver.go +++ b/platforms/sphero/sphero_driver.go @@ -1,6 +1,8 @@ package sphero import ( + "bytes" + "encoding/binary" "fmt" "time" @@ -22,6 +24,19 @@ type SpheroDriver struct { responseChannel chan []uint8 } +type Collision struct { + // Normalized impact components (direction of the collision event): + X, Y, Z int16 + // Thresholds exceeded by X (1h) and/or Y (2h) axis (bitmask): + Axis byte + // Power that cross threshold Xt + Xs: + XMagnitude, YMagnitude int16 + // Sphero's speed when impact detected: + Speed uint8 + // Millisecond timer + Timestamp uint32 +} + func NewSpheroDriver(a *SpheroAdaptor, name string) *SpheroDriver { s := &SpheroDriver{ Driver: *gobot.NewDriver( @@ -189,7 +204,14 @@ func (s *SpheroDriver) enableStopOnDisconnect() { } func (s *SpheroDriver) handleCollisionDetected(data []uint8) { - gobot.Publish(s.Event("collision"), data) + // ensure data is the right length: + if len(data) != 22 || data[4] != 17 { + return + } + var collision Collision + buffer := bytes.NewBuffer(data[5:]) // skip header + binary.Read(buffer, binary.BigEndian, &collision) + gobot.Publish(s.Event("collision"), collision) } func (s *SpheroDriver) getSyncResponse(packet *packet) []byte {