-
Notifications
You must be signed in to change notification settings - Fork 110
/
control_loop.go
281 lines (265 loc) · 7.11 KB
/
control_loop.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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
package control
import (
"context"
"sync"
"time"
"github.com/edaniels/golog"
"github.com/pkg/errors"
"go.viam.com/utils"
)
// controlBlockInternal Holds internal variables to control the flow of data between blocks.
type controlBlockInternal struct {
mu sync.Mutex
blockType controlBlockType
ins []chan []*Signal
outs []chan []*Signal
blk Block
}
// controlTicker Used to emit impulse on blocks which do not depend on inputs or are endpoints.
type controlTicker struct {
ticker *time.Ticker
stop chan bool
}
// Loop holds the loop config.
type Loop struct {
cfg Config
blocks map[string]*controlBlockInternal
ct controlTicker
logger golog.Logger
ts []chan time.Time
dt time.Duration
activeBackgroundWorkers sync.WaitGroup
cancelCtx context.Context
cancel context.CancelFunc
running bool
}
// NewLoop construct a new control loop for a specific endpoint.
func NewLoop(logger golog.Logger, cfg Config, m Controllable) (*Loop, error) {
return createLoop(logger, cfg, m)
}
func createLoop(logger golog.Logger, cfg Config, m Controllable) (*Loop, error) {
cancelCtx, cancel := context.WithCancel(context.Background())
l := Loop{
logger: logger,
cfg: cfg,
blocks: make(map[string]*controlBlockInternal),
cancelCtx: cancelCtx,
cancel: cancel,
running: false,
}
if l.cfg.Frequency == 0.0 || l.cfg.Frequency > 200 {
return nil, errors.New("loop frequency shouldn't be 0 or above 200Hz")
}
l.dt = time.Duration(float64(time.Second) * (1.0 / (l.cfg.Frequency)))
for _, bcfg := range cfg.Blocks {
blk, err := createBlock(bcfg, logger)
if err != nil {
return nil, err
}
l.blocks[bcfg.Name] = &controlBlockInternal{blk: blk, blockType: bcfg.Type}
if bcfg.Type == blockEndpoint {
l.blocks[bcfg.Name].blk.(*endpoint).ctr = m
}
}
for _, b := range l.blocks {
for _, dep := range b.blk.Config(l.cancelCtx).DependsOn {
blockDep, ok := l.blocks[dep]
if !ok {
return nil, errors.Errorf("block %s depends on %s but it does not exist", b.blk.Config(l.cancelCtx).Name, dep)
}
blockDep.outs = append(blockDep.outs, make(chan []*Signal))
b.ins = append(b.ins, blockDep.outs[len(blockDep.outs)-1])
}
}
for _, b := range l.blocks {
if len(b.blk.Config(l.cancelCtx).DependsOn) == 0 || b.blk.Config(l.cancelCtx).Type == blockEndpoint {
waitCh := make(chan struct{})
l.ts = append(l.ts, make(chan time.Time, 1))
l.activeBackgroundWorkers.Add(1)
utils.ManagedGo(func() {
t := l.ts[len(l.ts)-1]
b := b
close(waitCh)
for {
_, ok := <-t
if !ok {
b.mu.Lock()
for _, out := range b.outs {
close(out)
}
b.outs = nil
b.mu.Unlock()
return
}
v, _ := b.blk.Next(l.cancelCtx, nil, l.dt)
for _, out := range b.outs {
out <- v
}
}
}, l.activeBackgroundWorkers.Done)
<-waitCh
}
if len(b.blk.Config(l.cancelCtx).DependsOn) != 0 {
waitCh := make(chan struct{})
l.activeBackgroundWorkers.Add(1)
utils.ManagedGo(func() {
b := b
nInputs := len(b.ins)
close(waitCh)
for {
sw := make([]*Signal, nInputs)
for i, c := range b.ins {
r, ok := <-c
if !ok {
b.mu.Lock()
for _, out := range b.outs {
close(out)
}
// logger.Debugf("Closing outs for block %s %+v\r\n", b.blk.Config(ctx).Name, r)
b.outs = nil
b.mu.Unlock()
return
}
if len(r) == 1 {
sw[i] = r[0]
} else {
// TODO(npmenard) do we want to support multidimentional signals?
//nolint: makezero
sw = append(sw, r...)
}
}
v, ok := b.blk.Next(l.cancelCtx, sw, l.dt)
if ok {
for _, out := range b.outs {
out <- v
}
}
}
}, l.activeBackgroundWorkers.Done)
<-waitCh
}
}
return &l, nil
}
// OutputAt returns the Signal at the block name, error when the block doesn't exist.
func (l *Loop) OutputAt(ctx context.Context, name string) ([]*Signal, error) {
blk, ok := l.blocks[name]
if !ok {
return []*Signal{}, errors.Errorf("cannot return Signals for non existing block %s", name)
}
return blk.blk.Output(ctx), nil
}
// ConfigAt returns the Configl at the block name, error when the block doesn't exist.
func (l *Loop) ConfigAt(ctx context.Context, name string) (BlockConfig, error) {
blk, ok := l.blocks[name]
if !ok {
return BlockConfig{}, errors.Errorf("cannot return Config for non existing block %s", name)
}
return blk.blk.Config(ctx), nil
}
// SetConfigAt returns the Configl at the block name, error when the block doesn't exist.
func (l *Loop) SetConfigAt(ctx context.Context, name string, config BlockConfig) error {
blk, ok := l.blocks[name]
if !ok {
return errors.Errorf("cannot return Config for non existing block %s", name)
}
return blk.blk.UpdateConfig(ctx, config)
}
// BlockList returns the list of blocks in a control loop error when the list is empty.
func (l *Loop) BlockList(ctx context.Context) ([]string, error) {
var out []string
for k := range l.blocks {
out = append(out, k)
}
return out, nil
}
// Frequency returns the loop's frequency.
func (l *Loop) Frequency(ctx context.Context) (float64, error) {
return l.cfg.Frequency, nil
}
// Start starts the loop.
func (l *Loop) Start() error {
if len(l.ts) == 0 {
return errors.New("cannot start the control loop if there are no blocks depending on an impulse")
}
l.logger.Debugf("Running loop on %1.4f %+v\r\n", l.cfg.Frequency, l.dt)
l.ct = controlTicker{
ticker: time.NewTicker(l.dt),
stop: make(chan bool, 1),
}
waitCh := make(chan struct{})
l.activeBackgroundWorkers.Add(1)
utils.ManagedGo(func() {
ct := l.ct
ts := l.ts
close(waitCh)
for {
if l.cancelCtx.Err() != nil {
for _, c := range ts {
close(c)
}
return
}
select {
case t := <-ct.ticker.C:
for _, c := range ts {
c <- t
}
case <-ct.stop:
for _, c := range ts {
close(c)
}
return
case <-l.cancelCtx.Done():
for _, c := range ts {
close(c)
}
return
}
}
}, l.activeBackgroundWorkers.Done)
<-waitCh
l.running = true
return nil
}
// StartBenchmark special start function to benchmark speed of complex loop configurations.
func (l *Loop) startBenchmark(loops int) error {
if len(l.ts) == 0 {
return errors.New("cannot start the control loop if there are no blocks depending on an impulse")
}
waitCh := make(chan struct{})
l.activeBackgroundWorkers.Add(1)
utils.ManagedGo(func() {
ts := l.ts
close(waitCh)
for i := 0; i < loops; i++ {
if l.cancelCtx.Err() != nil {
for _, c := range ts {
close(c)
}
return
}
for _, c := range ts {
c <- time.Now()
}
}
for _, c := range ts {
close(c)
}
}, l.activeBackgroundWorkers.Done)
<-waitCh
return nil
}
// Stop stops then loop.
func (l *Loop) Stop() {
if l.running {
l.ct.ticker.Stop()
close(l.ct.stop)
l.activeBackgroundWorkers.Wait()
l.running = false
}
}
// GetConfig return the control loop config.
func (l *Loop) GetConfig(ctx context.Context) Config {
return l.cfg
}