-
Notifications
You must be signed in to change notification settings - Fork 110
/
dofbot.go
448 lines (367 loc) · 11 KB
/
dofbot.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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
// Package yahboom implements a yahboom based robot.
// code with commands found at http://www.yahboom.net/study/Dofbot-Pi
package yahboom
import (
"context"
// for embedding model file.
_ "embed"
"encoding/binary"
"fmt"
"math"
"sync"
"time"
"github.com/edaniels/golog"
"github.com/pkg/errors"
componentpb "go.viam.com/api/component/arm/v1"
"go.viam.com/utils"
"go.viam.com/rdk/components/arm"
"go.viam.com/rdk/components/board"
"go.viam.com/rdk/components/generic"
"go.viam.com/rdk/config"
"go.viam.com/rdk/motionplan"
"go.viam.com/rdk/operation"
"go.viam.com/rdk/referenceframe"
"go.viam.com/rdk/registry"
"go.viam.com/rdk/resource"
"go.viam.com/rdk/spatialmath"
rdkutils "go.viam.com/rdk/utils"
)
// ModelName is the model used to refer to the yahboom model.
var ModelName = resource.NewDefaultModel("yahboom-dofbot")
//go:embed dofbot.json
var modeljson []byte
// Model returns the kinematics model of the yahboom arm, also has all Frame information.
func Model(name string) (referenceframe.Model, error) {
return referenceframe.UnmarshalModelJSON(modeljson, name)
}
type jointConfig struct {
x, y, z float64
offset float64
}
var joints = []jointConfig{
{2200, 180, 100, 150},
{2200, 180, 100, 240},
{2200, 180, 100, 158},
{2200, 180, 100, 150},
{2200, 180, 100, 110},
{2200, 180, 100, 0},
}
func (jc jointConfig) toValues(n int) float64 {
d := float64(n) - jc.z
d /= jc.x
d *= jc.y
return d - jc.offset
}
func (jc jointConfig) toHw(degrees float64) int {
degrees = math.Max(-270, degrees)
degrees = math.Min(270, degrees)
hw := int((jc.x * ((degrees + jc.offset) / jc.y)) + jc.z)
if hw < 0 {
hw = 0
}
return hw
}
// AttrConfig is the config for a yahboom arm.
type AttrConfig struct {
Board string `json:"board"`
I2C string `json:"i2c"`
}
// Validate ensures all parts of the config are valid.
func (config *AttrConfig) Validate(path string) error {
if config.Board == "" {
return utils.NewConfigValidationFieldRequiredError(path, "board")
}
if config.I2C == "" {
return utils.NewConfigValidationFieldRequiredError(path, "i2c")
}
return nil
}
func init() {
registry.RegisterComponent(arm.Subtype, ModelName, registry.Component{
Constructor: func(ctx context.Context, deps registry.Dependencies, config config.Component, logger golog.Logger) (interface{}, error) {
return NewDofBot(ctx, deps, config, logger)
},
})
config.RegisterComponentAttributeMapConverter(arm.Subtype, ModelName,
func(attributes config.AttributeMap) (interface{}, error) {
var conf AttrConfig
return config.TransformAttributeMapToStruct(&conf, attributes)
}, &AttrConfig{})
}
// Dofbot implements a yahboom dofbot arm.
type Dofbot struct {
generic.Unimplemented
handle board.I2CHandle
model referenceframe.Model
mu sync.Mutex
muMove sync.Mutex
logger golog.Logger
opMgr operation.SingleOperationManager
stopped bool
}
// NewDofBot is a constructor to create a new dofbot arm.
func NewDofBot(ctx context.Context, deps registry.Dependencies, config config.Component, logger golog.Logger) (arm.LocalArm, error) {
var err error
attr, ok := config.ConvertedAttributes.(*AttrConfig)
if !ok {
return nil, rdkutils.NewUnexpectedTypeError(attr, config.ConvertedAttributes)
}
a := Dofbot{}
a.logger = logger
b, err := board.FromDependencies(deps, attr.Board)
if err != nil {
return nil, err
}
localB, ok := b.(board.LocalBoard)
if !ok {
return nil, fmt.Errorf("board %s is not local", attr.Board)
}
i2c, ok := localB.I2CByName(attr.I2C)
if !ok {
return nil, fmt.Errorf("no i2c for yahboom-dofbot arm %s", config.Name)
}
a.handle, err = i2c.OpenHandle(0x15)
if err != nil {
return nil, err
}
a.model, err = Model(config.Name)
if err != nil {
return nil, err
}
// sanity check if init succeeded
var pos *componentpb.JointPositions
pos, err = a.JointPositions(ctx, nil)
if err != nil {
return nil, fmt.Errorf("error reading joint positions during init: %w", err)
}
logger.Debug("Current joint positions: %v", pos)
return &a, nil
}
// EndPosition returns the current position of the arm.
func (a *Dofbot) EndPosition(ctx context.Context, extra map[string]interface{}) (spatialmath.Pose, error) {
joints, err := a.JointPositions(ctx, extra)
if err != nil {
return nil, fmt.Errorf("error getting joint positions: %w", err)
}
return motionplan.ComputeOOBPosition(a.model, joints)
}
// MoveToPosition moves the arm to the given absolute position.
func (a *Dofbot) MoveToPosition(ctx context.Context, pos spatialmath.Pose, extra map[string]interface{}) error {
ctx, done := a.opMgr.New(ctx)
defer done()
return arm.Move(ctx, a.logger, a, pos)
}
// MoveToJointPositions moves the arm's joints to the given positions.
func (a *Dofbot) MoveToJointPositions(ctx context.Context, pos *componentpb.JointPositions, extra map[string]interface{}) error {
// check that joint positions are not out of bounds
if err := arm.CheckDesiredJointPositions(ctx, a, pos.Values); err != nil {
return err
}
ctx, done := a.opMgr.New(ctx)
defer done()
a.muMove.Lock()
defer a.muMove.Unlock()
if a.stopped {
err := a.turnOnTorque(ctx)
a.logger.Warnf("error turning on torque %s: ", err)
}
if len(pos.Values) > 5 {
return fmt.Errorf("yahboom wrong number of degrees got %d, need at most 5", len(pos.Values))
}
for j := 0; j < 100; j++ {
success, err := func() (bool, error) {
a.mu.Lock()
defer a.mu.Unlock()
current, err := a.getJointPositionsInLock(ctx)
if err != nil {
return false, err
}
movedAny := false
for i, d := range pos.Values {
delta := math.Abs(current.Values[i] - d)
if delta < .5 {
continue
}
if j > 5 && delta < 2 {
// good enough
continue
}
movedAny = true
err := a.moveJointInLock(ctx, i+1, d)
if err != nil {
return false, fmt.Errorf("error moving joint %d: %w", i+1, err)
}
sleepFor := time.Duration(4+int(delta)) * time.Millisecond
time.Sleep(sleepFor)
}
return !movedAny, nil
}()
if err != nil {
return err
}
if success {
return nil
}
}
return errors.New("dofbot MoveToJointPositions timed out")
}
func (a *Dofbot) moveJointInLock(ctx context.Context, joint int, degrees float64) error {
pos := joints[joint-1].toHw(degrees)
buf := make([]byte, 5)
buf[0] = byte(0x10 + joint)
buf[1] = byte((pos >> 8) & 0xFF)
buf[2] = byte(pos & 0xFF)
// time
// TODO(erh): make configurable?
buf[3] = 0
buf[4] = 0xFF
return a.handle.Write(ctx, buf)
}
// JointPositions returns the current joint positions of the arm.
func (a *Dofbot) JointPositions(ctx context.Context, extra map[string]interface{}) (*componentpb.JointPositions, error) {
a.mu.Lock()
defer a.mu.Unlock()
return a.getJointPositionsInLock(ctx)
}
func (a *Dofbot) getJointPositionsInLock(ctx context.Context) (*componentpb.JointPositions, error) {
pos := componentpb.JointPositions{}
for i := 1; i <= 5; i++ {
x, err := a.readJointInLock(ctx, i)
if err != nil {
return nil, err
}
pos.Values = append(pos.Values, x)
}
return &pos, nil
}
func (a *Dofbot) readJointInLock(ctx context.Context, joint int) (float64, error) {
reg := byte(0x30 + joint)
err := a.handle.WriteByteData(ctx, reg, 0)
if err != nil {
return 0, fmt.Errorf("error requesting joint %v from register %v: %w", joint, reg, err)
}
time.Sleep(3 * time.Millisecond)
rd, err := a.handle.ReadBlockData(ctx, reg, 2)
if err != nil {
return 0, fmt.Errorf("error reading joint %v from register %v: %w", joint, reg, err)
}
time.Sleep(3 * time.Millisecond)
res := binary.BigEndian.Uint16(rd)
return joints[joint-1].toValues(int(res)), nil
}
// Stop is unimplemented for the dofbot.
func (a *Dofbot) Stop(ctx context.Context, extra map[string]interface{}) error {
a.mu.Lock()
defer a.mu.Unlock()
a.stopped = true
return a.turnOffTorque(ctx)
}
func (a *Dofbot) turnOffTorque(ctx context.Context) error {
buf := make([]byte, 2)
buf[0] = byte(0x1A)
buf[1] = byte(0x00)
return a.handle.Write(ctx, buf)
}
func (a *Dofbot) turnOnTorque(ctx context.Context) error {
buf := make([]byte, 2)
buf[0] = byte(0x1A)
buf[1] = byte(0x01)
return a.handle.Write(ctx, buf)
}
// GripperStop is unimplemented for the dofbot.
func (a *Dofbot) GripperStop(ctx context.Context) error {
a.mu.Lock()
defer a.mu.Unlock()
return a.Stop(ctx, nil)
}
// IsMoving returns whether the arm is moving.
func (a *Dofbot) IsMoving(ctx context.Context) (bool, error) {
return a.opMgr.OpRunning(), nil
}
// ModelFrame returns all the information necessary for including the arm in a FrameSystem.
func (a *Dofbot) ModelFrame() referenceframe.Model {
return a.model
}
// Open opens the gripper.
func (a *Dofbot) Open(ctx context.Context) error {
ctx, done := a.opMgr.New(ctx)
defer done()
a.mu.Lock()
defer a.mu.Unlock()
gripperPosition, err := a.readJointInLock(ctx, 6)
if err != nil {
return err
}
a.logger.Debug("In Open. Starting gripper position: ", gripperPosition)
return a.moveJointInLock(ctx, 6, 100)
}
const (
grabAngle = 240.0
minMovement = 5.0
)
// Grab makes the gripper grab.
// Approach: Move to close, poll until gripper reaches the closed state
// (position > grabAngle) or the position changes little (< minMovement)
// between iterations.
func (a *Dofbot) Grab(ctx context.Context) (bool, error) {
ctx, done := a.opMgr.New(ctx)
defer done()
a.mu.Lock()
defer a.mu.Unlock()
startingGripperPos, err := a.readJointInLock(ctx, 6)
if err != nil {
return false, err
}
a.logger.Debug("In Grab. Starting gripper position: ", startingGripperPos)
err = a.moveJointInLock(ctx, 6, grabAngle)
if err != nil {
return false, err
}
// wait a moment to get moving
if !utils.SelectContextOrWait(ctx, 200*time.Millisecond) {
return false, ctx.Err()
}
// wait till we stop moving
last := -1.0
for {
current, err := a.readJointInLock(ctx, 6)
if err != nil {
return false, err
}
if math.Abs(last-current) < minMovement || current > grabAngle {
last = current // last is used after the loop
break
}
last = current
if !utils.SelectContextOrWait(ctx, 20*time.Millisecond) {
return false, ctx.Err()
}
}
gripperPositionEnd, err := a.readJointInLock(ctx, 6)
if err != nil {
return false, err
}
a.logger.Debug("In Grab. Ending gripper position: ", gripperPositionEnd)
return last < grabAngle, a.moveJointInLock(ctx, 6, last+10) // squeeze a tiny bit
}
// CurrentInputs returns the current inputs of the arm.
func (a *Dofbot) CurrentInputs(ctx context.Context) ([]referenceframe.Input, error) {
res, err := a.JointPositions(ctx, nil)
if err != nil {
return nil, err
}
return a.model.InputFromProtobuf(res), nil
}
// GoToInputs moves the arm to the specified goal inputs.
func (a *Dofbot) GoToInputs(ctx context.Context, goal []referenceframe.Input) error {
// check that joint positions are not out of bounds
positionDegs := a.model.ProtobufFromInput(goal)
if err := arm.CheckDesiredJointPositions(ctx, a, positionDegs.Values); err != nil {
return err
}
return a.MoveToJointPositions(ctx, a.model.ProtobufFromInput(goal), nil)
}
// Close closes the arm.
func (a *Dofbot) Close() error {
return a.handle.Close()
}