1
0
mirror of https://github.com/hybridgroup/gobot.git synced 2025-04-27 13:48:56 +08:00
hybridgroup.gobot/connection.go

101 lines
1.9 KiB
Go
Raw Normal View History

2014-04-30 08:10:44 -07:00
package gobot
2014-04-29 13:20:32 -07:00
import (
"errors"
"fmt"
2014-04-29 13:20:32 -07:00
"log"
"reflect"
)
type Connection interface {
Connect() bool
Finalize() bool
2014-06-13 10:46:58 -07:00
port() string
name() string
setName(string)
2014-06-13 10:46:58 -07:00
params() map[string]interface{}
2014-04-29 13:20:32 -07:00
}
2014-06-10 15:16:11 -07:00
type JSONConnection struct {
2014-05-15 11:50:45 -07:00
Name string `json:"name"`
Port string `json:"port"`
Adaptor string `json:"adaptor"`
}
2014-04-30 08:10:44 -07:00
type connection struct {
2014-06-15 17:32:00 -07:00
Name string
Type string
Adaptor AdaptorInterface
Robot *Robot
2014-04-30 08:10:44 -07:00
}
2014-04-29 13:20:32 -07:00
type connections []*connection
// Start() starts all the connections.
func (c connections) Start() error {
var err error
log.Println("Starting connections...")
for _, connection := range c {
log.Println("Starting connection " + connection.Name + "...")
if connection.Connect() == false {
err = errors.New("Could not start connection")
break
}
}
return err
}
// Filanize() finalizes all the connections.
func (c connections) Finalize() {
for _, connection := range c {
connection.Finalize()
}
}
2014-04-30 08:10:44 -07:00
func NewConnection(adaptor AdaptorInterface, r *Robot) *connection {
if adaptor.name() == "" {
adaptor.setName(fmt.Sprintf("%X", Rand(int(^uint(0)>>1))))
}
2014-06-13 10:46:58 -07:00
t := reflect.ValueOf(adaptor).Type().String()
return &connection{
Type: t[1:len(t)],
Name: adaptor.name(),
Robot: r,
Adaptor: adaptor,
2014-04-29 13:20:32 -07:00
}
}
func (c *connection) Connect() bool {
log.Println("Connecting to " + c.Name + " on port " + c.port() + "...")
2014-04-29 13:20:32 -07:00
return c.Adaptor.Connect()
}
func (c *connection) Finalize() bool {
log.Println("Finalizing " + c.Name + "...")
return c.Adaptor.Finalize()
}
2014-05-15 11:50:45 -07:00
2014-06-10 15:16:11 -07:00
func (c *connection) ToJSON() *JSONConnection {
return &JSONConnection{
Name: c.Name,
Port: c.port(),
2014-06-10 15:16:11 -07:00
Adaptor: c.Type,
}
2014-05-15 11:50:45 -07:00
}
2014-06-13 10:46:58 -07:00
func (c *connection) port() string {
return c.Adaptor.port()
2014-06-13 10:46:58 -07:00
}
func (c *connection) name() string {
return c.Name
}
func (c *connection) setName(s string) {
c.Name = s
}
2014-06-13 10:46:58 -07:00
func (c *connection) params() map[string]interface{} {
return c.Adaptor.params()
}