forked from hybridgroup/gobot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconnection.go
95 lines (81 loc) · 1.93 KB
/
connection.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package gobot
import (
"errors"
"log"
"reflect"
)
type Connection interface {
Connect() bool
Finalize() bool
port() string
name() string
params() map[string]interface{}
}
type JSONConnection struct {
Name string `json:"name"`
Port string `json:"port"`
Adaptor string `json:"adaptor"`
}
type connection struct {
Name string `json:"-"`
Type string `json:"-"`
Adaptor AdaptorInterface `json:"-"`
Port string `json:"-"`
Robot *Robot `json:"-"`
Params map[string]interface{} `json:"-"`
}
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()
}
}
func NewConnection(adaptor AdaptorInterface, r *Robot) *connection {
t := reflect.ValueOf(adaptor).Type().String()
return &connection{
Type: t[1:len(t)],
Name: adaptor.name(),
Port: adaptor.port(),
Params: adaptor.params(),
Robot: r,
Adaptor: adaptor,
}
}
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()
}
func (c *connection) ToJSON() *JSONConnection {
return &JSONConnection{
Name: c.Name,
Port: c.Port,
Adaptor: c.Type,
}
}
func (c *connection) port() string {
return c.Port
}
func (c *connection) name() string {
return c.Name
}
func (c *connection) params() map[string]interface{} {
return c.Adaptor.params()
}