-
Notifications
You must be signed in to change notification settings - Fork 110
/
builtin.go
352 lines (298 loc) · 9.24 KB
/
builtin.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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
// Package builtin contains the default navigation service, along with a gRPC server and client
package builtin
import (
"context"
"fmt"
"math"
"sync"
"time"
"github.com/edaniels/golog"
geo "github.com/kellydunn/golang-geo"
"github.com/pkg/errors"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.viam.com/utils"
"go.viam.com/rdk/components/base"
"go.viam.com/rdk/components/movementsensor"
"go.viam.com/rdk/resource"
"go.viam.com/rdk/services/navigation"
)
const (
mmPerSecDefault = 500
degPerSecDefault = 45
)
func init() {
resource.RegisterService(navigation.API, resource.DefaultServiceModel, resource.Registration[navigation.Service, *Config]{
Constructor: func(
ctx context.Context,
deps resource.Dependencies,
conf resource.Config,
logger golog.Logger,
) (navigation.Service, error) {
return NewBuiltIn(ctx, deps, conf, logger)
},
})
}
// Config describes how to configure the service.
type Config struct {
Store navigation.StoreConfig `json:"store"`
BaseName string `json:"base"`
MovementSensorName string `json:"movement_sensor"`
DegPerSecDefault float64 `json:"degs_per_sec"`
MMPerSecDefault float64 `json:"mm_per_sec"`
}
// Validate creates the list of implicit dependencies.
func (conf *Config) Validate(path string) ([]string, error) {
var deps []string
if conf.BaseName == "" {
return nil, utils.NewConfigValidationFieldRequiredError(path, "base")
}
deps = append(deps, conf.BaseName)
if conf.MovementSensorName == "" {
return nil, utils.NewConfigValidationFieldRequiredError(path, "movement_sensor")
}
deps = append(deps, conf.MovementSensorName)
return deps, nil
}
// NewBuiltIn returns a new navigation service for the given robot.
func NewBuiltIn(ctx context.Context, deps resource.Dependencies, conf resource.Config, logger golog.Logger) (navigation.Service, error) {
cancelCtx, cancelFunc := context.WithCancel(context.Background())
navSvc := &builtIn{
Named: conf.ResourceName().AsNamed(),
logger: logger,
cancelCtx: cancelCtx,
cancelFunc: cancelFunc,
}
if err := navSvc.Reconfigure(ctx, deps, conf); err != nil {
return nil, err
}
return navSvc, nil
}
type builtIn struct {
resource.Named
mu sync.RWMutex
store navigation.NavStore
storeType string
mode navigation.Mode
base base.Base
movementSensor movementsensor.MovementSensor
mmPerSecDefault float64
degPerSecDefault float64
logger golog.Logger
cancelCtx context.Context
cancelFunc func()
activeBackgroundWorkers sync.WaitGroup
}
func (svc *builtIn) Reconfigure(ctx context.Context, deps resource.Dependencies, conf resource.Config) error {
svc.mu.RLock()
defer svc.mu.RUnlock()
svcConfig, err := resource.NativeConfig[*Config](conf)
if err != nil {
return err
}
base1, err := base.FromDependencies(deps, svcConfig.BaseName)
if err != nil {
return err
}
movementSensor, err := movementsensor.FromDependencies(deps, svcConfig.MovementSensorName)
if err != nil {
return err
}
var newStore navigation.NavStore
if svc.storeType != string(svcConfig.Store.Type) {
switch svcConfig.Store.Type {
case navigation.StoreTypeMemory:
newStore = navigation.NewMemoryNavigationStore()
case navigation.StoreTypeMongoDB:
var err error
newStore, err = navigation.NewMongoDBNavigationStore(ctx, svcConfig.Store.Config)
if err != nil {
return err
}
default:
return errors.Errorf("unknown store type %q", svcConfig.Store.Type)
}
} else {
newStore = svc.store
}
// get default speeds from config if set, else defaults from nav services const
straightSpeed := svcConfig.MMPerSecDefault
if straightSpeed == 0 {
straightSpeed = mmPerSecDefault
}
spinSpeed := svcConfig.DegPerSecDefault
if spinSpeed == 0 {
spinSpeed = degPerSecDefault
}
svc.store = newStore
svc.storeType = string(svcConfig.Store.Type)
svc.base = base1
svc.movementSensor = movementSensor
svc.mmPerSecDefault = straightSpeed
svc.degPerSecDefault = spinSpeed
return nil
}
func (svc *builtIn) Mode(ctx context.Context, extra map[string]interface{}) (navigation.Mode, error) {
svc.mu.RLock()
defer svc.mu.RUnlock()
return svc.mode, nil
}
func (svc *builtIn) SetMode(ctx context.Context, mode navigation.Mode, extra map[string]interface{}) error {
svc.mu.Lock()
defer svc.mu.Unlock()
if svc.mode == mode {
return nil
}
// switch modes
svc.cancelFunc()
svc.activeBackgroundWorkers.Wait()
cancelCtx, cancelFunc := context.WithCancel(context.Background())
svc.cancelCtx = cancelCtx
svc.cancelFunc = cancelFunc
svc.mode = navigation.ModeManual
if mode == navigation.ModeWaypoint {
if err := svc.startWaypoint(extra); err != nil {
return err
}
svc.mode = mode
}
return nil
}
func (svc *builtIn) computeCurrentBearing(ctx context.Context, path []*geo.Point) (float64, error) {
props, err := svc.movementSensor.Properties(ctx, nil)
if err != nil {
return 0, err
}
if props.CompassHeadingSupported {
return svc.movementSensor.CompassHeading(ctx, nil)
}
pathLen := len(path)
return fixAngle(path[pathLen-2].BearingTo(path[pathLen-1])), nil
}
func (svc *builtIn) startWaypoint(extra map[string]interface{}) error {
svc.activeBackgroundWorkers.Add(1)
utils.PanicCapturingGo(func() {
defer svc.activeBackgroundWorkers.Done()
path := []*geo.Point{}
for {
if !utils.SelectContextOrWait(svc.cancelCtx, 500*time.Millisecond) {
return
}
currentLoc, _, err := svc.movementSensor.Position(svc.cancelCtx, extra)
if err != nil {
svc.logger.Errorw("failed to get gps location", "error", err)
continue
}
if len(path) <= 1 || currentLoc.GreatCircleDistance(path[len(path)-1]) > .0001 {
// gps often updates less frequently
path = append(path, currentLoc)
if len(path) > 2 {
path = path[len(path)-2:]
}
}
navOnce := func(ctx context.Context) error {
if len(path) <= 1 {
return errors.New("not enough gps data")
}
currentBearing, err := svc.computeCurrentBearing(ctx, path)
if err != nil {
return err
}
bearingToGoal, distanceToGoal, err := svc.waypointDirectionAndDistanceToGo(ctx, currentLoc)
if err != nil {
return err
}
if distanceToGoal < .005 {
svc.logger.Debug("i made it")
return svc.waypointReached(ctx)
}
bearingDelta := computeBearing(bearingToGoal, currentBearing)
steeringDir := -bearingDelta / 180.0
svc.logger.Debugf("currentBearing: %0.0f bearingToGoal: %0.0f distanceToGoal: %0.3f bearingDelta: %0.1f steeringDir: %0.2f",
currentBearing, bearingToGoal, distanceToGoal, bearingDelta, steeringDir)
// TODO(erh->erd): maybe need an arc/stroke abstraction?
// - Remember that we added -1*bearingDelta instead of steeringDir
// - Test both naval/land to prove it works
if err := svc.base.Spin(ctx, -1*bearingDelta, svc.degPerSecDefault, nil); err != nil {
return fmt.Errorf("error turning: %w", err)
}
distanceMm := distanceToGoal * 1000 * 1000
distanceMm = math.Min(distanceMm, 10*1000)
if err := svc.base.MoveStraight(ctx, int(distanceMm), svc.mmPerSecDefault, nil); err != nil {
return fmt.Errorf("error moving %w", err)
}
return nil
}
if err := navOnce(svc.cancelCtx); err != nil {
svc.logger.Infof("error navigating: %s", err)
}
}
})
return nil
}
func (svc *builtIn) waypointDirectionAndDistanceToGo(ctx context.Context, currentLoc *geo.Point) (float64, float64, error) {
wp, err := svc.nextWaypoint(ctx)
if err != nil {
return 0, 0, err
}
goal := wp.ToPoint()
return fixAngle(currentLoc.BearingTo(goal)), currentLoc.GreatCircleDistance(goal), nil
}
func (svc *builtIn) Location(ctx context.Context, extra map[string]interface{}) (*geo.Point, error) {
if svc.movementSensor == nil {
return nil, errors.New("no way to get location")
}
loc, _, err := svc.movementSensor.Position(ctx, extra)
return loc, err
}
func (svc *builtIn) Waypoints(ctx context.Context, extra map[string]interface{}) ([]navigation.Waypoint, error) {
wps, err := svc.store.Waypoints(ctx)
if err != nil {
return nil, err
}
wpsCopy := make([]navigation.Waypoint, 0, len(wps))
wpsCopy = append(wpsCopy, wps...)
return wpsCopy, nil
}
func (svc *builtIn) AddWaypoint(ctx context.Context, point *geo.Point, extra map[string]interface{}) error {
_, err := svc.store.AddWaypoint(ctx, point)
return err
}
func (svc *builtIn) RemoveWaypoint(ctx context.Context, id primitive.ObjectID, extra map[string]interface{}) error {
return svc.store.RemoveWaypoint(ctx, id)
}
func (svc *builtIn) nextWaypoint(ctx context.Context) (navigation.Waypoint, error) {
return svc.store.NextWaypoint(ctx)
}
func (svc *builtIn) waypointReached(ctx context.Context) error {
wp, err := svc.nextWaypoint(ctx)
if err != nil {
return fmt.Errorf("can't mark waypoint reached: %w", err)
}
return svc.store.WaypointVisited(ctx, wp.ID)
}
func (svc *builtIn) Close(ctx context.Context) error {
svc.cancelFunc()
svc.activeBackgroundWorkers.Wait()
return svc.store.Close(ctx)
}
func fixAngle(a float64) float64 {
for a < 0 {
a += 360
}
for a > 360 {
a -= 360
}
return a
}
func computeBearing(a, b float64) float64 {
a = fixAngle(a)
b = fixAngle(b)
t := b - a
if t < -180 {
t += 360
}
if t > 180 {
t -= 360
}
return t
}