hybridgroup.gobot/platforms/sphero/sphero_adaptor.go

70 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"
)
2014-09-29 11:32:31 +08:00
// 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
},
}
}
func (a *Adaptor) Name() string { return a.name }
func (a *Adaptor) SetName(n string) { a.name = n }
func (a *Adaptor) Port() string { return a.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() (errs []error) {
if sp, err := a.connect(a.Port()); err != nil {
return []error{err}
} else {
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() (errs []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() (errs []error) {
if a.connected {
if err := a.sp.Close(); err != nil {
return []error{err}
}
a.connected = false
2014-11-20 08:17:14 +08:00
}
return
}
// Finalize finalizes the Sphero Adaptor
func (a *Adaptor) Finalize() (errs []error) {
return a.Disconnect()
}