blob: 3b16273484d3ce8ccb2ef75814dcc91d8d09ef71 [file] [log] [blame]
Comran Morshed5323ecb2015-12-26 20:50:55 +00001#include "frc971/control_loops/drivetrain/drivetrain.h"
Brian Silverman17f503e2015-08-02 18:17:18 -07002
Brian Silverman17f503e2015-08-02 18:17:18 -07003#include <sched.h>
James Kuszmaul61750662021-06-21 21:32:33 -07004
Brian Silverman17f503e2015-08-02 18:17:18 -07005#include <cmath>
Tyler Chatowbf0609c2021-07-31 16:13:27 -07006#include <cstdio>
Brian Silverman17f503e2015-08-02 18:17:18 -07007#include <memory>
Brian Silverman17f503e2015-08-02 18:17:18 -07008
James Kuszmaul61750662021-06-21 21:32:33 -07009#include "Eigen/Dense"
Philipp Schrader790cb542023-07-05 21:06:52 -070010
John Park33858a32018-09-28 23:05:48 -070011#include "aos/logging/logging.h"
Austin Schuh3a378462019-01-04 21:48:04 -080012#include "frc971/control_loops/drivetrain/down_estimator.h"
Austin Schuh3a378462019-01-04 21:48:04 -080013#include "frc971/control_loops/drivetrain/drivetrain_config.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070014#include "frc971/control_loops/drivetrain/drivetrain_goal_generated.h"
15#include "frc971/control_loops/drivetrain/drivetrain_output_generated.h"
16#include "frc971/control_loops/drivetrain/drivetrain_position_generated.h"
17#include "frc971/control_loops/drivetrain/drivetrain_status_generated.h"
Comran Morshed5323ecb2015-12-26 20:50:55 +000018#include "frc971/control_loops/drivetrain/polydrivetrain.h"
19#include "frc971/control_loops/drivetrain/ssdrivetrain.h"
Austin Schuh3a378462019-01-04 21:48:04 -080020#include "frc971/control_loops/runge_kutta.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070021#include "frc971/queues/gyro_generated.h"
Brian Silverman17f503e2015-08-02 18:17:18 -070022#include "frc971/shifter_hall_effect.h"
Austin Schuhac17fba2020-03-28 15:55:33 -070023#include "frc971/wpilib/imu_batch_generated.h"
Brian Silverman17f503e2015-08-02 18:17:18 -070024
Austin Schuh9993fb32017-03-15 20:17:46 -070025using ::aos::monotonic_clock;
26namespace chrono = ::std::chrono;
Brian Silverman17f503e2015-08-02 18:17:18 -070027
Comran Morshed5323ecb2015-12-26 20:50:55 +000028namespace frc971 {
Brian Silverman17f503e2015-08-02 18:17:18 -070029namespace control_loops {
Austin Schuh6197a182015-11-28 16:04:40 -080030namespace drivetrain {
Brian Silverman17f503e2015-08-02 18:17:18 -070031
James Kuszmaulc53de4a2022-03-12 21:32:06 -080032namespace {
33// Maximum variation to allow in the gyro when zeroing.
Austin Schuh8c76a9b2022-03-16 21:33:48 -070034constexpr double kMaxYawGyroZeroingRange = 0.08;
35} // namespace
James Kuszmaulc53de4a2022-03-12 21:32:06 -080036
Austin Schuhfb0f35c2021-02-14 21:25:29 -080037DrivetrainFilters::DrivetrainFilters(const DrivetrainConfig<double> &dt_config,
38 ::aos::EventLoop *event_loop,
39 LocalizerInterface *localizer)
40 : dt_config_(dt_config),
Alex Perrycb7da4b2019-08-28 19:35:56 -070041 localizer_control_fetcher_(
42 event_loop->MakeFetcher<LocalizerControl>("/drivetrain")),
Austin Schuh73b6e3b2019-05-27 16:37:15 -070043 imu_values_fetcher_(
James Kuszmaule5f67dd2022-02-12 20:08:29 -080044 event_loop->TryMakeFetcher<::frc971::IMUValuesBatch>("/drivetrain")),
Austin Schuh1ea89bb2019-05-27 16:59:59 -070045 gyro_reading_fetcher_(
46 event_loop->MakeFetcher<::frc971::sensors::GyroReading>(
Alex Perrycb7da4b2019-08-28 19:35:56 -070047 "/drivetrain")),
Austin Schuhfb0f35c2021-02-14 21:25:29 -080048 down_estimator_(dt_config_),
James Kuszmaul3431d622019-02-17 17:07:44 -080049 localizer_(localizer),
Austin Schuh41565602016-02-28 20:10:49 -080050 kf_(dt_config_.make_kf_drivetrain_loop()),
Austin Schuh093535c2016-03-05 23:21:00 -080051 left_gear_(dt_config_.default_high_gear ? Gear::HIGH : Gear::LOW),
52 right_gear_(dt_config_.default_high_gear ? Gear::HIGH : Gear::LOW),
53 left_high_requested_(dt_config_.default_high_gear),
54 right_high_requested_(dt_config_.default_high_gear) {
Austin Schuhfb0f35c2021-02-14 21:25:29 -080055 last_voltage_.setZero();
56 last_last_voltage_.setZero();
James Kuszmaul61750662021-06-21 21:32:33 -070057 frc971::controls::HPolytope<0>::Init();
James Kuszmaul30aca502020-01-19 15:05:33 -080058 event_loop->OnRun([this]() {
59 // On the first fetch, make sure that we are caught all the way up to the
60 // present.
James Kuszmaule5f67dd2022-02-12 20:08:29 -080061 if (imu_values_fetcher_.valid()) {
62 imu_values_fetcher_.Fetch();
63 }
James Kuszmaul30aca502020-01-19 15:05:33 -080064 });
James Kuszmaul2215d922020-02-11 17:17:26 -080065 if (dt_config.is_simulated) {
66 down_estimator_.assume_perfect_gravity();
67 }
Austin Schuh209f1702015-11-29 17:03:00 -080068}
69
Austin Schuhfb0f35c2021-02-14 21:25:29 -080070flatbuffers::Offset<LocalizerState> DrivetrainFilters::PopulateLocalizerState(
71 flatbuffers::FlatBufferBuilder *fbb) {
72 return localizer_->PopulateStatus(fbb);
73}
74flatbuffers::Offset<ImuZeroerState> DrivetrainFilters::PopulateImuZeroerState(
75 flatbuffers::FlatBufferBuilder *fbb) {
76 return imu_zeroer_.PopulateStatus(fbb);
Austin Schuh093535c2016-03-05 23:21:00 -080077}
78
Austin Schuhfb0f35c2021-02-14 21:25:29 -080079flatbuffers::Offset<DownEstimatorState>
80DrivetrainFilters::PopulateDownEstimatorState(
81 flatbuffers::FlatBufferBuilder *fbb,
82 aos::monotonic_clock::time_point monotonic_now) {
83 return down_estimator_.PopulateStatus(fbb, monotonic_now);
Austin Schuh093535c2016-03-05 23:21:00 -080084}
85
Austin Schuhfb0f35c2021-02-14 21:25:29 -080086void DrivetrainFilters::Reset(aos::monotonic_clock::time_point monotonic_now,
87 const drivetrain::Position *position) {
88 // If all the sensors got reset (e.g., due to wpilib_interface restarting),
89 // reset the localizer and down estimator to avoid weird jumps in the
90 // filters.
91 down_estimator_.Reset();
92 // Just reset the localizer to the current state, except for the encoders.
93 LocalizerInterface::Ekf::State X_hat = localizer_->Xhat();
94 X_hat(LocalizerInterface::StateIdx::kLeftEncoder) = position->left_encoder();
95 X_hat(LocalizerInterface::StateIdx::kRightEncoder) =
96 position->right_encoder();
97 localizer_->Reset(monotonic_now, X_hat);
98}
Austin Schuh9993fb32017-03-15 20:17:46 -070099
Austin Schuhfb0f35c2021-02-14 21:25:29 -0800100void DrivetrainFilters::Correct(aos::monotonic_clock::time_point monotonic_now,
101 const drivetrain::Position *position) {
Austin Schuh093535c2016-03-05 23:21:00 -0800102 // TODO(austin): Put gear detection logic here.
103 switch (dt_config_.shifter_type) {
104 case ShifterType::SIMPLE_SHIFTER:
105 // Force the right controller for simple shifters since we assume that
106 // gear switching is instantaneous.
107 if (left_high_requested_) {
108 left_gear_ = Gear::HIGH;
109 } else {
110 left_gear_ = Gear::LOW;
111 }
112 if (right_high_requested_) {
113 right_gear_ = Gear::HIGH;
114 } else {
115 right_gear_ = Gear::LOW;
116 }
117 break;
118 case ShifterType::HALL_EFFECT_SHIFTER:
Alex Perrycb7da4b2019-08-28 19:35:56 -0700119 left_gear_ = ComputeGear(position->left_shifter_position(),
Austin Schuh093535c2016-03-05 23:21:00 -0800120 dt_config_.left_drive, left_high_requested_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700121 right_gear_ = ComputeGear(position->right_shifter_position(),
Austin Schuh093535c2016-03-05 23:21:00 -0800122 dt_config_.right_drive, right_high_requested_);
123 break;
Adam Snaider18f44172016-10-22 15:30:21 -0700124 case ShifterType::NO_SHIFTER:
125 break;
Brian Silverman17f503e2015-08-02 18:17:18 -0700126 }
Brian Silverman17f503e2015-08-02 18:17:18 -0700127
James Kuszmaule5f67dd2022-02-12 20:08:29 -0800128 while (imu_values_fetcher_.valid() && imu_values_fetcher_.FetchNext()) {
Austin Schuhac17fba2020-03-28 15:55:33 -0700129 CHECK(imu_values_fetcher_->has_readings());
James Kuszmaul3e1bb272020-01-17 18:38:19 -0800130 last_gyro_time_ = monotonic_now;
Austin Schuhac17fba2020-03-28 15:55:33 -0700131 for (const IMUValues *value : *imu_values_fetcher_->readings()) {
132 imu_zeroer_.InsertMeasurement(*value);
133 if (!imu_zeroer_.Zeroed()) {
134 continue;
135 }
136 const aos::monotonic_clock::time_point reading_time(
137 std::chrono::nanoseconds(value->monotonic_timestamp_ns()));
138 if (last_imu_update_ == aos::monotonic_clock::min_time) {
139 last_imu_update_ = reading_time;
140 }
James Kuszmaul6d6e1302022-03-12 15:22:48 -0800141 down_estimator_.Predict(imu_zeroer_.ZeroedGyro().value(),
142 imu_zeroer_.ZeroedAccel().value(),
Austin Schuhac17fba2020-03-28 15:55:33 -0700143 reading_time - last_imu_update_);
James Kuszmaul3e1bb272020-01-17 18:38:19 -0800144 last_imu_update_ = reading_time;
145 }
James Kuszmaul3e1bb272020-01-17 18:38:19 -0800146 }
Diana Burgessd0180f12018-03-21 21:24:17 -0700147
James Kuszmaul3e1bb272020-01-17 18:38:19 -0800148 bool got_imu_reading = false;
James Kuszmaule5f67dd2022-02-12 20:08:29 -0800149 if (imu_values_fetcher_.valid() && imu_values_fetcher_.get() != nullptr) {
James Kuszmaulb7f45bb2020-02-26 20:27:48 -0800150 imu_zeroer_.ProcessMeasurements();
James Kuszmaul3e1bb272020-01-17 18:38:19 -0800151 got_imu_reading = true;
Austin Schuhac17fba2020-03-28 15:55:33 -0700152 CHECK(imu_values_fetcher_->has_readings());
James Kuszmaul0a981402021-10-09 21:00:34 -0700153 if (imu_values_fetcher_->readings()->size() > 0) {
154 const IMUValues *value = imu_values_fetcher_->readings()->Get(
155 imu_values_fetcher_->readings()->size() - 1);
156 switch (dt_config_.imu_type) {
157 case IMUType::IMU_X:
158 last_accel_ = -value->accelerometer_x();
159 break;
160 case IMUType::IMU_FLIPPED_X:
161 last_accel_ = value->accelerometer_x();
162 break;
163 case IMUType::IMU_Y:
164 last_accel_ = -value->accelerometer_y();
165 break;
166 case IMUType::IMU_Z:
167 last_accel_ = value->accelerometer_z();
168 break;
169 }
Diana Burgessd0180f12018-03-21 21:24:17 -0700170 }
Austin Schuh05c5a612016-04-02 15:10:25 -0700171 }
Austin Schuh05c5a612016-04-02 15:10:25 -0700172
Austin Schuh093535c2016-03-05 23:21:00 -0800173 // TODO(austin): Signal the current gear to both loops.
James Kuszmaul6d6e1302022-03-12 15:22:48 -0800174 bool imu_zeroer_zeroed = imu_zeroer_.Zeroed();
Austin Schuh093535c2016-03-05 23:21:00 -0800175
Campbell Crowley2527ed22017-02-17 21:10:02 -0800176 switch (dt_config_.gyro_type) {
177 case GyroType::IMU_X_GYRO:
James Kuszmaul3e1bb272020-01-17 18:38:19 -0800178 if (got_imu_reading) {
James Kuszmaul6d6e1302022-03-12 15:22:48 -0800179 last_gyro_rate_ =
180 imu_zeroer_zeroed ? imu_zeroer_.ZeroedGyro().value().x() : 0.0;
Campbell Crowley2527ed22017-02-17 21:10:02 -0800181 }
182 break;
183 case GyroType::IMU_Y_GYRO:
James Kuszmaul3e1bb272020-01-17 18:38:19 -0800184 if (got_imu_reading) {
James Kuszmaul6d6e1302022-03-12 15:22:48 -0800185 last_gyro_rate_ =
186 imu_zeroer_zeroed ? imu_zeroer_.ZeroedGyro().value().y() : 0.0;
Campbell Crowley2527ed22017-02-17 21:10:02 -0800187 }
188 break;
189 case GyroType::IMU_Z_GYRO:
James Kuszmaul3e1bb272020-01-17 18:38:19 -0800190 if (got_imu_reading) {
James Kuszmaul6d6e1302022-03-12 15:22:48 -0800191 last_gyro_rate_ =
192 imu_zeroer_zeroed ? imu_zeroer_.ZeroedGyro().value().z() : 0.0;
Campbell Crowley2527ed22017-02-17 21:10:02 -0800193 }
194 break;
Austin Schuh90b43b42019-01-04 07:45:05 +1100195 case GyroType::FLIPPED_IMU_Z_GYRO:
James Kuszmaul3e1bb272020-01-17 18:38:19 -0800196 if (got_imu_reading) {
James Kuszmaul6d6e1302022-03-12 15:22:48 -0800197 last_gyro_rate_ =
198 imu_zeroer_zeroed ? -imu_zeroer_.ZeroedGyro().value().z() : 0.0;
Austin Schuh90b43b42019-01-04 07:45:05 +1100199 }
200 break;
Campbell Crowley2527ed22017-02-17 21:10:02 -0800201 case GyroType::SPARTAN_GYRO:
Austin Schuh1ea89bb2019-05-27 16:59:59 -0700202 if (gyro_reading_fetcher_.Fetch()) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700203 last_gyro_rate_ = gyro_reading_fetcher_->velocity();
Austin Schuh9993fb32017-03-15 20:17:46 -0700204 last_gyro_time_ = monotonic_now;
Campbell Crowley2527ed22017-02-17 21:10:02 -0800205 }
206 break;
207 case GyroType::FLIPPED_SPARTAN_GYRO:
Austin Schuh1ea89bb2019-05-27 16:59:59 -0700208 if (gyro_reading_fetcher_.Fetch()) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700209 last_gyro_rate_ = -gyro_reading_fetcher_->velocity();
Austin Schuh9993fb32017-03-15 20:17:46 -0700210 last_gyro_time_ = monotonic_now;
Campbell Crowley2527ed22017-02-17 21:10:02 -0800211 }
212 break;
213 default:
Austin Schuhf257f3c2019-10-27 21:00:43 -0700214 AOS_LOG(FATAL, "invalid gyro configured");
Campbell Crowley2527ed22017-02-17 21:10:02 -0800215 break;
Austin Schuh9ab4d9d2016-02-16 23:55:44 -0800216 }
217
James Kuszmaulc53de4a2022-03-12 21:32:06 -0800218 switch (dt_config_.gyro_type) {
219 case GyroType::SPARTAN_GYRO:
220 case GyroType::FLIPPED_SPARTAN_GYRO:
221 if (!yaw_gyro_zero_.has_value()) {
222 yaw_gyro_zeroer_.AddData(last_gyro_rate_);
Philipp Schrader790cb542023-07-05 21:06:52 -0700223 if (yaw_gyro_zeroer_.full() &&
224 yaw_gyro_zeroer_.GetRange() < kMaxYawGyroZeroingRange) {
James Kuszmaulc53de4a2022-03-12 21:32:06 -0800225 yaw_gyro_zero_ = yaw_gyro_zeroer_.GetAverage()(0);
Austin Schuh8c76a9b2022-03-16 21:33:48 -0700226 VLOG(1) << "Zeroed to " << *yaw_gyro_zero_ << " Range "
227 << yaw_gyro_zeroer_.GetRange();
James Kuszmaulc53de4a2022-03-12 21:32:06 -0800228 }
229 }
230 ready_ = yaw_gyro_zero_.has_value();
231 if (ready_) {
232 last_gyro_rate_ = last_gyro_rate_ - yaw_gyro_zero_.value();
233 }
234 break;
235 case GyroType::IMU_X_GYRO:
236 case GyroType::IMU_Y_GYRO:
237 case GyroType::IMU_Z_GYRO:
238 case GyroType::FLIPPED_IMU_Z_GYRO:
239 ready_ = imu_zeroer_.Zeroed();
240 break;
241 }
James Kuszmaulddc69702021-03-24 21:55:03 -0700242
243 // TODO(james): How aggressively can we fault here? If we fault to
244 // aggressively, we might have issues during startup if wpilib_interface takes
245 // too long to start publishing IMU measurements.
Austin Schuh9993fb32017-03-15 20:17:46 -0700246 if (monotonic_now > last_gyro_time_ + chrono::milliseconds(20)) {
247 last_gyro_rate_ = 0.0;
248 }
249
James Kuszmaul1798c072022-02-13 15:32:11 -0800250 if (imu_values_fetcher_.valid()) {
251 localizer_->Update(
252 {last_last_voltage_(kLeftVoltage), last_last_voltage_(kRightVoltage)},
253 monotonic_now, position->left_encoder(), position->right_encoder(),
254 down_estimator_.avg_recent_yaw_rates(),
255 down_estimator_.avg_recent_accel());
256 } else {
257 localizer_->Update(
258 {last_last_voltage_(kLeftVoltage), last_last_voltage_(kRightVoltage)},
259 monotonic_now, position->left_encoder(), position->right_encoder(),
260 last_gyro_rate_, Eigen::Vector3d::Zero());
261 }
Austin Schuhfb0f35c2021-02-14 21:25:29 -0800262
263 // If we get a new message setting the absolute position, then reset the
264 // localizer.
265 if (localizer_control_fetcher_.Fetch()) {
266 VLOG(1) << "localizer_control "
267 << aos::FlatbufferToJson(localizer_control_fetcher_.get());
268 localizer_->ResetPosition(
269 monotonic_now, localizer_control_fetcher_->x(),
270 localizer_control_fetcher_->y(), localizer_control_fetcher_->theta(),
271 localizer_control_fetcher_->theta_uncertainty(),
272 !localizer_control_fetcher_->keep_current_theta());
273 }
274
275 kf_.set_index(ControllerIndexFromGears());
276
Austin Schuh6613a072016-01-06 19:54:48 -0800277 {
Diana Burgessd0180f12018-03-21 21:24:17 -0700278 Eigen::Matrix<double, 4, 1> Y;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700279 Y << position->left_encoder(), position->right_encoder(), last_gyro_rate_,
Diana Burgessd0180f12018-03-21 21:24:17 -0700280 last_accel_;
Austin Schuh6613a072016-01-06 19:54:48 -0800281 kf_.Correct(Y);
Austin Schuhfb0f35c2021-02-14 21:25:29 -0800282 }
283}
284
285Eigen::Matrix<double, 2, 1> DrivetrainFilters::VoltageError() const {
286 static_assert(kLeftError + 1 == kRightError);
287 Eigen::Matrix<double, 2, 2> error_K;
288 error_K << kf_.controller().K(kLeftVoltage, kLeftError), 0.0, 0.0,
289 kf_.controller().K(kRightVoltage, kRightError);
290 const Eigen::Matrix<double, 2, 1> voltage_error =
291 error_K * kf_.X_hat().block<2, 1>(kLeftError, 0);
292 return voltage_error;
293}
294
295void DrivetrainFilters::UpdateObserver(Eigen::Matrix<double, 2, 1> U) {
296 last_last_voltage_ = last_voltage_;
297
298 kf_.UpdateObserver(last_voltage_, dt_config_.dt);
299
300 last_voltage_ = U;
301}
302
303int DrivetrainFilters::ControllerIndexFromGears() const {
304 if (MaybeHigh(left_gear_)) {
305 if (MaybeHigh(right_gear_)) {
306 return 3;
307 } else {
308 return 2;
309 }
310 } else {
311 if (MaybeHigh(right_gear_)) {
312 return 1;
313 } else {
314 return 0;
James Kuszmaul891f4f12020-10-31 17:13:23 -0700315 }
Austin Schuh6613a072016-01-06 19:54:48 -0800316 }
Austin Schuhfb0f35c2021-02-14 21:25:29 -0800317}
318flatbuffers::Offset<GearLogging> DrivetrainFilters::CreateGearLogging(
319 flatbuffers::FlatBufferBuilder *fbb) const {
320 GearLogging::Builder gear_logging_builder(*fbb);
321 gear_logging_builder.add_left_state(static_cast<uint32_t>(left_gear_));
322 gear_logging_builder.add_right_state(static_cast<uint32_t>(right_gear_));
323 gear_logging_builder.add_left_loop_high(MaybeHigh(left_gear_));
324 gear_logging_builder.add_right_loop_high(MaybeHigh(right_gear_));
325 gear_logging_builder.add_controller_index(ControllerIndexFromGears());
326 return gear_logging_builder.Finish();
327}
Austin Schuh6613a072016-01-06 19:54:48 -0800328
Austin Schuhfb0f35c2021-02-14 21:25:29 -0800329Gear DrivetrainFilters::ComputeGear(
330 double shifter_position, const constants::ShifterHallEffect &shifter_config,
331 bool high_requested) const {
332 if (shifter_position < shifter_config.clear_low) {
333 return Gear::LOW;
334 } else if (shifter_position > shifter_config.clear_high) {
335 return Gear::HIGH;
336 } else {
337 if (high_requested) {
338 return Gear::SHIFTING_UP;
339 } else {
340 return Gear::SHIFTING_DOWN;
341 }
342 }
343}
344
345DrivetrainLoop::DrivetrainLoop(const DrivetrainConfig<double> &dt_config,
346 ::aos::EventLoop *event_loop,
347 LocalizerInterface *localizer,
348 const ::std::string &name)
James Kuszmaul61750662021-06-21 21:32:33 -0700349 : frc971::controls::ControlLoop<Goal, Position, Status, Output>(event_loop,
350 name),
Austin Schuhfb0f35c2021-02-14 21:25:29 -0800351 dt_config_(dt_config),
352 filters_(dt_config, event_loop, localizer),
353 dt_openloop_(dt_config_, filters_.kf()),
354 dt_closedloop_(dt_config_, filters_.kf(), localizer),
355 dt_spline_(dt_config_),
356 dt_line_follow_(dt_config_, localizer->target_selector()) {
357 event_loop->SetRuntimeRealtimePriority(30);
James Kuszmaul75a18c52021-03-10 22:02:07 -0800358 for (size_t ii = 0; ii < trajectory_fetchers_.size(); ++ii) {
359 trajectory_fetchers_[ii].fetcher =
360 event_loop->MakeFetcher<fb::Trajectory>("/drivetrain");
361 }
362}
363
364void DrivetrainLoop::UpdateTrajectoryFetchers() {
James Kuszmaul99af8b52021-03-28 10:50:15 -0700365 if (dt_spline_.trajectory_count() >= trajectory_fetchers_.size()) {
366 aos::monotonic_clock::time_point min_time = aos::monotonic_clock::max_time;
367 size_t min_fetcher_index = 0;
368 size_t fetcher_index = 0;
369 // Find the oldest spline to forget.
370 for (auto &fetcher : trajectory_fetchers_) {
371 CHECK_NE(fetcher.fetcher.context().monotonic_event_time,
372 monotonic_clock::min_time);
373 if (fetcher.fetcher.context().monotonic_event_time < min_time &&
374 !dt_spline_.IsCurrentTrajectory(fetcher.fetcher.get())) {
375 min_time = fetcher.fetcher.context().monotonic_event_time;
376 min_fetcher_index = fetcher_index;
377 }
378 ++fetcher_index;
379 }
380
381 dt_spline_.DeleteTrajectory(
382 trajectory_fetchers_[min_fetcher_index].fetcher.get());
383 trajectory_fetchers_[min_fetcher_index].in_use = false;
384 }
385
James Kuszmaul75a18c52021-03-10 22:02:07 -0800386 for (auto &fetcher : trajectory_fetchers_) {
387 const fb::Trajectory *trajectory = fetcher.fetcher.get();
388 // If the current fetcher is already being used by the SplineDrivetrain,
389 // don't touch it.
390 // We have to check both in_use and HasTrajectory because if
391 // in_use is true and HasTrajectory() is false, that implies that the
392 // SplineDrivetrain has finished executing the trajectory and disposed of
393 // it; if in_use is false and HasTrajectory() is true, that implies that
394 // this fetcher is at the same point in the queue as another fetcher, and
395 // that the other fetcher is the one that we are using to keep the message
396 // pinned.
397 // TODO(james): Consider garbage-collecting splines once we run out of
398 // fetchers.
399 if (fetcher.in_use && dt_spline_.HasTrajectory(trajectory)) {
400 continue;
401 }
402 fetcher.in_use = false;
403 // Go through and find the next Trajectory that isn't already held by the
404 // SplineDrivetrain, and add it.
405 while (fetcher.fetcher.FetchNext()) {
406 trajectory = fetcher.fetcher.get();
407 if (!dt_spline_.HasTrajectory(trajectory)) {
408 fetcher.in_use = true;
409 dt_spline_.AddTrajectory(trajectory);
410 break;
411 }
412 }
413 }
Austin Schuhfb0f35c2021-02-14 21:25:29 -0800414}
415
416void DrivetrainLoop::RunIteration(
417 const drivetrain::Goal *goal, const drivetrain::Position *position,
418 aos::Sender<drivetrain::Output>::Builder *output,
419 aos::Sender<drivetrain::Status>::Builder *status) {
420 const monotonic_clock::time_point monotonic_now =
421 event_loop()->monotonic_now();
422
423 if (!has_been_enabled_ && output) {
424 has_been_enabled_ = true;
425 }
426
427 if (WasReset()) {
428 filters_.Reset(monotonic_now, position);
429 }
430
James Kuszmaul75a18c52021-03-10 22:02:07 -0800431 UpdateTrajectoryFetchers();
432
Austin Schuhfb0f35c2021-02-14 21:25:29 -0800433 filters_.Correct(monotonic_now, position);
434
435 // Set the gear-logging parts of the status
436 CHECK(status);
437 flatbuffers::Offset<GearLogging> gear_logging_offset =
438 filters_.CreateGearLogging(status->fbb());
439
440 dt_openloop_.SetPosition(position, filters_.left_gear(),
441 filters_.right_gear());
Austin Schuh093535c2016-03-05 23:21:00 -0800442
Austin Schuh872723c2019-12-25 14:38:09 -0800443 ControllerType controller_type = ControllerType::POLYDRIVE;
Brian Silverman17f503e2015-08-02 18:17:18 -0700444 if (goal) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700445 controller_type = goal->controller_type();
Brian Silverman17f503e2015-08-02 18:17:18 -0700446
Alex Perrycb7da4b2019-08-28 19:35:56 -0700447 dt_closedloop_.SetGoal(goal);
448 dt_openloop_.SetGoal(goal->wheel(), goal->throttle(), goal->quickturn(),
449 goal->highgear());
450 dt_spline_.SetGoal(goal);
451 dt_line_follow_.SetGoal(monotonic_now, goal);
Brian Silverman17f503e2015-08-02 18:17:18 -0700452 }
453
Alex Perrycb7da4b2019-08-28 19:35:56 -0700454 dt_openloop_.Update(robot_state().voltage_battery());
Brian Silverman17f503e2015-08-02 18:17:18 -0700455
Alex Perrycb7da4b2019-08-28 19:35:56 -0700456 dt_closedloop_.Update(output != nullptr &&
Austin Schuh872723c2019-12-25 14:38:09 -0800457 controller_type == ControllerType::MOTION_PROFILE);
Austin Schuh78379ea2019-01-04 20:39:45 -0800458
James Kuszmaule39cbcf2019-02-27 20:48:34 -0800459 const Eigen::Matrix<double, 5, 1> trajectory_state =
Austin Schuhfb0f35c2021-02-14 21:25:29 -0800460 filters_.trajectory_state();
James Kuszmaule39cbcf2019-02-27 20:48:34 -0800461
James Kuszmaul897ef1a2020-10-25 17:51:10 -0700462 {
463 // TODO(james): The regular Kalman Filter's voltage error terms are
464 // currently unusable--either don't use voltage error at all for the spline
465 // following code, or use the EKF's voltage error estimates.
466 const Eigen::Matrix<double, 2, 1> voltage_error =
Austin Schuhfb0f35c2021-02-14 21:25:29 -0800467 0 * filters_.VoltageError();
James Kuszmaul897ef1a2020-10-25 17:51:10 -0700468 dt_spline_.Update(
469 output != nullptr && controller_type == ControllerType::SPLINE_FOLLOWER,
470 trajectory_state, voltage_error);
471 }
James Kuszmaule39cbcf2019-02-27 20:48:34 -0800472
James Kuszmaul38e79642019-03-09 15:48:27 -0800473 dt_line_follow_.Update(monotonic_now, trajectory_state);
Alex Perrya71badb2019-02-06 19:40:41 -0800474
Alex Perrycb7da4b2019-08-28 19:35:56 -0700475 OutputT output_struct;
476
Austin Schuh78379ea2019-01-04 20:39:45 -0800477 switch (controller_type) {
Austin Schuh872723c2019-12-25 14:38:09 -0800478 case ControllerType::POLYDRIVE:
Alex Perrycb7da4b2019-08-28 19:35:56 -0700479 dt_openloop_.SetOutput(output != nullptr ? &output_struct : nullptr);
Austin Schuh78379ea2019-01-04 20:39:45 -0800480 break;
Austin Schuh872723c2019-12-25 14:38:09 -0800481 case ControllerType::MOTION_PROFILE:
Alex Perrycb7da4b2019-08-28 19:35:56 -0700482 dt_closedloop_.SetOutput(output != nullptr ? &output_struct : nullptr);
Austin Schuh78379ea2019-01-04 20:39:45 -0800483 break;
Austin Schuh872723c2019-12-25 14:38:09 -0800484 case ControllerType::SPLINE_FOLLOWER:
Alex Perrycb7da4b2019-08-28 19:35:56 -0700485 dt_spline_.SetOutput(output != nullptr ? &output_struct : nullptr);
Alex Perry731b4602019-02-02 22:13:01 -0800486 break;
Austin Schuh872723c2019-12-25 14:38:09 -0800487 case ControllerType::LINE_FOLLOWER:
Alex Perrycb7da4b2019-08-28 19:35:56 -0700488 if (!dt_line_follow_.SetOutput(output != nullptr ? &output_struct
489 : nullptr)) {
James Kuszmaul5bc6fc92019-03-01 21:50:06 -0800490 // If the line follow drivetrain was unable to execute (generally due to
491 // not having a target), execute the regular teleop drivetrain.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700492 dt_openloop_.SetOutput(output != nullptr ? &output_struct : nullptr);
James Kuszmaul5bc6fc92019-03-01 21:50:06 -0800493 }
James Kuszmaule39cbcf2019-02-27 20:48:34 -0800494 break;
Brian Silverman17f503e2015-08-02 18:17:18 -0700495 }
496
Austin Schuh093535c2016-03-05 23:21:00 -0800497 // The output should now contain the shift request.
498
Brian Silverman17f503e2015-08-02 18:17:18 -0700499 // set the output status of the control loop state
500 if (status) {
Austin Schuh093535c2016-03-05 23:21:00 -0800501 Eigen::Matrix<double, 2, 1> linear =
Austin Schuhfb0f35c2021-02-14 21:25:29 -0800502 dt_config_.LeftRightToLinear(filters_.DrivetrainXHat());
Austin Schuh093535c2016-03-05 23:21:00 -0800503 Eigen::Matrix<double, 2, 1> angular =
Austin Schuhfb0f35c2021-02-14 21:25:29 -0800504 dt_config_.LeftRightToAngular(filters_.DrivetrainXHat());
Austin Schuh093535c2016-03-05 23:21:00 -0800505
Austin Schuhfb0f35c2021-02-14 21:25:29 -0800506 angular(0, 0) = filters_.localizer_theta();
Austin Schuh093535c2016-03-05 23:21:00 -0800507
508 Eigen::Matrix<double, 4, 1> gyro_left_right =
Austin Schuhd91c0d22016-10-15 21:24:28 -0700509 dt_config_.AngularLinearToLeftRight(linear, angular);
Austin Schuh093535c2016-03-05 23:21:00 -0800510
Alex Perrycb7da4b2019-08-28 19:35:56 -0700511 const flatbuffers::Offset<CIMLogging> cim_logging_offset =
James Kuszmaulaf5dfad2020-01-03 20:02:54 -0800512 dt_openloop_.PopulateShiftingStatus(status->fbb());
513
514 const flatbuffers::Offset<PolyDriveLogging> poly_drive_logging_offset =
Alex Perrycb7da4b2019-08-28 19:35:56 -0700515 dt_openloop_.PopulateStatus(status->fbb());
Austin Schuh093535c2016-03-05 23:21:00 -0800516
James Kuszmaul3e1bb272020-01-17 18:38:19 -0800517 const flatbuffers::Offset<DownEstimatorState> down_estimator_state_offset =
Austin Schuhfb0f35c2021-02-14 21:25:29 -0800518 filters_.PopulateDownEstimatorState(status->fbb(), monotonic_now);
James Kuszmaul2215d922020-02-11 17:17:26 -0800519
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800520 const flatbuffers::Offset<LocalizerState> localizer_offset =
Austin Schuhfb0f35c2021-02-14 21:25:29 -0800521 filters_.PopulateLocalizerState(status->fbb());
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800522
James Kuszmaul2215d922020-02-11 17:17:26 -0800523 const flatbuffers::Offset<ImuZeroerState> zeroer_offset =
Austin Schuhfb0f35c2021-02-14 21:25:29 -0800524 filters_.PopulateImuZeroerState(status->fbb());
James Kuszmaul3e1bb272020-01-17 18:38:19 -0800525
Alex Perrycb7da4b2019-08-28 19:35:56 -0700526 flatbuffers::Offset<LineFollowLogging> line_follow_logging_offset =
527 dt_line_follow_.PopulateStatus(status);
528 flatbuffers::Offset<TrajectoryLogging> trajectory_logging_offset =
529 dt_spline_.MakeTrajectoryLogging(status);
Austin Schuh093535c2016-03-05 23:21:00 -0800530
Austin Schuhfb0f35c2021-02-14 21:25:29 -0800531 Status::Builder builder = status->MakeBuilder<Status>();
Austin Schuh3a378462019-01-04 21:48:04 -0800532
Alex Perrycb7da4b2019-08-28 19:35:56 -0700533 dt_closedloop_.PopulateStatus(&builder);
Austin Schuh3a378462019-01-04 21:48:04 -0800534
Austin Schuh95771d92021-01-23 14:42:25 -0800535 builder.add_estimated_left_position(gyro_left_right(kLeftPosition));
536 builder.add_estimated_right_position(gyro_left_right(kRightPosition));
Austin Schuh41565602016-02-28 20:10:49 -0800537
Austin Schuh95771d92021-01-23 14:42:25 -0800538 builder.add_estimated_left_velocity(gyro_left_right(kLeftVelocity));
539 builder.add_estimated_right_velocity(gyro_left_right(kRightVelocity));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700540
541 if (dt_spline_.enable()) {
542 dt_spline_.PopulateStatus(&builder);
543 } else {
Austin Schuhfb0f35c2021-02-14 21:25:29 -0800544 builder.add_robot_speed((filters_.DrivetrainXHat(kLeftVelocity) +
545 filters_.DrivetrainXHat(kRightVelocity)) /
546 2.0);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700547 builder.add_output_was_capped(dt_closedloop_.output_was_capped());
Austin Schuhfb0f35c2021-02-14 21:25:29 -0800548 builder.add_uncapped_left_voltage(
549 filters_.DrivetrainUUncapped(kLeftVoltage));
550 builder.add_uncapped_right_voltage(
551 filters_.DrivetrainUUncapped(kRightVoltage));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700552 }
553
Austin Schuhfb0f35c2021-02-14 21:25:29 -0800554 builder.add_left_voltage_error(filters_.DrivetrainXHat(kLeftError));
555 builder.add_right_voltage_error(filters_.DrivetrainXHat(kRightError));
556 builder.add_estimated_angular_velocity_error(
557 filters_.DrivetrainXHat(kAngularError));
558 builder.add_estimated_heading(filters_.localizer_theta());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700559
Austin Schuhfb0f35c2021-02-14 21:25:29 -0800560 builder.add_x(filters_.x());
561 builder.add_y(filters_.y());
562 builder.add_theta(::aos::math::NormalizeAngle(filters_.localizer_theta()));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700563
Alex Perrycb7da4b2019-08-28 19:35:56 -0700564 builder.add_cim_logging(cim_logging_offset);
James Kuszmaulaf5dfad2020-01-03 20:02:54 -0800565 builder.add_poly_drive_logging(poly_drive_logging_offset);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700566 builder.add_gear_logging(gear_logging_offset);
567 builder.add_line_follow_logging(line_follow_logging_offset);
568 builder.add_trajectory_logging(trajectory_logging_offset);
James Kuszmaul3e1bb272020-01-17 18:38:19 -0800569 builder.add_down_estimator(down_estimator_state_offset);
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800570 builder.add_localizer(localizer_offset);
James Kuszmaul2215d922020-02-11 17:17:26 -0800571 builder.add_zeroing(zeroer_offset);
milind1f1dca32021-07-03 13:50:07 -0700572
573 builder.add_send_failures(status_failure_counter_.failures());
574
575 status_failure_counter_.Count(status->Send(builder.Finish()));
Brian Silverman17f503e2015-08-02 18:17:18 -0700576 }
Austin Schuh209f1702015-11-29 17:03:00 -0800577
James Kuszmaulddc69702021-03-24 21:55:03 -0700578 // If the filters aren't ready/valid, then disable all outputs (currently,
579 // this only happens if the IMU is faulted or has not zeroed).
580 // TODO(james): Add exceptions so that during competitive play the driver
581 // can retain minimal control of the robot.
582 if (!filters_.Ready()) {
583 output_struct.left_voltage = 0.0;
584 output_struct.right_voltage = 0.0;
585 }
586
Austin Schuh209f1702015-11-29 17:03:00 -0800587 double left_voltage = 0.0;
588 double right_voltage = 0.0;
589 if (output) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700590 left_voltage = output_struct.left_voltage;
591 right_voltage = output_struct.right_voltage;
Austin Schuhfb0f35c2021-02-14 21:25:29 -0800592 filters_.set_left_high_requested(output_struct.left_high);
593 filters_.set_right_high_requested(output_struct.right_high);
Austin Schuh209f1702015-11-29 17:03:00 -0800594 }
595
Alex Perrycb7da4b2019-08-28 19:35:56 -0700596 const double scalar = robot_state().voltage_battery() / 12.0;
Austin Schuh209f1702015-11-29 17:03:00 -0800597
598 left_voltage *= scalar;
599 right_voltage *= scalar;
600
Austin Schuh209f1702015-11-29 17:03:00 -0800601 // To validate, look at the following:
602
603 // Observed - dx/dt velocity for left, right.
604
605 // Angular velocity error compared to the gyro
606 // Gyro heading vs left-right
607 // Voltage error.
608
Austin Schuhfb0f35c2021-02-14 21:25:29 -0800609 {
610 Eigen::Matrix<double, 2, 1> U;
611 U(kLeftVoltage) = left_voltage;
612 U(kRightVoltage) = right_voltage;
613 filters_.UpdateObserver(U);
614 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700615
616 if (output) {
milind1f1dca32021-07-03 13:50:07 -0700617 output->CheckOk(output->Send(Output::Pack(*output->fbb(), &output_struct)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700618 }
Brian Silverman17f503e2015-08-02 18:17:18 -0700619}
620
Alex Perrycb7da4b2019-08-28 19:35:56 -0700621flatbuffers::Offset<Output> DrivetrainLoop::Zero(
622 aos::Sender<Output>::Builder *output) {
623 Output::Builder builder = output->MakeBuilder<Output>();
624 builder.add_left_voltage(0);
625 builder.add_right_voltage(0);
626 builder.add_left_high(dt_config_.default_high_gear);
627 builder.add_right_high(dt_config_.default_high_gear);
628 return builder.Finish();
Adam Snaiderbc918b62016-02-27 21:03:39 -0800629}
630
Austin Schuh6197a182015-11-28 16:04:40 -0800631} // namespace drivetrain
Brian Silverman17f503e2015-08-02 18:17:18 -0700632} // namespace control_loops
Comran Morshed5323ecb2015-12-26 20:50:55 +0000633} // namespace frc971