-
Notifications
You must be signed in to change notification settings - Fork 109
/
velocities.go
306 lines (277 loc) · 8.53 KB
/
velocities.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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
package sensorcontrolled
import (
"context"
"math"
"time"
"github.com/golang/geo/r3"
"go.viam.com/utils"
"go.viam.com/rdk/control"
rdkutils "go.viam.com/rdk/utils"
)
// TODO: RSDK-5355 useControlLoop bool should be removed after testing.
const (
useControlLoop = false
// rPiGain is 1/255 because the PWM signal on a pi (and most other boards)
// is limited to 8 bits, or the range 0-255.
rPiGain = 0.00392157
)
// setupControlLoops uses the embedded config in this file to initialize a control
// loop using the controls package and store in on the sensor controlled base struct
// the sensor base in the controllable interface that implements State and GetState
// called by the endpoint logic of the control thread and the controlLoopConfig
// is included at the end of this file.
func (sb *sensorBase) setupControlLoops() error {
// create control loop
loop, err := control.NewLoop(sb.logger, sb.controlLoopConfig, sb)
if err != nil {
return err
}
if err := loop.Start(); err != nil {
return err
}
sb.loop = loop
return nil
}
func (sb *sensorBase) updateControlConfig(
ctx context.Context, linearValue, angularValue float64,
) error {
// set linear setpoint config
linConf := control.BlockConfig{
Name: "linear_setpoint",
Type: "constant",
Attribute: rdkutils.AttributeMap{
"constant_val": linearValue,
},
DependsOn: []string{},
}
if err := sb.loop.SetConfigAt(ctx, "linear_setpoint", linConf); err != nil {
return err
}
// set angular setpoint config
angConf := control.BlockConfig{
Name: "angular_setpoint",
Type: "constant",
Attribute: rdkutils.AttributeMap{
"constant_val": angularValue,
},
DependsOn: []string{},
}
if err := sb.loop.SetConfigAt(ctx, "angular_setpoint", angConf); err != nil {
return err
}
return nil
}
func (sb *sensorBase) SetVelocity(
ctx context.Context, linear, angular r3.Vector, extra map[string]interface{},
) error {
sb.opMgr.CancelRunning(ctx)
// check if a sensor context has been started
if sb.sensorLoopDone != nil {
sb.sensorLoopDone()
}
// set the spin loop to false, so we do not skip the call to SetState in the control loop
sb.setPolling(false)
// start a sensor context for the sensor loop based on the longstanding base
// creator context, and add a timeout for the context
timeOut := 10 * time.Second
var sensorCtx context.Context
sensorCtx, sb.sensorLoopDone = context.WithTimeout(context.Background(), timeOut)
if useControlLoop {
// stop and restart loop
if sb.loop != nil {
if err := sb.Stop(ctx, nil); err != nil {
sb.logger.Error(err)
}
}
if err := sb.setupControlLoops(); err != nil {
return err
}
// convert linear.Y mmPerSec to mPerSec, angular.Z is degPerSec
if err := sb.updateControlConfig(ctx, linear.Y/1000.0, angular.Z); err != nil {
return err
}
// if we have a loop, let's use the SetState function to call the SetVelocity command
// through the control loop
sb.logger.CInfo(ctx, "using loop")
sb.pollsensors(sensorCtx, extra)
return nil
}
sb.logger.CInfo(ctx, "setting velocity without loop")
// else do not use the control loop and pass through the SetVelocity command
return sb.controlledBase.SetVelocity(ctx, linear, angular, extra)
}
// pollsensors is a busy loop in the background that passively polls the LinearVelocity and
// AngularVelocity API calls of the movementsensor attached to the sensor base
// and logs them for toruble shooting.
// This function can eventually be removed.
func (sb *sensorBase) pollsensors(ctx context.Context, extra map[string]interface{}) {
sb.activeBackgroundWorkers.Add(1)
utils.ManagedGo(func() {
ticker := time.NewTicker(velocitiesPollTime)
defer ticker.Stop()
for {
// check if we want to poll the sensor at all
// other API calls set this to false so that this for loop stops
if !sb.isPolling() {
ticker.Stop()
}
if err := ctx.Err(); err != nil {
return
}
select {
case <-ctx.Done():
return
case <-ticker.C:
linvel, err := sb.velocities.LinearVelocity(ctx, extra)
if err != nil {
sb.logger.CError(ctx, err)
return
}
angvel, err := sb.velocities.AngularVelocity(ctx, extra)
if err != nil {
sb.logger.CError(ctx, err)
return
}
if sensorDebug {
sb.logger.CInfof(ctx, "sensor readings: linear: %#v, angular %#v", linvel, angvel)
}
}
}
}, sb.activeBackgroundWorkers.Done)
}
func sign(x float64) float64 { // A quick helper function
if math.Signbit(x) {
return -1.0
}
return 1.0
}
// SetState is called in endpoint.go of the controls package by the control loop
// instantiated in this file. It is a helper function to call the sensor-controlled base's
// SetVelocity from within that package.
func (sb *sensorBase) SetState(ctx context.Context, state []*control.Signal) error {
sb.mu.Lock()
defer sb.mu.Unlock()
if sb.isPolling() {
// if the spin loop is polling, don't call set velocity, immediately return
// this allows us to keep the control loop running without stopping it until
// the resource Close has been called
sb.logger.CInfo(ctx, "skipping set state call")
return nil
}
sb.logger.CDebug(ctx, "setting state")
linvel := state[0].GetSignalValueAt(0)
// multiply by the direction of the linear velocity so that angular direction
// (cw/ccw) doesn't switch when the base is moving backwards
angvel := (state[1].GetSignalValueAt(0) * sign(linvel))
return sb.SetPower(ctx, r3.Vector{Y: linvel}, r3.Vector{Z: angvel}, nil)
}
// State is called in endpoint.go of the controls package by the control loop
// instantiated in this file. It is a helper function to call the sensor-controlled base's
// movementsensor and insert its LinearVelocity and AngularVelocity values
// in the signal in the control loop's thread in the endpoint code.
func (sb *sensorBase) State(ctx context.Context) ([]float64, error) {
sb.logger.CDebug(ctx, "getting state")
linvel, err := sb.velocities.LinearVelocity(ctx, nil)
if err != nil {
return []float64{}, err
}
angvel, err := sb.velocities.AngularVelocity(ctx, nil)
if err != nil {
return []float64{}, err
}
return []float64{linvel.Y, angvel.Z}, nil
}
// createControlLoopConfig creates a control loop config that is embedded in this file so a user
// does not have to configure the loop from within the attributes of the config file.
// it sets up a loop that takes a constant -> sum -> PID -> gain -> Endpoint -> feedback to sum
// structure. The gain is 0.0039 (1/255) to account for the PID range, the PID values are experimental
// this structure can change as hardware experiments with the viam base require.
func (sb *sensorBase) createControlLoopConfig() control.Config {
return control.Config{
Blocks: []control.BlockConfig{
{
Name: "endpoint",
Type: "endpoint",
Attribute: rdkutils.AttributeMap{
"base_name": sb.Name().ShortName(),
},
DependsOn: []string{"linear_gain", "angular_gain"},
},
{
Name: "linear_PID",
Type: "PID",
Attribute: rdkutils.AttributeMap{
"kD": 0.0,
"kI": 520.763911,
"kP": 291.489819,
"int_sat_lim_lo": -255.0,
"int_sat_lim_up": 255.0,
"limit_lo": -255.0,
"limit_up": 255.0,
"tune_method": "ziegerNicholsPI",
"tune_ssr_value": 2.0,
"tune_step_pct": 0.35,
},
DependsOn: []string{"sum"},
},
{
Name: "angular_PID",
Type: "PID",
Attribute: rdkutils.AttributeMap{
"kD": 0.0,
"kI": 0.904513,
"kP": 0.677894,
"int_sat_lim_lo": -255.0,
"int_sat_lim_up": 255.0,
"limit_lo": -255.0,
"limit_up": 255.0,
"tune_method": "ziegerNicholsPI",
"tune_ssr_value": 2.0,
"tune_step_pct": 0.35,
},
DependsOn: []string{"sum"},
},
{
Name: "sum",
Type: "sum",
Attribute: rdkutils.AttributeMap{
"sum_string": "++-",
},
DependsOn: []string{"linear_setpoint", "angular_setpoint", "endpoint"},
},
{
Name: "linear_gain",
Type: "gain",
Attribute: rdkutils.AttributeMap{
"gain": rPiGain,
},
DependsOn: []string{"linear_PID"},
},
{
Name: "angular_gain",
Type: "gain",
Attribute: rdkutils.AttributeMap{
"gain": rPiGain,
},
DependsOn: []string{"angular_PID"},
},
{
Name: "linear_setpoint",
Type: "constant",
Attribute: rdkutils.AttributeMap{
"constant_val": 0.0,
},
DependsOn: []string{},
},
{
Name: "angular_setpoint",
Type: "constant",
Attribute: rdkutils.AttributeMap{
"constant_val": 0.0,
},
DependsOn: []string{},
},
},
Frequency: 100,
}
}