hybridgroup.gobot/platforms/sphero/sphero_adaptor.go

78 lines
1.7 KiB
Go
Raw Normal View History

2014-04-27 09:07:04 +08:00
package sphero
import (
2014-09-29 11:32:31 +08:00
"io"
"github.com/tarm/serial"
)
// Adaptor represents a Connection to a Sphero
type Adaptor struct {
name string
port string
sp io.ReadWriteCloser
connected bool
connect func(string) (io.ReadWriteCloser, error)
}
// NewAdaptor returns a new Sphero Adaptor given a port
func NewAdaptor(port string) *Adaptor {
return &Adaptor{
name: "Sphero",
port: port,
connect: func(port string) (io.ReadWriteCloser, error) {
return serial.OpenPort(&serial.Config{Name: port, Baud: 115200})
2014-04-27 09:07:04 +08:00
},
}
}
// Name returns the Adaptor's name
func (a *Adaptor) Name() string { return a.name }
// SetName sets the Adaptor's name
func (a *Adaptor) SetName(n string) { a.name = n }
// Port returns the Adaptor's port
func (a *Adaptor) Port() string { return a.port }
// SetPort sets the Adaptor's port
func (a *Adaptor) SetPort(p string) { a.port = p }
2014-09-29 11:32:31 +08:00
// Connect initiates a connection to the Sphero. Returns true on successful connection.
func (a *Adaptor) Connect() (err error) {
sp, e := a.connect(a.Port())
if e != nil {
return e
2014-11-20 08:17:14 +08:00
}
a.sp = sp
a.connected = true
2014-11-20 08:17:14 +08:00
return
}
2014-09-29 11:32:31 +08:00
// Reconnect attempts to reconnect to the Sphero. If the Sphero has an active connection
// it will first close that connection and then establish a new connection.
// Returns true on Successful reconnection
func (a *Adaptor) Reconnect() (err error) {
if a.connected {
2014-04-27 09:07:04 +08:00
a.Disconnect()
}
2014-04-27 09:07:04 +08:00
return a.Connect()
}
2014-09-29 11:32:31 +08:00
// Disconnect terminates the connection to the Sphero. Returns true on successful disconnect.
func (a *Adaptor) Disconnect() error {
if a.connected {
if e := a.sp.Close(); e != nil {
return e
}
a.connected = false
2014-11-20 08:17:14 +08:00
}
return nil
}
// Finalize finalizes the Sphero Adaptor
func (a *Adaptor) Finalize() error {
return a.Disconnect()
}