blob: d5e2611e518b7804f37bfff3f6a591eebcb284ce [file] [log] [blame]
Austin Schuhd5ccb862017-03-11 22:06:36 -08001#include "y2017/control_loops/superstructure/column/column.h"
2
3#include <array>
4#include <chrono>
5#include <memory>
6#include <utility>
7
8#include "Eigen/Dense"
John Park33858a32018-09-28 23:05:48 -07009#include "aos/commonmath.h"
Austin Schuhd5ccb862017-03-11 22:06:36 -080010#include "frc971/constants.h"
11#include "frc971/control_loops/profiled_subsystem.h"
12#include "frc971/control_loops/state_feedback_loop.h"
13#include "y2017/control_loops/superstructure/column/column_integral_plant.h"
14#include "y2017/control_loops/superstructure/column/stuck_column_integral_plant.h"
15
16namespace y2017 {
17namespace control_loops {
18namespace superstructure {
19namespace column {
20
21namespace chrono = ::std::chrono;
22using ::aos::monotonic_clock;
23using ::frc971::zeroing::PulseIndexZeroingEstimator;
24
25namespace {
26constexpr double kTolerance = 10.0;
Austin Schuh4af3ac12017-04-09 18:34:01 -070027constexpr double kIndexerAcceleration = 50.0;
Austin Schuhd5ccb862017-03-11 22:06:36 -080028constexpr chrono::milliseconds kForwardTimeout{500};
Austin Schuh4af3ac12017-04-09 18:34:01 -070029constexpr chrono::milliseconds kReverseTimeout{1000};
30constexpr chrono::milliseconds kReverseMinTimeout{500};
Austin Schuhd5ccb862017-03-11 22:06:36 -080031} // namespace
32
33constexpr double Column::kZeroingVoltage;
34constexpr double Column::kOperatingVoltage;
35constexpr double Column::kIntakeZeroingMinDistance;
36constexpr double Column::kIntakeTolerance;
37constexpr double Column::kStuckZeroingTrackingError;
38
39ColumnProfiledSubsystem::ColumnProfiledSubsystem(
40 ::std::unique_ptr<
41 ::frc971::control_loops::SimpleCappedStateFeedbackLoop<6, 2, 2>>
42 loop,
43 const ::y2017::constants::Values::Column &zeroing_constants,
44 const ::frc971::constants::Range &range, double default_velocity,
45 double default_acceleration)
46 : ProfiledSubsystem<6, 1, ColumnZeroingEstimator, 2, 2>(
47 ::std::move(loop), {{zeroing_constants}}),
48 stuck_indexer_detector_(new StateFeedbackLoop<6, 2, 2>(
49 column::MakeStuckIntegralColumnLoop())),
James Kuszmaul61750662021-06-21 21:32:33 -070050 profile_(::frc971::controls::kLoopFrequency),
Austin Schuhd5ccb862017-03-11 22:06:36 -080051 range_(range),
52 default_velocity_(default_velocity),
53 default_acceleration_(default_acceleration) {
54 Y_.setZero();
55 offset_.setZero();
56 X_hat_current_.setZero();
57 stuck_indexer_X_hat_current_.setZero();
58 indexer_history_.fill(0);
59 AdjustProfile(0.0, 0.0);
60}
61
62void ColumnProfiledSubsystem::AddOffset(double indexer_offset_delta,
63 double turret_offset_delta) {
64 UpdateOffset(offset_(0, 0) + indexer_offset_delta,
65 offset_(1, 0) + turret_offset_delta);
66}
67
68void ColumnProfiledSubsystem::UpdateOffset(double indexer_offset,
69 double turret_offset) {
70 const double indexer_doffset = indexer_offset - offset_(0, 0);
71 const double turret_doffset = turret_offset - offset_(1, 0);
72
Austin Schuhf257f3c2019-10-27 21:00:43 -070073 AOS_LOG(INFO, "Adjusting indexer offset from %f to %f\n", offset_(0, 0),
74 indexer_offset);
75 AOS_LOG(INFO, "Adjusting turret offset from %f to %f\n", offset_(1, 0),
76 turret_offset);
Austin Schuhd5ccb862017-03-11 22:06:36 -080077
78 loop_->mutable_X_hat()(0, 0) += indexer_doffset;
79 loop_->mutable_X_hat()(2, 0) += turret_doffset + indexer_doffset;
80
81 stuck_indexer_detector_->mutable_X_hat()(0, 0) += indexer_doffset;
82 stuck_indexer_detector_->mutable_X_hat()(2, 0) +=
83 turret_doffset + indexer_doffset;
84 Y_(0, 0) += indexer_doffset;
85 Y_(1, 0) += turret_doffset;
86 turret_last_position_ += turret_doffset + indexer_doffset;
87 loop_->mutable_R(0, 0) += indexer_doffset;
88 loop_->mutable_R(2, 0) += turret_doffset + indexer_doffset;
89
90 profile_.MoveGoal(turret_doffset + indexer_doffset);
91 offset_(0, 0) = indexer_offset;
92 offset_(1, 0) = turret_offset;
93
94 CapGoal("R", &loop_->mutable_R());
95}
96
97void ColumnProfiledSubsystem::Correct(const ColumnPosition &new_position) {
98 estimators_[0].UpdateEstimate(new_position);
99
100 if (estimators_[0].error()) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700101 AOS_LOG(ERROR, "zeroing error\n");
Austin Schuhd5ccb862017-03-11 22:06:36 -0800102 return;
103 }
104
105 if (!initialized_) {
106 if (estimators_[0].offset_ready()) {
107 UpdateOffset(estimators_[0].indexer_offset(),
108 estimators_[0].turret_offset());
109 initialized_ = true;
110 }
111 }
112
113 if (!zeroed(0) && estimators_[0].zeroed()) {
114 UpdateOffset(estimators_[0].indexer_offset(),
115 estimators_[0].turret_offset());
116 set_zeroed(0, true);
117 }
118
119 turret_last_position_ = turret_position();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700120 Y_ << new_position.indexer()->encoder(), new_position.turret()->encoder();
Austin Schuhd5ccb862017-03-11 22:06:36 -0800121 Y_ += offset_;
122 loop_->Correct(Y_);
123
Alex Perrycb7da4b2019-08-28 19:35:56 -0700124 indexer_history_[indexer_history_position_] =
125 new_position.indexer()->encoder();
Austin Schuhd5ccb862017-03-11 22:06:36 -0800126 indexer_history_position_ = (indexer_history_position_ + 1) % kHistoryLength;
127
128 indexer_dt_velocity_ =
Alex Perrycb7da4b2019-08-28 19:35:56 -0700129 (new_position.indexer()->encoder() - indexer_last_position_) /
James Kuszmaul61750662021-06-21 21:32:33 -0700130 ::aos::time::DurationInSeconds(::frc971::controls::kLoopFrequency);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700131 indexer_last_position_ = new_position.indexer()->encoder();
Austin Schuhd5ccb862017-03-11 22:06:36 -0800132
133 stuck_indexer_detector_->Correct(Y_);
134
135 // Compute the oldest point in the history.
136 const int indexer_oldest_history_position =
137 ((indexer_history_position_ == 0) ? kHistoryLength
138 : indexer_history_position_) -
139 1;
140
141 // Compute the distance moved over that time period.
142 indexer_average_angular_velocity_ =
143 (indexer_history_[indexer_oldest_history_position] -
144 indexer_history_[indexer_history_position_]) /
James Kuszmaul61750662021-06-21 21:32:33 -0700145 (::aos::time::DurationInSeconds(::frc971::controls::kLoopFrequency) *
Austin Schuhd5ccb862017-03-11 22:06:36 -0800146 static_cast<double>(kHistoryLength - 1));
147
148 // Ready if average angular velocity is close to the goal.
149 indexer_error_ = indexer_average_angular_velocity_ - unprofiled_goal_(1, 0);
150
151 indexer_ready_ =
152 std::abs(indexer_error_) < kTolerance && unprofiled_goal_(1, 0) > 0.1;
153
154 // Pull state from the profiled subsystem.
155 X_hat_current_ = controller().X_hat();
156 stuck_indexer_X_hat_current_ = stuck_indexer_detector_->X_hat();
157 indexer_position_error_ = X_hat_current_(0, 0) - Y(0, 0);
158}
159
160void ColumnProfiledSubsystem::CapGoal(const char *name,
161 Eigen::Matrix<double, 6, 1> *goal) {
162 // Limit the goal to min/max allowable positions.
163 if (zeroed()) {
164 if ((*goal)(2, 0) > range_.upper) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700165 AOS_LOG(WARNING, "Goal %s above limit, %f > %f\n", name, (*goal)(2, 0),
166 range_.upper);
Austin Schuhd5ccb862017-03-11 22:06:36 -0800167 (*goal)(2, 0) = range_.upper;
168 }
169 if ((*goal)(2, 0) < range_.lower) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700170 AOS_LOG(WARNING, "Goal %s below limit, %f < %f\n", name, (*goal)(2, 0),
171 range_.lower);
Austin Schuhd5ccb862017-03-11 22:06:36 -0800172 (*goal)(2, 0) = range_.lower;
173 }
174 } else {
175 const double kMaxRange = range().upper_hard - range().lower_hard;
176
177 // Limit the goal to min/max allowable positions much less agressively.
178 // We don't know where the limits are, so we have to let the user move far
179 // enough to find them (and the index pulse which might be right next to
180 // one).
181 // Upper - lower hard may be a bit generous, but we are moving slow.
182
183 if ((*goal)(2, 0) > kMaxRange) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700184 AOS_LOG(WARNING, "Goal %s above limit, %f > %f\n", name, (*goal)(2, 0),
185 kMaxRange);
Austin Schuhd5ccb862017-03-11 22:06:36 -0800186 (*goal)(2, 0) = kMaxRange;
187 }
188 if ((*goal)(2, 0) < -kMaxRange) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700189 AOS_LOG(WARNING, "Goal %s below limit, %f < %f\n", name, (*goal)(2, 0),
190 -kMaxRange);
Austin Schuhd5ccb862017-03-11 22:06:36 -0800191 (*goal)(2, 0) = -kMaxRange;
192 }
193 }
194}
195
196void ColumnProfiledSubsystem::ForceGoal(double goal_velocity, double goal) {
197 set_unprofiled_goal(goal_velocity, goal);
198 loop_->mutable_R() = unprofiled_goal_;
199 loop_->mutable_next_R() = loop_->R();
200
201 const ::Eigen::Matrix<double, 6, 1> &R = loop_->R();
202 profile_.MoveCurrentState(R.block<2, 1>(2, 0));
203}
204
205void ColumnProfiledSubsystem::set_unprofiled_goal(double goal_velocity,
206 double unprofiled_goal) {
207 unprofiled_goal_(0, 0) = 0.0;
208 unprofiled_goal_(1, 0) = goal_velocity;
209 unprofiled_goal_(2, 0) = unprofiled_goal;
210 unprofiled_goal_(3, 0) = 0.0;
211 unprofiled_goal_(4, 0) = 0.0;
212 unprofiled_goal_(5, 0) = 0.0;
213 CapGoal("unprofiled R", &unprofiled_goal_);
214}
215
216void ColumnProfiledSubsystem::set_indexer_unprofiled_goal(
217 double goal_velocity) {
218 unprofiled_goal_(0, 0) = 0.0;
219 unprofiled_goal_(1, 0) = goal_velocity;
220 unprofiled_goal_(4, 0) = 0.0;
221 CapGoal("unprofiled R", &unprofiled_goal_);
222}
223
224void ColumnProfiledSubsystem::set_turret_unprofiled_goal(
225 double unprofiled_goal) {
226 unprofiled_goal_(2, 0) = unprofiled_goal;
227 unprofiled_goal_(3, 0) = 0.0;
228 unprofiled_goal_(5, 0) = 0.0;
229 CapGoal("unprofiled R", &unprofiled_goal_);
230}
231
232void ColumnProfiledSubsystem::Update(bool disable) {
233 // TODO(austin): If we really need to reset, reset the profiles, etc. That'll
234 // be covered by the layer above when disabled though, so we can get away with
235 // not doing it yet.
236 if (should_reset_) {
237 loop_->mutable_X_hat(0, 0) = Y_(0, 0);
238 loop_->mutable_X_hat(1, 0) = 0.0;
239 loop_->mutable_X_hat(2, 0) = Y_(0, 0) + Y_(1, 0);
240 loop_->mutable_X_hat(3, 0) = 0.0;
241 loop_->mutable_X_hat(4, 0) = 0.0;
242 loop_->mutable_X_hat(5, 0) = 0.0;
243
Austin Schuhf257f3c2019-10-27 21:00:43 -0700244 AOS_LOG(INFO, "Resetting\n");
Austin Schuhd5ccb862017-03-11 22:06:36 -0800245 stuck_indexer_detector_->mutable_X_hat() = loop_->X_hat();
246 should_reset_ = false;
247 saturated_ = false;
248 }
249
250 if (!disable) {
251 ::Eigen::Matrix<double, 2, 1> goal_state =
252 profile_.Update(unprofiled_goal_(2, 0), unprofiled_goal_(3, 0));
253
James Kuszmaul651fc3f2019-05-15 21:14:25 -0700254 constexpr double kDt =
James Kuszmaul61750662021-06-21 21:32:33 -0700255 ::aos::time::DurationInSeconds(::frc971::controls::kLoopFrequency);
Austin Schuh471d3b12017-03-25 20:49:14 -0700256
Austin Schuhd5ccb862017-03-11 22:06:36 -0800257 loop_->mutable_next_R(0, 0) = 0.0;
Austin Schuh471d3b12017-03-25 20:49:14 -0700258 // TODO(austin): This might not handle saturation right, but I'm not sure I
259 // really care.
260 loop_->mutable_next_R(1, 0) = ::aos::Clip(
261 unprofiled_goal_(1, 0), loop_->R(1, 0) - kIndexerAcceleration * kDt,
262 loop_->R(1, 0) + kIndexerAcceleration * kDt);
Austin Schuhd5ccb862017-03-11 22:06:36 -0800263 loop_->mutable_next_R(2, 0) = goal_state(0, 0);
264 loop_->mutable_next_R(3, 0) = goal_state(1, 0);
265 loop_->mutable_next_R(4, 0) = 0.0;
266 loop_->mutable_next_R(5, 0) = 0.0;
267 CapGoal("next R", &loop_->mutable_next_R());
268 }
269
270 // If the indexer goal velocity is low, switch to the indexer controller which
271 // won't fight to keep it moving at 0.
272 if (::std::abs(unprofiled_goal_(1, 0)) < 0.1) {
273 loop_->set_index(1);
274 } else {
275 loop_->set_index(0);
276 }
277 loop_->Update(disable);
278
279 if (!disable && loop_->U(1, 0) != loop_->U_uncapped(1, 0)) {
280 const ::Eigen::Matrix<double, 6, 1> &R = loop_->R();
281 profile_.MoveCurrentState(R.block<2, 1>(2, 0));
282 saturated_ = true;
283 } else {
284 saturated_ = false;
285 }
286
287 // Run the KF predict step.
288 stuck_indexer_detector_->UpdateObserver(loop_->U(),
James Kuszmaul61750662021-06-21 21:32:33 -0700289 ::frc971::controls::kLoopFrequency);
Austin Schuhd5ccb862017-03-11 22:06:36 -0800290}
291
292bool ColumnProfiledSubsystem::CheckHardLimits() {
293 // Returns whether hard limits have been exceeded.
294
James Kuszmaul651fc3f2019-05-15 21:14:25 -0700295 if (turret_position() > range_.upper_hard ||
296 turret_position() < range_.lower_hard) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700297 AOS_LOG(ERROR,
298 "ColumnProfiledSubsystem at %f out of bounds [%f, %f], ESTOPing\n",
299 turret_position(), range_.lower_hard, range_.upper_hard);
Austin Schuhd5ccb862017-03-11 22:06:36 -0800300 return true;
301 }
302
303 return false;
304}
305
306void ColumnProfiledSubsystem::AdjustProfile(
Alex Perrycb7da4b2019-08-28 19:35:56 -0700307 const ::frc971::ProfileParameters *profile_parameters) {
308 AdjustProfile(
309 profile_parameters == nullptr ? 0.0 : profile_parameters->max_velocity(),
310 profile_parameters == nullptr ? 0.0
311 : profile_parameters->max_acceleration());
Austin Schuhd5ccb862017-03-11 22:06:36 -0800312}
313
314void ColumnProfiledSubsystem::AdjustProfile(double max_angular_velocity,
315 double max_angular_acceleration) {
316 profile_.set_maximum_velocity(
317 ::frc971::control_loops::internal::UseUnlessZero(max_angular_velocity,
318 default_velocity_));
319 profile_.set_maximum_acceleration(
320 ::frc971::control_loops::internal::UseUnlessZero(max_angular_acceleration,
321 default_acceleration_));
322}
323
324double ColumnProfiledSubsystem::IndexerStuckVoltage() const {
325 // Compute the voltage from the control loop, excluding the voltage error
326 // term.
327 const double uncapped_applied_voltage =
328 uncapped_indexer_voltage() + X_hat(4, 0);
329 if (uncapped_applied_voltage < 0) {
330 return +stuck_indexer_X_hat_current_(4, 0);
331 } else {
332 return -stuck_indexer_X_hat_current_(4, 0);
333 }
334}
335bool ColumnProfiledSubsystem::IsIndexerStuck() const {
Austin Schuh546a0382017-04-16 19:10:18 -0700336 return IndexerStuckVoltage() > 4.0;
Austin Schuhd5ccb862017-03-11 22:06:36 -0800337}
338
339void ColumnProfiledSubsystem::PartialIndexerReset() {
340 mutable_X_hat(4, 0) = 0.0;
341 stuck_indexer_detector_->mutable_X_hat(4, 0) = 0.0;
Austin Schuh471d3b12017-03-25 20:49:14 -0700342 // Screw it, we are stuck. Reset the current goal to the current velocity so
343 // we start slewing faster to reverse if we have stopped.
344 loop_->mutable_R(1, 0) = X_hat(1, 0);
345 loop_->mutable_next_R(1, 0) = X_hat(1, 0);
Austin Schuhd5ccb862017-03-11 22:06:36 -0800346}
347
348void ColumnProfiledSubsystem::PartialTurretReset() {
349 mutable_X_hat(5, 0) = 0.0;
350 stuck_indexer_detector_->mutable_X_hat(5, 0) = 0.0;
351}
352
Alex Perrycb7da4b2019-08-28 19:35:56 -0700353void ColumnProfiledSubsystem::PopulateIndexerStatus(
354 IndexerStatus::Builder *status_builder) {
355 status_builder->add_avg_angular_velocity(indexer_average_angular_velocity_);
Austin Schuhd5ccb862017-03-11 22:06:36 -0800356
Alex Perrycb7da4b2019-08-28 19:35:56 -0700357 status_builder->add_angular_velocity(X_hat_current_(1, 0));
358 status_builder->add_ready(indexer_ready_);
Austin Schuhd5ccb862017-03-11 22:06:36 -0800359
Alex Perrycb7da4b2019-08-28 19:35:56 -0700360 status_builder->add_voltage_error(X_hat_current_(4, 0));
361 status_builder->add_stuck_voltage_error(stuck_indexer_X_hat_current_(4, 0));
362 status_builder->add_position_error(indexer_position_error_);
363 status_builder->add_instantaneous_velocity(indexer_dt_velocity_);
Austin Schuhd5ccb862017-03-11 22:06:36 -0800364
Alex Perrycb7da4b2019-08-28 19:35:56 -0700365 status_builder->add_stuck(IsIndexerStuck());
Austin Schuhd5ccb862017-03-11 22:06:36 -0800366
Alex Perrycb7da4b2019-08-28 19:35:56 -0700367 status_builder->add_stuck_voltage(IndexerStuckVoltage());
368}
369
370void ColumnProfiledSubsystem::PopulateTurretStatus(
371 TurretProfiledSubsystemStatus::Builder *status_builder,
372 flatbuffers::Offset<ColumnZeroingEstimator::State> estimator_state_offset) {
373 status_builder->add_zeroed(zeroed());
374
375 status_builder->add_position(X_hat(2, 0));
376 status_builder->add_velocity(X_hat(3, 0));
377 status_builder->add_goal_position(goal(2, 0));
378 status_builder->add_goal_velocity(goal(3, 0));
379 status_builder->add_unprofiled_goal_position(unprofiled_goal(2, 0));
380 status_builder->add_unprofiled_goal_velocity(unprofiled_goal(3, 0));
381 status_builder->add_voltage_error(X_hat(5, 0));
382 status_builder->add_calculated_velocity(
383 (turret_position() - turret_last_position_) /
James Kuszmaul61750662021-06-21 21:32:33 -0700384 ::aos::time::DurationInSeconds(::frc971::controls::kLoopFrequency));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700385
386 status_builder->add_estimator_state(estimator_state_offset);
387
388 Eigen::Matrix<double, 6, 1> error = controller().error();
389 status_builder->add_position_power(controller().controller().K(0, 0) *
390 error(0, 0));
391 status_builder->add_velocity_power(controller().controller().K(0, 1) *
392 error(1, 0));
Austin Schuhd5ccb862017-03-11 22:06:36 -0800393}
394
Austin Schuhb6c5c852019-05-19 20:13:31 -0700395Column::Column(::aos::EventLoop *event_loop)
396 : vision_time_adjuster_(event_loop),
397 profiled_subsystem_(
Austin Schuhd5ccb862017-03-11 22:06:36 -0800398 ::std::unique_ptr<
399 ::frc971::control_loops::SimpleCappedStateFeedbackLoop<6, 2, 2>>(
400 new ::frc971::control_loops::SimpleCappedStateFeedbackLoop<
401 6, 2, 2>(MakeIntegralColumnLoop())),
402 constants::GetValues().column, constants::Values::kTurretRange, 7.0,
Austin Schuh25db1262017-04-05 19:39:55 -0700403 50.0),
404 vision_error_(constants::GetValues().vision_error) {}
Austin Schuhd5ccb862017-03-11 22:06:36 -0800405
406void Column::Reset() {
407 state_ = State::UNINITIALIZED;
408 indexer_state_ = IndexerState::RUNNING;
409 profiled_subsystem_.Reset();
410 // intake will automatically clear the minimum position on reset, so we don't
411 // need to do it here.
412 freeze_ = false;
413}
414
Alex Perrycb7da4b2019-08-28 19:35:56 -0700415std::pair<flatbuffers::Offset<IndexerStatus>,
416 flatbuffers::Offset<TurretProfiledSubsystemStatus>>
417Column::Iterate(const ::aos::monotonic_clock::time_point monotonic_now,
418 const IndexerGoalT *unsafe_indexer_goal,
419 const TurretGoal *unsafe_turret_goal,
420 const ColumnPosition *position,
421 const vision::VisionStatus *vision_status,
422 double *indexer_output, double *turret_output,
423 flatbuffers::FlatBufferBuilder *fbb, intake::Intake *intake) {
Austin Schuhd5ccb862017-03-11 22:06:36 -0800424 bool disable = turret_output == nullptr || indexer_output == nullptr;
425 profiled_subsystem_.Correct(*position);
426
Austin Schuh92715362019-07-07 20:47:45 -0700427 vision_time_adjuster_.Tick(monotonic_now, profiled_subsystem_.X_hat(2, 0),
428 vision_status);
Austin Schuhac76bb32017-03-22 22:34:26 -0700429
Austin Schuhd5ccb862017-03-11 22:06:36 -0800430 switch (state_) {
431 case State::UNINITIALIZED:
432 // Wait in the uninitialized state until the turret is initialized.
433 // Set the goals to where we are now so when we start back up, we don't
434 // jump.
435 profiled_subsystem_.ForceGoal(0.0, profiled_subsystem_.turret_position());
436 state_ = State::ZEROING_UNINITIALIZED;
437
438 // Fall through so we can start the zeroing process immediately.
James Kuszmaul3ae42262019-11-08 12:33:41 -0800439 [[fallthrough]];
Austin Schuhd5ccb862017-03-11 22:06:36 -0800440
441 case State::ZEROING_UNINITIALIZED:
442 // Set up the profile to be the zeroing profile.
443 profiled_subsystem_.AdjustProfile(0.50, 3);
444
445 // Force the intake out.
446 intake->set_min_position(kIntakeZeroingMinDistance);
447
448 if (disable) {
449 // If we are disabled, we want to reset the turret to stay where it
450 // currently is.
451 profiled_subsystem_.ForceGoal(0.0,
452 profiled_subsystem_.turret_position());
453 } else if (profiled_subsystem_.initialized()) {
454 // If we are initialized, there's no value in continuing to move so stop
455 // and wait on the intake.
456 profiled_subsystem_.set_indexer_unprofiled_goal(0.0);
457 } else {
458 // Spin slowly backwards.
459 profiled_subsystem_.set_indexer_unprofiled_goal(2.0);
460 }
461
462 // See if we are zeroed or initialized and far enough out and execute the
463 // proper state transition.
464 if (profiled_subsystem_.zeroed()) {
465 intake->clear_min_position();
466 state_ = State::RUNNING;
467 } else if (profiled_subsystem_.initialized() &&
468 intake->position() >
469 kIntakeZeroingMinDistance - kIntakeTolerance) {
470 if (profiled_subsystem_.turret_position() > 0) {
471 // We need to move in the negative direction.
472 state_ = State::ZEROING_NEGATIVE;
473 } else {
474 // We need to move in the positive direction.
475 state_ = State::ZEROING_POSITIVE;
476 }
477 }
478 break;
479
480 case State::ZEROING_POSITIVE:
481 // We are now going to be moving in the positive direction towards 0. If
482 // we get close enough, we'll zero.
483 profiled_subsystem_.set_unprofiled_goal(0.0, 0.0);
484 intake->set_min_position(kIntakeZeroingMinDistance);
485
486 if (profiled_subsystem_.zeroed()) {
487 intake->clear_min_position();
488 state_ = State::RUNNING;
489 } else if (disable) {
490 // We are disabled, so pick back up from the current position.
491 profiled_subsystem_.ForceGoal(0.0,
492 profiled_subsystem_.turret_position());
493 } else if (profiled_subsystem_.turret_position() <
494 profiled_subsystem_.goal(2, 0) -
495 kStuckZeroingTrackingError ||
496 profiled_subsystem_.saturated()) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700497 AOS_LOG(
498 INFO,
Austin Schuhd5ccb862017-03-11 22:06:36 -0800499 "Turret stuck going positive, switching directions. At %f, goal "
500 "%f\n",
501 profiled_subsystem_.turret_position(),
502 profiled_subsystem_.goal(2, 0));
503 // The turret got too far behind. Declare it stuck and reverse.
504 profiled_subsystem_.AddOffset(0.0, 2.0 * M_PI);
505 profiled_subsystem_.set_unprofiled_goal(0.0, 0.0);
506 profiled_subsystem_.ForceGoal(0.0,
507 profiled_subsystem_.turret_position());
508 profiled_subsystem_.PartialTurretReset();
509 profiled_subsystem_.PartialIndexerReset();
510 state_ = State::ZEROING_NEGATIVE;
511 }
512 break;
513
514 case State::ZEROING_NEGATIVE:
515 // We are now going to be moving in the negative direction towards 0. If
516 // we get close enough, we'll zero.
517 profiled_subsystem_.set_unprofiled_goal(0.0, 0.0);
518 intake->set_min_position(kIntakeZeroingMinDistance);
519
520 if (profiled_subsystem_.zeroed()) {
521 intake->clear_min_position();
522 state_ = State::RUNNING;
523 } else if (disable) {
524 // We are disabled, so pick back up from the current position.
525 profiled_subsystem_.ForceGoal(0.0,
526 profiled_subsystem_.turret_position());
527 } else if (profiled_subsystem_.turret_position() >
528 profiled_subsystem_.goal(2, 0) +
529 kStuckZeroingTrackingError ||
530 profiled_subsystem_.saturated()) {
531 // The turret got too far behind. Declare it stuck and reverse.
Austin Schuhf257f3c2019-10-27 21:00:43 -0700532 AOS_LOG(
533 INFO,
Austin Schuhd5ccb862017-03-11 22:06:36 -0800534 "Turret stuck going negative, switching directions. At %f, goal "
535 "%f\n",
536 profiled_subsystem_.turret_position(),
537 profiled_subsystem_.goal(2, 0));
538 profiled_subsystem_.AddOffset(0.0, -2.0 * M_PI);
539 profiled_subsystem_.set_unprofiled_goal(0.0, 0.0);
540 profiled_subsystem_.ForceGoal(0.0,
541 profiled_subsystem_.turret_position());
542 profiled_subsystem_.PartialTurretReset();
543 profiled_subsystem_.PartialIndexerReset();
544 state_ = State::ZEROING_POSITIVE;
545 }
546 break;
547
548 case State::RUNNING: {
549 double starting_goal_angle = profiled_subsystem_.goal(2, 0);
550 if (disable) {
551 // Reset the profile to the current position so it starts from here when
552 // we get re-enabled.
553 profiled_subsystem_.ForceGoal(0.0,
554 profiled_subsystem_.turret_position());
555 }
556
557 if (unsafe_turret_goal && unsafe_indexer_goal) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700558 profiled_subsystem_.AdjustProfile(unsafe_turret_goal->profile_params());
Austin Schuhd5ccb862017-03-11 22:06:36 -0800559 profiled_subsystem_.set_unprofiled_goal(
James Kuszmaul61750662021-06-21 21:32:33 -0700560 unsafe_indexer_goal->angular_velocity, unsafe_turret_goal->angle());
Austin Schuhd5ccb862017-03-11 22:06:36 -0800561
Alex Perrycb7da4b2019-08-28 19:35:56 -0700562 if (unsafe_turret_goal->track()) {
Austin Schuhac76bb32017-03-22 22:34:26 -0700563 if (vision_time_adjuster_.valid()) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700564 AOS_LOG(INFO, "Vision aligning to %f\n",
565 vision_time_adjuster_.goal());
Austin Schuhac76bb32017-03-22 22:34:26 -0700566 profiled_subsystem_.set_turret_unprofiled_goal(
Austin Schuh25db1262017-04-05 19:39:55 -0700567 vision_time_adjuster_.goal() + vision_error_);
Austin Schuhac76bb32017-03-22 22:34:26 -0700568 }
Austin Schuhd85c66e2017-04-16 10:50:33 -0700569 } else {
570 vision_time_adjuster_.ResetTime();
Austin Schuhac76bb32017-03-22 22:34:26 -0700571 }
572
Austin Schuhd5ccb862017-03-11 22:06:36 -0800573 if (freeze_) {
574 profiled_subsystem_.ForceGoal(unsafe_indexer_goal->angular_velocity,
575 starting_goal_angle);
576 }
577 }
578
579 // ESTOP if we hit the hard limits.
580 if (profiled_subsystem_.CheckHardLimits() ||
581 profiled_subsystem_.error()) {
582 state_ = State::ESTOP;
583 }
584 } break;
585
586 case State::ESTOP:
Austin Schuhf257f3c2019-10-27 21:00:43 -0700587 AOS_LOG(ERROR, "Estop\n");
Austin Schuhd5ccb862017-03-11 22:06:36 -0800588 disable = true;
589 break;
590 }
591
592 // Start indexing at the suggested velocity.
593 // If a "stuck" event is detected, reverse. Stay reversed until either
594 // unstuck, or 0.5 seconds have elapsed.
595 // Then, start going forwards. Don't detect stuck for 0.5 seconds.
Austin Schuhd5ccb862017-03-11 22:06:36 -0800596 switch (indexer_state_) {
597 case IndexerState::RUNNING:
598 // The velocity goal is already set above in this case, so leave it
599 // alone.
600
601 // If we are stuck and weren't just reversing, try reversing to unstick
602 // us. We don't want to chatter back and forth too fast if reversing
603 // isn't working.
604 if (profiled_subsystem_.IsIndexerStuck() &&
605 monotonic_now > kForwardTimeout + last_transition_time_) {
606 indexer_state_ = IndexerState::REVERSING;
607 last_transition_time_ = monotonic_now;
608 profiled_subsystem_.PartialIndexerReset();
Austin Schuhf257f3c2019-10-27 21:00:43 -0700609 AOS_LOG(INFO, "Partial indexer reset while going forwards\n");
610 AOS_LOG(INFO, "Indexer RUNNING -> REVERSING\n");
Austin Schuhd5ccb862017-03-11 22:06:36 -0800611 }
612 break;
613 case IndexerState::REVERSING:
614 // "Reverse" "slowly".
615 profiled_subsystem_.set_indexer_unprofiled_goal(
616 -5.0 * ::aos::sign(profiled_subsystem_.unprofiled_goal(1, 0)));
617
618 // If we've timed out or are no longer stuck, try running again.
619 if ((!profiled_subsystem_.IsIndexerStuck() &&
620 monotonic_now > last_transition_time_ + kReverseMinTimeout) ||
621 monotonic_now > kReverseTimeout + last_transition_time_) {
622 indexer_state_ = IndexerState::RUNNING;
Austin Schuhf257f3c2019-10-27 21:00:43 -0700623 AOS_LOG(INFO, "Indexer REVERSING -> RUNNING, stuck %d\n",
624 profiled_subsystem_.IsIndexerStuck());
Austin Schuhd5ccb862017-03-11 22:06:36 -0800625
626 // Only reset if we got stuck going this way too.
627 if (monotonic_now > kReverseTimeout + last_transition_time_) {
Austin Schuhf257f3c2019-10-27 21:00:43 -0700628 AOS_LOG(INFO, "Partial indexer reset while reversing\n");
Austin Schuhd5ccb862017-03-11 22:06:36 -0800629 profiled_subsystem_.PartialIndexerReset();
630 }
631 last_transition_time_ = monotonic_now;
632 }
633 break;
634 }
635
636 // Set the voltage limits.
637 const double max_voltage =
638 (state_ == State::RUNNING) ? kOperatingVoltage : kZeroingVoltage;
639
640 profiled_subsystem_.set_max_voltage({{max_voltage, max_voltage}});
641
642 // Calculate the loops for a cycle.
643 profiled_subsystem_.Update(disable);
644
645 // Write out all the voltages.
646 if (indexer_output) {
647 *indexer_output = profiled_subsystem_.indexer_voltage();
648 }
649 if (turret_output) {
650 *turret_output = profiled_subsystem_.turret_voltage();
651 }
652
653 // Save debug/internal state.
654 // TODO(austin): Save more.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700655 flatbuffers::Offset<ColumnZeroingEstimator::State>
656 column_estimator_state_offset =
657 profiled_subsystem_.EstimatorState(fbb, 0);
658
659 TurretProfiledSubsystemStatus::Builder turret_status_builder(*fbb);
660 profiled_subsystem_.PopulateTurretStatus(&turret_status_builder,
661 column_estimator_state_offset);
662 turret_status_builder.add_estopped((state_ == State::ESTOP));
663 turret_status_builder.add_state(static_cast<int32_t>(state_));
664 turret_status_builder.add_turret_encoder_angle(
665 profiled_subsystem_.turret_position());
Austin Schuhac76bb32017-03-22 22:34:26 -0700666 if (vision_time_adjuster_.valid()) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700667 turret_status_builder.add_vision_angle(vision_time_adjuster_.goal());
668 turret_status_builder.add_raw_vision_angle(
669 vision_time_adjuster_.most_recent_vision_reading());
670 turret_status_builder.add_vision_tracking(true);
Austin Schuhac76bb32017-03-22 22:34:26 -0700671 } else {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700672 turret_status_builder.add_vision_angle(
673 ::std::numeric_limits<double>::quiet_NaN());
674 turret_status_builder.add_vision_tracking(false);
Austin Schuhac76bb32017-03-22 22:34:26 -0700675 }
Austin Schuhd5ccb862017-03-11 22:06:36 -0800676
Alex Perrycb7da4b2019-08-28 19:35:56 -0700677 flatbuffers::Offset<TurretProfiledSubsystemStatus> turret_status_offset =
678 turret_status_builder.Finish();
679
680 IndexerStatus::Builder indexer_status_builder(*fbb);
681 profiled_subsystem_.PopulateIndexerStatus(&indexer_status_builder);
682
683 indexer_status_builder.add_state(static_cast<int32_t>(indexer_state_));
684
685 flatbuffers::Offset<IndexerStatus> indexer_status_offset =
686 indexer_status_builder.Finish();
687
688 return std::make_pair(indexer_status_offset, turret_status_offset);
Austin Schuhd5ccb862017-03-11 22:06:36 -0800689}
690
691} // namespace column
692} // namespace superstructure
693} // namespace control_loops
694} // namespace y2017