-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
locomotive.go
102 lines (92 loc) · 1.97 KB
/
locomotive.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
package dcc
import (
"fmt"
"sync"
)
// Direction constants.
const (
Backward Direction = 0
Forward Direction = 1
)
// Direction represents the locomotive direction and can be
// Forward or Backward.
type Direction byte
// Locomotive represents a DCC device, usually a locomotive.
// Locomotives are represented by their name and address and
// include certain properties like speed, direction or FL.
// Each locomotive produces two packets: one speed and direction
// packet and one Function Group One packet.
type Locomotive struct {
Name string `json:"name"`
Address uint8 `json:"address"`
Speed uint8 `json:"speed"`
Direction Direction `json:"direction"`
Fl bool `json:"fl"`
F1 bool `json:"f1"`
F2 bool `json:"f2"`
F3 bool `json:"f3"`
F4 bool `json:"f4"`
mux sync.Mutex
speedPacket *Packet
flPacket *Packet
}
func (l *Locomotive) String() string {
var dir, fl, f1, f2, f3, f4 string = "", "off", "off", "off", "off", "off"
if l.Direction == Forward {
dir = ">"
} else {
dir = "<"
}
if l.Fl {
fl = "on"
}
if l.F1 {
f1 = "on"
}
if l.F2 {
f2 = "on"
}
if l.F3 {
f3 = "on"
}
if l.F4 {
f4 = "on"
}
return fmt.Sprintf("%s:%d |%d%s| |%s| |%s|%s|%s|%s|",
l.Name,
l.Address,
l.Speed,
dir,
fl,
f1,
f2,
f3,
f4)
}
func (l *Locomotive) sendPackets(d Driver) {
l.mux.Lock()
{
if l.speedPacket == nil {
l.speedPacket = NewSpeedAndDirectionPacket(d,
l.Address, l.Speed, l.Direction)
}
if l.flPacket == nil {
l.flPacket = NewFunctionGroupOnePacket(d,
l.Address, l.Fl, l.F1, l.F2, l.F3, l.F4)
}
l.speedPacket.Send()
l.flPacket.Send()
}
l.mux.Unlock()
}
// Apply makes any changes to the Locomotive's properties
// to be reflected in the packets generated for it and,
// therefore, alter the behaviour of the device on the tracks.
func (l *Locomotive) Apply() {
l.mux.Lock()
{
l.speedPacket = nil
l.flPacket = nil
}
l.mux.Unlock()
}