gobot.io/x/gobot/v2@v2.1.0/connection.go (about)

     1  package gobot
     2  
     3  import (
     4  	"log"
     5  	"reflect"
     6  
     7  	multierror "github.com/hashicorp/go-multierror"
     8  )
     9  
    10  // JSONConnection is a JSON representation of a Connection.
    11  type JSONConnection struct {
    12  	Name    string `json:"name"`
    13  	Adaptor string `json:"adaptor"`
    14  }
    15  
    16  // NewJSONConnection returns a JSONConnection given a Connection.
    17  func NewJSONConnection(connection Connection) *JSONConnection {
    18  	return &JSONConnection{
    19  		Name:    connection.Name(),
    20  		Adaptor: reflect.TypeOf(connection).String(),
    21  	}
    22  }
    23  
    24  // A Connection is an instance of an Adaptor
    25  type Connection Adaptor
    26  
    27  // Connections represents a collection of Connection
    28  type Connections []Connection
    29  
    30  // Len returns connections length
    31  func (c *Connections) Len() int {
    32  	return len(*c)
    33  }
    34  
    35  // Each enumerates through the Connections and calls specified callback function.
    36  func (c *Connections) Each(f func(Connection)) {
    37  	for _, connection := range *c {
    38  		f(connection)
    39  	}
    40  }
    41  
    42  // Start calls Connect on each Connection in c
    43  func (c *Connections) Start() (err error) {
    44  	log.Println("Starting connections...")
    45  	for _, connection := range *c {
    46  		info := "Starting connection " + connection.Name()
    47  
    48  		if porter, ok := connection.(Porter); ok {
    49  			info = info + " on port " + porter.Port()
    50  		}
    51  
    52  		log.Println(info + "...")
    53  
    54  		if cerr := connection.Connect(); cerr != nil {
    55  			err = multierror.Append(err, cerr)
    56  		}
    57  	}
    58  	return err
    59  }
    60  
    61  // Finalize calls Finalize on each Connection in c
    62  func (c *Connections) Finalize() (err error) {
    63  	for _, connection := range *c {
    64  		if cerr := connection.Finalize(); cerr != nil {
    65  			err = multierror.Append(err, cerr)
    66  		}
    67  	}
    68  	return err
    69  }