-
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
relay_driver.go
120 lines (99 loc) · 2.46 KB
/
relay_driver.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package gpio
import "gobot.io/x/gobot"
// RelayDriver represents a digital relay
type RelayDriver struct {
pin string
name string
connection DigitalWriter
high bool
Inverted bool
gobot.Commander
}
// NewRelayDriver return a new RelayDriver given a DigitalWriter and pin.
//
// Adds the following API Commands:
// "Toggle" - See RelayDriver.Toggle
// "On" - See RelayDriver.On
// "Off" - See RelayDriver.Off
func NewRelayDriver(a DigitalWriter, pin string) *RelayDriver {
l := &RelayDriver{
name: gobot.DefaultName("Relay"),
pin: pin,
connection: a,
high: false,
Inverted: false,
Commander: gobot.NewCommander(),
}
l.AddCommand("Toggle", func(params map[string]interface{}) interface{} {
return l.Toggle()
})
l.AddCommand("On", func(params map[string]interface{}) interface{} {
return l.On()
})
l.AddCommand("Off", func(params map[string]interface{}) interface{} {
return l.Off()
})
return l
}
// Start implements the Driver interface
func (l *RelayDriver) Start() (err error) { return }
// Halt implements the Driver interface
func (l *RelayDriver) Halt() (err error) { return }
// Name returns the RelayDrivers name
func (l *RelayDriver) Name() string { return l.name }
// SetName sets the RelayDrivers name
func (l *RelayDriver) SetName(n string) { l.name = n }
// Pin returns the RelayDrivers name
func (l *RelayDriver) Pin() string { return l.pin }
// Connection returns the RelayDrivers Connection
func (l *RelayDriver) Connection() gobot.Connection {
return l.connection.(gobot.Connection)
}
// State return true if the relay is On and false if the relay is Off
func (l *RelayDriver) State() bool {
if l.Inverted {
return !l.high
}
return l.high
}
// On sets the relay to a high state.
func (l *RelayDriver) On() (err error) {
newValue := byte(1)
if l.Inverted {
newValue = 0
}
if err = l.connection.DigitalWrite(l.Pin(), newValue); err != nil {
return
}
if l.Inverted {
l.high = false
} else {
l.high = true
}
return
}
// Off sets the relay to a low state.
func (l *RelayDriver) Off() (err error) {
newValue := byte(0)
if l.Inverted {
newValue = 1
}
if err = l.connection.DigitalWrite(l.Pin(), newValue); err != nil {
return
}
if l.Inverted {
l.high = true
} else {
l.high = false
}
return
}
// Toggle sets the relay to the opposite of it's current state
func (l *RelayDriver) Toggle() (err error) {
if l.State() {
err = l.Off()
} else {
err = l.On()
}
return
}