-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRobot.java
More file actions
321 lines (270 loc) · 12.3 KB
/
Robot.java
File metadata and controls
321 lines (270 loc) · 12.3 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
// Copyright 2021-2025 FRC 6328
// http://github.com/Mechanical-Advantage
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// version 3 as published by the Free Software Foundation or
// available in the root directory of this project.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
package frc.robot;
import java.util.HashMap;
import org.littletonrobotics.junction.LogFileUtil;
import org.littletonrobotics.junction.LoggedRobot;
import org.littletonrobotics.junction.Logger;
import org.littletonrobotics.junction.networktables.NT4Publisher;
import org.littletonrobotics.junction.wpilog.WPILOGReader;
import org.littletonrobotics.junction.wpilog.WPILOGWriter;
import org.xerosw.util.MessageDestination;
import org.xerosw.util.MessageDestinationThumbFile;
import org.xerosw.util.MessageLogger;
import org.xerosw.util.MessageType;
import org.xerosw.util.RobotTimeSource;
import com.ctre.phoenix6.swerve.SwerveModuleConstants;
import com.ctre.phoenix6.swerve.SwerveModuleConstants.DriveMotorArrangement;
import com.ctre.phoenix6.swerve.SwerveModuleConstants.SteerMotorArrangement;
import edu.wpi.first.math.geometry.Pose2d;
import edu.wpi.first.wpilibj.DriverStation;
import edu.wpi.first.wpilibj.RobotBase;
import edu.wpi.first.wpilibj.Threads;
import edu.wpi.first.wpilibj2.command.Command;
import edu.wpi.first.wpilibj2.command.CommandScheduler;
import frc.robot.commands.auto.AutoModeBaseCmd;
import frc.robot.commands.misc.StateCmd;
import frc.robot.generated.CompTunerConstants;
import frc.robot.subsystems.drive.Drive;
import frc.robot.subsystems.vision.MotionTrackerVision;
import frc.simulator.engine.SimulationEngine;
/**
* The VM is configured to automatically run this class, and to call the functions corresponding to
* each mode, as described in the TimedRobot documentation. If you change the name of this class or
* the package after creating this project, you must also update the build.gradle file in the
* project.
*/
public class Robot extends LoggedRobot {
private HashMap<String, String> output_state_ ;
private Command autonomousCommand;
private RobotContainer robotContainer;
private boolean hasSetupAutos = false;
private AutoModeBaseCmd appliedAuto = null ;
public Robot() throws RuntimeException {
//
// This is a hack, but it is the least intrusive approach based on where we are in the season
//
output_state_ = new HashMap<String, String>() ;
StateCmd.setRobot(this);
enableMessageLogger();
MessageLogger.getTheMessageLogger().startMessage(MessageType.Info).add("Robot code starting").endMessage() ;
// Record metadata
Logger.recordMetadata("ProjectName", BuildConstants.MAVEN_NAME);
Logger.recordMetadata("BuildDate", BuildConstants.BUILD_DATE);
Logger.recordMetadata("GitSHA", BuildConstants.GIT_SHA);
Logger.recordMetadata("GitDate", BuildConstants.GIT_DATE);
Logger.recordMetadata("GitBranch", BuildConstants.GIT_BRANCH);
Logger.recordMetadata("Robot", Constants.getRobot().toString());
Logger.recordMetadata("Mode", Constants.getMode().toString());
Logger.recordMetadata("SimulationType", Robot.useXeroSimulator() ? "Xero Sim" : "Regular Sim");
switch (BuildConstants.DIRTY) {
case 0:
Logger.recordMetadata("GitDirty", "All changes committed");
break;
case 1:
Logger.recordMetadata("GitDirty", "Uncomitted changes");
break;
default:
Logger.recordMetadata("GitDirty", "Unknown");
break;
}
// Set up data receivers & replay source
switch (Constants.getMode()) {
case REAL:
// Running on a real robot, log to a USB stick ("/U/logs")
Logger.addDataReceiver(new WPILOGWriter());
Logger.addDataReceiver(new NT4Publisher());
break;
case SIM:
// Running a physics simulator, log to NT
Logger.addDataReceiver(new NT4Publisher());
// Silence Joystick Warnings
DriverStation.silenceJoystickConnectionWarning(RobotBase.isSimulation());
break;
case REPLAY:
// Replaying a log, set up replay source
setUseTiming(false); // Run as fast as possible
String logPath = LogFileUtil.findReplayLog();
Logger.setReplaySource(new WPILOGReader(logPath));
Logger.addDataReceiver(new WPILOGWriter(LogFileUtil.addPathSuffix(logPath, "_replay")));
break;
}
// Start AdvantageKit logger
Logger.start();
// Check for valid swerve config
var modules =
new SwerveModuleConstants[] {
CompTunerConstants.FrontLeft,
CompTunerConstants.FrontRight,
CompTunerConstants.BackLeft,
CompTunerConstants.BackRight
};
for (var constants : modules) {
if (
constants.DriveMotorType != DriveMotorArrangement.TalonFX_Integrated ||
constants.SteerMotorType != SteerMotorArrangement.TalonFX_Integrated
) {
throw new RuntimeException("You are using an unsupported swerve configuration, which this template does not support without manual customization. The 2025 release of Phoenix supports some swerve configurations which were not available during 2025 beta testing, preventing any development and support from the AdvantageKit developers.");
}
}
if (Robot.useXeroSimulator()) {
String str = "threeCoralSideAuto" ;
SimulationEngine.initializeSimulator(this);
SimulationEngine.getInstance().initAll(str);
}
//
// For a one second delay. We try 10 times to get a one second delay and if
// our delay is interrupted, we start over. This delay is here because we see a race conditon
// at times that causes the Pidgeon 2 to not get initialized.
//
// boolean done = false ;
// for(int i = 0 ; i < 10 && !done ; i++) {
// done = true ;
// try {
// Thread.sleep(1000) ;
// }
// catch(Exception ex) {
// done = false ;
// }
// }
// Instantiate our RobotContainer. This will perform all our button bindings,
// and put our autonomous chooser on the dashboard.
robotContainer = RobotContainer.getInstance() ;
}
public static boolean useXeroSimulator() {
return Constants.getRobot() == Constants.RobotType.XEROSIM;
}
public void setNamedState(String key, String value) {
output_state_.put(key, value) ;
}
public void robotInit() {
super.robotInit() ;
if (Robot.useXeroSimulator() && SimulationEngine.getInstance() != null) {
//
// If we are simulating, create the simulation modules required
//
SimulationEngine.getInstance().createModels();
}
}
/** This function is called periodically during all modes. */
@Override
public void robotPeriodic() {
// Switch thread to high priority to improve loop timing
Threads.setCurrentThreadPriority(true, 99);
// Runs the Scheduler. This is responsible for polling buttons, adding
// newly-scheduled commands, running already-scheduled commands, removing
// finished or interrupted commands, and running subsystem periodic() methods.
// This must be called from the robot's periodic block in order for anything in
// the Command-based framework to work.
CommandScheduler.getInstance().run();
// Return to normal thread priority
Threads.setCurrentThreadPriority(false, 10);
for(String key : output_state_.keySet()) {
Logger.recordOutput("RobotState/" + key, output_state_.get(key)) ;
}
}
/** This function is called once when the robot is disabled. */
@Override
public void disabledInit() {}
/** This function is called periodically when disabled. */
@Override
public void disabledPeriodic() {
if(!hasSetupAutos && DriverStation.getAlliance().isPresent()) {
robotContainer.setupAutos();
hasSetupAutos = true;
}
if (hasSetupAutos) {
Command cmd = robotContainer.getAutonomousCommand();
if (cmd != null) {
AutoModeBaseCmd currentAuto = (AutoModeBaseCmd) cmd;
if (currentAuto != null) {
Drive drivebase = RobotContainer.getInstance().drivebase() ;
MotionTrackerVision quest = RobotContainer.getInstance().quest();
Pose2d autopose = currentAuto.getStartingPose() ;
if (appliedAuto == null || appliedAuto != currentAuto) { // Changing the Auto Mode
Logger.recordOutput("automode/name", currentAuto.getName()) ;
Logger.recordOutput("automode/pose", autopose) ;
Logger.recordOutput("poseinit/setting", "Robot Pose");
drivebase.setPose(autopose);
appliedAuto = currentAuto;
} else { // Initializing the Quest Repeatedly
quest.setPose(drivebase.getPose());
Logger.recordOutput("poseinit/setting", "Quest Pose");
}
}
}
}
}
/** This autonomous runs the autonomous command selected by your {@link RobotContainer} class. */
@Override
public void autonomousInit() {
autonomousCommand = robotContainer.getAutonomousCommand();
// schedule the autonomous command (example)
if (autonomousCommand != null) {
autonomousCommand.schedule();
}
}
/** This function is called periodically during autonomous. */
@Override
public void autonomousPeriodic() {}
/** This function is called once when teleop is enabled. */
@Override
public void teleopInit() {
// This makes sure that the autonomous stops running when
// teleop starts running. If you want the autonomous to
// continue until interrupted by another command, remove
// this line or comment it out.
if (autonomousCommand != null) {
autonomousCommand.cancel();
}
RobotContainer.getInstance().gamepad().setLocked(false);
}
/** This function is called periodically during operator control. */
@Override
public void teleopPeriodic() {}
/** This function is called once when test mode is enabled. */
@Override
public void testInit() {
// Cancels all running commands at the start of test mode.
CommandScheduler.getInstance().cancelAll();
}
/** This function is called periodically during test mode. */
@Override
public void testPeriodic() {}
/** This function is called once when the robot is first started up. */
@Override
public void simulationInit() {}
/** This function is called periodically whilst in simulation. */
@Override
public void simulationPeriodic() {
if (Robot.useXeroSimulator()) {
SimulationEngine engine = SimulationEngine.getInstance();
if (engine != null) {
engine.run(getPeriod());
}
}
}
private void enableMessageLogger() {
MessageDestination dest ;
MessageLogger logger = MessageLogger.getTheMessageLogger() ;
logger.setTimeSource(new RobotTimeSource());
String logpath = null ;
if (Robot.isSimulation()) {
logpath = "logs" ;
} else {
logpath = "/u" ;
}
dest = new MessageDestinationThumbFile(logpath, 250, RobotBase.isSimulation());
logger.addDestination(dest);
}
}