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

72 lines
1.6 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 (
"log"
"reflect"
multierror "github.com/hashicorp/go-multierror"
2014-04-29 13:20:32 -07:00
)
// JSONConnection is a JSON representation of a Connection.
2014-06-10 15:16:11 -07:00
type JSONConnection struct {
2014-05-15 11:50:45 -07:00
Name string `json:"name"`
Adaptor string `json:"adaptor"`
}
// NewJSONConnection returns a JSONConnection given a Connection.
func NewJSONConnection(connection Connection) *JSONConnection {
return &JSONConnection{
Name: connection.Name(),
Adaptor: reflect.TypeOf(connection).String(),
}
}
// A Connection is an instance of an Adaptor
type Connection Adaptor
// Connections represents a collection of Connection
type Connections []Connection
2014-06-23 20:33:59 -07:00
2014-10-15 12:57:07 -05:00
// Len returns connections length
func (c *Connections) Len() int {
2014-07-09 09:38:43 -07:00
return len(*c)
2014-06-23 20:33:59 -07:00
}
// Each enumerates through the Connections and calls specified callback function.
func (c *Connections) Each(f func(Connection)) {
2014-07-09 09:38:43 -07:00
for _, connection := range *c {
2014-06-23 20:33:59 -07:00
f(connection)
}
}
2014-04-29 13:20:32 -07:00
// Start calls Connect on each Connection in c
func (c *Connections) Start() error {
2014-04-29 13:20:32 -07:00
log.Println("Starting connections...")
var err error
2014-07-09 09:38:43 -07:00
for _, connection := range *c {
info := "Starting connection " + connection.Name()
2014-11-21 19:35:01 -08:00
if porter, ok := connection.(Porter); ok {
info = info + " on port " + porter.Port()
}
2014-11-21 19:35:01 -08:00
log.Println(info + "...")
2014-11-21 19:35:01 -08:00
if cerr := connection.Connect(); cerr != nil {
err = multierror.Append(err, cerr)
2014-04-29 13:20:32 -07:00
}
}
return err
2014-04-29 13:20:32 -07:00
}
// Finalize calls Finalize on each Connection in c
func (c *Connections) Finalize() error {
var err error
2014-07-09 09:38:43 -07:00
for _, connection := range *c {
if cerr := connection.Finalize(); cerr != nil {
err = multierror.Append(err, cerr)
}
2014-04-29 13:20:32 -07:00
}
return err
2014-04-29 13:20:32 -07:00
}