blob: cc61851c939c2252d8e2ff4b5fcb1a6ced8ec6aa [file] [log] [blame]
milind-u086d7262022-01-19 20:44:18 -08001#include "y2022/control_loops/superstructure/superstructure.h"
2
3#include "aos/events/event_loop.h"
Milind Upadhyay225156b2022-02-25 22:42:12 -08004#include "y2022/control_loops/superstructure/collision_avoidance.h"
milind-u086d7262022-01-19 20:44:18 -08005
6namespace y2022 {
7namespace control_loops {
8namespace superstructure {
9
10using frc971::control_loops::AbsoluteEncoderProfiledJointStatus;
11using frc971::control_loops::PotAndAbsoluteEncoderProfiledJointStatus;
Henry Speiser55aa3ba2022-02-21 23:21:12 -080012using frc971::control_loops::RelativeEncoderProfiledJointStatus;
milind-u086d7262022-01-19 20:44:18 -080013
14Superstructure::Superstructure(::aos::EventLoop *event_loop,
Henry Speiser55aa3ba2022-02-21 23:21:12 -080015 std::shared_ptr<const constants::Values> values,
milind-u086d7262022-01-19 20:44:18 -080016 const ::std::string &name)
17 : frc971::controls::ControlLoop<Goal, Position, Status, Output>(event_loop,
Siddhant Kanwar0e37f592022-02-21 19:26:50 -080018 name),
Austin Schuh39f26f62022-02-24 21:34:46 -080019 values_(values),
20 climber_(values_->climber.subsystem_params),
21 intake_front_(values_->intake_front.subsystem_params),
22 intake_back_(values_->intake_back.subsystem_params),
23 turret_(values_->turret.subsystem_params),
Ravago Jones5da06352022-03-04 20:26:24 -080024 catapult_(*values_),
Henry Speiser55aa3ba2022-02-21 23:21:12 -080025 drivetrain_status_fetcher_(
26 event_loop->MakeFetcher<frc971::control_loops::drivetrain::Status>(
Austin Schuh39f26f62022-02-24 21:34:46 -080027 "/drivetrain")),
Ravago Jones5da06352022-03-04 20:26:24 -080028 can_position_fetcher_(
29 event_loop->MakeFetcher<CANPosition>("/superstructure")) {
milind-u086d7262022-01-19 20:44:18 -080030 event_loop->SetRuntimeRealtimePriority(30);
31}
32
33void Superstructure::RunIteration(const Goal *unsafe_goal,
Siddhant Kanwar0e37f592022-02-21 19:26:50 -080034 const Position *position,
milind-u086d7262022-01-19 20:44:18 -080035 aos::Sender<Output>::Builder *output,
36 aos::Sender<Status>::Builder *status) {
37 if (WasReset()) {
38 AOS_LOG(ERROR, "WPILib reset, restarting\n");
Henry Speiser55aa3ba2022-02-21 23:21:12 -080039 intake_front_.Reset();
40 intake_back_.Reset();
41 turret_.Reset();
42 climber_.Reset();
Austin Schuh39f26f62022-02-24 21:34:46 -080043 catapult_.Reset();
Henry Speiser55aa3ba2022-02-21 23:21:12 -080044 }
45
Ravago Jones5da06352022-03-04 20:26:24 -080046 OutputT output_struct;
Milind Upadhyay225156b2022-02-25 22:42:12 -080047
Ravago Jones5da06352022-03-04 20:26:24 -080048 aos::FlatbufferFixedAllocatorArray<
49 frc971::control_loops::StaticZeroingSingleDOFProfiledSubsystemGoal, 64>
50 turret_goal_buffer;
51
52 const aos::monotonic_clock::time_point timestamp =
53 event_loop()->context().monotonic_event_time;
Milind Upadhyay225156b2022-02-25 22:42:12 -080054
Henry Speiser55aa3ba2022-02-21 23:21:12 -080055 drivetrain_status_fetcher_.Fetch();
56 const float velocity = robot_velocity();
57
James Kuszmaul84083f42022-02-27 17:24:38 -080058 const turret::Aimer::Goal *auto_aim_goal = nullptr;
59 if (drivetrain_status_fetcher_.get() != nullptr) {
60 aimer_.Update(drivetrain_status_fetcher_.get(),
61 turret::Aimer::ShotMode::kShootOnTheFly);
62 auto_aim_goal = aimer_.TurretGoal();
63 }
64
Ravago Jones5da06352022-03-04 20:26:24 -080065 const frc971::control_loops::StaticZeroingSingleDOFProfiledSubsystemGoal
66 *turret_goal = nullptr;
67 double roller_speed_compensated_front = 0.0;
68 double roller_speed_compensated_back = 0.0;
69 double transfer_roller_speed = 0.0;
70 double flipper_arms_voltage = 0.0;
Henry Speiser55aa3ba2022-02-21 23:21:12 -080071
72 if (unsafe_goal != nullptr) {
73 roller_speed_compensated_front =
74 unsafe_goal->roller_speed_front() +
75 std::max(velocity * unsafe_goal->roller_speed_compensation(), 0.0);
76
77 roller_speed_compensated_back =
78 unsafe_goal->roller_speed_back() -
79 std::min(velocity * unsafe_goal->roller_speed_compensation(), 0.0);
80
81 transfer_roller_speed = unsafe_goal->transfer_roller_speed();
milind-u086d7262022-01-19 20:44:18 -080082
James Kuszmaul84083f42022-02-27 17:24:38 -080083 turret_goal =
84 unsafe_goal->auto_aim() ? auto_aim_goal : unsafe_goal->turret();
85 }
Austin Schuh39f26f62022-02-24 21:34:46 -080086
Ravago Jones5da06352022-03-04 20:26:24 -080087 // Supersturcture state machine:
88 // 1. IDLE: Wait until an intake beambreak is triggerred, meaning that a ball
89 // is being intaked. This means that the transfer rollers have a ball. If
90 // we've been waiting here for too long without any beambreak triggered, the
91 // ball got lost, so reset.
92 // 2. TRANSFERRING: Until the turret reaches the loading position where the
93 // ball can be transferred into the catapult, wiggle the ball in place.
94 // Once the turret reaches the loading position, send the ball forward with
95 // the transfer rollers until the turret beambreak is triggered.
96 // If we have been in this state for too long, the ball probably got lost so
97 // reset back to IDLE.
98 // 3. LOADING: To load the ball into the catapult, put the flippers at the
99 // feeding speed. Wait for a timeout, and then wait until the ball has gone
100 // past the turret beambreak and the flippers have stopped moving, meaning
101 // that the ball is fully loaded in the catapult.
102 // 4. LOADED: Wait until the user asks us to fire to transition to the
103 // shooting stage. If asked to cancel the shot, reset back to the IDLE state.
104 // 5. SHOOTING: Open the flippers to get ready for the shot. If they don't
105 // open quickly enough, try reseating the ball and going back to the LOADING
106 // stage, which moves the flippers in the opposite direction first.
107 // Now, hold the flippers open and wait until the turret has reached its
108 // aiming goal. Once the turret is ready, tell the catapult to fire.
109 // If the flippers move back for some reason now, it could damage the
110 // catapult, so estop it. Otherwise, wait until the catapult shoots a ball and
111 // goes back to its return position. We have now finished the shot, so return
112 // to IDLE.
113
114 const bool is_spitting = ((intake_state_ == IntakeState::INTAKE_FRONT_BALL &&
115 transfer_roller_speed < 0) ||
116 (intake_state_ == IntakeState::INTAKE_BACK_BALL &&
117 transfer_roller_speed > 0));
118
119 // Intake handling should happen regardless of the turret state
120 if (position->intake_beambreak_front() || position->intake_beambreak_back()) {
121 if (intake_state_ == IntakeState::NO_BALL) {
122 if (position->intake_beambreak_front()) {
123 intake_state_ = IntakeState::INTAKE_FRONT_BALL;
124 } else if (position->intake_beambreak_back()) {
125 intake_state_ = IntakeState::INTAKE_BACK_BALL;
126 }
127 }
128
129 intake_beambreak_timer_ = timestamp;
130 }
131
132 if (intake_state_ != IntakeState::NO_BALL) {
133 // Block intaking in
134 roller_speed_compensated_front = 0.0;
135 roller_speed_compensated_back = 0.0;
136
137 const double wiggle_voltage =
138 (intake_state_ == IntakeState::INTAKE_FRONT_BALL
139 ? constants::Values::kTransferRollerFrontWiggleVoltage()
140 : constants::Values::kTransferRollerBackWiggleVoltage());
141 // Wiggle transfer rollers: send the ball back and forth while waiting
142 // for the turret or waiting for another shot to be completed
143 if ((intake_state_ == IntakeState::INTAKE_FRONT_BALL &&
144 position->intake_beambreak_front()) ||
145 (intake_state_ == IntakeState::INTAKE_BACK_BALL &&
146 position->intake_beambreak_back())) {
147 transfer_roller_speed = -wiggle_voltage;
148 } else {
149 transfer_roller_speed = wiggle_voltage;
150 }
151 }
152
153 switch (state_) {
154 case SuperstructureState::IDLE: {
155 if (timestamp >
156 intake_beambreak_timer_ + constants::Values::kBallLostTime()) {
157 intake_state_ = IntakeState::NO_BALL;
158 }
159
160 if (is_spitting) {
161 intake_state_ = IntakeState::NO_BALL;
162 }
163
164 if (intake_state_ == IntakeState::NO_BALL ||
165 !(position->intake_beambreak_front() ||
166 position->intake_beambreak_back())) {
167 break;
168 }
169
170 state_ = SuperstructureState::TRANSFERRING;
171 transferring_timer_ = timestamp;
172
173 // Save the side the ball is on for later
174
175 break;
176 }
177 case SuperstructureState::TRANSFERRING: {
178 // If we've been transferring for too long, the ball probably got lost
179 if (timestamp >
180 transferring_timer_ + constants::Values::kBallLostTime()) {
181 intake_state_ = IntakeState::NO_BALL;
182 break;
183 }
184
185 if (intake_state_ == IntakeState::NO_BALL) {
186 state_ = SuperstructureState::IDLE;
187 break;
188 }
189
190 double turret_loading_position =
191 (intake_state_ == IntakeState::INTAKE_FRONT_BALL
192 ? constants::Values::kTurretFrontIntakePos()
193 : constants::Values::kTurretBackIntakePos());
194
195 turret_goal_buffer.Finish(
196 frc971::control_loops::
197 CreateStaticZeroingSingleDOFProfiledSubsystemGoal(
198 *turret_goal_buffer.fbb(), turret_loading_position));
199 turret_goal = &turret_goal_buffer.message();
200
201 const bool turret_near_goal =
202 std::abs(turret_.estimated_position() - turret_loading_position) <
203 kTurretGoalThreshold;
204 if (!turret_near_goal) {
205 break; // Wait for turret to reach the chosen intake
206 }
207
208 // Transfer rollers and flipper arm belt on
209 transfer_roller_speed =
210 (intake_state_ == IntakeState::INTAKE_FRONT_BALL
211 ? constants::Values::kTransferRollerFrontVoltage()
212 : constants::Values::kTransferRollerBackVoltage());
213 flipper_arms_voltage = constants::Values::kFlipperFeedVoltage();
214
215 // Ball is in catapult
216 if (position->turret_beambreak()) {
217 intake_state_ = IntakeState::NO_BALL;
218 state_ = SuperstructureState::LOADING;
219 loading_timer_ = timestamp;
220 }
221 break;
222 }
223 case SuperstructureState::LOADING: {
224 flipper_arms_voltage = constants::Values::kFlipperFeedVoltage();
225
226 // Keep feeding for kExtraLoadingTime
227
228 can_position_fetcher_.Fetch();
229 const bool flipper_arm_roller_is_stopped =
230 can_position_fetcher_.get() != nullptr &&
231 std::abs(
232 can_position_fetcher_->flipper_arm_integrated_sensor_velocity()) <
233 0.01;
234
235 const bool reading_is_recent =
236 can_position_fetcher_.get() != nullptr &&
237 (timestamp < can_position_fetcher_.context().monotonic_event_time +
238 constants::Values::kFlipperVelocityValidTime());
239
240 // The ball should go past the turret beambreak to be loaded.
241 // If we got a CAN reading not too long ago, the flippers should have also
242 // stopped.
243 // TODO(milind): maybe it's better to update loading_timer_ as long as the
244 // turret beambreak is triggered.
245 if (timestamp > loading_timer_ + constants::Values::kExtraLoadingTime() &&
246 !position->turret_beambreak() &&
247 (flipper_arm_roller_is_stopped || !reading_is_recent)) {
248 state_ = SuperstructureState::LOADED;
249 reseating_in_catapult_ = false;
250 }
251 break;
252 }
253 case SuperstructureState::LOADED: {
254 if (unsafe_goal != nullptr) {
255 if (unsafe_goal->cancel_shot()) {
256 // Cancel the shot process
257 state_ = SuperstructureState::IDLE;
258 } else if (unsafe_goal->fire()) {
259 // Start if we were asked to and the turret is at goal
260 state_ = SuperstructureState::SHOOTING;
261 prev_shot_count_ = catapult_.shot_count();
262
263 // Reset opening timeout
264 flipper_opening_start_time_ = timestamp;
265 }
266 }
267 break;
268 }
269 case SuperstructureState::SHOOTING: {
270 // Opening flipper arms could fail, wait until they are open using their
271 // potentiometers (the member below is just named encoder).
272 // Be a little more lenient if the flippers were already open in case of
273 // noise or collisions.
274 const double flipper_open_position =
275 (flippers_open_ ? constants::Values::kReseatFlipperPosition()
276 : constants::Values::kFlipperOpenPosition());
277 flippers_open_ =
278 position->flipper_arm_left()->encoder() >= flipper_open_position &&
279 position->flipper_arm_right()->encoder() >= flipper_open_position;
280
281 if (flippers_open_) {
282 // Hold at kFlipperHoldVoltage
283 flipper_arms_voltage = constants::Values::kFlipperHoldVoltage();
284 } else {
285 // Open at kFlipperOpenVoltage
286 flipper_arms_voltage = constants::Values::kFlipperOpenVoltage();
287 }
288
289 if (!flippers_open_ &&
290 timestamp >
291 loading_timer_ + constants::Values::kFlipperOpeningTimeout()) {
292 // Reseat the ball and try again
293 state_ = SuperstructureState::LOADING;
294 loading_timer_ = timestamp;
295 reseating_in_catapult_ = true;
296 break;
297 }
298
299 const bool turret_near_goal =
300 turret_goal != nullptr &&
301 std::abs(turret_goal->unsafe_goal() - turret_.position()) <
302 kTurretGoalThreshold;
303
304 // If the turret reached the aiming goal, fire!
305 if (flippers_open_ && turret_near_goal) {
306 fire_ = true;
307 }
308
309 // If we started firing and the flippers closed a bit, estop to prevent
310 // damage
311 if (fire_ && !flippers_open_) {
312 catapult_.Estop();
313 }
314
315 const bool near_return_position =
316 (unsafe_goal != nullptr && unsafe_goal->has_catapult() &&
317 unsafe_goal->catapult()->has_return_position() &&
318 std::abs(unsafe_goal->catapult()->return_position()->unsafe_goal() -
319 catapult_.estimated_position()) < kCatapultGoalThreshold);
320
321 // Once the shot is complete and the catapult is back to its return
322 // position, go back to IDLE
323 if (catapult_.shot_count() > prev_shot_count_ && near_return_position) {
324 prev_shot_count_ = catapult_.shot_count();
325 fire_ = false;
326 state_ = SuperstructureState::IDLE;
327 }
328
329 break;
330 }
331 }
332
333 collision_avoidance_.UpdateGoal(
334 {.intake_front_position = intake_front_.estimated_position(),
335 .intake_back_position = intake_back_.estimated_position(),
336 .turret_position = turret_.estimated_position()},
337 turret_goal);
338
339 turret_.set_min_position(collision_avoidance_.min_turret_goal());
340 turret_.set_max_position(collision_avoidance_.max_turret_goal());
341 intake_front_.set_min_position(collision_avoidance_.min_intake_front_goal());
342 intake_front_.set_max_position(collision_avoidance_.max_intake_front_goal());
343 intake_back_.set_min_position(collision_avoidance_.min_intake_back_goal());
344 intake_back_.set_max_position(collision_avoidance_.max_intake_back_goal());
345
James Kuszmaul84083f42022-02-27 17:24:38 -0800346 const flatbuffers::Offset<AimerStatus> aimer_offset =
347 aimer_.PopulateStatus(status->fbb());
348
Ravago Jones5da06352022-03-04 20:26:24 -0800349 // Disable the catapult if we want to restart to prevent damage with flippers
Austin Schuh39f26f62022-02-24 21:34:46 -0800350 const flatbuffers::Offset<PotAndAbsoluteEncoderProfiledJointStatus>
Ravago Jones5da06352022-03-04 20:26:24 -0800351 catapult_status_offset =
352 catapult_.Iterate(unsafe_goal, position,
353 output != nullptr && !catapult_.estopped()
354 ? &(output_struct.catapult_voltage)
355 : nullptr,
356 fire_, status->fbb());
Siddhant Kanwar0e37f592022-02-21 19:26:50 -0800357
Ravago Jones5da06352022-03-04 20:26:24 -0800358 const flatbuffers::Offset<RelativeEncoderProfiledJointStatus>
Siddhant Kanwar0e37f592022-02-21 19:26:50 -0800359 climber_status_offset = climber_.Iterate(
360 unsafe_goal != nullptr ? unsafe_goal->climber() : nullptr,
Austin Schuh7f120362022-03-05 17:10:11 -0800361 position->climber(),
362 output != nullptr ? &output_struct.climber_voltage : nullptr,
363 status->fbb());
Siddhant Kanwar0e37f592022-02-21 19:26:50 -0800364
Ravago Jones5da06352022-03-04 20:26:24 -0800365 const flatbuffers::Offset<PotAndAbsoluteEncoderProfiledJointStatus>
Henry Speiser55aa3ba2022-02-21 23:21:12 -0800366 intake_status_offset_front = intake_front_.Iterate(
367 unsafe_goal != nullptr ? unsafe_goal->intake_front() : nullptr,
Austin Schuh7f120362022-03-05 17:10:11 -0800368 position->intake_front(),
369 output != nullptr ? &output_struct.intake_voltage_front : nullptr,
Henry Speiser55aa3ba2022-02-21 23:21:12 -0800370 status->fbb());
371
Ravago Jones5da06352022-03-04 20:26:24 -0800372 const flatbuffers::Offset<PotAndAbsoluteEncoderProfiledJointStatus>
Henry Speiser55aa3ba2022-02-21 23:21:12 -0800373 intake_status_offset_back = intake_back_.Iterate(
374 unsafe_goal != nullptr ? unsafe_goal->intake_back() : nullptr,
Austin Schuh7f120362022-03-05 17:10:11 -0800375 position->intake_back(),
376 output != nullptr ? &output_struct.intake_voltage_back : nullptr,
Henry Speiser55aa3ba2022-02-21 23:21:12 -0800377 status->fbb());
378
Ravago Jones5da06352022-03-04 20:26:24 -0800379 const flatbuffers::Offset<PotAndAbsoluteEncoderProfiledJointStatus>
Austin Schuh7f120362022-03-05 17:10:11 -0800380 turret_status_offset = turret_.Iterate(
381 turret_goal, position->turret(),
382 output != nullptr ? &output_struct.turret_voltage : nullptr,
383 status->fbb());
Henry Speiser55aa3ba2022-02-21 23:21:12 -0800384
Siddhant Kanwar0e37f592022-02-21 19:26:50 -0800385 if (output != nullptr) {
Henry Speiser55aa3ba2022-02-21 23:21:12 -0800386 output_struct.roller_voltage_front = roller_speed_compensated_front;
387 output_struct.roller_voltage_back = roller_speed_compensated_back;
388 output_struct.transfer_roller_voltage = transfer_roller_speed;
Ravago Jones5da06352022-03-04 20:26:24 -0800389 output_struct.flipper_arms_voltage = flipper_arms_voltage;
Henry Speiser55aa3ba2022-02-21 23:21:12 -0800390
milind-u086d7262022-01-19 20:44:18 -0800391 output->CheckOk(output->Send(Output::Pack(*output->fbb(), &output_struct)));
392 }
393
394 Status::Builder status_builder = status->MakeBuilder<Status>();
395
Henry Speiser55aa3ba2022-02-21 23:21:12 -0800396 const bool zeroed = intake_front_.zeroed() && intake_back_.zeroed() &&
Ravago Jones5da06352022-03-04 20:26:24 -0800397 turret_.zeroed() && climber_.zeroed() &&
398 catapult_.zeroed();
Henry Speiser55aa3ba2022-02-21 23:21:12 -0800399 const bool estopped = intake_front_.estopped() || intake_back_.estopped() ||
Ravago Jones5da06352022-03-04 20:26:24 -0800400 turret_.estopped() || climber_.estopped() ||
401 catapult_.estopped();
Henry Speiser55aa3ba2022-02-21 23:21:12 -0800402
403 status_builder.add_zeroed(zeroed);
404 status_builder.add_estopped(estopped);
405
406 status_builder.add_intake_front(intake_status_offset_front);
407 status_builder.add_intake_back(intake_status_offset_back);
408 status_builder.add_turret(turret_status_offset);
Siddhant Kanwar0e37f592022-02-21 19:26:50 -0800409 status_builder.add_climber(climber_status_offset);
Ravago Jones5da06352022-03-04 20:26:24 -0800410
Austin Schuh39f26f62022-02-24 21:34:46 -0800411 status_builder.add_catapult(catapult_status_offset);
412 status_builder.add_solve_time(catapult_.solve_time());
Austin Schuh80fc2752022-02-25 13:33:56 -0800413 status_builder.add_shot_count(catapult_.shot_count());
Ravago Jones5da06352022-03-04 20:26:24 -0800414 status_builder.add_mpc_active(catapult_.mpc_active());
415
416 status_builder.add_flippers_open(flippers_open_);
417 status_builder.add_reseating_in_catapult(reseating_in_catapult_);
418 status_builder.add_fire(fire_);
419 status_builder.add_state(state_);
420 status_builder.add_intake_state(intake_state_);
milind-u086d7262022-01-19 20:44:18 -0800421
James Kuszmaul84083f42022-02-27 17:24:38 -0800422 status_builder.add_aimer(aimer_offset);
423
milind-u086d7262022-01-19 20:44:18 -0800424 (void)status->Send(status_builder.Finish());
425}
426
Henry Speiser55aa3ba2022-02-21 23:21:12 -0800427double Superstructure::robot_velocity() const {
428 return (drivetrain_status_fetcher_.get() != nullptr
429 ? drivetrain_status_fetcher_->robot_speed()
430 : 0.0);
431}
432
milind-u086d7262022-01-19 20:44:18 -0800433} // namespace superstructure
434} // namespace control_loops
435} // namespace y2022