gobot.io/x/gobot@v1.16.0/platforms/sphero/sphero_adaptor.go (about) 1 package sphero 2 3 import ( 4 "io" 5 6 "gobot.io/x/gobot" 7 8 "go.bug.st/serial" 9 ) 10 11 // Adaptor represents a Connection to a Sphero 12 type Adaptor struct { 13 name string 14 port string 15 sp io.ReadWriteCloser 16 connected bool 17 connect func(string) (io.ReadWriteCloser, error) 18 } 19 20 // NewAdaptor returns a new Sphero Adaptor given a port 21 func NewAdaptor(port string) *Adaptor { 22 return &Adaptor{ 23 name: gobot.DefaultName("Sphero"), 24 port: port, 25 connect: func(port string) (io.ReadWriteCloser, error) { 26 return serial.Open(port, &serial.Mode{BaudRate: 115200}) 27 }, 28 } 29 } 30 31 // Name returns the Adaptor's name 32 func (a *Adaptor) Name() string { return a.name } 33 34 // SetName sets the Adaptor's name 35 func (a *Adaptor) SetName(n string) { a.name = n } 36 37 // Port returns the Adaptor's port 38 func (a *Adaptor) Port() string { return a.port } 39 40 // SetPort sets the Adaptor's port 41 func (a *Adaptor) SetPort(p string) { a.port = p } 42 43 // Connect initiates a connection to the Sphero. Returns true on successful connection. 44 func (a *Adaptor) Connect() (err error) { 45 sp, e := a.connect(a.Port()) 46 if e != nil { 47 return e 48 } 49 50 a.sp = sp 51 a.connected = true 52 return 53 } 54 55 // Reconnect attempts to reconnect to the Sphero. If the Sphero has an active connection 56 // it will first close that connection and then establish a new connection. 57 // Returns true on Successful reconnection 58 func (a *Adaptor) Reconnect() (err error) { 59 if a.connected { 60 a.Disconnect() 61 } 62 return a.Connect() 63 } 64 65 // Disconnect terminates the connection to the Sphero. Returns true on successful disconnect. 66 func (a *Adaptor) Disconnect() error { 67 if a.connected { 68 if e := a.sp.Close(); e != nil { 69 return e 70 } 71 a.connected = false 72 } 73 return nil 74 } 75 76 // Finalize finalizes the Sphero Adaptor 77 func (a *Adaptor) Finalize() error { 78 return a.Disconnect() 79 }