-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathswitch.go
100 lines (78 loc) · 1.83 KB
/
switch.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
package main
import (
"strconv"
"sync"
"time"
"gobot.io/x/gobot/drivers/gpio"
"gobot.io/x/gobot/platforms/raspi"
)
const (
// How long to keep the on/off relay energized
onSwitchDelay = 250
)
// TrainSwitch models the circuit used to control the turnout switch
type TrainSwitch struct {
onOffSwitch *gpio.RelayDriver
trackSwitch *gpio.RelayDriver
state bool
lock sync.Mutex
}
// NewTrainSwitch creates a new turnout switch
func NewTrainSwitch(r *raspi.Adaptor, onOffPin, directionPin int) *TrainSwitch {
ts := &TrainSwitch{
onOffSwitch: gpio.NewRelayDriver(r, strconv.Itoa(onOffPin)),
trackSwitch: gpio.NewRelayDriver(r, strconv.Itoa(directionPin)),
}
ts.onOffSwitch.Off()
ts.trackSwitch.Off()
return ts
}
// Status returns true if the switch is on
func (ts *TrainSwitch) Status() bool {
ts.lock.Lock()
defer ts.lock.Unlock()
return ts.state
}
// Toggle toggles a switch between off and on
func (ts *TrainSwitch) Toggle() (bool, error) {
ts.lock.Lock()
defer ts.lock.Unlock()
if err := ts.executeDirectional(!ts.state); err != nil {
return false, err
}
return ts.state, nil
}
// On turns a switch to the On position
func (ts *TrainSwitch) On() error {
ts.lock.Lock()
defer ts.lock.Unlock()
return ts.executeDirectional(true)
}
// Off turns the switch off
func (ts *TrainSwitch) Off() error {
ts.lock.Lock()
defer ts.lock.Unlock()
return ts.executeDirectional(false)
}
func (ts *TrainSwitch) executeDirectional(on bool) error {
if ts.state == on {
return nil
}
f := ts.trackSwitch.Off
if on {
f = ts.trackSwitch.On
}
if err := f(); err != nil {
return err
}
time.Sleep(time.Millisecond * 20)
if err := ts.onOffSwitch.On(); err != nil {
return err
}
time.Sleep(time.Millisecond * onSwitchDelay)
if err := ts.onOffSwitch.Off(); err != nil {
return err
}
ts.state = on
return nil
}