blob: 81f1d8de53c17f6d883c18f05c3a6d98255fba9e [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/drivetrain_config.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070013#include "frc971/control_loops/drivetrain/drivetrain_goal_generated.h"
14#include "frc971/control_loops/drivetrain/drivetrain_output_generated.h"
15#include "frc971/control_loops/drivetrain/drivetrain_position_generated.h"
16#include "frc971/control_loops/drivetrain/drivetrain_status_generated.h"
Comran Morshed5323ecb2015-12-26 20:50:55 +000017#include "frc971/control_loops/drivetrain/polydrivetrain.h"
18#include "frc971/control_loops/drivetrain/ssdrivetrain.h"
Austin Schuh3a378462019-01-04 21:48:04 -080019#include "frc971/control_loops/runge_kutta.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070020#include "frc971/queues/gyro_generated.h"
Brian Silverman17f503e2015-08-02 18:17:18 -070021#include "frc971/shifter_hall_effect.h"
Austin Schuhac17fba2020-03-28 15:55:33 -070022#include "frc971/wpilib/imu_batch_generated.h"
Brian Silverman17f503e2015-08-02 18:17:18 -070023
Austin Schuh9993fb32017-03-15 20:17:46 -070024using ::aos::monotonic_clock;
25namespace chrono = ::std::chrono;
Brian Silverman17f503e2015-08-02 18:17:18 -070026
Stephan Pleinesf63bde82024-01-13 15:59:33 -080027namespace frc971::control_loops::drivetrain {
Brian Silverman17f503e2015-08-02 18:17:18 -070028
James Kuszmaulc53de4a2022-03-12 21:32:06 -080029namespace {
30// Maximum variation to allow in the gyro when zeroing.
James Kuszmaul7aa33a92024-03-17 17:25:36 -070031constexpr double kMaxYawGyroZeroingRange = 0.15;
Austin Schuh8c76a9b2022-03-16 21:33:48 -070032} // namespace
James Kuszmaulc53de4a2022-03-12 21:32:06 -080033
Austin Schuhfb0f35c2021-02-14 21:25:29 -080034DrivetrainFilters::DrivetrainFilters(const DrivetrainConfig<double> &dt_config,
35 ::aos::EventLoop *event_loop,
36 LocalizerInterface *localizer)
37 : dt_config_(dt_config),
Alex Perrycb7da4b2019-08-28 19:35:56 -070038 localizer_control_fetcher_(
39 event_loop->MakeFetcher<LocalizerControl>("/drivetrain")),
Austin Schuh73b6e3b2019-05-27 16:37:15 -070040 imu_values_fetcher_(
James Kuszmaule5f67dd2022-02-12 20:08:29 -080041 event_loop->TryMakeFetcher<::frc971::IMUValuesBatch>("/drivetrain")),
Austin Schuh1ea89bb2019-05-27 16:59:59 -070042 gyro_reading_fetcher_(
43 event_loop->MakeFetcher<::frc971::sensors::GyroReading>(
Alex Perrycb7da4b2019-08-28 19:35:56 -070044 "/drivetrain")),
Austin Schuhfb0f35c2021-02-14 21:25:29 -080045 down_estimator_(dt_config_),
James Kuszmaul3431d622019-02-17 17:07:44 -080046 localizer_(localizer),
Austin Schuh41565602016-02-28 20:10:49 -080047 kf_(dt_config_.make_kf_drivetrain_loop()),
Austin Schuh093535c2016-03-05 23:21:00 -080048 left_gear_(dt_config_.default_high_gear ? Gear::HIGH : Gear::LOW),
49 right_gear_(dt_config_.default_high_gear ? Gear::HIGH : Gear::LOW),
50 left_high_requested_(dt_config_.default_high_gear),
51 right_high_requested_(dt_config_.default_high_gear) {
Austin Schuhfb0f35c2021-02-14 21:25:29 -080052 last_voltage_.setZero();
53 last_last_voltage_.setZero();
James Kuszmaul61750662021-06-21 21:32:33 -070054 frc971::controls::HPolytope<0>::Init();
James Kuszmaul30aca502020-01-19 15:05:33 -080055 event_loop->OnRun([this]() {
56 // On the first fetch, make sure that we are caught all the way up to the
57 // present.
James Kuszmaule5f67dd2022-02-12 20:08:29 -080058 if (imu_values_fetcher_.valid()) {
59 imu_values_fetcher_.Fetch();
60 }
James Kuszmaul30aca502020-01-19 15:05:33 -080061 });
James Kuszmaul2215d922020-02-11 17:17:26 -080062 if (dt_config.is_simulated) {
63 down_estimator_.assume_perfect_gravity();
64 }
Austin Schuh209f1702015-11-29 17:03:00 -080065}
66
Austin Schuhfb0f35c2021-02-14 21:25:29 -080067flatbuffers::Offset<LocalizerState> DrivetrainFilters::PopulateLocalizerState(
68 flatbuffers::FlatBufferBuilder *fbb) {
69 return localizer_->PopulateStatus(fbb);
70}
71flatbuffers::Offset<ImuZeroerState> DrivetrainFilters::PopulateImuZeroerState(
72 flatbuffers::FlatBufferBuilder *fbb) {
73 return imu_zeroer_.PopulateStatus(fbb);
Austin Schuh093535c2016-03-05 23:21:00 -080074}
75
Austin Schuhfb0f35c2021-02-14 21:25:29 -080076flatbuffers::Offset<DownEstimatorState>
77DrivetrainFilters::PopulateDownEstimatorState(
78 flatbuffers::FlatBufferBuilder *fbb,
79 aos::monotonic_clock::time_point monotonic_now) {
80 return down_estimator_.PopulateStatus(fbb, monotonic_now);
Austin Schuh093535c2016-03-05 23:21:00 -080081}
82
Austin Schuhfb0f35c2021-02-14 21:25:29 -080083void DrivetrainFilters::Reset(aos::monotonic_clock::time_point monotonic_now,
84 const drivetrain::Position *position) {
85 // If all the sensors got reset (e.g., due to wpilib_interface restarting),
86 // reset the localizer and down estimator to avoid weird jumps in the
87 // filters.
88 down_estimator_.Reset();
89 // Just reset the localizer to the current state, except for the encoders.
90 LocalizerInterface::Ekf::State X_hat = localizer_->Xhat();
91 X_hat(LocalizerInterface::StateIdx::kLeftEncoder) = position->left_encoder();
92 X_hat(LocalizerInterface::StateIdx::kRightEncoder) =
93 position->right_encoder();
94 localizer_->Reset(monotonic_now, X_hat);
95}
Austin Schuh9993fb32017-03-15 20:17:46 -070096
Austin Schuhfb0f35c2021-02-14 21:25:29 -080097void DrivetrainFilters::Correct(aos::monotonic_clock::time_point monotonic_now,
98 const drivetrain::Position *position) {
Austin Schuh093535c2016-03-05 23:21:00 -080099 // TODO(austin): Put gear detection logic here.
100 switch (dt_config_.shifter_type) {
James Kuszmaul68025332024-01-20 17:06:02 -0800101 case ShifterType::kSimpleShifter:
Austin Schuh093535c2016-03-05 23:21:00 -0800102 // Force the right controller for simple shifters since we assume that
103 // gear switching is instantaneous.
104 if (left_high_requested_) {
105 left_gear_ = Gear::HIGH;
106 } else {
107 left_gear_ = Gear::LOW;
108 }
109 if (right_high_requested_) {
110 right_gear_ = Gear::HIGH;
111 } else {
112 right_gear_ = Gear::LOW;
113 }
114 break;
James Kuszmaul68025332024-01-20 17:06:02 -0800115 case ShifterType::kHallEffectShifter:
Alex Perrycb7da4b2019-08-28 19:35:56 -0700116 left_gear_ = ComputeGear(position->left_shifter_position(),
Austin Schuh093535c2016-03-05 23:21:00 -0800117 dt_config_.left_drive, left_high_requested_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700118 right_gear_ = ComputeGear(position->right_shifter_position(),
Austin Schuh093535c2016-03-05 23:21:00 -0800119 dt_config_.right_drive, right_high_requested_);
120 break;
James Kuszmaul68025332024-01-20 17:06:02 -0800121 case ShifterType::kNoShifter:
Adam Snaider18f44172016-10-22 15:30:21 -0700122 break;
Brian Silverman17f503e2015-08-02 18:17:18 -0700123 }
Brian Silverman17f503e2015-08-02 18:17:18 -0700124
James Kuszmaule5f67dd2022-02-12 20:08:29 -0800125 while (imu_values_fetcher_.valid() && imu_values_fetcher_.FetchNext()) {
Austin Schuhac17fba2020-03-28 15:55:33 -0700126 CHECK(imu_values_fetcher_->has_readings());
James Kuszmaul3e1bb272020-01-17 18:38:19 -0800127 last_gyro_time_ = monotonic_now;
Austin Schuhac17fba2020-03-28 15:55:33 -0700128 for (const IMUValues *value : *imu_values_fetcher_->readings()) {
129 imu_zeroer_.InsertMeasurement(*value);
130 if (!imu_zeroer_.Zeroed()) {
131 continue;
132 }
133 const aos::monotonic_clock::time_point reading_time(
134 std::chrono::nanoseconds(value->monotonic_timestamp_ns()));
135 if (last_imu_update_ == aos::monotonic_clock::min_time) {
136 last_imu_update_ = reading_time;
137 }
James Kuszmaul6d6e1302022-03-12 15:22:48 -0800138 down_estimator_.Predict(imu_zeroer_.ZeroedGyro().value(),
139 imu_zeroer_.ZeroedAccel().value(),
Austin Schuhac17fba2020-03-28 15:55:33 -0700140 reading_time - last_imu_update_);
James Kuszmaul3e1bb272020-01-17 18:38:19 -0800141 last_imu_update_ = reading_time;
142 }
James Kuszmaul3e1bb272020-01-17 18:38:19 -0800143 }
Diana Burgessd0180f12018-03-21 21:24:17 -0700144
James Kuszmaul3e1bb272020-01-17 18:38:19 -0800145 bool got_imu_reading = false;
James Kuszmaule5f67dd2022-02-12 20:08:29 -0800146 if (imu_values_fetcher_.valid() && imu_values_fetcher_.get() != nullptr) {
James Kuszmaulb7f45bb2020-02-26 20:27:48 -0800147 imu_zeroer_.ProcessMeasurements();
James Kuszmaul3e1bb272020-01-17 18:38:19 -0800148 got_imu_reading = true;
Austin Schuhac17fba2020-03-28 15:55:33 -0700149 CHECK(imu_values_fetcher_->has_readings());
James Kuszmaul0a981402021-10-09 21:00:34 -0700150 if (imu_values_fetcher_->readings()->size() > 0) {
151 const IMUValues *value = imu_values_fetcher_->readings()->Get(
152 imu_values_fetcher_->readings()->size() - 1);
153 switch (dt_config_.imu_type) {
James Kuszmaul68025332024-01-20 17:06:02 -0800154 case ImuType::kImuX:
James Kuszmaul0a981402021-10-09 21:00:34 -0700155 last_accel_ = -value->accelerometer_x();
156 break;
James Kuszmaul68025332024-01-20 17:06:02 -0800157 case ImuType::kImuFlippedX:
James Kuszmaul0a981402021-10-09 21:00:34 -0700158 last_accel_ = value->accelerometer_x();
159 break;
James Kuszmaul68025332024-01-20 17:06:02 -0800160 case ImuType::kImuY:
James Kuszmaul0a981402021-10-09 21:00:34 -0700161 last_accel_ = -value->accelerometer_y();
162 break;
James Kuszmaul68025332024-01-20 17:06:02 -0800163 case ImuType::kImuZ:
James Kuszmaul0a981402021-10-09 21:00:34 -0700164 last_accel_ = value->accelerometer_z();
165 break;
166 }
Diana Burgessd0180f12018-03-21 21:24:17 -0700167 }
Austin Schuh05c5a612016-04-02 15:10:25 -0700168 }
Austin Schuh05c5a612016-04-02 15:10:25 -0700169
Austin Schuh093535c2016-03-05 23:21:00 -0800170 // TODO(austin): Signal the current gear to both loops.
James Kuszmaul6d6e1302022-03-12 15:22:48 -0800171 bool imu_zeroer_zeroed = imu_zeroer_.Zeroed();
Austin Schuh093535c2016-03-05 23:21:00 -0800172
Campbell Crowley2527ed22017-02-17 21:10:02 -0800173 switch (dt_config_.gyro_type) {
James Kuszmaul68025332024-01-20 17:06:02 -0800174 case GyroType::kImuXGyro:
James Kuszmaul3e1bb272020-01-17 18:38:19 -0800175 if (got_imu_reading) {
James Kuszmaul6d6e1302022-03-12 15:22:48 -0800176 last_gyro_rate_ =
177 imu_zeroer_zeroed ? imu_zeroer_.ZeroedGyro().value().x() : 0.0;
Campbell Crowley2527ed22017-02-17 21:10:02 -0800178 }
179 break;
James Kuszmaul68025332024-01-20 17:06:02 -0800180 case GyroType::kImuYGyro:
James Kuszmaul3e1bb272020-01-17 18:38:19 -0800181 if (got_imu_reading) {
James Kuszmaul6d6e1302022-03-12 15:22:48 -0800182 last_gyro_rate_ =
183 imu_zeroer_zeroed ? imu_zeroer_.ZeroedGyro().value().y() : 0.0;
Campbell Crowley2527ed22017-02-17 21:10:02 -0800184 }
185 break;
James Kuszmaul68025332024-01-20 17:06:02 -0800186 case GyroType::kImuZGyro:
James Kuszmaul3e1bb272020-01-17 18:38:19 -0800187 if (got_imu_reading) {
James Kuszmaul6d6e1302022-03-12 15:22:48 -0800188 last_gyro_rate_ =
189 imu_zeroer_zeroed ? imu_zeroer_.ZeroedGyro().value().z() : 0.0;
Campbell Crowley2527ed22017-02-17 21:10:02 -0800190 }
191 break;
James Kuszmaul68025332024-01-20 17:06:02 -0800192 case GyroType::kFlippedImuZGyro:
James Kuszmaul3e1bb272020-01-17 18:38:19 -0800193 if (got_imu_reading) {
James Kuszmaul6d6e1302022-03-12 15:22:48 -0800194 last_gyro_rate_ =
195 imu_zeroer_zeroed ? -imu_zeroer_.ZeroedGyro().value().z() : 0.0;
Austin Schuh90b43b42019-01-04 07:45:05 +1100196 }
197 break;
James Kuszmaul68025332024-01-20 17:06:02 -0800198 case GyroType::kSpartanGyro:
Austin Schuh1ea89bb2019-05-27 16:59:59 -0700199 if (gyro_reading_fetcher_.Fetch()) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700200 last_gyro_rate_ = gyro_reading_fetcher_->velocity();
Austin Schuh9993fb32017-03-15 20:17:46 -0700201 last_gyro_time_ = monotonic_now;
Campbell Crowley2527ed22017-02-17 21:10:02 -0800202 }
203 break;
James Kuszmaul68025332024-01-20 17:06:02 -0800204 case GyroType::kFlippedSpartanGyro:
Austin Schuh1ea89bb2019-05-27 16:59:59 -0700205 if (gyro_reading_fetcher_.Fetch()) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700206 last_gyro_rate_ = -gyro_reading_fetcher_->velocity();
Austin Schuh9993fb32017-03-15 20:17:46 -0700207 last_gyro_time_ = monotonic_now;
Campbell Crowley2527ed22017-02-17 21:10:02 -0800208 }
209 break;
210 default:
Austin Schuhf257f3c2019-10-27 21:00:43 -0700211 AOS_LOG(FATAL, "invalid gyro configured");
Campbell Crowley2527ed22017-02-17 21:10:02 -0800212 break;
Austin Schuh9ab4d9d2016-02-16 23:55:44 -0800213 }
214
James Kuszmaulc53de4a2022-03-12 21:32:06 -0800215 switch (dt_config_.gyro_type) {
James Kuszmaul68025332024-01-20 17:06:02 -0800216 case GyroType::kSpartanGyro:
217 case GyroType::kFlippedSpartanGyro:
James Kuszmaulc53de4a2022-03-12 21:32:06 -0800218 if (!yaw_gyro_zero_.has_value()) {
219 yaw_gyro_zeroer_.AddData(last_gyro_rate_);
Philipp Schrader790cb542023-07-05 21:06:52 -0700220 if (yaw_gyro_zeroer_.full() &&
221 yaw_gyro_zeroer_.GetRange() < kMaxYawGyroZeroingRange) {
James Kuszmaulc53de4a2022-03-12 21:32:06 -0800222 yaw_gyro_zero_ = yaw_gyro_zeroer_.GetAverage()(0);
Austin Schuh8c76a9b2022-03-16 21:33:48 -0700223 VLOG(1) << "Zeroed to " << *yaw_gyro_zero_ << " Range "
224 << yaw_gyro_zeroer_.GetRange();
James Kuszmaulc53de4a2022-03-12 21:32:06 -0800225 }
226 }
227 ready_ = yaw_gyro_zero_.has_value();
228 if (ready_) {
229 last_gyro_rate_ = last_gyro_rate_ - yaw_gyro_zero_.value();
230 }
231 break;
James Kuszmaul68025332024-01-20 17:06:02 -0800232 case GyroType::kImuXGyro:
233 case GyroType::kImuYGyro:
234 case GyroType::kImuZGyro:
235 case GyroType::kFlippedImuZGyro:
James Kuszmaulc53de4a2022-03-12 21:32:06 -0800236 ready_ = imu_zeroer_.Zeroed();
237 break;
238 }
James Kuszmaulddc69702021-03-24 21:55:03 -0700239
240 // TODO(james): How aggressively can we fault here? If we fault to
241 // aggressively, we might have issues during startup if wpilib_interface takes
242 // too long to start publishing IMU measurements.
Austin Schuh9993fb32017-03-15 20:17:46 -0700243 if (monotonic_now > last_gyro_time_ + chrono::milliseconds(20)) {
244 last_gyro_rate_ = 0.0;
245 }
246
James Kuszmaul1798c072022-02-13 15:32:11 -0800247 if (imu_values_fetcher_.valid()) {
248 localizer_->Update(
249 {last_last_voltage_(kLeftVoltage), last_last_voltage_(kRightVoltage)},
250 monotonic_now, position->left_encoder(), position->right_encoder(),
251 down_estimator_.avg_recent_yaw_rates(),
252 down_estimator_.avg_recent_accel());
253 } else {
254 localizer_->Update(
255 {last_last_voltage_(kLeftVoltage), last_last_voltage_(kRightVoltage)},
256 monotonic_now, position->left_encoder(), position->right_encoder(),
257 last_gyro_rate_, Eigen::Vector3d::Zero());
258 }
Austin Schuhfb0f35c2021-02-14 21:25:29 -0800259
260 // If we get a new message setting the absolute position, then reset the
261 // localizer.
262 if (localizer_control_fetcher_.Fetch()) {
263 VLOG(1) << "localizer_control "
264 << aos::FlatbufferToJson(localizer_control_fetcher_.get());
265 localizer_->ResetPosition(
266 monotonic_now, localizer_control_fetcher_->x(),
267 localizer_control_fetcher_->y(), localizer_control_fetcher_->theta(),
268 localizer_control_fetcher_->theta_uncertainty(),
269 !localizer_control_fetcher_->keep_current_theta());
270 }
271
272 kf_.set_index(ControllerIndexFromGears());
273
Austin Schuh6613a072016-01-06 19:54:48 -0800274 {
Diana Burgessd0180f12018-03-21 21:24:17 -0700275 Eigen::Matrix<double, 4, 1> Y;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700276 Y << position->left_encoder(), position->right_encoder(), last_gyro_rate_,
Diana Burgessd0180f12018-03-21 21:24:17 -0700277 last_accel_;
Austin Schuh6613a072016-01-06 19:54:48 -0800278 kf_.Correct(Y);
Austin Schuhfb0f35c2021-02-14 21:25:29 -0800279 }
280}
281
282Eigen::Matrix<double, 2, 1> DrivetrainFilters::VoltageError() const {
283 static_assert(kLeftError + 1 == kRightError);
284 Eigen::Matrix<double, 2, 2> error_K;
285 error_K << kf_.controller().K(kLeftVoltage, kLeftError), 0.0, 0.0,
286 kf_.controller().K(kRightVoltage, kRightError);
287 const Eigen::Matrix<double, 2, 1> voltage_error =
288 error_K * kf_.X_hat().block<2, 1>(kLeftError, 0);
289 return voltage_error;
290}
291
292void DrivetrainFilters::UpdateObserver(Eigen::Matrix<double, 2, 1> U) {
293 last_last_voltage_ = last_voltage_;
294
295 kf_.UpdateObserver(last_voltage_, dt_config_.dt);
296
297 last_voltage_ = U;
298}
299
300int DrivetrainFilters::ControllerIndexFromGears() const {
301 if (MaybeHigh(left_gear_)) {
302 if (MaybeHigh(right_gear_)) {
303 return 3;
304 } else {
305 return 2;
306 }
307 } else {
308 if (MaybeHigh(right_gear_)) {
309 return 1;
310 } else {
311 return 0;
James Kuszmaul891f4f12020-10-31 17:13:23 -0700312 }
Austin Schuh6613a072016-01-06 19:54:48 -0800313 }
Austin Schuhfb0f35c2021-02-14 21:25:29 -0800314}
315flatbuffers::Offset<GearLogging> DrivetrainFilters::CreateGearLogging(
316 flatbuffers::FlatBufferBuilder *fbb) const {
317 GearLogging::Builder gear_logging_builder(*fbb);
318 gear_logging_builder.add_left_state(static_cast<uint32_t>(left_gear_));
319 gear_logging_builder.add_right_state(static_cast<uint32_t>(right_gear_));
320 gear_logging_builder.add_left_loop_high(MaybeHigh(left_gear_));
321 gear_logging_builder.add_right_loop_high(MaybeHigh(right_gear_));
322 gear_logging_builder.add_controller_index(ControllerIndexFromGears());
323 return gear_logging_builder.Finish();
324}
Austin Schuh6613a072016-01-06 19:54:48 -0800325
Austin Schuhfb0f35c2021-02-14 21:25:29 -0800326Gear DrivetrainFilters::ComputeGear(
327 double shifter_position, const constants::ShifterHallEffect &shifter_config,
328 bool high_requested) const {
James Kuszmaul68025332024-01-20 17:06:02 -0800329 if (shifter_position < shifter_config.clear_low()) {
Austin Schuhfb0f35c2021-02-14 21:25:29 -0800330 return Gear::LOW;
James Kuszmaul68025332024-01-20 17:06:02 -0800331 } else if (shifter_position > shifter_config.clear_high()) {
Austin Schuhfb0f35c2021-02-14 21:25:29 -0800332 return Gear::HIGH;
333 } else {
334 if (high_requested) {
335 return Gear::SHIFTING_UP;
336 } else {
337 return Gear::SHIFTING_DOWN;
338 }
339 }
340}
341
342DrivetrainLoop::DrivetrainLoop(const DrivetrainConfig<double> &dt_config,
343 ::aos::EventLoop *event_loop,
344 LocalizerInterface *localizer,
345 const ::std::string &name)
James Kuszmaul61750662021-06-21 21:32:33 -0700346 : frc971::controls::ControlLoop<Goal, Position, Status, Output>(event_loop,
347 name),
Austin Schuhfb0f35c2021-02-14 21:25:29 -0800348 dt_config_(dt_config),
349 filters_(dt_config, event_loop, localizer),
350 dt_openloop_(dt_config_, filters_.kf()),
351 dt_closedloop_(dt_config_, filters_.kf(), localizer),
352 dt_spline_(dt_config_),
James Kuszmaulf6aa0382024-03-01 19:46:05 -0800353 dt_line_follow_(dt_config_, localizer->target_selector()),
354 localizer_input_sender_(
355 event_loop->TryMakeSender<
356 frc971::control_loops::drivetrain::RioLocalizerInputsStatic>(
357 "/drivetrain")) {
Austin Schuhed5ce8b2024-03-16 21:16:41 -0700358 event_loop->SetRuntimeRealtimePriority(37);
James Kuszmaul75a18c52021-03-10 22:02:07 -0800359 for (size_t ii = 0; ii < trajectory_fetchers_.size(); ++ii) {
360 trajectory_fetchers_[ii].fetcher =
361 event_loop->MakeFetcher<fb::Trajectory>("/drivetrain");
362 }
363}
364
365void DrivetrainLoop::UpdateTrajectoryFetchers() {
James Kuszmaul99af8b52021-03-28 10:50:15 -0700366 if (dt_spline_.trajectory_count() >= trajectory_fetchers_.size()) {
367 aos::monotonic_clock::time_point min_time = aos::monotonic_clock::max_time;
368 size_t min_fetcher_index = 0;
369 size_t fetcher_index = 0;
370 // Find the oldest spline to forget.
371 for (auto &fetcher : trajectory_fetchers_) {
372 CHECK_NE(fetcher.fetcher.context().monotonic_event_time,
373 monotonic_clock::min_time);
374 if (fetcher.fetcher.context().monotonic_event_time < min_time &&
375 !dt_spline_.IsCurrentTrajectory(fetcher.fetcher.get())) {
376 min_time = fetcher.fetcher.context().monotonic_event_time;
377 min_fetcher_index = fetcher_index;
378 }
379 ++fetcher_index;
380 }
381
382 dt_spline_.DeleteTrajectory(
383 trajectory_fetchers_[min_fetcher_index].fetcher.get());
384 trajectory_fetchers_[min_fetcher_index].in_use = false;
385 }
386
James Kuszmaul75a18c52021-03-10 22:02:07 -0800387 for (auto &fetcher : trajectory_fetchers_) {
388 const fb::Trajectory *trajectory = fetcher.fetcher.get();
389 // If the current fetcher is already being used by the SplineDrivetrain,
390 // don't touch it.
391 // We have to check both in_use and HasTrajectory because if
392 // in_use is true and HasTrajectory() is false, that implies that the
393 // SplineDrivetrain has finished executing the trajectory and disposed of
394 // it; if in_use is false and HasTrajectory() is true, that implies that
395 // this fetcher is at the same point in the queue as another fetcher, and
396 // that the other fetcher is the one that we are using to keep the message
397 // pinned.
398 // TODO(james): Consider garbage-collecting splines once we run out of
399 // fetchers.
400 if (fetcher.in_use && dt_spline_.HasTrajectory(trajectory)) {
401 continue;
402 }
403 fetcher.in_use = false;
404 // Go through and find the next Trajectory that isn't already held by the
405 // SplineDrivetrain, and add it.
406 while (fetcher.fetcher.FetchNext()) {
407 trajectory = fetcher.fetcher.get();
408 if (!dt_spline_.HasTrajectory(trajectory)) {
409 fetcher.in_use = true;
410 dt_spline_.AddTrajectory(trajectory);
411 break;
412 }
413 }
414 }
Austin Schuhfb0f35c2021-02-14 21:25:29 -0800415}
416
417void DrivetrainLoop::RunIteration(
418 const drivetrain::Goal *goal, const drivetrain::Position *position,
419 aos::Sender<drivetrain::Output>::Builder *output,
420 aos::Sender<drivetrain::Status>::Builder *status) {
421 const monotonic_clock::time_point monotonic_now =
422 event_loop()->monotonic_now();
423
424 if (!has_been_enabled_ && output) {
425 has_been_enabled_ = true;
426 }
427
428 if (WasReset()) {
429 filters_.Reset(monotonic_now, position);
430 }
431
James Kuszmaul75a18c52021-03-10 22:02:07 -0800432 UpdateTrajectoryFetchers();
433
Austin Schuhfb0f35c2021-02-14 21:25:29 -0800434 filters_.Correct(monotonic_now, position);
435
436 // Set the gear-logging parts of the status
437 CHECK(status);
438 flatbuffers::Offset<GearLogging> gear_logging_offset =
439 filters_.CreateGearLogging(status->fbb());
440
441 dt_openloop_.SetPosition(position, filters_.left_gear(),
442 filters_.right_gear());
Austin Schuh093535c2016-03-05 23:21:00 -0800443
Austin Schuh872723c2019-12-25 14:38:09 -0800444 ControllerType controller_type = ControllerType::POLYDRIVE;
Brian Silverman17f503e2015-08-02 18:17:18 -0700445 if (goal) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700446 controller_type = goal->controller_type();
Brian Silverman17f503e2015-08-02 18:17:18 -0700447
Alex Perrycb7da4b2019-08-28 19:35:56 -0700448 dt_closedloop_.SetGoal(goal);
449 dt_openloop_.SetGoal(goal->wheel(), goal->throttle(), goal->quickturn(),
450 goal->highgear());
451 dt_spline_.SetGoal(goal);
452 dt_line_follow_.SetGoal(monotonic_now, goal);
Brian Silverman17f503e2015-08-02 18:17:18 -0700453 }
454
Alex Perrycb7da4b2019-08-28 19:35:56 -0700455 dt_openloop_.Update(robot_state().voltage_battery());
Brian Silverman17f503e2015-08-02 18:17:18 -0700456
Alex Perrycb7da4b2019-08-28 19:35:56 -0700457 dt_closedloop_.Update(output != nullptr &&
Austin Schuh872723c2019-12-25 14:38:09 -0800458 controller_type == ControllerType::MOTION_PROFILE);
Austin Schuh78379ea2019-01-04 20:39:45 -0800459
James Kuszmaule39cbcf2019-02-27 20:48:34 -0800460 const Eigen::Matrix<double, 5, 1> trajectory_state =
Austin Schuhfb0f35c2021-02-14 21:25:29 -0800461 filters_.trajectory_state();
James Kuszmaule39cbcf2019-02-27 20:48:34 -0800462
James Kuszmaul897ef1a2020-10-25 17:51:10 -0700463 {
464 // TODO(james): The regular Kalman Filter's voltage error terms are
465 // currently unusable--either don't use voltage error at all for the spline
466 // following code, or use the EKF's voltage error estimates.
467 const Eigen::Matrix<double, 2, 1> voltage_error =
Austin Schuhfb0f35c2021-02-14 21:25:29 -0800468 0 * filters_.VoltageError();
James Kuszmaul897ef1a2020-10-25 17:51:10 -0700469 dt_spline_.Update(
470 output != nullptr && controller_type == ControllerType::SPLINE_FOLLOWER,
471 trajectory_state, voltage_error);
472 }
James Kuszmaule39cbcf2019-02-27 20:48:34 -0800473
James Kuszmaul38e79642019-03-09 15:48:27 -0800474 dt_line_follow_.Update(monotonic_now, trajectory_state);
Alex Perrya71badb2019-02-06 19:40:41 -0800475
Alex Perrycb7da4b2019-08-28 19:35:56 -0700476 OutputT output_struct;
477
Austin Schuh78379ea2019-01-04 20:39:45 -0800478 switch (controller_type) {
Austin Schuh872723c2019-12-25 14:38:09 -0800479 case ControllerType::POLYDRIVE:
Alex Perrycb7da4b2019-08-28 19:35:56 -0700480 dt_openloop_.SetOutput(output != nullptr ? &output_struct : nullptr);
Austin Schuh78379ea2019-01-04 20:39:45 -0800481 break;
Austin Schuh872723c2019-12-25 14:38:09 -0800482 case ControllerType::MOTION_PROFILE:
Alex Perrycb7da4b2019-08-28 19:35:56 -0700483 dt_closedloop_.SetOutput(output != nullptr ? &output_struct : nullptr);
Austin Schuh78379ea2019-01-04 20:39:45 -0800484 break;
Austin Schuh872723c2019-12-25 14:38:09 -0800485 case ControllerType::SPLINE_FOLLOWER:
Alex Perrycb7da4b2019-08-28 19:35:56 -0700486 dt_spline_.SetOutput(output != nullptr ? &output_struct : nullptr);
Alex Perry731b4602019-02-02 22:13:01 -0800487 break;
Austin Schuh872723c2019-12-25 14:38:09 -0800488 case ControllerType::LINE_FOLLOWER:
Alex Perrycb7da4b2019-08-28 19:35:56 -0700489 if (!dt_line_follow_.SetOutput(output != nullptr ? &output_struct
490 : nullptr)) {
James Kuszmaul5bc6fc92019-03-01 21:50:06 -0800491 // If the line follow drivetrain was unable to execute (generally due to
492 // not having a target), execute the regular teleop drivetrain.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700493 dt_openloop_.SetOutput(output != nullptr ? &output_struct : nullptr);
James Kuszmaul5bc6fc92019-03-01 21:50:06 -0800494 }
James Kuszmaule39cbcf2019-02-27 20:48:34 -0800495 break;
Brian Silverman17f503e2015-08-02 18:17:18 -0700496 }
497
Austin Schuh093535c2016-03-05 23:21:00 -0800498 // The output should now contain the shift request.
499
Brian Silverman17f503e2015-08-02 18:17:18 -0700500 // set the output status of the control loop state
501 if (status) {
Austin Schuh093535c2016-03-05 23:21:00 -0800502 Eigen::Matrix<double, 2, 1> linear =
Austin Schuhfb0f35c2021-02-14 21:25:29 -0800503 dt_config_.LeftRightToLinear(filters_.DrivetrainXHat());
Austin Schuh093535c2016-03-05 23:21:00 -0800504 Eigen::Matrix<double, 2, 1> angular =
Austin Schuhfb0f35c2021-02-14 21:25:29 -0800505 dt_config_.LeftRightToAngular(filters_.DrivetrainXHat());
Austin Schuh093535c2016-03-05 23:21:00 -0800506
Austin Schuhfb0f35c2021-02-14 21:25:29 -0800507 angular(0, 0) = filters_.localizer_theta();
Austin Schuh093535c2016-03-05 23:21:00 -0800508
509 Eigen::Matrix<double, 4, 1> gyro_left_right =
Austin Schuhd91c0d22016-10-15 21:24:28 -0700510 dt_config_.AngularLinearToLeftRight(linear, angular);
Austin Schuh093535c2016-03-05 23:21:00 -0800511
Alex Perrycb7da4b2019-08-28 19:35:56 -0700512 const flatbuffers::Offset<CIMLogging> cim_logging_offset =
James Kuszmaulaf5dfad2020-01-03 20:02:54 -0800513 dt_openloop_.PopulateShiftingStatus(status->fbb());
514
515 const flatbuffers::Offset<PolyDriveLogging> poly_drive_logging_offset =
Alex Perrycb7da4b2019-08-28 19:35:56 -0700516 dt_openloop_.PopulateStatus(status->fbb());
Austin Schuh093535c2016-03-05 23:21:00 -0800517
James Kuszmaul3e1bb272020-01-17 18:38:19 -0800518 const flatbuffers::Offset<DownEstimatorState> down_estimator_state_offset =
Austin Schuhfb0f35c2021-02-14 21:25:29 -0800519 filters_.PopulateDownEstimatorState(status->fbb(), monotonic_now);
James Kuszmaul2215d922020-02-11 17:17:26 -0800520
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800521 const flatbuffers::Offset<LocalizerState> localizer_offset =
Austin Schuhfb0f35c2021-02-14 21:25:29 -0800522 filters_.PopulateLocalizerState(status->fbb());
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800523
James Kuszmaul2215d922020-02-11 17:17:26 -0800524 const flatbuffers::Offset<ImuZeroerState> zeroer_offset =
Austin Schuhfb0f35c2021-02-14 21:25:29 -0800525 filters_.PopulateImuZeroerState(status->fbb());
James Kuszmaul3e1bb272020-01-17 18:38:19 -0800526
Alex Perrycb7da4b2019-08-28 19:35:56 -0700527 flatbuffers::Offset<LineFollowLogging> line_follow_logging_offset =
528 dt_line_follow_.PopulateStatus(status);
529 flatbuffers::Offset<TrajectoryLogging> trajectory_logging_offset =
530 dt_spline_.MakeTrajectoryLogging(status);
Austin Schuh093535c2016-03-05 23:21:00 -0800531
Austin Schuhfb0f35c2021-02-14 21:25:29 -0800532 Status::Builder builder = status->MakeBuilder<Status>();
Austin Schuh3a378462019-01-04 21:48:04 -0800533
Alex Perrycb7da4b2019-08-28 19:35:56 -0700534 dt_closedloop_.PopulateStatus(&builder);
Austin Schuh3a378462019-01-04 21:48:04 -0800535
Austin Schuh95771d92021-01-23 14:42:25 -0800536 builder.add_estimated_left_position(gyro_left_right(kLeftPosition));
537 builder.add_estimated_right_position(gyro_left_right(kRightPosition));
Austin Schuh41565602016-02-28 20:10:49 -0800538
Austin Schuh95771d92021-01-23 14:42:25 -0800539 builder.add_estimated_left_velocity(gyro_left_right(kLeftVelocity));
540 builder.add_estimated_right_velocity(gyro_left_right(kRightVelocity));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700541
542 if (dt_spline_.enable()) {
543 dt_spline_.PopulateStatus(&builder);
544 } else {
Austin Schuhfb0f35c2021-02-14 21:25:29 -0800545 builder.add_robot_speed((filters_.DrivetrainXHat(kLeftVelocity) +
546 filters_.DrivetrainXHat(kRightVelocity)) /
547 2.0);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700548 builder.add_output_was_capped(dt_closedloop_.output_was_capped());
Austin Schuhfb0f35c2021-02-14 21:25:29 -0800549 builder.add_uncapped_left_voltage(
550 filters_.DrivetrainUUncapped(kLeftVoltage));
551 builder.add_uncapped_right_voltage(
552 filters_.DrivetrainUUncapped(kRightVoltage));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700553 }
554
Austin Schuhfb0f35c2021-02-14 21:25:29 -0800555 builder.add_left_voltage_error(filters_.DrivetrainXHat(kLeftError));
556 builder.add_right_voltage_error(filters_.DrivetrainXHat(kRightError));
557 builder.add_estimated_angular_velocity_error(
558 filters_.DrivetrainXHat(kAngularError));
559 builder.add_estimated_heading(filters_.localizer_theta());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700560
Austin Schuhfb0f35c2021-02-14 21:25:29 -0800561 builder.add_x(filters_.x());
562 builder.add_y(filters_.y());
563 builder.add_theta(::aos::math::NormalizeAngle(filters_.localizer_theta()));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700564
Alex Perrycb7da4b2019-08-28 19:35:56 -0700565 builder.add_cim_logging(cim_logging_offset);
James Kuszmaulaf5dfad2020-01-03 20:02:54 -0800566 builder.add_poly_drive_logging(poly_drive_logging_offset);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700567 builder.add_gear_logging(gear_logging_offset);
568 builder.add_line_follow_logging(line_follow_logging_offset);
569 builder.add_trajectory_logging(trajectory_logging_offset);
James Kuszmaul3e1bb272020-01-17 18:38:19 -0800570 builder.add_down_estimator(down_estimator_state_offset);
James Kuszmaul3c5b4d32020-02-11 17:22:14 -0800571 builder.add_localizer(localizer_offset);
James Kuszmaul2215d922020-02-11 17:17:26 -0800572 builder.add_zeroing(zeroer_offset);
James Kuszmaul7aa33a92024-03-17 17:25:36 -0700573 builder.add_filters_ready(filters_.Ready());
milind1f1dca32021-07-03 13:50:07 -0700574
575 builder.add_send_failures(status_failure_counter_.failures());
576
577 status_failure_counter_.Count(status->Send(builder.Finish()));
Brian Silverman17f503e2015-08-02 18:17:18 -0700578 }
Austin Schuh209f1702015-11-29 17:03:00 -0800579
James Kuszmaulddc69702021-03-24 21:55:03 -0700580 // If the filters aren't ready/valid, then disable all outputs (currently,
581 // this only happens if the IMU is faulted or has not zeroed).
582 // TODO(james): Add exceptions so that during competitive play the driver
583 // can retain minimal control of the robot.
584 if (!filters_.Ready()) {
585 output_struct.left_voltage = 0.0;
586 output_struct.right_voltage = 0.0;
587 }
588
Austin Schuh209f1702015-11-29 17:03:00 -0800589 double left_voltage = 0.0;
590 double right_voltage = 0.0;
591 if (output) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700592 left_voltage = output_struct.left_voltage;
593 right_voltage = output_struct.right_voltage;
Austin Schuhfb0f35c2021-02-14 21:25:29 -0800594 filters_.set_left_high_requested(output_struct.left_high);
595 filters_.set_right_high_requested(output_struct.right_high);
Austin Schuh209f1702015-11-29 17:03:00 -0800596 }
597
Alex Perrycb7da4b2019-08-28 19:35:56 -0700598 const double scalar = robot_state().voltage_battery() / 12.0;
Austin Schuh209f1702015-11-29 17:03:00 -0800599
600 left_voltage *= scalar;
601 right_voltage *= scalar;
602
Austin Schuh209f1702015-11-29 17:03:00 -0800603 // To validate, look at the following:
604
605 // Observed - dx/dt velocity for left, right.
606
607 // Angular velocity error compared to the gyro
608 // Gyro heading vs left-right
609 // Voltage error.
610
Austin Schuhfb0f35c2021-02-14 21:25:29 -0800611 {
612 Eigen::Matrix<double, 2, 1> U;
613 U(kLeftVoltage) = left_voltage;
614 U(kRightVoltage) = right_voltage;
615 filters_.UpdateObserver(U);
616 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700617
618 if (output) {
milind1f1dca32021-07-03 13:50:07 -0700619 output->CheckOk(output->Send(Output::Pack(*output->fbb(), &output_struct)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700620 }
James Kuszmaulf6aa0382024-03-01 19:46:05 -0800621
622 if (localizer_input_sender_.valid()) {
623 auto localizer_input_builder = localizer_input_sender_.MakeStaticBuilder();
624 localizer_input_builder->set_left_encoder(position->left_encoder());
625 localizer_input_builder->set_right_encoder(position->right_encoder());
626 if (output) {
627 localizer_input_builder->set_left_voltage(output_struct.left_voltage);
628 localizer_input_builder->set_right_voltage(output_struct.right_voltage);
629 }
630 localizer_input_builder.CheckOk(localizer_input_builder.Send());
631 }
Brian Silverman17f503e2015-08-02 18:17:18 -0700632}
633
Alex Perrycb7da4b2019-08-28 19:35:56 -0700634flatbuffers::Offset<Output> DrivetrainLoop::Zero(
635 aos::Sender<Output>::Builder *output) {
636 Output::Builder builder = output->MakeBuilder<Output>();
637 builder.add_left_voltage(0);
638 builder.add_right_voltage(0);
639 builder.add_left_high(dt_config_.default_high_gear);
640 builder.add_right_high(dt_config_.default_high_gear);
641 return builder.Finish();
Adam Snaiderbc918b62016-02-27 21:03:39 -0800642}
643
Stephan Pleinesf63bde82024-01-13 15:59:33 -0800644} // namespace frc971::control_loops::drivetrain