2014-04-30 23:10:44 +08:00
|
|
|
package gobot
|
2014-04-30 04:20:32 +08:00
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"log"
|
|
|
|
"reflect"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Connection interface {
|
|
|
|
Connect() bool
|
|
|
|
Finalize() bool
|
|
|
|
}
|
|
|
|
|
2014-04-30 23:10:44 +08:00
|
|
|
type connection struct {
|
|
|
|
Name string `json:"name"`
|
|
|
|
Type string `json:"adaptor"`
|
|
|
|
Adaptor AdaptorInterface `json:"-"`
|
|
|
|
Port string `json:"-"`
|
|
|
|
Robot *Robot `json:"-"`
|
|
|
|
Params map[string]interface{} `json:"-"`
|
|
|
|
}
|
|
|
|
|
2014-04-30 04:20:32 +08: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 23:10:44 +08:00
|
|
|
func NewConnection(adaptor AdaptorInterface, r *Robot) *connection {
|
2014-04-30 04:20:32 +08:00
|
|
|
c := new(connection)
|
|
|
|
s := reflect.ValueOf(adaptor).Type().String()
|
|
|
|
c.Type = s[1:len(s)]
|
2014-04-30 23:10:44 +08:00
|
|
|
c.Name = FieldByNamePtr(adaptor, "Name").String()
|
|
|
|
c.Port = FieldByNamePtr(adaptor, "Port").String()
|
2014-04-30 04:20:32 +08:00
|
|
|
c.Params = make(map[string]interface{})
|
2014-04-30 23:10:44 +08:00
|
|
|
keys := FieldByNamePtr(adaptor, "Params").MapKeys()
|
2014-04-30 04:20:32 +08:00
|
|
|
for k := range keys {
|
2014-04-30 23:10:44 +08:00
|
|
|
c.Params[keys[k].String()] = FieldByNamePtr(adaptor, "Params").MapIndex(keys[k])
|
2014-04-30 04:20:32 +08:00
|
|
|
}
|
|
|
|
c.Robot = r
|
|
|
|
c.Adaptor = adaptor
|
|
|
|
return c
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *connection) Connect() bool {
|
|
|
|
log.Println("Connecting to " + c.Name + " on port " + c.Port + "...")
|
|
|
|
return c.Adaptor.Connect()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *connection) Finalize() bool {
|
|
|
|
log.Println("Finalizing " + c.Name + "...")
|
|
|
|
return c.Adaptor.Finalize()
|
|
|
|
}
|