-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsnippets.json
More file actions
7556 lines (7556 loc) · 489 KB
/
snippets.json
File metadata and controls
7556 lines (7556 loc) · 489 KB
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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{
"BasicOpMode Linear": {
"prefix": "basicOpModeLinear",
"description": "This file contains an minimal example of a Linear \"OpMode\". An OpMode is a 'program' that runs in either\nthe autonomous or the teleop period of an FTC match. The names of OpModes appear on the menu\nof the FTC Driver Station. When a selection is made from the menu, the corresponding OpMode\nclass is instantiated on the Robot Controller and executed.\n\nThis particular OpMode just executes a basic Tank Drive Teleop for a two wheeled robot\nIt includes all the skeletal structure that all linear OpModes contain.\n\nUse Android Studio to Copy this Class, and Paste it into your team's code folder with a new name.\nRemove or comment out the @Disabled line to add this opmode to the Driver Station OpMode list\n ",
"body": [
"public class BasicOpMode_Linear extends LinearOpMode {",
"",
" // Declare OpMode members.",
" private ElapsedTime runtime = new ElapsedTime();",
" private DcMotor leftDrive = null;",
" private DcMotor rightDrive = null;",
"",
" @Override",
" public void runOpMode() {",
" telemetry.addData(\"Status\", \"Initialized\");",
" telemetry.update();",
"",
" // Initialize the hardware variables. Note that the strings used here as parameters",
" // to 'get' must correspond to the names assigned during the robot configuration",
" // step (using the FTC Robot Controller app on the phone).",
" leftDrive = hardwareMap.get(DcMotor.class, \"left_drive\");",
" rightDrive = hardwareMap.get(DcMotor.class, \"right_drive\");",
"",
" // To drive forward, most robots need the motor on one side to be reversed, because the axles point in opposite directions.",
" // Pushing the left stick forward MUST make robot go forward. So adjust these two lines based on your first test drive.",
" // Note: The settings here assume direct drive on left and right wheels. Gear Reduction or 90 Deg drives may require direction flips",
" leftDrive.setDirection(DcMotor.Direction.REVERSE);",
" rightDrive.setDirection(DcMotor.Direction.FORWARD);",
"",
" // Wait for the game to start (driver presses PLAY)",
" waitForStart();",
" runtime.reset();",
"",
" // run until the end of the match (driver presses STOP)",
" while (opModeIsActive()) {",
"",
" // Setup a variable for each drive wheel to save power level for telemetry",
" double leftPower;",
" double rightPower;",
"",
" // Choose to drive using either Tank Mode, or POV Mode",
" // Comment out the method that's not used. The default below is POV.",
"",
" // POV Mode uses left stick to go forward, and right stick to turn.",
" // - This uses basic math to combine motions and is easier to drive straight.",
" double drive = -gamepad1.left_stick_y;",
" double turn = gamepad1.right_stick_x;",
" leftPower = Range.clip(drive + turn, -1.0, 1.0) ;",
" rightPower = Range.clip(drive - turn, -1.0, 1.0) ;",
"",
" // Tank Mode uses one stick to control each wheel.",
" // - This requires no math, but it is hard to drive forward slowly and keep straight.",
" // leftPower = -gamepad1.left_stick_y ;",
" // rightPower = -gamepad1.right_stick_y ;",
"",
" // Send calculated power to wheels",
" leftDrive.setPower(leftPower);",
" rightDrive.setPower(rightPower);",
"",
" // Show the elapsed game time and wheel power.",
" telemetry.addData(\"Status\", \"Run Time: \" + runtime.toString());",
" telemetry.addData(\"Motors\", \"left (%.2f), right (%.2f)\", leftPower, rightPower);",
" telemetry.update();",
" }",
" }",
"}",
""
]
},
"ConceptVuforiaNavigationWebcam": {
"prefix": "conceptVuforiaNavigationWebcam",
"description": " Sample one frame from the Vuforia stream and write it to a .PNG image file on the robot\n controller in the /sdcard/FIRST/data directory. The images can be downloaded using Android\n Studio's Device File Explorer, ADB, or the Media Transfer Protocol (MTP) integration into\n Windows Explorer, among other means. The images can be useful during robot design and calibration\n in order to get a sense of what the camera is actually seeing and so assist in camera\n aiming and alignment.\n ",
"body": [
"public class ConceptVuforiaNavigationWebcam extends LinearOpMode {",
"",
" public static final String TAG = \"Vuforia Navigation Sample\";",
"",
" OpenGLMatrix lastLocation = null;",
"",
" /**",
" * @see #captureFrameToFile()",
" */",
" int captureCounter = 0;",
" File captureDirectory = AppUtil.ROBOT_DATA_DIR;",
"",
" /**",
" * {@link #vuforia} is the variable we will use to store our instance of the Vuforia",
" * localization engine.",
" */",
" VuforiaLocalizer vuforia;",
"",
" /**",
" * This is the webcam we are to use. As with other hardware devices such as motors and",
" * servos, this device is identified using the robot configuration tool in the FTC application.",
" */",
" WebcamName webcamName;",
"",
" @Override public void runOpMode() {",
"",
" /*",
" * Retrieve the camera we are to use.",
" */",
" webcamName = hardwareMap.get(WebcamName.class, \"Webcam 1\");",
"",
" /*",
" * To start up Vuforia, tell it the view that we wish to use for camera monitor (on the RC phone);",
" * If no camera monitor is desired, use the parameterless constructor instead (commented out below).",
" */",
" int cameraMonitorViewId = hardwareMap.appContext.getResources().getIdentifier(\"cameraMonitorViewId\", \"id\", hardwareMap.appContext.getPackageName());",
" VuforiaLocalizer.Parameters parameters = new VuforiaLocalizer.Parameters(cameraMonitorViewId);",
"",
" // OR... Do Not Activate the Camera Monitor View, to save power",
" // VuforiaLocalizer.Parameters parameters = new VuforiaLocalizer.Parameters();",
"",
" /*",
" * IMPORTANT: You need to obtain your own license key to use Vuforia. The string below with which",
" * 'parameters.vuforiaLicenseKey' is initialized is for illustration only, and will not function.",
" * A Vuforia 'Development' license key, can be obtained free of charge from the Vuforia developer",
" * web site at https://developer.vuforia.com/license-manager.",
" *",
" * Vuforia license keys are always 380 characters long, and look as if they contain mostly",
" * random data. As an example, here is a example of a fragment of a valid key:",
" * ... yIgIzTqZ4mWjk9wd3cZO9T1axEqzuhxoGlfOOI2dRzKS4T0hQ8kT ...",
" * Once you've obtained a license key, copy the string from the Vuforia web site",
" * and paste it in to your code on the next line, between the double quotes.",
" */",
" parameters.vuforiaLicenseKey = \" -- YOUR NEW VUFORIA KEY GOES HERE --- \";",
"",
" /**",
" * We also indicate which camera on the RC we wish to use.",
" */",
" parameters.cameraName = webcamName;",
"",
" /**",
" * Instantiate the Vuforia engine",
" */",
" vuforia = ClassFactory.getInstance().createVuforia(parameters);",
"",
" /**",
" * Because this opmode processes frames in order to write them to a file, we tell Vuforia",
" * that we want to ensure that certain frame formats are available in the {@link Frame}s we",
" * see.",
" */",
" vuforia.enableConvertFrameToBitmap();",
"",
" /** @see #captureFrameToFile() */",
" AppUtil.getInstance().ensureDirectoryExists(captureDirectory);",
"",
"",
" /**",
" * Load the data sets that for the trackable objects we wish to track. These particular data",
" * sets are stored in the 'assets' part of our application (you'll see them in the Android",
" * Studio 'Project' view over there on the left of the screen). You can make your own datasets",
" * with the Vuforia Target Manager: https://developer.vuforia.com/target-manager. PDFs for the",
" * example \"StonesAndChips\", datasets can be found in in this project in the",
" * documentation directory.",
" */",
" VuforiaTrackables stonesAndChips = vuforia.loadTrackablesFromAsset(\"StonesAndChips\");",
" VuforiaTrackable redTarget = stonesAndChips.get(0);",
" redTarget.setName(\"RedTarget\"); // Stones",
"",
" VuforiaTrackable blueTarget = stonesAndChips.get(1);",
" blueTarget.setName(\"BlueTarget\"); // Chips",
"",
" /** For convenience, gather together all the trackable objects in one easily-iterable collection */",
" List<VuforiaTrackable> allTrackables = new ArrayList<VuforiaTrackable>();",
" allTrackables.addAll(stonesAndChips);",
"",
" /**",
" * We use units of mm here because that's the recommended units of measurement for the",
" * size values specified in the XML for the ImageTarget trackables in data sets. E.g.:",
" * <ImageTarget name=\"stones\" size=\"247 173\"/>",
" * You don't *have to* use mm here, but the units here and the units used in the XML",
" * target configuration files *must* correspond for the math to work out correctly.",
" */",
" float mmPerInch = 25.4f;",
" float mmBotWidth = 18 * mmPerInch; // ... or whatever is right for your robot",
" float mmFTCFieldWidth = (12*12 - 2) * mmPerInch; // the FTC field is ~11'10\" center-to-center of the glass panels",
"",
" /**",
" * In order for localization to work, we need to tell the system where each target we",
" * wish to use for navigation resides on the field, and we need to specify where on the robot",
" * the camera resides. These specifications are in the form of <em>transformation matrices.</em>",
" * Transformation matrices are a central, important concept in the math here involved in localization.",
" * See <a href=\"https://en.wikipedia.org/wiki/Transformation_matrix\">Transformation Matrix</a>",
" * for detailed information. Commonly, you'll encounter transformation matrices as instances",
" * of the {@link OpenGLMatrix} class.",
" *",
" * For the most part, you don't need to understand the details of the math of how transformation",
" * matrices work inside (as fascinating as that is, truly). Just remember these key points:",
" * <ol>",
" *",
" * <li>You can put two transformations together to produce a third that combines the effect of",
" * both of them. If, for example, you have a rotation transform R and a translation transform T,",
" * then the combined transformation matrix RT which does the rotation first and then the translation",
" * is given by {@code RT = T.multiplied(R)}. That is, the transforms are multiplied in the",
" * <em>reverse</em> of the chronological order in which they applied.</li>",
" *",
" * <li>A common way to create useful transforms is to use methods in the {@link OpenGLMatrix}",
" * class and the Orientation class. See, for example, {@link OpenGLMatrix#translation(float,",
" * float, float)}, {@link OpenGLMatrix#rotation(AngleUnit, float, float, float, float)}, and",
" * {@link Orientation#getRotationMatrix(AxesReference, AxesOrder, AngleUnit, float, float, float)}.",
" * Related methods in {@link OpenGLMatrix}, such as {@link OpenGLMatrix#rotated(AngleUnit,",
" * float, float, float, float)}, are syntactic shorthands for creating a new transform and",
" * then immediately multiplying the receiver by it, which can be convenient at times.</li>",
" *",
" * <li>If you want to break open the black box of a transformation matrix to understand",
" * what it's doing inside, use {@link MatrixF#getTranslation()} to fetch how much the",
" * transform will move you in x, y, and z, and use {@link Orientation#getOrientation(MatrixF,",
" * AxesReference, AxesOrder, AngleUnit)} to determine the rotational motion that the transform",
" * will impart. See {@link #format(OpenGLMatrix)} below for an example.</li>",
" *",
" * </ol>",
" *",
" * This example places the \"stones\" image on the perimeter wall to the Left",
" * of the Red Driver station wall. Similar to the Red Beacon Location on the Res-Q",
" *",
" * This example places the \"chips\" image on the perimeter wall to the Right",
" * of the Blue Driver station. Similar to the Blue Beacon Location on the Res-Q",
" *",
" * See the doc folder of this project for a description of the Field Coordinate System",
" * conventions.",
" *",
" * Initially the target is conceptually lying at the origin of the Field Coordinate System",
" * (the center of the field), facing up.",
" *",
" * In this configuration, the target's coordinate system aligns with that of the field.",
" *",
" * In a real situation we'd also account for the vertical (Z) offset of the target,",
" * but for simplicity, we ignore that here; for a real robot, you'll want to fix that.",
" *",
" * To place the Stones Target on the Red Audience wall:",
" * - First we rotate it 90 around the field's X axis to flip it upright",
" * - Then we rotate it 90 around the field's Z access to face it away from the audience.",
" * - Finally, we translate it back along the X axis towards the red audience wall.",
" */",
" OpenGLMatrix redTargetLocationOnField = OpenGLMatrix",
" /* Then we translate the target off to the RED WALL. Our translation here",
" is a negative translation in X.*/",
" .translation(-mmFTCFieldWidth/2, 0, 0)",
" .multiplied(Orientation.getRotationMatrix(",
" /* First, in the fixed (field) coordinate system, we rotate 90deg in X, then 90 in Z */",
" AxesReference.EXTRINSIC, AxesOrder.XZX,",
" AngleUnit.DEGREES, 90, 90, 0));",
" redTarget.setLocationFtcFieldFromTarget(redTargetLocationOnField);",
" RobotLog.ii(TAG, \"Red Target=%s\", format(redTargetLocationOnField));",
"",
" /*",
" * To place the Stones Target on the Blue Audience wall:",
" * - First we rotate it 90 around the field's X axis to flip it upright",
" * - Finally, we translate it along the Y axis towards the blue audience wall.",
" */",
" OpenGLMatrix blueTargetLocationOnField = OpenGLMatrix",
" /* Then we translate the target off to the Blue Audience wall.",
" Our translation here is a positive translation in Y.*/",
" .translation(0, mmFTCFieldWidth/2, 0)",
" .multiplied(Orientation.getRotationMatrix(",
" /* First, in the fixed (field) coordinate system, we rotate 90deg in X */",
" AxesReference.EXTRINSIC, AxesOrder.XZX,",
" AngleUnit.DEGREES, 90, 0, 0));",
" blueTarget.setLocationFtcFieldFromTarget(blueTargetLocationOnField);",
" RobotLog.ii(TAG, \"Blue Target=%s\", format(blueTargetLocationOnField));",
"",
" /**",
" * We also need to tell Vuforia where the <em>cameras</em> are relative to the robot.",
" *",
" * Just as there is a Field Coordinate System, so too there is a Robot Coordinate System.",
" * The two share many similarities. The origin of the Robot Coordinate System is wherever",
" * you choose to make it on the robot, but typically you'd choose somewhere in the middle",
" * of the robot. From that origin, the Y axis is horizontal and positive out towards the",
" * \"front\" of the robot (however you choose \"front\" to be defined), the X axis is horizontal",
" * and positive out towards the \"right\" of the robot (i.e.: 90deg horizontally clockwise from",
" * the positive Y axis), and the Z axis is vertical towards the sky.",
" *",
" * Similarly, for each camera there is a Camera Coordinate System. The origin of a Camera",
" * Coordinate System lies in the middle of the sensor inside of the camera. The Z axis is",
" * positive coming out of the lens of the camera in a direction perpendicular to the plane",
" * of the sensor. When looking at the face of the lens of the camera (down the positive Z",
" * axis), the X axis is positive off to the right in the plane of the sensor, and the Y axis",
" * is positive out the top of the lens in the plane of the sensor at 90 horizontally",
" * counter clockwise from the X axis.",
" *",
" * Next, there is Phone Coordinate System (for robots that have phones, of course), though",
" * with the advent of Vuforia support for Webcams, this coordinate system is less significant",
" * than it was previously. The Phone Coordinate System is defined thusly: with the phone in",
" * flat front of you in portrait mode (i.e. as it is when running the robot controller app)",
" * and you are staring straight at the face of the phone,",
" * * X is positive heading off to your right,",
" * * Y is positive heading up through the top edge of the phone, and",
" * * Z is pointing out of the screen, toward you.",
" * The origin of the Phone Coordinate System is at the origin of the Camera Coordinate System",
" * of the front-facing camera on the phone.",
" *",
" * Finally, it is worth noting that trackable Vuforia Image Targets have their <em>own</em>",
" * coordinate system (see {@link VuforiaTrackable}. This is sometimes referred to as the",
" * Target Coordinate System. In keeping with the above, when looking at the target in its",
" * natural orientation, in the Target Coodinate System",
" * * X is positive heading off to your right,",
" * * Y is positive heading up through the top edge of the target, and",
" * * Z is pointing out of the target, toward you.",
" *",
" * One can observe that the Camera Coordinate System of the front-facing camera on a phone",
" * coincides with the Phone Coordinate System. Further, when a phone is placed on its back",
" * at the origin of the Robot Coordinate System and aligned appropriately, those coordinate",
" * systems also coincide with the Robot Coordinate System. Got it?",
" *",
" * In this example here, we're going to assume that we put the camera on the right side",
" * of the robot (facing outwards, of course). To determine the transformation matrix that",
" * describes that location, first consider the camera as lying on its back at the origin",
" * of the Robot Coordinate System such that the Camera Coordinate System and Robot Coordinate",
" * System coincide. Then the transformation we need is",
" * * first a rotation of the camera by +90deg along the robot X axis,",
" * * then a rotation of the camera by +90deg along the robot Z axis, and",
" * * finally a translation of the camera to the side of the robot.",
" *",
" * When determining whether a rotation is positive or negative, consider yourself as looking",
" * down the (positive) axis of rotation from the positive towards the origin. Positive rotations",
" * are then CCW, and negative rotations CW. An example: consider looking down the positive Z",
" * axis towards the origin. A positive rotation about Z (ie: a rotation parallel to the the X-Y",
" * plane) is then CCW, as one would normally expect from the usual classic 2D geometry.",
" */",
"",
" OpenGLMatrix robotFromCamera = OpenGLMatrix",
" .translation(mmBotWidth/2,0,0)",
" .multiplied(Orientation.getRotationMatrix(",
" AxesReference.EXTRINSIC, AxesOrder.XZY,",
" AngleUnit.DEGREES, 90, 90, 0));",
" RobotLog.ii(TAG, \"camera=%s\", format(robotFromCamera));",
"",
" /**",
" * Let the trackable listeners we care about know where the camera is. We know that each",
" * listener is a {@link VuforiaTrackableDefaultListener} and can so safely cast because",
" * we have not ourselves installed a listener of a different type.",
" */",
" ((VuforiaTrackableDefaultListener)redTarget.getListener()).setCameraLocationOnRobot(parameters.cameraName, robotFromCamera);",
" ((VuforiaTrackableDefaultListener)blueTarget.getListener()).setCameraLocationOnRobot(parameters.cameraName, robotFromCamera);",
"",
" /**",
" * A brief tutorial: here's how all the math is going to work:",
" *",
" * C = robotFromCamera maps camera coords -> robot coords",
" * P = tracker.getPose() maps image target coords -> camera coords",
" * L = redTargetLocationOnField maps image target coords -> field coords",
" *",
" * So",
" *",
" * C.inverted() maps robot coords -> camera coords",
" * P.inverted() maps camera coords -> imageTarget coords",
" *",
" * Putting that all together,",
" *",
" * L x P.inverted() x C.inverted() maps robot coords to field coords.",
" *",
" * @see VuforiaTrackableDefaultListener#getRobotLocation()",
" */",
"",
" /** Wait for the game to begin */",
" telemetry.addData(\">\", \"Press Play to start tracking\");",
" telemetry.update();",
" waitForStart();",
"",
" /** Start tracking the data sets we care about. */",
" stonesAndChips.activate();",
"",
" boolean buttonPressed = false;",
" while (opModeIsActive()) {",
"",
" if (gamepad1.a && !buttonPressed) {",
" captureFrameToFile();",
" }",
" buttonPressed = gamepad1.a;",
"",
" for (VuforiaTrackable trackable : allTrackables) {",
" /**",
" * getUpdatedRobotLocation() will return null if no new information is available since",
" * the last time that call was made, or if the trackable is not currently visible.",
" * getRobotLocation() will return null if the trackable is not currently visible.",
" */",
" telemetry.addData(trackable.getName(), ((VuforiaTrackableDefaultListener)trackable.getListener()).isVisible() ? \"Visible\" : \"Not Visible\"); //",
"",
" OpenGLMatrix robotLocationTransform = ((VuforiaTrackableDefaultListener)trackable.getListener()).getUpdatedRobotLocation();",
" if (robotLocationTransform != null) {",
" lastLocation = robotLocationTransform;",
" }",
" }",
" /**",
" * Provide feedback as to where the robot was last located (if we know).",
" */",
" if (lastLocation != null) {",
" // RobotLog.vv(TAG, \"robot=%s\", format(lastLocation));",
" telemetry.addData(\"Pos\", format(lastLocation));",
" } else {",
" telemetry.addData(\"Pos\", \"Unknown\");",
" }",
" telemetry.update();",
" }",
" }",
"",
" /**",
" * A simple utility that extracts positioning information from a transformation matrix",
" * and formats it in a form palatable to a human being.",
" */",
" String format(OpenGLMatrix transformationMatrix) {",
" return transformationMatrix.formatAsTransform();",
" }",
"",
" /**",
" * Sample one frame from the Vuforia stream and write it to a .PNG image file on the robot",
" * controller in the /sdcard/FIRST/data directory. The images can be downloaded using Android",
" * Studio's Device File Explorer, ADB, or the Media Transfer Protocol (MTP) integration into",
" * Windows Explorer, among other means. The images can be useful during robot design and calibration",
" * in order to get a sense of what the camera is actually seeing and so assist in camera",
" * aiming and alignment.",
" */",
" void captureFrameToFile() {",
" vuforia.getFrameOnce(Continuation.create(ThreadPool.getDefault(), new Consumer<Frame>()",
" {",
" @Override public void accept(Frame frame)",
" {",
" Bitmap bitmap = vuforia.convertFrameToBitmap(frame);",
" if (bitmap != null) {",
" File file = new File(captureDirectory, String.format(Locale.getDefault(), \"VuforiaFrame-%d.png\", captureCounter++));",
" try {",
" FileOutputStream outputStream = new FileOutputStream(file);",
" try {",
" bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);",
" } finally {",
" outputStream.close();",
" telemetry.log().add(\"captured %s\", file.getName());",
" }",
" } catch (IOException e) {",
" RobotLog.ee(TAG, e, \"exception in captureFrameToFile()\");",
" }",
" }",
" }",
" }));",
" }",
"}",
""
]
},
"ConceptSoundsOnBotJava": {
"prefix": "conceptSoundsOnBotJava",
"description": "This file demonstrates how to play simple sounds on both the RC and DS phones.\nIt illustrates how to play sound files that have been copied to the RC Phone\nThis technique is best suited for use with OnBotJava since it does not require the app to be modified.\n\nOperation:\n\nGamepad X & B buttons are used to trigger sounds in this example, but any event can be used.\nNote: Time should be allowed for sounds to complete before playing other sounds.\n\n To play a new sound, you will need to copy the .wav files to the phone, and then provide the full path to them as part of your OpMode.\n This is done in this sample for the two sound files. silver.wav and gold.wav\n\n You can put the files in a variety of soundPaths, but we recommend you put them in the /FIRST/blocks/sounds folder.\n Your OpModes will have guaranteed access to this folder, and you can transfer files into this folder using the BLOCKS web page.\n -- There is a link called \"sounds\" on the right hand side of the color bar on the BLOCKS page that can be used to send sound files to this folder by default.\n Or you can use Windows File Manager, or ADB to transfer the sound files\n\n To get full use of THIS sample, you will need to copy two sound file called silver.wav and gold.wav to /FIRST/blocks/sounds on the RC phone.\n They can be located here:\n https://github.com/ftctechnh/ftc_app/tree/master/FtcRobotController/src/main/res/raw/gold.wav\n https://github.com/ftctechnh/ftc_app/tree/master/FtcRobotController/src/main/res/raw/silver.wav\n ",
"body": [
"public class ConceptSoundsOnBotJava extends LinearOpMode {",
"",
" // Point to sound files on the phone's drive",
" private String soundPath = \"/FIRST/blocks/sounds\";",
" private File goldFile = new File(\"/sdcard\" + soundPath + \"/gold.wav\");",
" private File silverFile = new File(\"/sdcard\" + soundPath + \"/silver.wav\");",
"",
" // Declare OpMode members.",
" private boolean isX = false; // Gamepad button state variables",
" private boolean isB = false;",
"",
" private boolean wasX = false; // Gamepad button history variables",
" private boolean WasB = false;",
"",
" @Override",
" public void runOpMode() {",
"",
" // Make sure that the sound files exist on the phone",
" boolean goldFound = goldFile.exists();",
" boolean silverFound = silverFile.exists();",
"",
" // Display sound status",
" telemetry.addData(\"gold sound\", goldFound ? \"Found\" : \"NOT Found \\nCopy gold.wav to \" + soundPath );",
" telemetry.addData(\"silver sound\", silverFound ? \"Found\" : \"NOT Found \\nCopy silver.wav to \" + soundPath );",
"",
" // Wait for the game to start (driver presses PLAY)",
" telemetry.addData(\">\", \"Press Start to continue\");",
" telemetry.update();",
" waitForStart();",
"",
" telemetry.addData(\">\", \"Press X or B to play sounds.\");",
" telemetry.update();",
"",
" // run until the end of the match (driver presses STOP)",
" while (opModeIsActive()) {",
"",
" // say Silver each time gamepad X is pressed (This sound is a resource)",
" if (silverFound && (isX = gamepad1.x) && !wasX) {",
" SoundPlayer.getInstance().startPlaying(hardwareMap.appContext, silverFile);",
" telemetry.addData(\\\"Playing\\\", \\\"Silver File\\\");",
" telemetry.update();",
" }",
"",
" // say Gold each time gamepad B is pressed (This sound is a resource)",
" if (goldFound && (isB = gamepad1.b) && !WasB) {",
" SoundPlayer.getInstance().startPlaying(hardwareMap.appContext, goldFile);",
" telemetry.addData(\\\"Playing\\\", \\\"Gold File\\\");",
" telemetry.update();",
" }",
"",
" // Save last button states",
" wasX = isX;",
" WasB = isB;",
" }",
" }",
"}",
""
]
},
"ConceptSoundsASJava": {
"prefix": "conceptSoundsASJava",
"description": "This file demonstrates how to play simple sounds on both the RC and DS phones.\nIt illustrates how to build sounds into your application as a resource.\nThis technique is best suited for use with Android Studio since it assumes you will be creating a new application\n\nIf you are using OnBotJava, please see the ConceptSoundsOnBotJava sample\n\nUse Android Studio to Copy this Class, and Paste it into your team's code folder with a new name.\nRemove or comment out the @Disabled line to add this opmode to the Driver Station OpMode list\n\nOperation:\n\nGamepad X & B buttons are used to trigger sounds in this example, but any event can be used.\nNote: Time should be allowed for sounds to complete before playing other sounds.\n\nFor sound files to be used as a compiled-in resource, they need to be located in a folder called \"raw\" under your \"res\" (resources) folder.\nYou can create your own \"raw\" folder from scratch, or you can copy the one from the FtcRobotController module.\n\n Android Studio coders will ultimately need a folder in your path as follows:\n <project root>/TeamCode/src/main/res/raw\n\n Copy any .wav files you want to play into this folder.\n Make sure that your files ONLY use lower-case characters, and have no spaces or special characters other than underscore.\n\n The name you give your .wav files will become the resource ID for these sounds.\n eg: gold.wav becomes R.raw.gold\n\n If you wish to use the sounds provided for this sample, they are located in:\n <project root>/FtcRobotController/src/main/res/raw\n You can copy and paste the entire 'raw' folder using Android Studio.\n\n ",
"body": [
"public class ConceptSoundsASJava extends LinearOpMode {",
"",
" // Declare OpMode members.",
" private boolean goldFound; // Sound file present flags",
" private boolean silverFound;",
"",
" private boolean isX = false; // Gamepad button state variables",
" private boolean isB = false;",
"",
" private boolean wasX = false; // Gamepad button history variables",
" private boolean WasB = false;",
"",
" @Override",
" public void runOpMode() {",
"",
" // Determine Resource IDs for sounds built into the RC application.",
" int silverSoundID = hardwareMap.appContext.getResources().getIdentifier(\"silver\\\", \\\"raw\\\", hardwareMap.appContext.getPackageName());",
" int goldSoundID = hardwareMap.appContext.getResources().getIdentifier(\\\"gold\\\", \\\"raw\\\", hardwareMap.appContext.getPackageName());",
"",
" // Determine if sound resources are found.",
" // Note: Preloading is NOT required, but it's a good way to verify all your sounds are available before you run.",
" if (goldSoundID != 0)",
" goldFound = SoundPlayer.getInstance().preload(hardwareMap.appContext, goldSoundID);",
"",
" if (silverSoundID != 0)",
" silverFound = SoundPlayer.getInstance().preload(hardwareMap.appContext, silverSoundID);",
"",
" // Display sound status",
" telemetry.addData(\\\"gold resource\\\", goldFound ? \\\"Found\\\" : \\\"NOT found\\n Add gold.wav to /src/main/res/raw\\\" );",
" telemetry.addData(\\\"silver resource\\\", silverFound ? \\\"Found\\\" : \\\"Not found\\n Add silver.wav to /src/main/res/raw\\\" );",
"",
" // Wait for the game to start (driver presses PLAY)",
" telemetry.addData(\\\">\\\", \\\"Press Start to continue\\\");",
" telemetry.update();",
" waitForStart();",
"",
" telemetry.addData(\\\">\\\", \\\"Press X, B to play sounds.\\\");",
" telemetry.update();",
"",
" // run until the end of the match (driver presses STOP)",
" while (opModeIsActive()) {",
"",
" // say Silver each time gamepad X is pressed (This sound is a resource)",
" if (silverFound && (isX = gamepad1.x) && !wasX) {",
" SoundPlayer.getInstance().startPlaying(hardwareMap.appContext, silverSoundID);",
" telemetry.addData(\\\"Playing\\\", \\\"Resource Silver\\\");",
" telemetry.update();",
" }",
"",
" // say Gold each time gamepad B is pressed (This sound is a resource)",
" if (goldFound && (isB = gamepad1.b) && !WasB) {",
" SoundPlayer.getInstance().startPlaying(hardwareMap.appContext, goldSoundID);",
" telemetry.addData(\\\"Playing\\\", \\\"Resource Gold\\\");",
" telemetry.update();",
" }",
"",
" // Save last button states",
" wasX = isX;",
" WasB = isB;",
" }",
" }",
"}",
""
]
},
"ConceptRampMotorSpeed": {
"prefix": "conceptRampMotorSpeed",
"description": "This OpMode ramps a single motor speed up and down repeatedly until Stop is pressed.\nThe code is structured as a LinearOpMode\n\nThis code assumes a DC motor configured with the name \"left_drive\" as is found on a Robot.\n\nINCREMENT sets how much to increase/decrease the power each cycle\nCYCLE_MS sets the update period.\n\nUse Android Studio to Copy this Class, and Paste it into your team's code folder with a new name.\nRemove or comment out the @Disabled line to add this opmode to the Driver Station OpMode list\n ",
"body": [
"public class ConceptRampMotorSpeed extends LinearOpMode {",
"",
" static final double INCREMENT = 0.01; // amount to ramp motor each CYCLE_MS cycle",
" static final int CYCLE_MS = 50; // period of each cycle",
" static final double MAX_FWD = 1.0; // Maximum FWD power applied to motor",
" static final double MAX_REV = -1.0; // Maximum REV power applied to motor",
"",
" // Define class members",
" DcMotor motor;",
" double power = 0;",
" boolean rampUp = true;",
"",
"",
" @Override",
" public void runOpMode() {",
"",
" // Connect to motor (Assume standard left wheel)",
" // Change the text in quotes to match any motor name on your robot.",
" motor = hardwareMap.get(DcMotor.class, \"left_drive\\\");",
"",
" // Wait for the start button",
" telemetry.addData(\\\">\\\", \\\"Press Start to run Motors.\\\" );",
" telemetry.update();",
" waitForStart();",
"",
" // Ramp motor speeds till stop pressed.",
" while(opModeIsActive()) {",
"",
" // Ramp the motors, according to the rampUp variable.",
" if (rampUp) {",
" // Keep stepping up until we hit the max value.",
" power += INCREMENT ;",
" if (power >= MAX_FWD ) {",
" power = MAX_FWD;",
" rampUp = !rampUp; // Switch ramp direction",
" }",
" }",
" else {",
" // Keep stepping down until we hit the min value.",
" power -= INCREMENT ;",
" if (power <= MAX_REV ) {",
" power = MAX_REV;",
" rampUp = !rampUp; // Switch ramp direction",
" }",
" }",
"",
" // Display the current value",
" telemetry.addData(\\\"Motor Power\\\", \\\"%5.2f\\\", power);",
" telemetry.addData(\\\">\\\", \\\"Press Stop to end test.\\\" );",
" telemetry.update();",
"",
" // Set the motor to the new power and pause;",
" motor.setPower(power);",
" sleep(CYCLE_MS);",
" idle();",
" }",
"",
" // Turn off motor and signal done;",
" motor.setPower(0);",
" telemetry.addData(\\\">\\\", \\\"Done\\\");",
" telemetry.update();",
"",
" }",
"}",
""
]
},
"ConceptCompassCalibration": {
"prefix": "conceptCompassCalibration",
"description": "This file illustrates the concept of calibrating a MR Compass\n This code assumes there is a compass configured with the name \"compass\"\n\n This code will put the compass into calibration mode, wait three seconds and then attempt\n to rotate two full turns clockwise. This will allow the compass to do a magnetic calibration.\n\n Once compete, the program will put the compass back into measurement mode and check to see if the\n calibration was successful.\n\nUse Android Studio to Copy this Class, and Paste it into your team's code folder with a new name.\nRemove or comment out the @Disabled line to add this opmode to the Driver Station OpMode list\n ",
"body": [
"public class ConceptCompassCalibration extends LinearOpMode {",
"",
" /* Declare OpMode members. */",
" public DcMotor leftDrive = null;",
" public DcMotor rightDrive = null;",
" private ElapsedTime runtime = new ElapsedTime();",
" CompassSensor compass;",
"",
" final static double MOTOR_POWER = 0.2; // scale from 0 to 1",
" static final long HOLD_TIME_MS = 3000;",
" static final double CAL_TIME_SEC = 20;",
"",
" @Override",
" public void runOpMode() {",
"",
" // Initialize the drive system variables.",
" leftDrive = hardwareMap.get(DcMotor.class, \"left_drive\\\");",
" rightDrive = hardwareMap.get(DcMotor.class, \\\"right_drive\\\");",
"",
" // To drive forward, most robots need the motor on one side to be reversed, because the axles point in opposite directions.",
" // Pushing the left stick forward MUST make robot go forward. So adjust these two lines based on your first test drive.",
" // Note: The settings here assume direct drive on left and right wheels. Gear Reduction or 90 Deg drives may require direction flips",
" leftDrive.setDirection(DcMotor.Direction.REVERSE);",
" rightDrive.setDirection(DcMotor.Direction.FORWARD);",
"",
" // get a reference to our Compass Sensor object.",
" compass = hardwareMap.get(CompassSensor.class, \\\"compass\\\");",
"",
" // Send telemetry message to signify robot waiting;",
" telemetry.addData(\\\"Status\\\", \\\"Ready to cal\\\"); //",
" telemetry.update();",
"",
" // Wait for the game to start (driver presses PLAY)",
" waitForStart();",
"",
" // Set the compass to calibration mode",
" compass.setMode(CompassSensor.CompassMode.CALIBRATION_MODE);",
" telemetry.addData(\\\"Compass\\\", \\\"Compass in calibration mode\\\");",
" telemetry.update();",
"",
" sleep(HOLD_TIME_MS); // Just do a sleep while we switch modes",
"",
" // Start the robot rotating clockwise",
" telemetry.addData(\\\"Compass\\\", \\\"Calibration mode. Turning the robot...\\\");",
" telemetry.update();",
" leftDrive.setPower(MOTOR_POWER);",
" rightDrive.setPower(-MOTOR_POWER);",
"",
" // run until time expires OR the driver presses STOP;",
" runtime.reset();",
" while (opModeIsActive() && (runtime.time() < CAL_TIME_SEC)) {",
" idle();",
" }",
"",
" // Stop all motors and turn off claibration",
" leftDrive.setPower(0);",
" rightDrive.setPower(0);",
" compass.setMode(CompassSensor.CompassMode.MEASUREMENT_MODE);",
" telemetry.addData(\\\"Compass\\\", \\\"Returning to measurement mode\\\");",
" telemetry.update();",
"",
" sleep(HOLD_TIME_MS); // Just do a sleep while we switch modes",
"",
" // Report whether the Calibration was successful or not.",
" if (compass.calibrationFailed())",
" telemetry.addData(\\\"Compass\\\", \\\"Calibrate Failed. Try Again!\\\");",
" else",
" telemetry.addData(\\\"Compass\\\", \\\"Calibrate Passed.\\\");",
" telemetry.update();",
" }",
"}",
""
]
},
"ConceptI2cAddressChange": {
"prefix": "conceptI2cAddressChange",
"description": "An example of a linear op mode that shows how to change the I2C address.\n ",
"body": [
"public class ConceptI2cAddressChange extends LinearOpMode {",
"",
" public static final int ADDRESS_SET_NEW_I2C_ADDRESS = 0x70;",
" // trigger bytes used to change I2C address on ModernRobotics sensors.",
" public static final byte TRIGGER_BYTE_1 = 0x55;",
" public static final byte TRIGGER_BYTE_2 = (byte) 0xaa;",
"",
" // Expected bytes from the Modern Robotics IR Seeker V3 memory map",
" public static final byte IR_SEEKER_V3_FIRMWARE_REV = 0x12;",
" public static final byte IR_SEEKER_V3_SENSOR_ID = 0x49;",
" public static final I2cAddr IR_SEEKER_V3_ORIGINAL_ADDRESS = I2cAddr.create8bit(0x38);",
"",
" // Expected bytes from the Modern Robotics Color Sensor memory map",
" public static final byte COLOR_SENSOR_FIRMWARE_REV = 0x10;",
" public static final byte COLOR_SENSOR_SENSOR_ID = 0x43;",
" public static final byte COLOR_SENSOR_ORIGINAL_ADDRESS = 0x3C;",
"",
" public static final byte MANUFACTURER_CODE = 0x4d;",
" // Currently, this is set to expect the bytes from the IR Seeker.",
" // If you change these values so you're setting \"FIRMWARE_REV\\\" to",
" // COLOR_SENSOR_FIRMWARE_REV, and \\\"SENSOR_ID\\\" to \\\"COLOR_SENSOR_SENSOR_ID\\\",",
" // you'll be able to change the I2C address of the ModernRoboticsColorSensor.",
" // If the bytes you're expecting are different than what this op mode finds,",
" // a comparison will be printed out into the logfile.",
" public static final byte FIRMWARE_REV = IR_SEEKER_V3_FIRMWARE_REV;",
" public static final byte SENSOR_ID = IR_SEEKER_V3_SENSOR_ID;",
"",
" // These byte values are common with most Modern Robotics sensors.",
" public static final int READ_MODE = 0x80;",
" public static final int ADDRESS_MEMORY_START = 0x0;",
" public static final int TOTAL_MEMORY_LENGTH = 0x0c;",
" public static final int BUFFER_CHANGE_ADDRESS_LENGTH = 0x03;",
"",
" // The port where your sensor is connected.",
" int port = 5;",
"",
" byte[] readCache;",
" Lock readLock;",
" byte[] writeCache;",
" Lock writeLock;",
"",
" I2cAddr currentAddress = IR_SEEKER_V3_ORIGINAL_ADDRESS;",
" // I2c addresses on Modern Robotics devices must be divisible by 2, and between 0x7e and 0x10",
" // Different hardware may have different rules.",
" // Be sure to read the requirements for the hardware you're using!",
" // If you use an invalid address, you may make your device completely unusable.",
" I2cAddr newAddress = I2cAddr.create8bit(0x42);",
"",
" DeviceInterfaceModule dim;",
"",
" @Override",
" public void runOpMode() {",
"",
" // set up the hardware devices we are going to use",
" dim = hardwareMap.get(DeviceInterfaceModule.class, \\\"dim\\\");",
"",
" readCache = dim.getI2cReadCache(port);",
" readLock = dim.getI2cReadCacheLock(port);",
" writeCache = dim.getI2cWriteCache(port);",
" writeLock = dim.getI2cWriteCacheLock(port);",
"",
" // I2c addresses on Modern Robotics devices must be divisible by 2, and between 0x7e and 0x10",
" // Different hardware may have different rules.",
" // Be sure to read the requirements for the hardware you're using!",
" ModernRoboticsUsbDeviceInterfaceModule.throwIfModernRoboticsI2cAddressIsInvalid(newAddress);",
"",
" // wait for the start button to be pressed",
" waitForStart();",
"",
" performAction(\\\"read\\\", port, currentAddress, ADDRESS_MEMORY_START, TOTAL_MEMORY_LENGTH);",
"",
" while(!dim.isI2cPortReady(port)) {",
" telemetry.addData(\\\"I2cAddressChange\\\", \\\"waiting for the port to be ready...\\\");",
" telemetry.update();",
" sleep(1000);",
" }",
"",
" // update the local cache",
" dim.readI2cCacheFromController(port);",
"",
" // make sure the first bytes are what we think they should be.",
" int count = 0;",
" int[] initialArray = {READ_MODE, currentAddress.get8Bit(), ADDRESS_MEMORY_START, TOTAL_MEMORY_LENGTH, FIRMWARE_REV, MANUFACTURER_CODE, SENSOR_ID};",
" while (!foundExpectedBytes(initialArray, readLock, readCache)) {",
" telemetry.addData(\\\"I2cAddressChange\\\", \\\"Confirming that we're reading the correct bytes...\\\");",
" telemetry.update();",
" dim.readI2cCacheFromController(port);",
" sleep(1000);",
" count++;",
" // if we go too long with failure, we probably are expecting the wrong bytes.",
" if (count >= 10) {",
" telemetry.addData(\\\"I2cAddressChange\\\", String.format(\\\"Looping too long with no change, probably have the wrong address. Current address: 8bit=0x%02x\\\", currentAddress.get8Bit()));",
" hardwareMap.irSeekerSensor.get(String.format(\\\"Looping too long with no change, probably have the wrong address. Current address: 8bit=0x%02x\\\", currentAddress.get8Bit()));",
" telemetry.update();",
" }",
" }",
"",
" // Enable writes to the correct segment of the memory map.",
" performAction(\\\"write\\\", port, currentAddress, ADDRESS_SET_NEW_I2C_ADDRESS, BUFFER_CHANGE_ADDRESS_LENGTH);",
"",
" // Write out the trigger bytes, and the new desired address.",
" writeNewAddress();",
" dim.setI2cPortActionFlag(port);",
" dim.writeI2cCacheToController(port);",
"",
" telemetry.addData(\\\"I2cAddressChange\\\", \\\"Giving the hardware 60 seconds to make the change...\\\");",
" telemetry.update();",
"",
" // Changing the I2C address takes some time.",
" sleep(60000);",
"",
" // Query the new address and see if we can get the bytes we expect.",
" dim.enableI2cReadMode(port, newAddress, ADDRESS_MEMORY_START, TOTAL_MEMORY_LENGTH);",
" dim.setI2cPortActionFlag(port);",
" dim.writeI2cCacheToController(port);",
"",
" int[] confirmArray = {READ_MODE, newAddress.get8Bit(), ADDRESS_MEMORY_START, TOTAL_MEMORY_LENGTH, FIRMWARE_REV, MANUFACTURER_CODE, SENSOR_ID};",
" while (!foundExpectedBytes(confirmArray, readLock, readCache)) {",
" telemetry.addData(\\\"I2cAddressChange\\\", \\\"Have not confirmed the changes yet...\\\");",
" telemetry.update();",
" dim.readI2cCacheFromController(port);",
" sleep(1000);",
" }",
"",
" telemetry.addData(\\\"I2cAddressChange\\\", \\\"Successfully changed the I2C address. New address: 8bit=0x%02x\\\", newAddress.get8Bit());",
" telemetry.update();",
" RobotLog.i(\\\"Successfully changed the I2C address.\\\" + String.format(\\\"New address: 8bit=0x%02x\\\", newAddress.get8Bit()));",
"",
" /**** IMPORTANT NOTE ******/",
" // You need to add a line like this at the top of your op mode",
" // to update the I2cAddress in the driver.",
" //irSeeker.setI2cAddress(newAddress);",
" /***************************/",
"",
" }",
"",
" private boolean foundExpectedBytes(int[] byteArray, Lock lock, byte[] cache) {",
" try {",
" lock.lock();",
" boolean allMatch = true;",
" StringBuilder s = new StringBuilder(300 * 4);",
" String mismatch = \\\"\\\";",
" for (int i = 0; i < byteArray.length; i++) {",
" s.append(String.format(\\\"expected: %02x, got: %02x \\n\\\", TypeConversion.unsignedByteToInt( (byte) byteArray[i]), cache[i]));",
" if (TypeConversion.unsignedByteToInt(cache[i]) != TypeConversion.unsignedByteToInt( (byte) byteArray[i])) {",
" mismatch = String.format(\\\"i: %d, byteArray[i]: %02x, cache[i]: %02x\\\", i, byteArray[i], cache[i]);",
" allMatch = false;",
" }",
" }",
" RobotLog.e(s.toString() + \\\"\\n allMatch: \\\" + allMatch + \\\", mismatch: \\\" + mismatch);",
" return allMatch;",
" } finally {",
" lock.unlock();",
" }",
" }",
"",
" private void performAction(String actionName, int port, I2cAddr i2cAddress, int memAddress, int memLength) {",
" if (actionName.equalsIgnoreCase(\\\"read\\\")) dim.enableI2cReadMode(port, i2cAddress, memAddress, memLength);",
" if (actionName.equalsIgnoreCase(\\\"write\\\")) dim.enableI2cWriteMode(port, i2cAddress, memAddress, memLength);",
"",
" dim.setI2cPortActionFlag(port);",
" dim.writeI2cCacheToController(port);",
" dim.readI2cCacheFromController(port);",
" }",
"",
" private void writeNewAddress() {",
" try {",
" writeLock.lock();",
" writeCache[4] = (byte) newAddress.get8Bit();",
" writeCache[5] = TRIGGER_BYTE_1;",
" writeCache[6] = TRIGGER_BYTE_2;",
" } finally {",
" writeLock.unlock();",
" }",
" }",
"}",
""
]
},
"ConceptMotorBulkRead": {
"prefix": "conceptMotorBulkRead",
"description": "No Description Given",
"body": [
"public class ConceptMotorBulkRead extends LinearOpMode {",
"",
" final int TEST_CYCLES = 500; // Number of control cycles to run to determine cycle times.",
"",
" private DcMotorEx m1, m2, m3, m4; // Motor Objects",
" private long e1, e2, e3, e4; // Encoder Values",
" private double v1, v2, v3, v4; // Velocities",
"",
" // Cycle Times",
" double t1 = 0;",
" double t2 = 0;",
" double t3 = 0;",
"",
" @Override",
" public void runOpMode() {",
"",
" int cycles;",
"",
" // Important Step 1: Make sure you use DcMotorEx when you instantiate your motors.",
" m1 = hardwareMap.get(DcMotorEx.class, \"m1\\\"); // Configure the robot to use these 4 motor names,",
" m2 = hardwareMap.get(DcMotorEx.class, \\\"m2\\\"); // or change these strings to match your existing Robot Configuration.",
" m3 = hardwareMap.get(DcMotorEx.class, \\\"m3\\\");",
" m4 = hardwareMap.get(DcMotorEx.class, \\\"m4\\\");",
"",
" // Important Step 2: Get access to a list of Expansion Hub Modules to enable changing caching methods.",
" List<LynxModule> allHubs = hardwareMap.getAll(LynxModule.class);",
"",
" ElapsedTime timer = new ElapsedTime();",
"",
" telemetry.addData(\\\">\\\", \\\"Press play to start tests\\\");",
" telemetry.addData(\\\">\\\", \\\"Test results will update for each access method.\\\");",
" telemetry.update();",
" waitForStart();",
"",
" // --------------------------------------------------------------------------------------",
" // Run control loop using legacy encoder reads",
" // In this mode, a single read is done for each encoder position, and a bulk read is done for each velocity read.",
" // This is the worst case scenario.",
" // This is the same as using LynxModule.BulkCachingMode.OFF",
" // --------------------------------------------------------------------------------------",
"",
" displayCycleTimes(\\\"Test 1 of 3 (Wait for completion)\\\");",
"",
" timer.reset();",
" cycles = 0;",
" while (opModeIsActive() && (cycles++ < TEST_CYCLES)) {",
" e1 = m1.getCurrentPosition();",
" e2 = m2.getCurrentPosition();",
" e3 = m3.getCurrentPosition();",
" e4 = m4.getCurrentPosition();",
"",
" v1 = m1.getVelocity();",
" v2 = m2.getVelocity();",
" v3 = m3.getVelocity();",
" v4 = m4.getVelocity();",
"",
" // Put Control loop action code here.",
"",
" }",
" // calculate the average cycle time.",
" t1 = timer.milliseconds() / cycles;",
" displayCycleTimes(\\\"Test 2 of 3 (Wait for completion)\\\");",
"",
" // --------------------------------------------------------------------------------------",
" // Run test cycles using AUTO cache mode",
" // In this mode, only one bulk read is done per cycle, UNLESS you read a specific encoder/velocity item AGAIN in that cycle.",
" // --------------------------------------------------------------------------------------",
"",
" // Important Step 3: Option A. Set all Expansion hubs to use the AUTO Bulk Caching mode",
" for (LynxModule module : allHubs) {",
" module.setBulkCachingMode(LynxModule.BulkCachingMode.AUTO);",
" }",
"",
" timer.reset();",
" cycles = 0;",
" while (opModeIsActive() && (cycles++ < TEST_CYCLES)) {",
" e1 = m1.getCurrentPosition(); // Uses 1 bulk-read for all 4 encoder/velocity reads,",
" e2 = m2.getCurrentPosition(); // but don't do any `get` operations more than once per cycle.",
" e3 = m3.getCurrentPosition();",
" e4 = m4.getCurrentPosition();",
"",
" v1 = m1.getVelocity();",
" v2 = m2.getVelocity();",
" v3 = m3.getVelocity();",
" v4 = m4.getVelocity();",
"",
" // Put Control loop action code here.",
"",
" }",
" // calculate the average cycle time.",
" t2 = timer.milliseconds() / cycles;",